diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 75aa11963..000000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..1fb97c83b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +tmp +.DS_Store +build_out +_jnaerator.* \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..9bcf99945 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: java +jdk: + - oraclejdk8 diff --git a/README.md b/README.md index fa7c04750..d24b6804d 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,23 @@ -This repository hosts source code for the following (related) projects : +This repository (used to) host / incubated source code for the following (related) projects : -* [JNAerator](http://code.google.com/p/jnaerator/) parses C, C++ and Objective-C headers and generates Java bindings for use with BridJ, JNA or Rococoa +* [JNAerator](http://github.com/ochafik/JNAerator) parses C, C++ and Objective-C headers and generates Java bindings for use with BridJ, JNA or Rococoa [CHANGELOG](https://github.com/ochafik/nativelibs4java/blob/master/libraries/jnaerator/CHANGELOG) | [FAQ](http://code.google.com/p/jnaerator/wiki/JNAeratorFAQ) | [Credits and License](http://code.google.com/p/jnaerator/wiki/CreditsAndLicense) -* [BridJ](http://code.google.com/p/bridj/) is a runtime library that lets Java developers use C/C++ with dynamic bindings (no need to compile any native bindings) +* [BridJ](http://github.com/ochafik/BridJ) is a runtime library that lets Java developers use C/C++ with dynamic bindings (no need to compile any native bindings) [CHANGELOG](https://github.com/ochafik/nativelibs4java/blob/master/libraries/BridJ/CHANGELOG) | [FAQ](http://code.google.com/p/bridj/wiki/FAQ) | [JavaDoc](http://nativelibs4java.sourceforge.net/bridj/api/development/) | [Credits and License](http://code.google.com/p/bridj/wiki/CreditsAndLicense) -* [JavaCL](http://code.google.com/p/javacl/) provides OpenCL bindings + a high-level object-oriented API that hides away much of the complexity of GPGPU + useful utilities +* [JavaCL](http://github.com/ochafik/JavaCL) provides OpenCL bindings + a high-level object-oriented API that hides away much of the complexity of GPGPU + useful utilities [CHANGELOG](https://github.com/ochafik/nativelibs4java/blob/master/libraries/OpenCL/CHANGELOG) | [FAQ](http://code.google.com/p/javacl/wiki/FAQ) | [JavaDoc](http://nativelibs4java.sourceforge.net/javacl/api/stable/) | [Credits and License](http://code.google.com/p/bridj/wiki/CreditsAndLicense) -* [ScalaCL](http://code.google.com/p/scalacl/) provides GPGPU-powered collections for Scala, with map/filter operations running straight on the GPU (effectively converts Scala code to OpenCL) +* [ScalaCL](http://code.google.com/p/scalacl/) provides GPGPU-powered collections for Scala, with map/filter operations running straight on the GPU (converts Scala code to OpenCL). + + _ScalaCL moved to its own repository: [ochafik/ScalaCL](https://github.com/ochafik/ScalaCL)._ [FAQ](http://code.google.com/p/scalacl/wiki/FAQ) | [Credits and License](http://code.google.com/p/bridj/wiki/CreditsAndLicense) * [Scalaxy](http://code.google.com/p/scalaxy/) plugs into the Scala compiler to optimize Scala code (in particular, makes for loops much faster) + _Scalaxy moved to its own repository: [ochafik/Scalaxy](https://github.com/ochafik/Scalaxy)._ + Please read [Olivier Chafik's blog](http://ochafik.com/blog/) for announcements. diff --git a/libraries/BridJ-OSGi/pom.xml b/libraries/BridJ-OSGi/pom.xml deleted file mode 100644 index 7c7a81299..000000000 --- a/libraries/BridJ-OSGi/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - bridj-osgi - BridJ OSGi Bundle - http://code.google.com/p/bridj/ - 0.6.2-SNAPSHOT - bundle - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - - com.nativelibs4java - bridj - 0.6.2-SNAPSHOT - - - org.osgi - org.osgi.core - 4.3.0 - provided - - - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - ${pom.groupId}.${pom.artifactId} - ${pom.name} - ${pom.version} - - org.bridj.OSGiBundleActivator - - - org.bridj.relocated.* - - - org.osgi.framework - - - org.bridj, - org.bridj.ann, - org.bridj.cpp, - org.bridj.cpp.com, - org.bridj.cpp.com.shell, - org.bridj.demangling, - org.bridj.jawt, - org.bridj.objc, - org.bridj.dyncall, - org.bridj.util - - - - - - - - - - - - diff --git a/libraries/BridJ-OSGi/src/main/java/org/bridj/OSGiBundleActivator.java b/libraries/BridJ-OSGi/src/main/java/org/bridj/OSGiBundleActivator.java deleted file mode 100644 index 0c83ba6eb..000000000 --- a/libraries/BridJ-OSGi/src/main/java/org/bridj/OSGiBundleActivator.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bridj; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -public class OSGiBundleActivator implements BundleActivator { - - public void start(BundleContext bundleContext) { - //System.out.println("Starting BridJ"); - } - - public void stop(BundleContext bundleContext) { - //System.out.println("Stopping BridJ"); - } -} diff --git a/libraries/BridJ/.gitignore b/libraries/BridJ/.gitignore deleted file mode 100644 index acc396ecd..000000000 --- a/libraries/BridJ/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -target -project/boot -project/target -*~ -src/main/cpp/bridj/build_out -src/test/cpp/test/build_out -bug*.txt -*.obj -*.pdb -*.idb -*.dep -*.lib -*.htm -*.ilk -*.manifest -*.manifest.res -*.pch -*.ncb -*.suo -*.user -*.exp -src/main/cpp/buildsys/vs2008/Release -src/main/cpp/buildsys/vs2008/Debug -src/main/cpp/buildsys/vs2008/x64/Release -src/main/cpp/buildsys/vs2008/x64/Debug -dependency-reduced-pom.xml -dyncall/* -dyncallBefore/* -*.log -dalvik diff --git a/libraries/BridJ/BuildNative b/libraries/BridJ/BuildNative deleted file mode 100755 index be88e7870..000000000 --- a/libraries/BridJ/BuildNative +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -function failed() { - echo "$@" - exit 1 -} - -cd `dirname $0` -export DYNCALL_HOME=`pwd`/dyncall - -if [[ ! -d "$DYNCALL_HOME" ]] -then - `pwd`/admin/checkout_and_patch_dyncall.sh src/main/cpp/bridj/dyncall.diff || failed "Failed to checkout and patch dyncall" -fi - -if [[ -z "$BRIDJ_TARGETS" ]] ; then - if [[ -d /Applications && ! -z "$ANDROID_NDK_HOME" ]] ; then - #BRIDJ_TARGETS="default ios android" ; - BRIDJ_TARGETS="default android" ; - else - BRIDJ_TARGETS="default" ; - fi ; -fi - -cd `dirname $0`/src/main/cpp/bridj - -for TARGET in $BRIDJ_TARGETS ; do - if [[ "$DEBUG" == "1" ]] ; then - TARGET=$TARGET BUILD_CONFIG=debug ./Make.sh $@ || failed "Make failed" - else - if [[ "$@" == "fast" ]] ; then - TARGET=$TARGET ./Make.sh || failed "Make failed" - else - TARGET=$TARGET ./Make.sh $@ || failed "Make failed" - fi ; - fi ; -done - diff --git a/libraries/BridJ/BuildNative.cmd b/libraries/BridJ/BuildNative.cmd deleted file mode 100644 index e5c5c6bd8..000000000 --- a/libraries/BridJ/BuildNative.cmd +++ /dev/null @@ -1,60 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -pushd . -cd src\main\cpp\buildsys\vs2008 - -call SetEnv.cmd -call CopyRulesIfNeeded.cmd - -pushd .. -call GenerateJNIStubs.cmd -popd - -if "%CONFIG%" == "" set CONFIGS=Release Debug -if not "%CONFIG%" == "" set CONFIGS=%CONFIG% -if "%CONFIG%" == "" set CONFIG=Release - -for %%C in (%CONFIGS%) do ( - REM if exists "c:\Program Files (x86)" - call "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 - REM if not exists "c:\Program Files (x86)" call "c:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 - devenv /nologo /useenv /Build "%%C|Win32" bridj.sln - echo. - - REM if exists "c:\Program Files (x86)" - call "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86_amd64 - REM if not exists "c:\Program Files (x86)" call "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86_amd64 - devenv /nologo /useenv /Build "%%C|x64" bridj.sln - echo. -) - -for %%T in (win32 win64) do ( - del ..\..\..\resources\org\bridj\lib\%%T\*.dll - del ..\..\..\..\test\resources\org\bridj\lib\%%T\*.dll -) - -rem set CONFIG=Debug -rem set CONFIG=Release - -copy %CONFIG%\bridj.dll ..\..\..\resources\org\bridj\lib\win32 -copy %CONFIG%\test.dll ..\..\..\..\test\resources\org\bridj\lib\win32 - -copy x64\%CONFIG%\bridj.dll ..\..\..\resources\org\bridj\lib\win64 -copy x64\%CONFIG%\test.dll ..\..\..\..\test\resources\org\bridj\lib\win64 - -rem if "%CONFIG%" == "Debug" ( - - copy %CONFIG%\bridj.pdb ..\..\..\resources\org\bridj\lib\win32 - copy %CONFIG%\test.pdb ..\..\..\..\test\resources\org\bridj\lib\win32 - - copy x64\%CONFIG%\bridj.pdb ..\..\..\resources\org\bridj\lib\win64 - copy x64\%CONFIG%\test.pdb ..\..\..\..\test\resources\org\bridj\lib\win64 -rem ) -rem echo Copied files from %CONFIG% : -rem dir %CONFIG%\bridj.dll x64\%CONFIG%\bridj.dll - - -popd - -if not "%1" == "nopause" pause diff --git a/libraries/BridJ/BuildNative_Debug b/libraries/BridJ/BuildNative_Debug deleted file mode 100755 index 8c97a9c51..000000000 --- a/libraries/BridJ/BuildNative_Debug +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -DEBUG=1 BRIDJ_TARGETS=default `dirname $0`/BuildNative $@ || exit 1 diff --git a/libraries/BridJ/BuildNative_Debug.cmd b/libraries/BridJ/BuildNative_Debug.cmd deleted file mode 100644 index b030ff0d2..000000000 --- a/libraries/BridJ/BuildNative_Debug.cmd +++ /dev/null @@ -1,5 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -set CONFIG=Debug -call BuildNative.cmd diff --git a/libraries/BridJ/CHANGELOG b/libraries/BridJ/CHANGELOG deleted file mode 100644 index ad2a378bd..000000000 --- a/libraries/BridJ/CHANGELOG +++ /dev/null @@ -1,227 +0,0 @@ -Current development version (0.6.2-SNAPSHOT) - -- Fixed serious crashes on Win64 in assembler optimizations -- Fixed handling of classloaders in some use-cases (issue #283) -- Fixed Platform.open(File) (issue #306) -- Fixed Pointer.copyTo(dest, elementCount) (issue #317) -- Fixed alignment of struct array fields (issue #319) -- Added parsing of Mach-O compressed symbols tries (LC_DYLD_INFO command) to dyncall (issue #311) -- Added Pointer.withoutValidityInformation() (yields faster, unsafe pointer) -- Added BridJ.subclassWithSynchronizedNativeMethods(Class) to create a subclass where all native methods are overridden -- Added Pointer.getIntAtIndex(long) / .setIntAtIndex(long, int) (and with all primitive variants) -- Removed ios-package (binaries for iOS/arm) - -BridJ 0.6.1 (20120415, commit 6bc061dfce06b941086a29f696195e82fbaffbdc) - -- Release artifacts are available in Maven Central -- Fixed wchar_t and WideCString on MacOS X (issue #295) -- Fixed @Name annotation -- Fixed deletion of temporary extracted library files with shutdown hook (issue #197) -- Fixed Unix binaries dependency on GLIBC 2.11 (lowered to version 2.2.5) (issue #195) -- Fixed some pointer methods : 3D pointers allocation, Pointer.setXXXsAtOffset, float endianness conversion -- Fixed regression on struct-valued struct fields (when implemented by java fields) (issue #200) -- Fixed crash with valued enum return values (issue #196) -- Fixed crash of dynamic callbacks on Win32 -- Fixed attachment of native threads in native -> Java callbacks (should attach them as JVM daemon threads) -- Fixed C++ inner class name-mangling matching -- Fixed signature of ITaskbarList3.SetProgressValue (issue #218) -- Fixed Pointer.getByteBuffer() and Pointer.getBytes() (and all their type variants !) -- Fixed StructIO.getEnumField (now returns an IntValuedEnum) -- Fixed handling of CLong / SizeT java fields in structs (cf. issue #253) -- Fixed StructIO.FieldDecl accessibility to allow override of all StructIO.Customizer methods (cf. issue #220) -- Fixed regression on libc, created with null path (issue #217) -- Fixed back-references in Visual C++ demangler (issue #291) -- Fixed binding of IntValuedEnum types -- Fixed handling of virtual destructors with GCC-compiled libraries (and virtual table pointer + runtime guess / check of virtual index for virtual methods) (issue #281) -- Fixed shortcuts in GCC4Demangler (contrib from RŽmi ƒmonet, issue #211) -- Added support for PointerIO> (issue #261) -- Added ProcessUtils.getCurrentProcessId() -- Allow libname.so and name.so for embedded libraries on Unix (issue #215) -- Enhanced multi-threaded performance of PointerIO.getInstance (issue #203) -- Added Pointer.getXxxs(XxxBuffer) -- Added alias mechanism for annotations : any annotation which class is itself annotated by @Ptr / @CLong can serve as an alias (issue #202) -- Added native error log when LoadLibrary or dlopen failed -- Added IntValuedEnum FlagSet.fromValue(int, E...) -- Enabled all compiler optimizations on all platforms but win32 -- Updated doc of Pointer.getXxxs() -- Added experimental by-value struct support on amd64 for structs larger than 64 bits (disabled by default, set -Dbridj.structsByValue=true or BRIDJ_STRUCTS_BY_VALUE=1 to enable) - -BridJ 0.6 (20111107, commit 4950e5c58f32869ce460dbbc59fe969865dd9288) - -- Added errno/GetLastError() mechanism : declare methods to throw org.bridj.LastError and it's all handled automatically (issue #74) -- Added protected mode (-Dbridj.protected=true / BRIDJ_PROTECTED=1), to prevent native crashes (makes BridJ bindings slower + disables optimized raw calls). -- Added proxy-based Objective-C delegates support (forwards unknown methods to a Java instance) (issue #188) -- Added Objective-C 2.0 blocks support (similar to callbacks, inherit from ObjCBlock instead of Callback) (issue #192) -- Added Pointer.asList() and .asList(ListType) to get a List view of the pointed memory - - depending on the ListType, the view can be mutable / resizeable - - removed the List interface from Pointer (which is now just an Iterable) - - added Pointer.allocateList(type, capacity) to create a NativeList from scratch (has a .getPointer method to grab the resulting memory at the end) -- Added Pointer.moveBytesTo(Pointer) -- Added support for embedded libraries extraction from "lib/arch" paths (along with "org/bridj/lib/arch", where arch uses BridJ's convention) -- Added TimeT (time_t), timeval classes (issue #72) -- Added Platform.getMachine() (same result as `uname -m`) -- Added support for multiarch Linux distributions (issue #2) -- Added support for versioned library file names (issue #72) -- Added global allocated memory alignment setting (BRIDJ_DEFAULT_ALIGNMENT env. var. & bridj.defaultAlignment property), + Pointer.allocateAlignedArray -- Added basic calls log mechanism (disables direct mode) : -Dbridj.logCalls=true or BRIDJ_LOG_CALLS=1 (only logs the method name & signature, not the arguments or returned values) -- Added BridJ.setMinLogLevel(Level) (issue #190) -- Added Platform.addEmbeddedLibraryResourceRoot(root) to use & customize the embedded library extraction feature in user projects -- Added support for packed structs (@Struct(pack = 1), or any other pack value) -- Added check of BridJ environment variables and Java properties : if any BRIDJ_* env. var. or bridj.* property does not exist, it will log warnings + full list of valid options -- Added @JNIBound annotation to mark native methods that should not be bound by BridJ but by plain old JNI -- Fixed Pointer.next/.offset methods (used to throw errors a the end of iteration) -- Fixed Pointer.getNativeObjectAtOffset(long byteOffset, Type type) -- Fixed struct fields implemented as Java fields -- Fixed resolution of MacOS X "ApplicationServices" framework binaries, such as CoreGraphics -- Fixed some COM bugs with IUnknown -- Fixed demangling/matching of CLong & SizeT -- Fixed CLong & SizeT arguments -- Fixed Objective-C runtime (basic features), added NSString constructor & NSDictionary (with conversion to/from Map) -- Fixed crashes on Win32 (when using Pointer class in bound function arguments) -- Fixed crash during deallocation of Callbacks + fixed leak of Callbacks (now need to retain a reference to callbacks or use BridJ.protectFromGC / unprotectFromGC) -- Made the StructIO customization mechanism more flexible -- Made JawtLibrary public -- Various Javadoc tweaks - -BridJ 0.5 (r2128, 20110621) - -- Added support for Android(arm) platform -- Added Pointer.clone() that duplicates the memory (requires a pointer with bounds information) -- Added various pre-packaged specialized subsets of BridJ : c-only, windows-only, macosx-only, unix-only, linux-only, ios-only, android -- Added Pointer.allocateDynamicCallback(DynamicCallback, callingConv, returnType, paramTypes...) -- Added BridJ native library path override : one can set the BRIDJ_LIBRARY environment variable or the "bridj.library" property to the full path of libbridj.so/.dylib/.dll - -BridJ 0.4.2 (r2009, 20110527) - -- Fixed behaviour in environments with a null default classloader (as in Scala 2.9.0) -- Added support for Java 1.5 (issue #57) -- Added support for MacOS X 10.4, 10.5 (was previously restricted to 10.6) - -BridJ 0.4.1 (r1990, 20110513) - -- Fixed callbacks on Windows x86 -- Fixed multithreaded callbacks ! (callbacks called in a different thread than the one that created them used to hang indefinitely) -- Fixed Pointer and ValuedEnum arguments and return values in callbacks -- Fixed loading of libraries that depend on other libraries in the same directory on Windows (issue #65) -- Fixed BridJ.sizeOf(Pointer.class), sizeOf(SizeT.class), sizeOf(CLong.class)... -- Enhanced C++ templates support -- Added support for Windows APIs Unicode vs. ANSI functions renaming (e.g. SendMessage being one of SendMessageW or SendMessageA, depending on Platform.useUnicodeVersionOfWindowsAPIs) -- Added deprecated support for struct fields implemented as Java fields, to ease up migration from JNA (needs manual calls to BridJ.writeToNative(struct) and BridJ.readFromNative(struct)) (issue #54) -- Added preliminary read-only support for STL's std::vector C++ type -- Added BridJ.describe(Type) to describe structs layouts (automatically logged for each struct type when BRIDJ_DEBUG=1 or -Dbridj.debug=true) -- Added BridJ.describe(NativeObject). -- Added StructObject.toString() (calls BridJ.describe(this)) -- Added BRIDJ_DEBUG_POINTERS=1 (or -Dbridj.debug.pointers=true) to display extended pointer allocation / deallocation debug information -- Reorganized Windows COM packages (moved out DirectX code to it own top-level project : com.nativelibs4java:directx4java) -- Implemented FlagSet.equals - -BridJ 0.4 (r1869, 20110408) - -- Added parsing of GNU LD scripts (issue #61) -- Fixed demangling of size_t / long C types with GCC -- Fixed Linux x86 symbols -- Added experimental C++ virtual overrides : it is now possible to subclass C++ classes from Java, even with anonymous inner classes ! (no support for multiple inheritance yet) -- Fixed crash in C++ destructors at the JVM shutdown (issue #60) -- Fixed callbacks with float args -- Added support for varargs functions -- Fixed size computation of structs with array fields (issue #64) - -BridJ 0.3.1 (r1817, 20110329) - -- Introduced basic C++ templates support (binding of compiled template classes, not template methods / functions yet) -- Added dynamic functions support : Pointer.asDynamicFunction(callConv, returnType, argTypes...) -- Added support for arbitrary C++ constructors -- Added support for __stdcall callbacks -- Added COM VARIANT class with very basic data conversion support -- Added many COM UUID definitions (from uuids.h, codecapi.h, ksuuids.h) -- Added Solaris x86 support -- Added @DisableDirect annotation to force-disable raw assembly optimizations (also see BRIDJ_DIRECT=0 or -Dbridj.direct=false for global disable) -- Fixed long return values (issue #47) -- Fixed '@Ptr long' return values on 32 bits platforms -- Fixed structs sub-structs and array fields -- Fixed unions : - - pure unions can be created with the @Union annotation on the union class (+ fields annotated with @Field(value = uniqueId)) - - structs with unioned fields can be defined with fields annotated with @Field(value = uniqueId, unionWith = indexOfTheFirstFieldOfTheUnion) -- Fixed size computation of unions & structs (issue #51) -- Fixed JAWTUtils on win32 (issue #52) -- Fixed Pointer.pointerToAddress(long, Class, Releaser) (issue #48) -- Fixed incomplete refactoring (issue #58) -- Moved all the is64Bits(), isWindows()... methods and SIZE_T_SIZE constants out of JNI class into new Platform class -- Moved the C++ symbols demanglers to package org.bridj.demangling -- Renamed Pointer.asPointerTo(Type) to Pointer.as(Type) -- Enhanced FlagSet (added toString(), toEnum(), fromValue(ValuedEnum)) -- Enhanced Pointer (added allocate(Type), allocateArray(Type, long)) -- Greatly enhanced the API Javadoc - -BridJ 0.3 (r1638, 20110204): - -- Fixed binding of "c" library on Unix -- Fixed iteration on unbound native-allocated pointers (issue 37). -- Fixed Visual C++ demangling (issue 36 : bad handling of back-references). -- Added Pointer.getBuffer(), getSizeTs(), getCLongs() and other missing methods. -- Fixed byteOffset-related issues in CLong and SizeT pointer read/write methods. -- Renamed most pointer byteOffset methods with an -AtOffset suffix (for instance, Pointer.getInt(long) becomes getIntAtOffset(long)) -- Inverted charset and StringType arguments in Pointer.getString / .setString methods -- Renamed Pointer.withIO(PointerIO) to Pointer.as(PointerIO) -- Added Pointer.asUntyped() (equiv. to Pointer.as((Class)null)) -- Allow pointerToBuffer on a non-direct buffer (and added Pointer.updateBuffer -to copy data back to non-direct buffer if needed) -- Assume @Runtime(CRuntime.class) by default -- Autodetect calling convention on Windows (based on name mangling), unless convention is explicitely specified with @Convention(Style.X) -- Added BRIDJ__LIBRARY environment variables to hard-code the shared library path in priority -- Added library alias mechanism : BridJ.setNativeLibraryActualName, .addNativeLibraryAlias -- Fixed callbacks-related Win32 crashes -- Fixed super-critical bug on Windows 32 bits with size_t arguments ! -- Fixed some Pointer endianness bugs - -BridJ 0.2 (r1330, 20101011): - -- Renamed package com.bridj to org.bridj -- Vastly improved JNAerator support : now decent and complete :-) -- Enhanced C support - - Faster structs that rely more on JNAerator - - Optimized structs performance (added comparison tests with Javolution & JNA) -- Enhanced C++ support : - - Automatic call of C++ destructors - - Better GCC demangling (contributed by Remi Emonet) - - Fixed long and size_t signature matching (@CLong and @Ptr annotations) - - Fixed size computation of (simply) inherited structs and classes -- Enhanced Pointer class : - - Full JavaDocs - - Implements List - - Support for 2D & 3D arrays, with syntax directly equivalent to C : - float array[100][200]; - float value = array[i][j]; - Is now : - Pointer> array = pointerToFloats(new float[width][height]); - // or - Pointer> array = pointerToFloats(width, height); - float value = array.get(i).get(j); - - More consistent read/write methods, added variants for CLong, SizeT, Boolean, CString, WideCString, PascalString, WidePascalString... - - Renamed getRemainingElements to getValidElements, getRemainingBytes to getValidBytes - - Added standard bounds-checked util methods : - - Pointer.copyTo (memcpy) - - moveTo (memmov) - - clearBytes (memset) - - findByte (memchr) - - Fixed multiple-endianness support for floats and doubles -- Added JAWTUtils.getNativePeerHandle(Component) -- Refactored native libraries (a bit smaller) -- Enhanced runtime : - - Accept .drv as .dll files on Windows - - Support for name aliasing (@Name, in addition to the @Symbol annotation that bypasses demangling) - - Now compiling native libraries with full optimizations - - Fixed assembler optimizations on Win32, added experimental optimizations for Linux64 - - Can now control assembler optimizations : BridJ.setDirectModeEnabled(boolean) -- Built for Win32/64, MacOS X (Universal: x86, x64, ppc), Ubuntu Linux (x86, x64) - -BridJ 0.1 - -- Basic support for C (enums, functions, callbacks, structs with native getters/setters) -- Basic support for C++ with annotations- and demangling-based dynamic signature matching : - - Normal and virtual methods - - No class fields - - No templates - - No destructors - - No non-trivial constructors) -- Built for Win32/64, MacOS X (Universal: x86, x64, ppc), Linux32 diff --git a/libraries/BridJ/CleanNative b/libraries/BridJ/CleanNative deleted file mode 100755 index 2da20a291..000000000 --- a/libraries/BridJ/CleanNative +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -rm -fR src/test/cpp/test/build_out -rm -fR src/main/cpp/test/build_out -bash BuildNative clean || exit 1 diff --git a/libraries/BridJ/CleanNative.cmd b/libraries/BridJ/CleanNative.cmd deleted file mode 100644 index d048670a6..000000000 --- a/libraries/BridJ/CleanNative.cmd +++ /dev/null @@ -1,25 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -pushd . -cd src\main\cpp\buildsys\vs2008 - -for /D %%F in (dyncall32 dyncall64 dyncallback32 dyncallback64 dynload bridj32 bridj64) do ( - for %%S in (x64 Debug Release obj build) do ( - if exist "%%F\%%S" ( - echo Deleting "%%F\%%S" - rmdir /S /Q "%%F\%%S" - ) - ) -) - -del /Q x64\Release\*.* -del /Q x64\Debug\*.* -del /Q Release\*.* -del /Q Debug\*.* - -del /Q *.ncb - -popd - -if not "%1" == "nopause" pause diff --git a/libraries/BridJ/CommitBinaries b/libraries/BridJ/CommitBinaries deleted file mode 100755 index a2cb0bf59..000000000 --- a/libraries/BridJ/CommitBinaries +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -./GitConfig - -FILES=`git status | egrep 'modified:|new file:' | sed 's/#//' | sed 's/modified://' | sed 's/new file://' | egrep '\.so|\.dylib'` - -PLATFORM="$1" -if [[ -z "$PLATFORM" ]] ; then - PLATFORM="`uname -sm`" ; -fi - -if [[ ! -z "$FILES" ]] ; then - git commit -m "BridJ: updated binaries for $PLATFORM" $FILES ; -fi diff --git a/libraries/BridJ/CopyVisualStudioBinaries.cmd b/libraries/BridJ/CopyVisualStudioBinaries.cmd deleted file mode 100644 index 3b141e1de..000000000 --- a/libraries/BridJ/CopyVisualStudioBinaries.cmd +++ /dev/null @@ -1,11 +0,0 @@ -@echo off -setlocal - -set VS_DIR=src\main\cpp\buildsys\vs2008\Debug - -copy %VS_DIR%\bridj.dll src\main\resources\win32 -copy %VS_DIR%\bridj.pdb src\main\resources\win32 -copy %VS_DIR%\test.dll src\test\resources\win32 -copy %VS_DIR%\test.pdb src\test\resources\win32 - -rem pause diff --git a/libraries/BridJ/GitConfig b/libraries/BridJ/GitConfig deleted file mode 100755 index 3a8b3780a..000000000 --- a/libraries/BridJ/GitConfig +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -git config --global user.name "Olivier Chafik" -git config --global user.email "olivier.chafik@gmail.com" - -#git commit --amend --reset-author diff --git a/libraries/BridJ/LICENSE b/libraries/BridJ/LICENSE deleted file mode 100644 index 0e05f127a..000000000 --- a/libraries/BridJ/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2012, Olivier Chafik -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Olivier Chafik nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 THE REGENTS AND 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. diff --git a/libraries/BridJ/ProxyGen.java b/libraries/BridJ/ProxyGen.java deleted file mode 100644 index 3b2210d83..000000000 --- a/libraries/BridJ/ProxyGen.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.bridj; -import java.util.*; -import java.io.*; -import java.lang.reflect.*; -import org.bridj.util.JNIUtils; -import static org.bridj.demangling.Demangler.*; - -/** - * mvn compile exec:java -o -Dexec.mainClass=org.bridj.ProxyGen - * @author ochafik - */ -public class ProxyGen { - - public static class Toto { - public native CLong testCLong(CLong a); - public native SizeT testSizeT(SizeT a); - public native Pointer testIntPtr(Pointer p, int a, double b); - } - public static void main(String[] args) throws Exception { - String p = generateProxy(Toto.class); - System.out.println(p); - } - /* - - */ - public static String generateProxy(Class interfaceClass) throws Exception { - StringBuilder b = new StringBuilder(); - b.append("#include \n"); - b.append("#ifdef _WIN32\n"); - b.append("#define PROXY_EXPORT __declspec(dllexport)\n"); - b.append("#else\n"); - b.append("#define PROXY_EXPORT\n"); - b.append("#endif\n"); - b.append("#define FIND_GLOBAL_CLASS(name) (*env)->NewGlobalRef(env, (*env)->FindClass(env, name))\n"); - - - List methods = new ArrayList(); - int iClassName = 0, iMethodName = 0; - Map classVarNames = new HashMap(); - - for (Method m : interfaceClass.getDeclaredMethods()) { - try { - ProxiedMethod pm = getProxiedMethod(m); - String classVarName = classVarNames.get(pm.owner); - if (classVarName == null) - classVarNames.put(pm.owner, classVarName = "gClass" + (++iClassName)); - pm.classVarName = classVarName; - pm.methodVarName = "gMethod" + (++iMethodName); - methods.add(pm); - } catch (Throwable th) { - // th.printStackTrace(); - } - } - - b.append("jboolean inited = JNI_FALSE;\n"); - String instanceVarName = "gProxiedInstance"; - b.append("JNIEnv* env = NULL;\n"); - b.append("JavaVM* jvm = NULL;\n"); - b.append("jobject ").append(instanceVarName).append(" = NULL;\n"); - for (String n : classVarNames.values()) - b.append("jclass ").append(n).append(" = NULL;\n"); - - for (ProxiedMethod pm : methods) - b.append("jmethodID ").append(pm.methodVarName).append(" = NULL;\n"); - - String jniInit = "jni_init"; - b.append("void ").append(jniInit).append("(JNIEnv* env) {\n"); - b.append("\tif (inited) return; else inited = JNI_TRUE;\n"); - - for (Map.Entry e : classVarNames.entrySet()) { - String n = e.getValue(); - Class c = e.getKey(); - b.append("\t").append(n).append(" = ").append("FIND_GLOBAL_CLASS(\"").append(JNIUtils.getNativeName(c)).append("\");\n"); - } - for (ProxiedMethod pm : methods) { - int mods = pm.method.getModifiers(); - b.append("\t").append(pm.methodVarName).append(" = "). - append("(*env)->").append(Modifier.isStatic(mods) ? "GetStaticMethodID" : "GetMethodID"). - append("(env, ").append(pm.classVarName).append(", \"").append(pm.name).append("\", \"").append(pm.jni_signature).append("\");\n"); - } - b.append("}\n"); - - for (ProxiedMethod pm : methods) { - b.append("PROXY_EXPORT ").append(pm.c_signature).append(" {\n"); - int mods = pm.method.getModifiers(); - - b.append("\t").append(jniInit).append("();\n"); - b.append("\t"); - if (pm.method.getReturnType() != null && !pm.method.getReturnType().equals(void.class)) - b.append("return "); - - StringBuilder r = new StringBuilder(); - - boolean stat = Modifier.isStatic(mods); - r.append("(*env)->").append("Call" + (stat ? "Static" : "") + pm.retCapitalized + "Method").append("(env, "); - if (stat) - r.append(pm.classVarName); - else - r.append(instanceVarName); - for (String argValue : pm.argValues) { - r.append(", \n\t\t"); - r.append(argValue); - } - - // TODO... - r.append("\n\t)"); - b.append(c_signature(pm.method.getReturnType(), r.toString())[2]); - - b.append(";\n"); - - b.append("}\n"); - } - - - return b.toString(); - } - static ProxiedMethod getProxiedMethod(Method method) { - ProxiedMethod p = new ProxiedMethod(method); - - return p; - } - static String jni_capitalized(Class c) { - if (c == int.class) - return "Int"; - if (c == long.class) - return "Long"; - if (c == short.class) - return "Short"; - if (c == byte.class) - return "Byte"; - if (c == boolean.class) - return "Bool"; - if (c == double.class) - return "Double"; - if (c == float.class) - return "Float"; - if (c == char.class) - return "Char"; - if (c == void.class) - return "Void"; - return "Object"; - } - static String[] strs(String... vals) { - return vals; - } - static String[] c_signature(Class c, String expr) { - if (c.isPrimitive()) - return strs("j" + c.toString(), expr, expr); - if (c == Pointer.class) - return strs("void*", "createPointerFromIO(env, " + expr + ", NULL)", "getPointerPeer(env, " + expr + ")"); // TODO callIO - if (c == CLong.class) - return strs("long", "BoxCLong(env, " + expr + ")", "UnBoxCLong(env, " + expr + ")"); - if (c == SizeT.class) - return strs("size_t", "BoxSizeT(env, " + expr + ")", "UnBoxSizeT(env, " + expr + ")"); - if (c == TimeT.class) - return strs("time_t", "BoxTimeT(env, " + expr + ")", "UnBoxTimeT(env, " + expr + ")"); - - throw new UnsupportedOperationException("Cannot compute C signature for " + c.getName()); - } - static class ProxiedMethod { - String methodVarName, classVarName; - Method method; - String name; - String jni_signature, c_signature, c_args; - Class owner; - - List argTypes = new ArrayList(), argNames = new ArrayList(), argValues = new ArrayList(); - String retType, retCapitalized; - - public ProxiedMethod(Method method) { - this.method = method; - this.name = //method instanceof Constructor ? "" : - method.getName(); - this.owner = method.getDeclaringClass(); - - StringBuffer - jni_sig = new StringBuffer("("), - c_sig = new StringBuffer(); - - retCapitalized = jni_capitalized(method.getReturnType()); - String[] sigArg = c_signature(method.getReturnType(), "?"); - c_sig.append(retType = sigArg[0]).append(" ").append(name).append("("); - int i = 0; - for (Class c : method.getParameterTypes()) { - jni_sig.append(JNIUtils.getNativeSignature(c)); - if (i > 0) - c_sig.append(", "); - - String argName = "arg" + (i + 1); - sigArg = c_signature(c, argName); - String argType = sigArg[0]; - - argTypes.add(argType); - argNames.add(argName); - argValues.add(sigArg[1]); - - c_sig.append(argType).append(" ").append(argName); - i++; - } - c_sig.append(")"); - jni_sig.append(")").append(JNIUtils.getNativeSignature(method.getReturnType())); - this.jni_signature = jni_sig.toString(); - this.c_signature = c_sig.toString(); - } - } - -} diff --git a/libraries/BridJ/README.md b/libraries/BridJ/README.md new file mode 100644 index 000000000..9146db25c --- /dev/null +++ b/libraries/BridJ/README.md @@ -0,0 +1,4 @@ +[BridJ](http://bridj.googlecode.com) has migrated to its own repository: [ochafik/BridJ](http://github.com/ochafik/BridJ). + +Please [file issues there](http://github.com/ochafik/BridJ/issues). + diff --git a/libraries/BridJ/RebuildNative b/libraries/BridJ/RebuildNative deleted file mode 100755 index abdb0b8ee..000000000 --- a/libraries/BridJ/RebuildNative +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -./BuildNative clean -./BuildNative - -if [[ -d /Applications ]] ; then - # MacOS X - for T in ios android ; do - TARGET=$T ./BuildNative clean - TARGET=$T ./BuildNative fast ; - done ; -fi - - diff --git a/libraries/BridJ/Run.java b/libraries/BridJ/Run.java deleted file mode 100644 index 860a30433..000000000 --- a/libraries/BridJ/Run.java +++ /dev/null @@ -1,40 +0,0 @@ - -import java.io.IOException; -import org.bridj.BridJ; -import org.bridj.DynamicCallback; -import org.bridj.DynamicFunction; -import org.bridj.Pointer; -import org.bridj.objc.FoundationLibrary; -import org.bridj.objc.NSString; - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -/** - * - * @author ochafik - */ -public class Run { - public static void main(String[] args) throws IOException { - //Pointer ps = FoundationLibrary.pointerToNSString("Hehe"); - //NSString s = ps.get(); - BridJ.getNativeLibrary("src/test/resources/org/bridj/lib/darwin_universal/libtest.dylib").release(); - /* - Pointer dc = Pointer.allocateDynamicCallback( - new DynamicCallback() { - - public Integer apply(Object... args) { - int a = (Integer)args[0]; - int b = (Integer)args[1]; - return a + b; - } - - }, null, int.class, int.class, int.class - ); - DynamicFunction df = dc.asUntyped().asDynamicFunction(null, int.class, int.class, int.class); - int ret = df.apply(1, 2); - */ - } -} diff --git a/libraries/BridJ/Start 32bits Visual Studio.cmd b/libraries/BridJ/Start 32bits Visual Studio.cmd deleted file mode 100644 index e0998f611..000000000 --- a/libraries/BridJ/Start 32bits Visual Studio.cmd +++ /dev/null @@ -1,9 +0,0 @@ -@echo off -setlocal - -cd src\main\cpp\buildsys\vs2008 -call SetEnv.cmd -setlocal enabledelayedexpansion -call CopyRulesIfNeeded.cmd - -start bridj.sln \ No newline at end of file diff --git a/libraries/BridJ/Start 64bits Visual Studio.cmd b/libraries/BridJ/Start 64bits Visual Studio.cmd deleted file mode 100644 index a265baad2..000000000 --- a/libraries/BridJ/Start 64bits Visual Studio.cmd +++ /dev/null @@ -1,8 +0,0 @@ -@echo off - -cd src\main\cpp\buildsys\vs2008 -call SetEnv.cmd -call CopyRulesIfNeeded.cmd -call "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86_amd64 - -devenv /useenv bridj.sln diff --git a/libraries/BridJ/admin/android-dx-package b/libraries/BridJ/admin/android-dx-package deleted file mode 100755 index 100453435..000000000 --- a/libraries/BridJ/admin/android-dx-package +++ /dev/null @@ -1,158 +0,0 @@ -#!/bin/bash -# -# This script bundles Android's dx tool for OSS Sonatype Maven Repository. -# For more details, see http://docs.sonatype.org/x/vgBl -# - -GIT_URL="https://android.googlesource.com/platform/dalvik" - -git clone $GIT_URL || ( echo "Failed to clone $GIT_URL" && exit 1 ) - -cd dalvik/dx - -DX_VERSION=`cat src/com/android/dx/Version.java | grep VERSION | sed -E 's/^.*"(.*)".*$/\1/'` - -if [[ -z "$DX_VERSION" ]] -then - echo "Failed to detect version of dx" - exit 1 -else - echo "Detected version of dx : $DX_VERSION" -fi - -echo " - - 4.0.0 - com.google.android.tools - dx - Android SDK's dx Tool - http://developer.android.com/guide/developing/tools/index.html - $DX_VERSION - jar - - - dx is an Android SDK platform tool that transforms Java bytecode (and JARs) into Dalvik VM 'DEX' code. - - - - - - - Apache 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - -Copyright (C) 2006 The Android Open Source Project - -Licensed under the Apache License, Version 2.0 (the \"License\"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an \"AS IS\" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - - - - - - - - - - scm:git:$GIT_URL - $GIT_URL - - - - org.sonatype.oss - oss-parent - 7 - - - - src - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - - attach-javadocs - - jar - - - - - - - - - - gpg - - false - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - -" > pom.xml - -mvn clean install $@ || ( echo "Failed" && exit 1 ) - -cd target - -jar -cvf ../dx-$DX_VERSION.jar \ - dx-$DX_VERSION.pom \ - dx-$DX_VERSION.pom.asc \ - dx-$DX_VERSION.jar \ - dx-$DX_VERSION.jar.asc \ - dx-$DX_VERSION-sources.jar \ - dx-$DX_VERSION-sources.jar.asc \ - dx-$DX_VERSION-javadoc.jar \ - dx-$DX_VERSION-javadoc.jar.asc - -cd .. -echo " -Generation of bundle succeeded. -Now please upload file `pwd`/bundle.jar to https://oss.sonatype.org/ (in \"Staging Upload\" tab) -(for more details, see http://docs.sonatype.org/x/vgBl)" diff --git a/libraries/BridJ/admin/build farms machines b/libraries/BridJ/admin/build farms machines deleted file mode 100644 index 23044e824..000000000 --- a/libraries/BridJ/admin/build farms machines +++ /dev/null @@ -1,8 +0,0 @@ -OpenBSD 4.6 / sparc64 : -ssh -p 9204 ochafik@gcc64.fsffrance.org - -Linux 2.6 / sparc64 : -ssh -p 9084 ochafik@gcc64.fsffrance.org - -Sourceforge Shell : -ssh -t opentator,nativelibs4java@shell.sourceforge.net create diff --git a/libraries/BridJ/admin/checkout_and_patch_dyncall.sh b/libraries/BridJ/admin/checkout_and_patch_dyncall.sh deleted file mode 100755 index 5b32a04a3..000000000 --- a/libraries/BridJ/admin/checkout_and_patch_dyncall.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -# -# This script checkouts dyncall (http://dyncall.org/), applies BridJ-specific patches to it and builds it. -# Usage : patch_dyncall.sh directory -# - -function failed() { - echo "$@" - exit 1 -} - -if [[ -z "$DYNCALL_HOME" ]] ; then - failed "DYNCALL_HOME not set" -fi - -if [[ -d "$DYNCALL_HOME" ]] ; then - failed "DYNCALL_HOME = $DYNCALL_HOME already exists" -fi - -if [[ -z "$1" ]] ; then - failed "No path to the diff" -fi - -PATCH_FILE=`pwd`/$1 - -#if [[ ! -d `dirname $DYNCALL_HOME` ]] ; then -# mkdir `dirname $DYNCALL_HOME` || failed "Failed to create parent directory for $DYNCALL_HOME" -#fi - -#echo "Checking out dyncall to $DYNCALL_HOME..." -svn co https://dyncall.org/svn/dyncall/trunk $DYNCALL_HOME || failed "Failed to checkout dyncall to $DYNCALL_HOME" -cd $DYNCALL_HOME || failed "Failed to go to $DYNCALL_HOME" - -echo "Applying BridJ's dyncall patches..." - -if [ ! `which gpatch` ] ; then - PATCH_CMD=patch -else - PATCH_CMD=gpatch -fi - -$PATCH_CMD -i $PATCH_FILE -N -p0 || ( rm -fR $DYNCALL_HOME && failed "Patch failed, deleted $DYNCALL_HOME" ) - -echo "Ensuring all diffed files are added to SVN..." -svn add `find . -type f | grep -v .svn` 2> /dev/null - -echo "Displaying svn status..." -svn status - diff --git a/libraries/BridJ/admin/compressLibraries b/libraries/BridJ/admin/compressLibraries deleted file mode 100755 index 267f221b4..000000000 --- a/libraries/BridJ/admin/compressLibraries +++ /dev/null @@ -1,19 +0,0 @@ -DIR=src/main/resources/org/bridj/lib - -echo "Before :" -ls -l $DIR/*/*.so* $DIR/*/*.dylib* $DIR/*/*.dll* - -# rm -fR src/main/resources/lib src/main/resources/org/bridj/lib/iphoneos* -# 7z a src/main/resources/lib.7z src/main/resources/org/bridj/lib -# rm -fR src/main/resources/org -# exit 1 - - -for F in `find $DIR -name '*.so' -or -name '*.dylib' -or -name '*.dll'` ; do - 7z a $F.7z $F > /dev/null ; -done - -rm $DIR/*/*.so $DIR/*/*.dylib $DIR/*/*.dll - -echo "After :" -ls -l $DIR/*/*.so* $DIR/*/*.dylib* $DIR/*/*.dll* diff --git a/libraries/BridJ/admin/debug windows.txt b/libraries/BridJ/admin/debug windows.txt deleted file mode 100644 index 7f8bfbd12..000000000 --- a/libraries/BridJ/admin/debug windows.txt +++ /dev/null @@ -1,7 +0,0 @@ -32 bits : - -c:\Program Files (x86)\Java\jdk1.6.0_20\bin\java.exe --cp C:\src\nativelibs4java\libraries\Runtime\BridJ\target\bridj-0.7-SNAPSHOT.jar Run -C:\src\nativelibs4java\libraries\Runtime\BridJ -BRIDJ_LIBRARY=C:\src\nativelibs4java\libraries\Runtime\BridJ\src\main\cpp\buildsys\vs2008\Debug\bridj.dll - diff --git a/libraries/BridJ/admin/patch_dyncall.sh b/libraries/BridJ/admin/patch_dyncall.sh deleted file mode 100644 index 1d1590fed..000000000 --- a/libraries/BridJ/admin/patch_dyncall.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash -# -# This script checkouts dyncall (http://dyncall.org/), applies BridJ-specific patches to it and builds it. -# Usage : patch_dyncall.sh directory -# - -if [[ -z "$1" ]] ; then - echo "Please provide a name for the dyncall checkout directory as first and unique argument" - exit 1 ; -fi - -DYNCALL_HOME=`pwd`/$1 - -if [[ -d "$DYNCALL_HOME" ]] ; then - echo "Directory $DYNCALL_HOME already exists." - echo "Please backup or remove with 'rm -fR $DYNCALL_HOME' and retry (or use a different name)" - exit 1 ; -fi - -echo "Checking out dyncall to $DYNCALL_HOME..." -svn co https://dyncall.org/svn/dyncall/trunk $DYNCALL_HOME -cd $DYNCALL_HOME - -if [[ "$NO_PATCH" != "1" ]] ; then - echo "Retrieving BridJ's dyncall patches..." - svn export https://nativelibs4java.googlecode.com/svn/trunk/libraries/Runtime/BridJ/src/main/cpp/bridj/dyncall.diff - echo "Applying BridJ's dyncall patches..." - gpatch -i dyncall.diff -N -p0 || patch -i dyncall.diff -N -p0 ; -fi - -cd dyncall -echo "Configuring..." -if [[ -d /System/Library/Frameworks/ ]] ; then sh ./configure --target-universal ; -else sh ./configure ; fi - -echo "Building..." -make clean -make - -echo "Listing build results :" -find $DYNCALL_HOME/dyncall/*/build_out diff --git a/libraries/BridJ/admin/resetLibraries b/libraries/BridJ/admin/resetLibraries deleted file mode 100755 index 18fe86947..000000000 --- a/libraries/BridJ/admin/resetLibraries +++ /dev/null @@ -1,2 +0,0 @@ -rm -fR src/main/resources/* -git checkout src/main/resources/ diff --git a/libraries/BridJ/admin/setup_freebsd8.2.sh b/libraries/BridJ/admin/setup_freebsd8.2.sh deleted file mode 100644 index 6de0552d8..000000000 --- a/libraries/BridJ/admin/setup_freebsd8.2.sh +++ /dev/null @@ -1,5 +0,0 @@ - -pkg_add -r gnome2 openjdk6 scala maven2 git - - -echo "/usr/local/bin/gnome-session" > ~/.xinitrc diff --git a/libraries/BridJ/admin/setup_iphone.sh b/libraries/BridJ/admin/setup_iphone.sh deleted file mode 100644 index 058a40ac5..000000000 --- a/libraries/BridJ/admin/setup_iphone.sh +++ /dev/null @@ -1,97 +0,0 @@ -# Also see http://www.alexwhittemore.com/?p=398 - -apt-get install jikes jamvm vim - -# Add MacBook Pro key for autologin : -mkdir ~/.ssh -touch ~/.ssh/authorized_keys -echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq9hvZ0QQYxxRQES6ktR+pCVfHPb2AV/ociz0W9ycM9PUFR3aMZ/mj5x3OjoQZfNn3Rpy9Sx9ybQcM8uZLt+U1T4n4EdV2FehKeyIdm8IQaBTfMIDG3oNNdakgnZaSahs6LRUkJnZ7XvWxoP/bmj1ujpySvKioq9K38kGnuuE4CcW2Lm9yHv0X8o/sn8uBOD+64o4XS8vw6rr5Gbl15GYsaiPVmR3To3D4+L1U6sKmUXaa+ny2w0SgN6iAFmIFeYiUQ3s3nnjLou1Wk01Gzv2K2ywgD4e2bzHOjurVlEx8mwWWYLuS0XcaBp6Q9S3ofVj9YaPfT9WDrU3YB4RB/H83Q== olivier.chafik@gmail.com" >> ~/.ssh/authorized_keys - -# Install GCC : -# http://blog.syshalt.net/index.php/2010/09/12/compile-c-applications-with-gcc-on-ios-4-iphone/ - -wget http://www.syshalt.net/pub/iphone/gcc-iphone/fake-libgcc_1.0_iphoneos-arm.deb -dpkg Ði fake-libgcc_1.0_iphoneos-arm.deb -apt-get install iphone-gcc -wget http://www.syshalt.net/iphone/gcc-iphone/sdk-2.0-headers.tar.gz -tar -xvzf sdk-2.0-headers.tar.gz -cd include-2.0-sdk-ready-for-iphone -cp Ðr * /usr/include -cd .. -wget http://www.syshalt.net/iphone/gcc-iphone/gcc_files.tar.gz -tar -xvzf gcc_files.tar.gz -cd gcc_files -cp Ðr * /usr/lib -apt-get install ldid -chmod -R 755 /usr/include -# Sign your compiled aplication using: -# ldid ÐS - -export IOS_SDK=/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -export LIBSTD_CPP_VERSION=6.0.9 - -ssh root@iphone "mv /usr/include/c++ /usr/include/c++-old" -scp -r $IOS_SDK/usr/include/c++ root@iphone:/usr/include/c++ -scp $IOS_SDK/usr/lib/libstdc++.$LIBSTD_CPP_VERSION.dylib root@iphone:/usr/lib/libstdc++.$LIBSTD_CPP_VERSION.dylib -ssh root@iphone "ln -s /usr/lib/libstdc++.$LIBSTD_CPP_VERSION.dylib /usr/lib/libstdc++.dylib" - -# Install Scala and sbt : -export USER_LOGIN=mobile -export USER_HOME=/var/$USER_LOGIN - -cd -mkdir bin -cd bin -export SCALA_HOME=$USER_HOME/bin/scala -export SCALA_VERSION=2.9.0.1 -wget http://www.scala-lang.org/downloads/distrib/files/scala-$SCALA_VERSION.tgz -mv scala-$SCALA_VERSION.tgz scala-$SCALA_VERSION.tar.gz -gunzip scala-$SCALA_VERSION.tar.gz -tar xvf scala-$SCALA_VERSION.tar -rm -fR $SCALA_HOME -mv scala-$SCALA_VERSION $SCALA_HOME -rm scala-$SCALA_VERSION.tar.gz - - -export SBT_HOME=$USER_HOME/bin -#mkdir $SBT_HOME -wget http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.4.jar -O $SBT_HOME/sbt-launch.jar -echo 'java -server -XX:+UseParallelGC -XX:+DoEscapeAnalysis -XX:+UseCompressedOops -Xmx512M -jar' $SBT_HOME'/sbt-launch.jar "$@"' > $SBT_HOME/sbt -chmod +x $SBT_HOME/sbt - -# -# JamVM -# -# http://draenog.blogspot.com/2011/02/openjdkjamvm-git-repository.html -cd -cd src -git clone git://git.berlios.de/jamvm -cd jamvm -./autogen.sh --with-java-runtime-library=openjdk - - -# -# Set paths -# -echo " -export SCALA_HOME=$USER_HOME/bin/scala -export DYNCALL_HOME=$USER_HOME/src/dyncall - -export PATH=$USER_HOME/bin:\$PATH -export PATH=\$SCALA_HOME/bin:\$PATH - -" > ~/.profile - -# Install Maven -cd -cd bin -export MAVEN_VERSION=2.2.1 -wget ftp://ftp.inria.fr/pub/Apache//maven/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz -tar zxvf apache-maven-$MAVEN_VERSION-bin.tar.gz -echo "export PATH=`pwd`/apache-maven-$MAVEN_VERSION/bin:\$PATH" >> ~/.profile -chmod +x apache-maven-$MAVEN_VERSION/bin/* - - -# Backup -# http://www.iphonedownloadblog.com/2010/11/24/how-to-backup-your-cydia-apps/ -ssh root@iphone "dpkg --get-selections" > admin/iphone.pkgs diff --git a/libraries/BridJ/admin/setup_linux.sh b/libraries/BridJ/admin/setup_linux.sh deleted file mode 100644 index cd36cf932..000000000 --- a/libraries/BridJ/admin/setup_linux.sh +++ /dev/null @@ -1,6 +0,0 @@ - - -# Install RabbitVCS -#sudo add-apt-repository ppa:rabbitvcs/ppa -#sudo apt-get install rabbitvcs-core rabbitvcs-nautilus rabbitvcs-thunar rabbitvcs-gedit rabbitvcs-cli -sudo apt-get install git diff --git a/libraries/BridJ/admin/setup_linux_buildFarm.sh b/libraries/BridJ/admin/setup_linux_buildFarm.sh deleted file mode 100644 index e264965e7..000000000 --- a/libraries/BridJ/admin/setup_linux_buildFarm.sh +++ /dev/null @@ -1,32 +0,0 @@ -sudo apt-get install subversion git maven2 - -mkdir src -mkdir bin - -cd src - -svn co https://dyncall.org/svn/dyncall/trunk dyncall -git clone https://ochafik@github.com/ochafik/nativelibs4java.git - -cd dyncall -echo "export DYNCALL_HOME=\"`pwd`\"" >> ~/.bashrc - -cat ../nativelibs4java/libraries/Runtime/BridJ/src/main/cpp/bridj/dyncall.diff | sed 's/~\/src\/dyncall\///' | patch -p0 - -cd -cd src/nativelibs4java/libraries -mvn install -DskipTests - -#cd -#cd bin -# -#export MAVEN_VERSION=2.2.1 -#wget ftp://ftp.inria.fr/pub/Apache//maven/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz -#tar zxvf apache-maven-$MAVEN_VERSION-bin.tar.gz -#echo "export PATH=`pwd`/apache-maven-$MAVEN_VERSION/bin:\$PATH" >> ~/.bashrc -#chmod +x apache-maven-$MAVEN_VERSION/bin/* - -#cd -#bash - - diff --git a/libraries/BridJ/admin/setup_openbsd.sh b/libraries/BridJ/admin/setup_openbsd.sh deleted file mode 100644 index 1a769329b..000000000 --- a/libraries/BridJ/admin/setup_openbsd.sh +++ /dev/null @@ -1,13 +0,0 @@ -# http://www.openbsd.org/faq/faq15.html -# http://www.cyberciti.biz/faq/openbsd-install-ports-collection/ -# su -# cd /usr -# mv ports ports.old -# wget ftp://ftp.openbsd.org/pub/OpenBSD/$(uname -r)/ports.tar.gz -# tar -zxvf ports.tar.gz - -sudo pkg_add install jdk-1.7 - -sudo pkg_add install jdk-1.6 - - diff --git a/libraries/BridJ/admin/setup_solaris10.sh b/libraries/BridJ/admin/setup_solaris10.sh deleted file mode 100644 index 40613e73a..000000000 --- a/libraries/BridJ/admin/setup_solaris10.sh +++ /dev/null @@ -1,114 +0,0 @@ -# -# Solaris 10 VirtualBox image : -# https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_SMI-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=virtualbox-s10U8-x86-G-F@CDS-CDS_SMI -# -# Solaris DVD downloads : -# http://www.oracle.com/technetwork/server-storage/solaris/downloads/index.html -# -# Install Blastwave's packaging system for GCC and al. (see commands below) : -# http://www.blastwave.org/jir/blastwave.fam -# -# Eclipse Solaris downloads : -# http://ftp.rnl.ist.utl.pt/pub/eclipse/downloads/drops/R-3.5-200906111540/solPlatform.php -# -# Install JDK 6 : -# http://www.oracle.com/technetwork/java/javase/downloads/index.html -# -pkgadd -G -d http://download.blastwave.org/csw/pkgutil_`/sbin/uname -p`.pkg -/opt/csw/bin/pkgutil --catalog -/opt/csw/bin/pkgutil -y --install gnupg textutils -/opt/csw/bin/gpg --keyserver pgp.mit.edu --recv-keys A1999E90 -gpg --list-keys - -echo "Trust -5 -quit -" | /opt/csw/bin/gpg --edit-key A1999E90 - -# Uncomment the line '# use_gpg = 1' : -cat /etc/opt/csw/pkgutil.conf | sed 's/# use_gpg/use_gpg/' > .tmp -rm /etc/opt/csw/pkgutil.conf.old -rm /etc/opt/csw/pkgutil.conf /etc/opt/csw/pkgutil.conf.old -mv .tmp /etc/opt/csw/pkgutil.conf - -/opt/csw/bin/pkgutil -y --install maven2 gcc4 curl openssh p7zip bzip2 subversion vim binutils wget git - -# -# NOW RUN THIS AS A NORMAL USER : -# - -export USER_LOGIN=ochafik -export USER_HOME=/export/home/$USER_LOGIN -export USER_NAME="Olivier Chafik" -export BIN_DIR="/export/home/$USER_LOGIN/bin" - -useradd -d /export/home/$USER_LOGIN -m -s /bin/bash -c "$USER_NAME" $USER_LOGIN - -su $USER_LOGIN - -mkdir src -mkdir bin - -ls -s /opt/csw/bin/gar $BIN_DIR -ls -s /opt/csw/bin/gmake $BIN_DIR -ls -s /opt/csw/gcc4/bin/gcc $BIN_DIR - -cd src - -svn co https://dyncall.org/svn/dyncall/trunk dyncall -svn co https://nativelibs4java.googlecode.com/svn/trunk/libraries nativelibs4java - -cd .. -cd bin - -ln -s /opt/csw/bin/gar ar - -cd .. - -# -# Scala & sbt -# -export SCALA_HOME=/export/home/$USER_LOGIN/bin/scala -export SCALA_VERSION=2.9.0.1.final -wget http://www.scala-lang.org/downloads/distrib/files/scala-$SCALA_VERSION.tgz -mv scala-$SCALA_VERSION.tgz scala-$SCALA_VERSION.tar.gz -gunzip scala-$SCALA_VERSION.tar.gz -tar xvf scala-$SCALA_VERSION.tar -rm -fR $SCALA_HOME -mv scala-$SCALA_VERSION $SCALA_HOME -rm scala-$SCALA_VERSION.tar.gz - -export SBT_HOME=/export/home/$USER_LOGIN/bin -#mkdir $SBT_HOME -wget http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.4.jar -O $SBT_HOME/sbt-launch.jar -echo 'java -server -XX:+UseParallelGC -XX:+DoEscapeAnalysis -XX:+UseCompressedOops -Xmx512M -jar' $SBT_HOME'/sbt-launch.jar "$@"' > $SBT_HOME/sbt -chmod +x $SBT_HOME/sbt - -# jEdit : -JEDIT_VERSION=4.3.2 -wget http://downloads.sourceforge.net/project/jedit/jedit/$JEDIT_VERSION/jedit${JEDIT_VERSION}install.jar -java -jar jedit${JEDIT_VERSION}install.jar - -# -# Set paths -# -echo " -export SCALA_HOME=$USER_HOME/bin/scala -export DYNCALL_HOME=$USER_HOME/src/dyncall -export JAVA_HOME=$USER_HOME/bin/jdk1.6.0_24 - -export PATH=$USER_HOME/bin:\$PATH -export PATH=\$JAVA_HOME/bin:\$PATH -export PATH=\$SCALA_HOME/bin:\$PATH -export PATH=/opt/csw/bin:\$PATH -export PATH=/opt/csw/gcc4/bin:\$PATH - -export LD_LIBRARY_PATH=/opt/csw/lib:/opt/csw/gcc4/lib:\$LD_LIBRARY_PATH - -alias cc=gcc -alias ar=gar -alias make=gmake -alias sed=gsed -" > ~/.bashrc - - diff --git a/libraries/BridJ/admin/uncompressLibraries b/libraries/BridJ/admin/uncompressLibraries deleted file mode 100755 index fd62d003d..000000000 --- a/libraries/BridJ/admin/uncompressLibraries +++ /dev/null @@ -1,8 +0,0 @@ -DIR=src/main/resources/org/bridj/lib - -for F in `find $DIR -name '*.7z'` ; do - echo 7z e $(F/.\//) `dirname $F` ; -done - -#ls -l */*.so* */*.dylib* -#rm */*.7z diff --git a/libraries/BridJ/admin/updateAndRebuild b/libraries/BridJ/admin/updateAndRebuild deleted file mode 100644 index 56fdeadf6..000000000 --- a/libraries/BridJ/admin/updateAndRebuild +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash - -BRIDJ_DIR=`pwd` -export DYNCALL_HOME=$BRIDJ_DIR/dyncall -DYNCALL_PATCH=$BRIDJ_DIR/src/main/cpp/bridj/dyncall.diff - -rm $BRIDJ_DIR/*.log > /dev/null - -echo "Updating BridJ" -cd $BRIDJ_DIR -#git stash -git pull origin master > $BRIDJ_DIR/git-pull.log 2>&1 || ( cat $BRIDJ_DIR/git-pull.log && exit 1 ) - -echo "Checking out dyncall" -rm -fR $DYNCALL_BASE -mkdir $DYNCALL_BASE -svn co https://dyncall.org/svn/dyncall/trunk/dyncall $DYNCALL_HOME > $BRIDJ_DIR/dyncall-checkout.log 2>&1 || ( cat $BRIDJ_DIR/dyncall-checkout.log && exit 1 ) - -echo "Patching dyncall" -cd $DYNCALL_BASE -( gpatch -i $DYNCALL_PATCH -N -p0 || patch -i $DYNCALL_PATCH -N -p0 ) > $BRIDJ_DIR/dyncall-patch.log 2>&1 || ( cat $BRIDJ_DIR/dyncall-patch.log && exit 1 ) - -cd $BRIDJ_DIR - -echo "Cleaning Maven build" -mvn clean > $BRIDJ_DIR/maven-clean.log 2>&1 || ( cat $BRIDJ_DIR/maven-clean.log && exit 1 ) - -echo "Compiling sources" -mvn test-compile > $BRIDJ_DIR/maven-compile.log 2>&1 || ( cat $BRIDJ_DIR/maven-compile.log && exit 1 ) - - -if [[ -d /Applications ]] ; then - BUILD_TARGETS="default ios android" ; -else - BUILD_TARGETS="default" ; -fi - -for T in $BUILD_TARGETS ; do - echo "Cleaning native $T build" - TARGET=$T ./CleanNative > $BRIDJ_DIR/clean-native-$T.log 2>&1 || ( cat $BRIDJ_DIR/clean-native-$T.log && exit 1 ) - echo "Building native $T libraries" - TARGET=$T ./BuildNative > $BRIDJ_DIR/build-native-$T.log 2>&1 || ( cat $BRIDJ_DIR/build-native-$T.log && exit 1 ) ; -done - -export BRIDJ_NO_OBJC=1 - -echo "Installing Maven artifacts" -mvn install > $BRIDJ_DIR/mvn-install.log 2>&1 || ( cat $BRIDJ_DIR/mvn-install.log && exit 1 ) - -$BRIDJ_DIR/CommitBinaries > $BRIDJ_DIR/git-commit-binaries.log 2>&1 || ( cat $BRIDJ_DIR/git-commit-binaries.log && exit 1 ) - -git push origin master > $BRIDJ_DIR/git-push.log 2>&1 || ( cat $BRIDJ_DIR/git-push.log && exit 1 ) diff --git a/libraries/BridJ/android-sdk-dx.pom b/libraries/BridJ/android-sdk-dx.pom deleted file mode 100644 index d3811e829..000000000 --- a/libraries/BridJ/android-sdk-dx.pom +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - com.nativelibs4java - com.google.android.dx - Android SDK's dx Tool - http://developer.android.com/guide/developing/tools/index.html - 11 - jar - - dx is an Android SDK platform tool that transforms Java bytecode (and JARs) into Dalvik VM 'DEX' code. - - - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - - - - diff --git a/libraries/BridJ/buildMac b/libraries/BridJ/buildMac deleted file mode 100755 index c2f25013e..000000000 --- a/libraries/BridJ/buildMac +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -for T in default ios android ; do - TARGET=$T ./CleanNative - TARGET=$T ./BuildNative fast || ( echo "Failed to build native target $T !" && exit 1 ) ; -done diff --git a/libraries/BridJ/cleanAll b/libraries/BridJ/cleanAll deleted file mode 100644 index e5e672f09..000000000 --- a/libraries/BridJ/cleanAll +++ /dev/null @@ -1,13 +0,0 @@ -mvn clean - -rm -fR src/main/cpp/bridj/build_out/ - -ANDROID_TEST_LIB_DIR=src/main/cpp/android-test -rm -fR $ANDROID_TEST_LIB_DIR/lib/* -rm -fR $ANDROID_TEST_LIB_DIR/bin -rm -fR $ANDROID_TEST_LIB_DIR/libs -rm -fR $ANDROID_TEST_LIB_DIR/obj -rm -fR $ANDROID_TEST_LIB_DIR/gen - -rm -fR src/test/cpp/bridj/build_out/ - diff --git a/libraries/BridJ/compile b/libraries/BridJ/compile deleted file mode 100644 index b8f601df3..000000000 --- a/libraries/BridJ/compile +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -# -alias javac="java -jar ~/bin/ecj-3.7M7.jar" -DYNCALL_HOME=./dyncall - -JUNIT_VERSION=4.8.2 -JUNIT_JAR_NAME=junit-$JUNIT_VERSION.jar -JUNIT_JAR=~/bin/$JUNIT_JAR_NAME -JUNIT_URL=https://github.com/downloads/KentBeck/junit/$JUNIT_JAR_NAME - -BRIDJ_VERSION=0.5-SNAPSHOT -BRIDJ_JAR_NAME=bridj-$BRIDJ_VERSION.jar -BRIDJ_JAR=target/$BRIDJ_JAR_NAME -BRIDJ_URL=http://nativelibs4java.sourceforge.net/maven/com/nativelibs4java/bridj/$BRIDJ_VERSION/$BRIDJ_JAR_NAME - -JAVA_SOURCE=1.6 -JAVA_TARGET=1.6 - -JAVA_ARGS="-source $JAVA_SOURCE -target $JAVA_TARGET " - -if [[ -z "$NO_MVN" ]] ; then - mvn velocity:generate ; -fi -sh BuildNative - -if [[ "$DOWNLOAD_JAR" != "1" ]] ; then - javac -d target/classes/ `find src/main/java -name '*.java'` `find target/generated-sources/main -name '*.java'` -sourcepath src/main/java $JAVA_ARGS || (echo "Compilation of main failed" && exit 1) ; -else - if [[ ! -e "$BRIDJ_JAR" ]] ; then - wget -P target $BRIDJ_URL ; - fi ; -fi - -javac -d target/test-classes/ -classpath target/bridj-*-SNAPSHOT.jar:target/classes `find src/test/java -name '*.java'` `find target/generated-sources/test -name '*.java'` -sourcepath src/test/java $JAVA_ARGS || (echo "Compilation of tests failed" && exit 1) - -if [[ ! -e "$JUNIT_JAR" ]] ; then - wget --no-check-certificate -P ~/bin $JUNIT_URL ; -fi - -ALL_TEST_CLASSES=`ls src/test/java/org/bridj/*.java target/generated-sources/test/org/bridj/*.java | sed 's/src\/test\/java\///g' | sed 's/\.java//g'` | tr '/' '.' - -echo "Available test classes :\n$ALL_TEST_CLASSES" -TEST_CLASSES=${TEST_CLASSES:-$ALL_TEST_CLASSES} - -java -cp $JUNIT_JAR:target/bridj-*-SNAPSHOT.jar:target/classes:target/test-classes org.junit.runner.JUnitCore $TEST_CLASSES - - diff --git a/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.patch b/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.patch deleted file mode 100644 index 830b89ba4..000000000 --- a/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.patch +++ /dev/null @@ -1,144 +0,0 @@ -diff --git a/GSPFramework/src/main/java/com/bridj/Demangler.java b/GSPFramework/src/main/java/com/bridj/Demangler.java -index fa2510d..9f92ce8 100644 ---- a/GSPFramework/src/main/java/com/bridj/Demangler.java -+++ b/GSPFramework/src/main/java/com/bridj/Demangler.java -@@ -232,12 +232,22 @@ public abstract class Demangler { - - } - -- public static class PointerType { -+ public static class PointerTypeRef extends TypeRef { -+ -+ public TypeRef pointedType; -+ -+ public PointerTypeRef(TypeRef pointedType) { -+ this.pointedType = pointedType; -+ } - -+ @Override -+ public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { -+ return b.append("com.bridj.Pointer"); -+ } - } - - protected static TypeRef pointerType(TypeRef tr) { -- return classType(Pointer.class); // TODO -+ return new PointerTypeRef(tr); - } - protected static TypeRef classType(final Class c, Class... annotations) { - return classType(c, null, annotations); -diff --git a/GSPFramework/src/main/java/com/bridj/cpp/GCC4Demangler.java b/GSPFramework/src/main/java/com/bridj/cpp/GCC4Demangler.java -index 8e779d5..7df1f65 100644 ---- a/GSPFramework/src/main/java/com/bridj/cpp/GCC4Demangler.java -+++ b/GSPFramework/src/main/java/com/bridj/cpp/GCC4Demangler.java -@@ -1,35 +1,67 @@ - package com.bridj.cpp; - - import java.util.ArrayList; --import java.util.HashMap; - import java.util.List; --import java.util.Map; - - import com.bridj.Demangler; - import com.bridj.JNI; - import com.bridj.NativeLibrary; --import com.bridj.Pointer; - import com.bridj.Demangler.ClassRef; - import com.bridj.Demangler.DemanglingException; - import com.bridj.Demangler.MemberRef; - import com.bridj.Demangler.NamespaceRef; - import com.bridj.Demangler.TypeRef; - import com.bridj.Demangler.SpecialName; -+import java.util.HashMap; -+import java.util.Map; - - public class GCC4Demangler extends Demangler { - - public GCC4Demangler(NativeLibrary library, String symbol) { - super(library, symbol); - } -- -+ -+ private Map shortcuts = new HashMap(); -+ int nextShortcutId = -1; -+ private String nextShortcutId() { -+ int n = nextShortcutId++; -+ return n == -1 ? "_" : Integer.toString(n, 36).toUpperCase() + "_"; -+ } -+ -+ private TypeRef parseShortcutType() { -+ if (peekChar() == '_') { -+ return shortcuts.get(Character.toString(consumeChar())); -+ } -+ String id = ""; -+ while (peekChar() != '_') { -+ id += consumeChar(); -+ } -+ id += consumeChar(); -+ TypeRef res = shortcuts.get(id); -+ return res; -+ } -+ private TypeRef parsePointerType() throws DemanglingException { -+ TypeRef pointed = parseType(); -+ TypeRef res = pointerType(pointed); -+ String id = nextShortcutId(); -+ shortcuts.put(id, res); -+ return res; -+ } -+ - public TypeRef parseType() throws DemanglingException { -- if (Character.isDigit(peekChar())) -- return simpleType(parseName()); -+ if (Character.isDigit(peekChar())) { -+ String name = parseName(); -+ String id = nextShortcutId(); -+ TypeRef res = simpleType(name); -+ shortcuts.put(id, res); -+ return res; -+ } - - switch (consumeChar()) { -+ case 'S': -+ return parseShortcutType(); - case 'P': -- parseType(); // TODO we don't care what this points to right now -- return classType(Pointer.class); -+ return parsePointerType(); - case 'F': - // TODO parse function type correctly !!! - while (consumeChar() != 'E') {} -@@ -42,8 +74,9 @@ public class GCC4Demangler extends Demangler { - case 'c': - case 'a': - case 'h': // unsigned -- case 'b': // bool - return classType(Byte.TYPE); -+ case 'b': // bool -+ return classType(Boolean.TYPE); - case 'l': - case 'm': // unsigned - return classType(JNI.is64Bits() ? Long.TYPE : Integer.TYPE); -@@ -90,7 +123,9 @@ public class GCC4Demangler extends Demangler { - mr.setMemberName(str); - return mr; - } -- consumeCharIf('_'); -+ // REVIEW-IT: ignore _ _ instead of counting it as _ -+ if (peekChar() == '_') -+ return null; // can be a type info, a virtual table or strange things like that - expectChars('Z'); - - if (peekChar() == 'T') -@@ -99,8 +134,11 @@ public class GCC4Demangler extends Demangler { - List ns = new ArrayList(); - if (consumeCharIf('N')) { - do { -+ // TODO better than simple increment -+ nextShortcutId++; - ns.add(parseName()); - } while (Character.isDigit(peekChar())); -+ nextShortcutId--; // correct the fact that we parsed one too much - mr.setMemberName(ns.remove(ns.size() - 1)); - if (!ns.isEmpty()) { - ClassRef parent = new ClassRef(); - diff --git a/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.txt b/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.txt deleted file mode 100644 index fd207238a..000000000 --- a/libraries/BridJ/contribs/Remi Emonet/bridj-patch-over-r992.txt +++ /dev/null @@ -1,39 +0,0 @@ - -=== version de base === - -Si mes commentaires de commit dans mon historique sont corrects, la version du svn que j'ai modifiée est la révision 992. - - -=== taille du prefix pour le patch === - -Depuis le dossier parent de "com/" ("src/main/java" dans le cas de maven), la taille du prefix est 5 (-p5). - cd src/main/java - patch -p5 < bridj-patch-over-r992.patch - - -=== Copyright Transfert Declaration === - -I, Rémi Emonet, declare being the only author of the attached patch file "bridj-patch-over-r992.patch" -(with sha1sum: 1c2ddd23c08cc76b19c8805b1277ab3059c884a2). - -I fully transfer the copyright for this patch to Olivier Chafik for a -possible integration into the "BridJ" project provided it uses -opensource licenses such as BSD license, Apache license, MIT license -or any equivalent licensing scheme. - - - - -=== NOTES INTERNES === - -git diff -p 393941 HEAD com/ > ../../../bridj-patch-over-r992.txt - -== HEAD -commit 45199b5a18cfee500939dd6fe7ea35ca71489600 -Author: Rémi Emonet -Date: Tue Jul 27 20:51:54 2010 +0200 -== 393941 -commit 39394111ba4f11cf1428cca41d7205f6b51d6dc9 -Author: Rémi Emonet -Date: Fri May 21 23:58:47 2010 +0200 - diff --git a/libraries/BridJ/echo-dx-pom b/libraries/BridJ/echo-dx-pom deleted file mode 100644 index f211a4e2c..000000000 --- a/libraries/BridJ/echo-dx-pom +++ /dev/null @@ -1,23 +0,0 @@ -echo " - 4.0.0 - com.nativelibs4java - com.google.android.dx - Android SDK's dx Tool - http://developer.android.com/guide/developing/tools/index.html - $ANDROID_SDK_VERSION - jar - - dx is an Android SDK platform tool that transforms Java bytecode (and JARs) into Dalvik VM 'DEX' code. - - - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - - - -" > android-sdk-dx.pom diff --git a/libraries/BridJ/pom.xml b/libraries/BridJ/pom.xml deleted file mode 100644 index 2738c8817..000000000 --- a/libraries/BridJ/pom.xml +++ /dev/null @@ -1,555 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - bridj - BridJ (NativeLibs4Java C/C++ Interop Layer) - http://code.google.com/p/bridj/ - 0.6.2-SNAPSHOT - jar - - - v0_6_2 - - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - - org.ow2.asm - asm - 4.0 - - - net.java.dev.jna - jna - 3.4.0 - test - - - - javolution - javolution - 5.5.1 - test - - - - com.google.android - android - 2.3.3 - provided - - - - com.google.android.tools - dx - 1.7 - - - - - - - - - - com.nativelibs4java - maven-velocity-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - org.objectweb.asm - org.bridj.relocated.org.objectweb.asm - - org.objectweb.asm.* - org.objectweb.asm.signature.* - - - - - - - - c-package - package - - shade - - - true - c-only - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/cpp/** - org/bridj/objc/** - org/bridj/cs/** - org/bridj/lib/android_*/** - lib/armeabi/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - mac-package - package - - shade - - - true - macosx-only - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/cpp/com/** - org/bridj/cpp/mfc/** - org/bridj/cs/** - org/bridj/lib/linux_*/** - org/bridj/lib/android_*/** - lib/armeabi/** - org/bridj/lib/sunos_*/** - org/bridj/lib/win*/** - org/bridj/lib/iphoneos_*/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - win-package - package - - shade - - - true - windows-only - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/objc/** - org/bridj/lib/linux_*/** - org/bridj/lib/android_*/** - lib/armeabi/** - org/bridj/lib/sunos_*/** - org/bridj/lib/iphoneos_*/** - org/bridj/lib/darwin_*/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - unix-package - package - - shade - - - true - unix-only - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/cpp/com/** - org/bridj/cpp/mfc/** - org/bridj/cs/** - org/bridj/objc/** - org/bridj/lib/win*/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - linux-package - package - - shade - - - true - linux-only - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/cpp/com/** - org/bridj/cpp/mfc/** - org/bridj/objc/** - org/bridj/cs/** - org/bridj/lib/win*/** - org/bridj/lib/sunos_*/** - org/bridj/lib/iphoneos_*/** - org/bridj/lib/darwin_*/** - org/bridj/lib/android_*/** - lib/armeabi/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - android-package - package - - shade - - - true - android - - - com.google.android.tools:dx - - - junit:junit - - - - - com.nativelibs4java:bridj - - org/bridj/cpp/com/** - org/bridj/cpp/mfc/** - org/bridj/cs/** - org/bridj/lib/linux_*/** - org/bridj/lib/sunos_*/** - org/bridj/lib/iphoneos_*/** - org/bridj/lib/darwin_*/** - org/bridj/lib/win*/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - full-package - package - - shade - - - false - - - - com.google.android.tools:dx - - - - - com.nativelibs4java:bridj - - org/bridj/Android** - org/bridj/lib/android_*/** - org/bridj/lib/iphoneos_*/** - lib/armeabi/** - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - Core Packages - org.bridj:org.bridj.cpp:org.bridj.jawt:org.bridj.ann - - - Extension Packages - org.bridj.cs*:org.bridj.objc*:org.bridj.cpp.* - - - Demos Packages - org.bridj.demos - - - Shouldn't-be-there-really Packages - org.bridj.examples:org.bridj.func:org.bridj.util - - - - - - - - - - - - native - - false - - native - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - generate-resources - - exec - - - - ${basedir}/BuildNative - ${basedir} - - - - - - - - - - - - - - diff --git a/libraries/BridJ/runProtectionTest b/libraries/BridJ/runProtectionTest deleted file mode 100644 index 36289be8d..000000000 --- a/libraries/BridJ/runProtectionTest +++ /dev/null @@ -1 +0,0 @@ -BRIDJ_PROTECTED=1 mvn test -o -Dtest=ExceptionsTest diff --git a/libraries/BridJ/runTestsCLI b/libraries/BridJ/runTestsCLI deleted file mode 100644 index ba0d60b97..000000000 --- a/libraries/BridJ/runTestsCLI +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -if [[ ! -f junit.jar ]] ; then cp ~/.m2/repository/junit/junit/4.8.2/junit-4.8.2.jar junit.jar ; fi -if [[ ! -f jna.jar ]] ; then cp ~/.m2/repository/net/java/dev/jna/jna/3.2.7/jna-3.2.7.jar jna.jar ; fi -if [[ ! -f javolution.jar ]] ; then cp ~/.m2/repository/javolution/javolution/5.5.1/javolution-5.5.1.jar javolution.jar ; fi - -MVN_VERSION="`cat pom.xml | grep '\(.*\)<\/version>.*/\1/g'`" - -mvn clean package -DskipTests - -echo "#\n# ARM binaries :" -unzip -l target/bridj-$MVN_VERSION.jar | grep arm - -if [[ "$1" == "copy" ]] ; then - for F in junit.jar jna.jar javolution.jar target/bridj-$MVN_VERSION.jar target/bridj-$MVN_VERSION-tests.jar ; do - scp $F mobile@iphone:src/nativelibs4java/Runtime/BridJ/$F ; - done ; -else - #export JUNIT_TEST_CLASSES="`find target/test-classes/org/bridj/*Test.class | sed 's/\.class//' | sed 's/target\/test-classes\/org\/bridj\///' | tr / .`" - #export JUNIT_TEST_CLASSES="`find target/test-classes/org/bridj/*Test.class | sed 's/\.class//' | sed 's/target\/test-classes\///' | tr / .`" - - JUNIT_TESTS="`unzip -l target/bridj-$MVN_VERSION-tests.jar | grep '.*Test.class' | grep -v '\\$' | sed 's/.*org/org/' | sed 's/\.class//' | tr / . `" - - java -cp target/bridj-$MVN_VERSION.jar:target/bridj-$MVN_VERSION-tests.jar:junit.jar:jna.jar:javolution.jar org.junit.runner.JUnitCore $JUNIT_TESTS ; - -fi diff --git a/libraries/BridJ/src/main/Run.java b/libraries/BridJ/src/main/Run.java deleted file mode 100644 index 28adba5c2..000000000 --- a/libraries/BridJ/src/main/Run.java +++ /dev/null @@ -1,52 +0,0 @@ - -import org.bridj.BridJ; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import org.bridj.objc.NSObject; -import org.bridj.objc.ObjCBlock; - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -/** - * - * @author ochafik - */ -public class Run { - public static class Foundation { - public static class NSEvent extends NSObject { - //@Selector("addLocalMonitorForEventsMatchingMask:handler:") - public static native Pointer addGlobalMonitorForEventsMatchingMask_handler(long mask, Pointer handler); - } - - public abstract static class NSEventGlobalCallback extends ObjCBlock { - public abstract void callback(Pointer event); - } - } - - public static void main(String[] args) throws Exception { - BridJ.register(Foundation.NSEvent.class); - - final boolean called[] = new boolean[1]; - Foundation.NSEventGlobalCallback handler = new Foundation.NSEventGlobalCallback() { - @Override - public void callback(Pointer event) { - System.out.println("Event: " + event); - called[0] = true; - } - }; - - //System.out.println("handler: " + handler); - - Pointer hook = Foundation.NSEvent.addGlobalMonitorForEventsMatchingMask_handler(-1L/*1 << 1*/, pointerTo(handler)); - - //System.out.println("hook: " + hook); - - Thread.sleep(10000); - - System.out.println("Called : " + called[0]); - System.in.read(); - } -} diff --git a/libraries/BridJ/src/main/cpp/Build Windows.cmd b/libraries/BridJ/src/main/cpp/Build Windows.cmd deleted file mode 100644 index 1ac2a320d..000000000 --- a/libraries/BridJ/src/main/cpp/Build Windows.cmd +++ /dev/null @@ -1,16 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -call SetEnv.cmd - -for %%F in (java java\build java\build\classes) do mkdir %%F >NUL 2>NUL - -"%JAVA_HOME%\bin\javac.exe" -d java\build\classes -classpath java\src java\src\bridj\*.java java\src\com\ochafik\jni\*.java java\src\com\ochafik\jni\ann\*.java - -"%JAVA_HOME%\bin\javah.exe" -d jni -classpath java\build\classes com.nativelibs4java.runtime.JNI com.nativelibs4java.runtime.DynCall com.nativelibs4java.runtime.DynCall com.nativelibs4java.runtime.Platform - -pushd ..\buildsys\vs2008 -call BuildAll.cmd nopause -popd - -pause diff --git a/libraries/BridJ/src/main/cpp/Debugger.txt b/libraries/BridJ/src/main/cpp/Debugger.txt deleted file mode 100644 index 5751ef744..000000000 --- a/libraries/BridJ/src/main/cpp/Debugger.txt +++ /dev/null @@ -1,3 +0,0 @@ -"$(JAVA_HOME)\bin\java.exe" --cp c:\Users\Olivier\Prog\dyncall\dyncall\bridj\java\build\classes bridj.Main -c:\Users\Olivier\Prog\dyncall\dyncall\buildsys\vs2008\x64\Debug diff --git a/libraries/BridJ/src/main/cpp/RunMainDebug32.cmd b/libraries/BridJ/src/main/cpp/RunMainDebug32.cmd deleted file mode 100644 index 33d72738f..000000000 --- a/libraries/BridJ/src/main/cpp/RunMainDebug32.cmd +++ /dev/null @@ -1,11 +0,0 @@ - -@echo off -setlocal enabledelayedexpansion - -pushd ..\buildsys\vs2008\Debug - -"%JAVA_HOME%\bin\java.exe" -classpath ..\..\..\bridj\classes bridj.Main - -popd - -pause diff --git a/libraries/BridJ/src/main/cpp/android-test/AndroidManifest.xml b/libraries/BridJ/src/main/cpp/android-test/AndroidManifest.xml deleted file mode 100644 index 583193466..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/AndroidManifest.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/android-test/build.properties.template b/libraries/BridJ/src/main/cpp/android-test/build.properties.template deleted file mode 100644 index 68321a6bc..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/build.properties.template +++ /dev/null @@ -1,17 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "build.properties", and override values to adapt the script to your -# project structure. - -# Project target. -#target=android-11 - -jar.libs.dir=lib -key.store=/Users/ochafik/security/ochafik.keystore -key.alias=ochafik2009 -key.alias.password= - diff --git a/libraries/BridJ/src/main/cpp/android-test/build.sh b/libraries/BridJ/src/main/cpp/android-test/build.sh deleted file mode 100644 index c211ef3bc..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/build.sh +++ /dev/null @@ -1,117 +0,0 @@ -# -# See http://developer.android.com/guide/developing/building/building-cmdline.html -# -echo "You should ensure an emulator is running : android&" - -PROJECT_HOME=../../../.. -MVN_VERSION="`cat $PROJECT_HOME/pom.xml | grep '\(.*\)<\/version>.*/\1/g'`" -BRIDJ_ANDROID_JAR_NAME=bridj-$MVN_VERSION-android.jar -BRIDJ_ANDROID_JAR=$PROJECT_HOME/target/$BRIDJ_ANDROID_JAR_NAME -ANDROID_PROJECT_HOME=`pwd` - -echo "BridJ version = $MVN_VERSION" - -function buildBridJ { - cd $PROJECT_HOME - #rm target/*.jar - mvn clean - mvn package -DskipTests - cd $ANDROID_PROJECT_HOME -} - -if [[ ! -f "$BRIDJ_ANDROID_JAR" ]] ; then - echo "$BRIDJ_ANDROID_JAR is missing. Building BridJ first..." - buildBridJ - if [[ ! -f "$BRIDJ_ANDROID_JAR" ]] ; then - echo "Failed to build the Android JAR !" - exit 1 ; - fi ; -fi - -if [[ ! -f build.properties.template ]] ; then - echo "build.properties.template does not exist !" - exit 1 ; -fi - -function helpQuit { - echo "# -# List of valid build commands (can be combined) : -# -# package Build BridJ JAR (will be done implicitly if the JAR doesn't exist) -# emulator Install into running emulator -# device Install into USB-plugged device -# release Build Release Android package -# debug Build Debug Android package -# start Start on emulator -# clean Clean all (BridJ, native builds...) -# -# Default build commands = $DEFAULT_BUILD_CMDS -# Typical debug commands = package emulator start -# - " - exit 1 -} - -DEFAULT_BUILD_CMDS="package release" -if [[ "$*" == "" ]] ; then - BUILD_CMDS=$DEFAULT_BUILD_CMDS ; -else - BUILD_CMDS=$* ; -fi - -cat build.properties.template > build.properties - -if [[ -z "$ANDROID_SDK_HOME" ]] ; then - echo "ANDROID_SDK_HOME is not defined !" - exit 1 ; -fi -echo "sdk.dir=$ANDROID_SDK_HOME" >> build.properties ; - -if [[ ! -z "$KEYSTORE_PASS" ]] ; then - echo "key.store.password=$KEYSTORE_PASS" >> build.properties ; -fi - -APK_FILE=bin/TouchExampleActivity-release.apk - -function compile { - ndk-build -C . - ant $* - rm build.properties -} - -echo "# Provided build commands = $BUILD_CMDS" - -for C in $BUILD_CMDS ; do - case $C in - clean) - cd $PROJECT_HOME - sh cleanAll - cd $ANDROID_PROJECT_HOME - ;; - package) - buildBridJ - rm lib/$BRIDJ_ANDROID_JAR_NAME - cp -f $BRIDJ_ANDROID_JAR lib - ;; - emulator) - compile install - ;; - device) - compile debug - adb -d install $APK_FILE - ;; - debug) - compile debug - ;; - release) - compile release - ;; - start) - adb shell am start -a android.intent.action.MAIN -n com.example.hellojni/com.example.hellojni.HelloJni - ;; - *) - helpQuit - ;; - esac ; -done - diff --git a/libraries/BridJ/src/main/cpp/android-test/build.xml b/libraries/BridJ/src/main/cpp/android-test/build.xml deleted file mode 100644 index 805e30cbe..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/build.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/android-test/default.properties b/libraries/BridJ/src/main/cpp/android-test/default.properties deleted file mode 100644 index 510b0908b..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/default.properties +++ /dev/null @@ -1,11 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "build.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-11 diff --git a/libraries/BridJ/src/main/cpp/android-test/jni/Android.mk b/libraries/BridJ/src/main/cpp/android-test/jni/Android.mk deleted file mode 100644 index 6ccf381ca..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/jni/Android.mk +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (C) 2009 The Android Open Source Project -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := hello-jni -LOCAL_SRC_FILES := hello-jni.c - -include $(BUILD_SHARED_LIBRARY) diff --git a/libraries/BridJ/src/main/cpp/android-test/jni/hello-jni.c b/libraries/BridJ/src/main/cpp/android-test/jni/hello-jni.c deleted file mode 100644 index 90debbfb7..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/jni/hello-jni.c +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#include -#include - -/* This is a trivial JNI example where we use a native method - * to return a new VM String. See the corresponding Java source - * file located at: - * - * apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java - */ -jstring -Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, - jobject thiz ) -{ - return (*env)->NewStringUTF(env, "Hello from JNI !"); -} - -int addTwoInts(int a, int b) { - return a + b; -} -int passTwoIntsToCallback(int a, int b, int (*cb)(int, int)) { - return cb(a, b); -} diff --git a/libraries/BridJ/src/main/cpp/android-test/res/values/strings.xml b/libraries/BridJ/src/main/cpp/android-test/res/values/strings.xml deleted file mode 100644 index c5260737b..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - HelloJni - diff --git a/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/BridJLib.java b/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/BridJLib.java deleted file mode 100644 index bde4db940..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/BridJLib.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.example.hellojni; - -import org.bridj.*; -import org.bridj.ann.*; - -@Library("hello-jni") -public class BridJLib { - static { - BridJ.register(); - } - public static native int addTwoInts(int a, int b); - /* - public static abstract class passTwoIntsToCallback_cb extends Callback { - public abstract int apply(int a, int b); - } - //public static native int passTwoIntsToCallback(int a, int b, Pointer cb); - //*/ - public static native int passTwoIntsToCallback(int a, int b, Pointer cb); - - @Library("c") - public static native int access(Pointer path, int amode); -} diff --git a/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/HelloJni.java b/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/HelloJni.java deleted file mode 100644 index 1e2ef3448..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/src/com/example/hellojni/HelloJni.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.example.hellojni; - -import android.app.Activity; - -import android.widget.TextView; -import android.os.Bundle; -import java.io.StringWriter; -import java.io.PrintWriter; -import org.bridj.*; -import static org.bridj.Pointer.*; - -public class HelloJni extends Activity -{ - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - - /* Create a TextView and set its content. - * the text is retrieved by calling a native - * function. - */ - TextView tv = new TextView(this); - StringWriter text = new StringWriter(); - PrintWriter pout = new PrintWriter(text); - pout.println(stringFromJNI()); - - AndroidSupport.setApplication(getApplication()); - - //pout.println(HelloJni.class.getClassLoader().getResource("lib/armeabi/libbridj.so")); - try { - - //BridJ.register(BridJLib.class); - - int a = 10, b = 100; - pout.println(a + " + " + b + " = " + BridJLib.addTwoInts(a, b) + " (computed in BridJ-bound native function !)"); - pout.println("Access(.) = " + BridJLib.access(pointerToCString("."), 0)); - /* - for (Symbol sym : BridJ.getNativeLibrary("unistd").getSymbols()) { - if (sym.getSymbol().contains("access")) - pout.println(sym.getSymbol()); - } - */ - final int fa = 2, fb = 3; - Pointer pcb; - /* - final BridJLib.passTwoIntsToCallback_cb cb = new BridJLib.passTwoIntsToCallback_cb() { - public int apply(int a, int b) { - return a * fa + b * fb; - } - }; - pcb = pointerTo(cb); - //*/ - ///* - pcb = allocateDynamicCallback( - new DynamicCallback() { - public Integer apply(Object... args) { - int a = (Integer)args[0]; - int b = (Integer)args[1]; - return a * fa + b * fb; - //return cb.apply(a, b); - } - }, - null, - int.class, - int.class, - int.class - ); - //*/ - pout.println(a + " * " + fa + " + " + b + " * " + fb + " = " + BridJLib.passTwoIntsToCallback(a, b, pcb) + " (through BridJ callback !)"); - - } catch (Throwable th) { - while (th.getCause() != null) - th = th.getCause(); - th.printStackTrace(pout); - } - tv.setText(text.toString()); - setContentView(tv); - } - - /* A native method that is implemented by the - * 'hello-jni' native library, which is packaged - * with this application. - */ - public native String stringFromJNI(); - - /* This is another native method declaration that is *not* - * implemented by 'hello-jni'. This is simply to show that - * you can declare as many native methods in your Java code - * as you want, their implementation is searched in the - * currently loaded native libraries only the first time - * you call them. - * - * Trying to call this function will result in a - * java.lang.UnsatisfiedLinkError exception ! - */ - public native String unimplementedStringFromJNI(); - - /* this is used to load the 'hello-jni' library on application - * startup. The library has already been unpacked into - * /data/data/com.example.HelloJni/lib/libhello-jni.so at - * installation time by the package manager. - */ - static { - System.loadLibrary("hello-jni"); - } -} diff --git a/libraries/BridJ/src/main/cpp/android-test/tests/AndroidManifest.xml b/libraries/BridJ/src/main/cpp/android-test/tests/AndroidManifest.xml deleted file mode 100644 index d6be01ebf..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/tests/AndroidManifest.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/android-test/tests/default.properties b/libraries/BridJ/src/main/cpp/android-test/tests/default.properties deleted file mode 100644 index 4513a1e4f..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/tests/default.properties +++ /dev/null @@ -1,11 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "build.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-3 diff --git a/libraries/BridJ/src/main/cpp/android-test/tests/src/com/example/HelloJni/HelloJniTest.java b/libraries/BridJ/src/main/cpp/android-test/tests/src/com/example/HelloJni/HelloJniTest.java deleted file mode 100644 index 519d85768..000000000 --- a/libraries/BridJ/src/main/cpp/android-test/tests/src/com/example/HelloJni/HelloJniTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.example.HelloJni; - -import android.test.ActivityInstrumentationTestCase; - -/** - * This is a simple framework for a test of an Application. See - * {@link android.test.ApplicationTestCase ApplicationTestCase} for more information on - * how to write and extend Application tests. - *

- * To run this test, you can type: - * adb shell am instrument -w \ - * -e class com.example.HelloJni.HelloJniTest \ - * com.example.HelloJni.tests/android.test.InstrumentationTestRunner - */ -public class HelloJniTest extends ActivityInstrumentationTestCase { - - public HelloJniTest() { - super("com.example.HelloJni", HelloJni.class); - } - -} diff --git a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.pbxproj b/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.pbxproj deleted file mode 100644 index d2b01f702..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.pbxproj +++ /dev/null @@ -1,291 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXContainerItemProxy section */ - 90E6FC5B15BC0CA900A88421 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 90E6FC4F15BC0CA900A88421 /* testexe.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 90E6FC2815BC0C3400A88421; - remoteInfo = testexe; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 90E6FBEF15BC0BBE00A88421 /* CallbackHandler.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CallbackHandler.c; sourceTree = ""; }; - 90E6FBF015BC0BBE00A88421 /* CppHandler.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CppHandler.c; sourceTree = ""; }; - 90E6FBF115BC0BBE00A88421 /* Exceptions.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Exceptions.c; sourceTree = ""; }; - 90E6FBF215BC0BBE00A88421 /* FunctionHandler.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = FunctionHandler.c; sourceTree = ""; }; - 90E6FBF315BC0BBE00A88421 /* GenericJavaCallbackHandlers.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = GenericJavaCallbackHandlers.c; sourceTree = ""; }; - 90E6FBF415BC0BBE00A88421 /* HandlersCommon.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = HandlersCommon.c; sourceTree = ""; }; - 90E6FBF515BC0BBE00A88421 /* JNI.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = JNI.c; sourceTree = ""; }; - 90E6FBF615BC0BBE00A88421 /* ObjCHandler.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ObjCHandler.c; sourceTree = ""; }; - 90E6FBF715BC0BBE00A88421 /* Platform.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Platform.c; sourceTree = ""; }; - 90E6FBF815BC0BBE00A88421 /* Pointer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Pointer.c; sourceTree = ""; }; - 90E6FBF915BC0BBE00A88421 /* RawNativeForwardCallback.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = RawNativeForwardCallback.c; sourceTree = ""; }; - 90E6FBFA15BC0BBE00A88421 /* ThreadLocal.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ThreadLocal.c; sourceTree = ""; }; - 90E6FBFB15BC0BBE00A88421 /* bridj.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = bridj.hpp; sourceTree = ""; }; - 90E6FBFC15BC0BBE00A88421 /* Exceptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Exceptions.h; sourceTree = ""; }; - 90E6FBFD15BC0BBE00A88421 /* HandlersCommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HandlersCommon.h; sourceTree = ""; }; - 90E6FBFE15BC0BBE00A88421 /* JNI_prim.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JNI_prim.h; sourceTree = ""; }; - 90E6FBFF15BC0BBE00A88421 /* JNI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JNI.h; sourceTree = ""; }; - 90E6FC0015BC0BBE00A88421 /* ObjCProxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ObjCProxy.h; sourceTree = ""; }; - 90E6FC0115BC0BBE00A88421 /* org_bridj_BridJ_CastingType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_BridJ_CastingType.h; sourceTree = ""; }; - 90E6FC0215BC0BBE00A88421 /* org_bridj_BridJ_Switch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_BridJ_Switch.h; sourceTree = ""; }; - 90E6FC0315BC0BBE00A88421 /* org_bridj_BridJ.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_BridJ.h; sourceTree = ""; }; - 90E6FC0415BC0BBE00A88421 /* org_bridj_JNI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_JNI.h; sourceTree = ""; }; - 90E6FC0515BC0BBE00A88421 /* org_bridj_objc_ObjCJNI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_objc_ObjCJNI.h; sourceTree = ""; }; - 90E6FC0615BC0BBE00A88421 /* org_bridj_Platform_DeleteFiles.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Platform_DeleteFiles.h; sourceTree = ""; }; - 90E6FC0715BC0BBE00A88421 /* org_bridj_Platform.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Platform.h; sourceTree = ""; }; - 90E6FC0815BC0BBE00A88421 /* org_bridj_Pointer_DisorderedPointer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_DisorderedPointer.h; sourceTree = ""; }; - 90E6FC0915BC0BBE00A88421 /* org_bridj_Pointer_FreeReleaser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_FreeReleaser.h; sourceTree = ""; }; - 90E6FC0A15BC0BBE00A88421 /* org_bridj_Pointer_ListType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_ListType.h; sourceTree = ""; }; - 90E6FC0B15BC0BBE00A88421 /* org_bridj_Pointer_OrderedPointer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_OrderedPointer.h; sourceTree = ""; }; - 90E6FC0C15BC0BBE00A88421 /* org_bridj_Pointer_Releaser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_Releaser.h; sourceTree = ""; }; - 90E6FC0D15BC0BBE00A88421 /* org_bridj_Pointer_StringType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer_StringType.h; sourceTree = ""; }; - 90E6FC0E15BC0BBE00A88421 /* org_bridj_Pointer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = org_bridj_Pointer.h; sourceTree = ""; }; - 90E6FC0F15BC0BBE00A88421 /* Pointer_prim.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Pointer_prim.h; sourceTree = ""; }; - 90E6FC1015BC0BBE00A88421 /* PrimDefs_boolean.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_boolean.h; sourceTree = ""; }; - 90E6FC1115BC0BBE00A88421 /* PrimDefs_byte.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_byte.h; sourceTree = ""; }; - 90E6FC1215BC0BBE00A88421 /* PrimDefs_char.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_char.h; sourceTree = ""; }; - 90E6FC1315BC0BBE00A88421 /* PrimDefs_double.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_double.h; sourceTree = ""; }; - 90E6FC1415BC0BBE00A88421 /* PrimDefs_float.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_float.h; sourceTree = ""; }; - 90E6FC1515BC0BBE00A88421 /* PrimDefs_int.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_int.h; sourceTree = ""; }; - 90E6FC1615BC0BBE00A88421 /* PrimDefs_long.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_long.h; sourceTree = ""; }; - 90E6FC1715BC0BBE00A88421 /* PrimDefs_short.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_short.h; sourceTree = ""; }; - 90E6FC1815BC0BBE00A88421 /* PrimDefs_undef.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrimDefs_undef.h; sourceTree = ""; }; - 90E6FC1915BC0BBE00A88421 /* Protected.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Protected.h; sourceTree = ""; }; - 90E6FC1A15BC0BBE00A88421 /* RawNativeForwardCallback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RawNativeForwardCallback.h; sourceTree = ""; }; - 90E6FC1C15BC0BCD00A88421 /* RawNativeForwardCallback_Darwin64.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = RawNativeForwardCallback_Darwin64.s; sourceTree = ""; }; - 90E6FC4C15BC0CA900A88421 /* test.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = test.xcodeproj; path = ../../../test/cpp/test/test.xcodeproj; sourceTree = ""; }; - 90E6FC4F15BC0CA900A88421 /* testexe.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = testexe.xcodeproj; path = ../../../test/cpp/test/testexe.xcodeproj; sourceTree = ""; }; - 90E6FC7215BC0D8600A88421 /* Init.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = Init.c; path = "../../../../target/generated-resources/org/bridj/Init.c"; sourceTree = ""; }; - 90E6FC7415BC0EEE00A88421 /* libbridj.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libbridj.dylib; path = build_out/darwin_universal_gcc_release/libbridj.dylib; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXGroup section */ - 90E6FBDF15BC0B7F00A88421 = { - isa = PBXGroup; - children = ( - 90E6FC7415BC0EEE00A88421 /* libbridj.dylib */, - 90E6FC4C15BC0CA900A88421 /* test.xcodeproj */, - 90E6FC4F15BC0CA900A88421 /* testexe.xcodeproj */, - 90E6FBEF15BC0BBE00A88421 /* CallbackHandler.c */, - 90E6FC7215BC0D8600A88421 /* Init.c */, - 90E6FBF015BC0BBE00A88421 /* CppHandler.c */, - 90E6FBF115BC0BBE00A88421 /* Exceptions.c */, - 90E6FBF215BC0BBE00A88421 /* FunctionHandler.c */, - 90E6FBF315BC0BBE00A88421 /* GenericJavaCallbackHandlers.c */, - 90E6FBF415BC0BBE00A88421 /* HandlersCommon.c */, - 90E6FBF515BC0BBE00A88421 /* JNI.c */, - 90E6FBF615BC0BBE00A88421 /* ObjCHandler.c */, - 90E6FC1C15BC0BCD00A88421 /* RawNativeForwardCallback_Darwin64.s */, - 90E6FBF715BC0BBE00A88421 /* Platform.c */, - 90E6FBF815BC0BBE00A88421 /* Pointer.c */, - 90E6FBF915BC0BBE00A88421 /* RawNativeForwardCallback.c */, - 90E6FBFA15BC0BBE00A88421 /* ThreadLocal.c */, - 90E6FBFB15BC0BBE00A88421 /* bridj.hpp */, - 90E6FBFC15BC0BBE00A88421 /* Exceptions.h */, - 90E6FBFD15BC0BBE00A88421 /* HandlersCommon.h */, - 90E6FBFE15BC0BBE00A88421 /* JNI_prim.h */, - 90E6FBFF15BC0BBE00A88421 /* JNI.h */, - 90E6FC0015BC0BBE00A88421 /* ObjCProxy.h */, - 90E6FC0115BC0BBE00A88421 /* org_bridj_BridJ_CastingType.h */, - 90E6FC0215BC0BBE00A88421 /* org_bridj_BridJ_Switch.h */, - 90E6FC0315BC0BBE00A88421 /* org_bridj_BridJ.h */, - 90E6FC0415BC0BBE00A88421 /* org_bridj_JNI.h */, - 90E6FC0515BC0BBE00A88421 /* org_bridj_objc_ObjCJNI.h */, - 90E6FC0615BC0BBE00A88421 /* org_bridj_Platform_DeleteFiles.h */, - 90E6FC0715BC0BBE00A88421 /* org_bridj_Platform.h */, - 90E6FC0815BC0BBE00A88421 /* org_bridj_Pointer_DisorderedPointer.h */, - 90E6FC0915BC0BBE00A88421 /* org_bridj_Pointer_FreeReleaser.h */, - 90E6FC0A15BC0BBE00A88421 /* org_bridj_Pointer_ListType.h */, - 90E6FC0B15BC0BBE00A88421 /* org_bridj_Pointer_OrderedPointer.h */, - 90E6FC0C15BC0BBE00A88421 /* org_bridj_Pointer_Releaser.h */, - 90E6FC0D15BC0BBE00A88421 /* org_bridj_Pointer_StringType.h */, - 90E6FC0E15BC0BBE00A88421 /* org_bridj_Pointer.h */, - 90E6FC0F15BC0BBE00A88421 /* Pointer_prim.h */, - 90E6FC1015BC0BBE00A88421 /* PrimDefs_boolean.h */, - 90E6FC1115BC0BBE00A88421 /* PrimDefs_byte.h */, - 90E6FC1215BC0BBE00A88421 /* PrimDefs_char.h */, - 90E6FC1315BC0BBE00A88421 /* PrimDefs_double.h */, - 90E6FC1415BC0BBE00A88421 /* PrimDefs_float.h */, - 90E6FC1515BC0BBE00A88421 /* PrimDefs_int.h */, - 90E6FC1615BC0BBE00A88421 /* PrimDefs_long.h */, - 90E6FC1715BC0BBE00A88421 /* PrimDefs_short.h */, - 90E6FC1815BC0BBE00A88421 /* PrimDefs_undef.h */, - 90E6FC1915BC0BBE00A88421 /* Protected.h */, - 90E6FC1A15BC0BBE00A88421 /* RawNativeForwardCallback.h */, - ); - sourceTree = ""; - }; - 90E6FC4D15BC0CA900A88421 /* Products */ = { - isa = PBXGroup; - children = ( - ); - name = Products; - sourceTree = ""; - }; - 90E6FC5015BC0CA900A88421 /* Products */ = { - isa = PBXGroup; - children = ( - 90E6FC5C15BC0CA900A88421 /* testexe */, - ); - name = Products; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXLegacyTarget section */ - 90E6FBE615BC0B7F00A88421 /* BridJ */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "$(ACTION)"; - buildConfigurationList = 90E6FBE915BC0B7F00A88421 /* Build configuration list for PBXLegacyTarget "BridJ" */; - buildPhases = ( - ); - buildToolPath = ./BuildNative; - buildWorkingDirectory = /Users/ochafik/github/nativelibs4java2/libraries/BridJ; - dependencies = ( - ); - name = BridJ; - passBuildSettingsInEnvironment = 0; - productName = BridJ; - }; -/* End PBXLegacyTarget section */ - -/* Begin PBXProject section */ - 90E6FBE115BC0B7F00A88421 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 90E6FBE415BC0B7F00A88421 /* Build configuration list for PBXProject "BridJ" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 90E6FBDF15BC0B7F00A88421; - projectDirPath = ""; - projectReferences = ( - { - ProductGroup = 90E6FC4D15BC0CA900A88421 /* Products */; - ProjectRef = 90E6FC4C15BC0CA900A88421 /* test.xcodeproj */; - }, - { - ProductGroup = 90E6FC5015BC0CA900A88421 /* Products */; - ProjectRef = 90E6FC4F15BC0CA900A88421 /* testexe.xcodeproj */; - }, - ); - projectRoot = ""; - targets = ( - 90E6FBE615BC0B7F00A88421 /* BridJ */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXReferenceProxy section */ - 90E6FC5C15BC0CA900A88421 /* testexe */ = { - isa = PBXReferenceProxy; - fileType = "compiled.mach-o.executable"; - path = testexe; - remoteRef = 90E6FC5B15BC0CA900A88421 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; -/* End PBXReferenceProxy section */ - -/* Begin XCBuildConfiguration section */ - 90E6FBE715BC0B7F00A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - }; - name = Debug; - }; - 90E6FBE815BC0B7F00A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - SDKROOT = macosx; - }; - name = Release; - }; - 90E6FBEA15BC0B7F00A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEBUGGING_SYMBOLS = YES; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - OTHER_CFLAGS = ""; - OTHER_LDFLAGS = ""; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 90E6FBEB15BC0B7F00A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - OTHER_CFLAGS = ""; - OTHER_LDFLAGS = ""; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 90E6FBE415BC0B7F00A88421 /* Build configuration list for PBXProject "BridJ" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FBE715BC0B7F00A88421 /* Debug */, - 90E6FBE815BC0B7F00A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 90E6FBE915BC0B7F00A88421 /* Build configuration list for PBXLegacyTarget "BridJ" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FBEA15BC0B7F00A88421 /* Debug */, - 90E6FBEB15BC0B7F00A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 90E6FBE115BC0B7F00A88421 /* Project object */; -} diff --git a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 552bab937..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate b/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index a48080edb..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate +++ /dev/null @@ -1,8727 +0,0 @@ - - - - - $archiver - NSKeyedArchiver - $objects - - $null - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 2 - - - CF$UID - 3 - - - NS.objects - - - CF$UID - 4 - - - CF$UID - 509 - - - - IDEWorkspaceDocument - 437BBE79-358F-484A-B29D-8B85A2BBDE40 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 5 - - - CF$UID - 6 - - - CF$UID - 7 - - - CF$UID - 8 - - - CF$UID - 9 - - - CF$UID - 10 - - - CF$UID - 11 - - - CF$UID - 12 - - - CF$UID - 13 - - - CF$UID - 14 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 16 - - - CF$UID - 389 - - - CF$UID - 466 - - - CF$UID - 471 - - - CF$UID - 474 - - - CF$UID - 504 - - - CF$UID - 505 - - - CF$UID - 15 - - - CF$UID - 15 - - - - BreakpointsActivated - DefaultEditorStatesForURLs - DebuggingWindowBehavior - ActiveRunDestination - ActiveScheme - LastCompletedPersistentSchemeBasedActivityReport - DocumentWindows - RecentEditorDocumentURLs - AppFocusInMiniDebugging - MiniDebuggingConsole - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 17 - - - CF$UID - 18 - - - CF$UID - 19 - - - NS.objects - - - CF$UID - 20 - - - CF$UID - 63 - - - CF$UID - 431 - - - - Xcode.IDEKit.EditorDocument.LogDocument - Xcode.Xcode3ProjectSupport.EditorDocument.Xcode3Project - Xcode.IDEKit.EditorDocument.SourceCode - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 21 - - - CF$UID - 24 - - - CF$UID - 26 - - - CF$UID - 28 - - - CF$UID - 30 - - - CF$UID - 32 - - - CF$UID - 34 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 38 - - - CF$UID - 43 - - - CF$UID - 51 - - - CF$UID - 52 - - - CF$UID - 55 - - - CF$UID - 58 - - - CF$UID - 59 - - - CF$UID - 62 - - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 22 - - - x-xcode-log://626D3045-105F-454C-9B2E-8FA42B5A44B1 - - $classes - - NSURL - NSObject - - $classname - NSURL - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 25 - - - x-xcode-log://BC56E414-FD4F-43FA-BD86-9A84FE712A61 - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 27 - - - x-xcode-log://06D558AF-D6FD-4035-91AC-6B989EDF8E18 - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 29 - - - x-xcode-log://A0D030CB-E69A-496B-A108-D13D9734B1D9 - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 31 - - - x-xcode-log://683ED24A-5E03-4CD9-B87E-3786D2188237 - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 33 - - - x-xcode-log://9F95F3A3-C311-4619-A3BD-1CF79A793595 - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 35 - - - x-xcode-log://05051506-6BE2-470E-B3B0-33BCBEDC981C - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 37 - - - x-xcode-log://582ACB13-2A29-412C-B8EB-8A6B56062410 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 40 - - - - SelectedDocumentLocations - - $class - - CF$UID - 41 - - NS.objects - - - - $classes - - NSArray - NSObject - - $classname - NSArray - - - $classes - - NSMutableDictionary - NSDictionary - NSObject - - $classname - NSMutableDictionary - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 44 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 45 - - - - - $class - - CF$UID - 50 - - documentURL - - CF$UID - 25 - - expandTranscript - - indexPath - - CF$UID - 46 - - timestamp - - CF$UID - 0 - - - - $class - - CF$UID - 49 - - NSIndexPathData - - CF$UID - 47 - - NSIndexPathLength - 2 - - - $class - - CF$UID - 48 - - NS.data - - AAE= - - - - $classes - - NSMutableData - NSData - NSObject - - $classname - NSMutableData - - - $classes - - NSIndexPath - NSObject - - $classname - NSIndexPath - - - $classes - - IDELogDocumentLocation - DVTDocumentLocation - NSObject - - $classname - IDELogDocumentLocation - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 40 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 53 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 54 - - - - - $class - - CF$UID - 50 - - documentURL - - CF$UID - 29 - - expandTranscript - - indexPath - - CF$UID - 46 - - timestamp - - CF$UID - 0 - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 56 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 57 - - - - - $class - - CF$UID - 50 - - documentURL - - CF$UID - 31 - - expandTranscript - - indexPath - - CF$UID - 46 - - timestamp - - CF$UID - 0 - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 40 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 60 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 61 - - - - - $class - - CF$UID - 50 - - documentURL - - CF$UID - 35 - - expandTranscript - - indexPath - - CF$UID - 46 - - timestamp - - CF$UID - 0 - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 39 - - - NS.objects - - - CF$UID - 40 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 64 - - - CF$UID - 67 - - - CF$UID - 69 - - - CF$UID - 71 - - - CF$UID - 73 - - - CF$UID - 75 - - - CF$UID - 77 - - - NS.objects - - - CF$UID - 79 - - - CF$UID - 107 - - - CF$UID - 133 - - - CF$UID - 150 - - - CF$UID - 167 - - - CF$UID - 182 - - - CF$UID - 392 - - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 65 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/BridJ/BridJ.xcodeproj/ - - - $classes - - NSMutableString - NSString - NSObject - - $classname - NSMutableString - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 68 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/ - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 70 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/test.xcodeproj/ - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 72 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/test/test.xcodeproj/ - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 74 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/test/test.xcodeproj/ - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 76 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/testexe/testexe.xcodeproj/ - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 78 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/ - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 80 - - - CF$UID - 81 - - - CF$UID - 82 - - - CF$UID - 83 - - - NS.objects - - - CF$UID - 84 - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 106 - - - - Xcode3ProjectEditor.sourceList.splitview - Xcode3ProjectEditorPreviousTargetEditorClass - Xcode3ProjectEditorSelectedDocumentLocations - Xcode3ProjectEditor_Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 85 - - - NS.objects - - - CF$UID - 86 - - - - DVTSplitViewItems - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 87 - - - CF$UID - 93 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 88 - - - CF$UID - 89 - - - NS.objects - - - CF$UID - 90 - - - CF$UID - 91 - - - - DVTIdentifier - DVTViewMagnitude - - 162 - - $classes - - NSDictionary - NSObject - - $classname - NSDictionary - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 88 - - - CF$UID - 89 - - - NS.objects - - - CF$UID - 90 - - - CF$UID - 94 - - - - 978 - - $classes - - NSMutableArray - NSArray - NSObject - - $classname - NSMutableArray - - Xcode3InfoEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 98 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 99 - - selection - - CF$UID - 101 - - timestamp - - CF$UID - 100 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/BridJ/BridJ.xcodeproj/ - 364645253.34489298 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 102 - - - CF$UID - 103 - - - NS.objects - - - CF$UID - 96 - - - CF$UID - 104 - - - - Editor - Target - BridJ - - $classes - - Xcode3ProjectDocumentLocation - DVTDocumentLocation - NSObject - - $classname - Xcode3ProjectDocumentLocation - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 111 - - - NS.objects - - - CF$UID - 112 - - - CF$UID - 122 - - - CF$UID - 123 - - - CF$UID - 132 - - - - Xcode3ProjectEditor.sourceList.splitview - Xcode3ProjectEditorPreviousTargetEditorClass - Xcode3ProjectEditorSelectedDocumentLocations - Xcode3ProjectEditor_Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 114 - - - - DVTSplitViewItems - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 115 - - - CF$UID - 120 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 119 - - - - DVTIdentifier - DVTViewMagnitude - - 170 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 121 - - - - 970 - Xcode3InfoEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 124 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 125 - - selection - - CF$UID - 127 - - timestamp - - CF$UID - 126 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/ - 364646665.29499203 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - NS.objects - - - CF$UID - 130 - - - CF$UID - 131 - - - - Editor - Target - Xcode3InfoEditor - BridJ - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 134 - - - NS.objects - - - CF$UID - 135 - - - CF$UID - 141 - - - CF$UID - 142 - - - CF$UID - 149 - - - - Xcode3ProjectEditor_Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 136 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 137 - - - CF$UID - 139 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 138 - - - - 170 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 140 - - - - 970 - Xcode3InfoEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 143 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 144 - - selection - - CF$UID - 146 - - timestamp - - CF$UID - 145 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/test.xcodeproj/ - 364646228.51984698 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - NS.objects - - - CF$UID - 147 - - - CF$UID - 148 - - - - Xcode3InfoEditor - test - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 151 - - - NS.objects - - - CF$UID - 152 - - - CF$UID - 158 - - - CF$UID - 159 - - - CF$UID - 166 - - - - Xcode3ProjectEditor_Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 153 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 154 - - - CF$UID - 156 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 155 - - - - 162 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 157 - - - - 978 - Xcode3InfoEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 160 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 161 - - selection - - CF$UID - 163 - - timestamp - - CF$UID - 162 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/test/test.xcodeproj/ - 364645505.51002502 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - NS.objects - - - CF$UID - 164 - - - CF$UID - 165 - - - - Xcode3InfoEditor - test - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 151 - - - NS.objects - - - CF$UID - 168 - - - CF$UID - 174 - - - CF$UID - 175 - - - CF$UID - 181 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 169 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 170 - - - CF$UID - 172 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 171 - - - - 162 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 173 - - - - 978 - Xcode3InfoEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 176 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 177 - - selection - - CF$UID - 179 - - timestamp - - CF$UID - 178 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/test/test.xcodeproj/ - 364645513.434147 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - NS.objects - - - CF$UID - 180 - - - CF$UID - 165 - - - - Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 183 - - - NS.objects - - - CF$UID - 184 - - - CF$UID - 190 - - - CF$UID - 191 - - - CF$UID - 391 - - - - Xcode3ProjectEditor_Xcode3BuildSettingsEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 185 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 186 - - - CF$UID - 188 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 187 - - - - 162 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 189 - - - - 978 - Xcode3BuildSettingsEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 192 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 193 - - selection - - CF$UID - 195 - - timestamp - - CF$UID - 194 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/testexe/testexe.xcodeproj/ - 364645431.81506598 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - CF$UID - 196 - - - NS.objects - - - CF$UID - 197 - - - CF$UID - 198 - - - CF$UID - 199 - - - - Xcode3BuildSettingsEditorLocations - Xcode3BuildSettingsEditor - testexe - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 200 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 201 - - - CF$UID - 202 - - - CF$UID - 203 - - - CF$UID - 204 - - - CF$UID - 205 - - - CF$UID - 206 - - - NS.objects - - - CF$UID - 207 - - - CF$UID - 388 - - - CF$UID - 389 - - - CF$UID - 389 - - - CF$UID - 389 - - - CF$UID - 390 - - - - Collapsed Build Property Categories - Selected Build Properties - Xcode3BuildSettingsEditorDisplayMode - Xcode3BuildPropertyValueDisplayMode - Xcode3BuildSettingsEditorMode - Xcode3BuildPropertyNameDisplayMode - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 208 - - - CF$UID - 209 - - - CF$UID - 210 - - - CF$UID - 211 - - - CF$UID - 212 - - - CF$UID - 213 - - - CF$UID - 214 - - - CF$UID - 215 - - - CF$UID - 216 - - - CF$UID - 217 - - - CF$UID - 218 - - - CF$UID - 219 - - - CF$UID - 220 - - - CF$UID - 221 - - - CF$UID - 222 - - - CF$UID - 223 - - - CF$UID - 224 - - - CF$UID - 225 - - - CF$UID - 226 - - - CF$UID - 227 - - - CF$UID - 228 - - - CF$UID - 229 - - - CF$UID - 230 - - - CF$UID - 231 - - - CF$UID - 232 - - - CF$UID - 233 - - - CF$UID - 234 - - - CF$UID - 235 - - - CF$UID - 236 - - - CF$UID - 237 - - - CF$UID - 238 - - - CF$UID - 239 - - - CF$UID - 240 - - - CF$UID - 241 - - - CF$UID - 242 - - - CF$UID - 243 - - - CF$UID - 244 - - - CF$UID - 245 - - - CF$UID - 246 - - - CF$UID - 247 - - - CF$UID - 248 - - - CF$UID - 249 - - - CF$UID - 250 - - - CF$UID - 251 - - - CF$UID - 252 - - - CF$UID - 253 - - - CF$UID - 254 - - - CF$UID - 255 - - - CF$UID - 256 - - - CF$UID - 257 - - - CF$UID - 258 - - - CF$UID - 259 - - - CF$UID - 260 - - - CF$UID - 261 - - - CF$UID - 262 - - - CF$UID - 263 - - - CF$UID - 264 - - - CF$UID - 265 - - - CF$UID - 266 - - - CF$UID - 267 - - - CF$UID - 268 - - - CF$UID - 269 - - - CF$UID - 270 - - - CF$UID - 271 - - - CF$UID - 272 - - - CF$UID - 273 - - - CF$UID - 274 - - - CF$UID - 275 - - - CF$UID - 276 - - - CF$UID - 277 - - - CF$UID - 278 - - - CF$UID - 279 - - - CF$UID - 280 - - - CF$UID - 281 - - - CF$UID - 282 - - - CF$UID - 283 - - - CF$UID - 284 - - - CF$UID - 285 - - - CF$UID - 286 - - - CF$UID - 287 - - - CF$UID - 288 - - - CF$UID - 289 - - - CF$UID - 290 - - - CF$UID - 291 - - - CF$UID - 292 - - - CF$UID - 293 - - - CF$UID - 294 - - - CF$UID - 295 - - - CF$UID - 296 - - - CF$UID - 297 - - - CF$UID - 298 - - - CF$UID - 299 - - - CF$UID - 300 - - - CF$UID - 301 - - - CF$UID - 302 - - - CF$UID - 303 - - - CF$UID - 304 - - - CF$UID - 305 - - - CF$UID - 306 - - - CF$UID - 307 - - - CF$UID - 308 - - - CF$UID - 309 - - - CF$UID - 310 - - - CF$UID - 311 - - - CF$UID - 312 - - - CF$UID - 313 - - - CF$UID - 314 - - - CF$UID - 315 - - - CF$UID - 316 - - - CF$UID - 317 - - - CF$UID - 318 - - - CF$UID - 319 - - - CF$UID - 320 - - - CF$UID - 321 - - - CF$UID - 322 - - - CF$UID - 323 - - - CF$UID - 324 - - - CF$UID - 325 - - - CF$UID - 326 - - - CF$UID - 327 - - - CF$UID - 328 - - - CF$UID - 329 - - - CF$UID - 330 - - - CF$UID - 331 - - - CF$UID - 332 - - - CF$UID - 333 - - - CF$UID - 334 - - - CF$UID - 335 - - - CF$UID - 336 - - - CF$UID - 337 - - - CF$UID - 338 - - - CF$UID - 339 - - - CF$UID - 340 - - - CF$UID - 341 - - - CF$UID - 342 - - - CF$UID - 343 - - - CF$UID - 344 - - - CF$UID - 345 - - - CF$UID - 346 - - - CF$UID - 347 - - - CF$UID - 348 - - - CF$UID - 349 - - - CF$UID - 350 - - - CF$UID - 351 - - - CF$UID - 352 - - - CF$UID - 353 - - - CF$UID - 354 - - - CF$UID - 355 - - - CF$UID - 356 - - - CF$UID - 357 - - - CF$UID - 358 - - - CF$UID - 359 - - - CF$UID - 360 - - - CF$UID - 361 - - - CF$UID - 362 - - - CF$UID - 363 - - - CF$UID - 364 - - - CF$UID - 365 - - - CF$UID - 366 - - - CF$UID - 367 - - - CF$UID - 368 - - - CF$UID - 369 - - - CF$UID - 370 - - - CF$UID - 371 - - - CF$UID - 372 - - - CF$UID - 373 - - - CF$UID - 374 - - - CF$UID - 375 - - - CF$UID - 376 - - - CF$UID - 377 - - - CF$UID - 378 - - - CF$UID - 379 - - - CF$UID - 380 - - - CF$UID - 381 - - - CF$UID - 382 - - - CF$UID - 383 - - - CF$UID - 384 - - - CF$UID - 385 - - - CF$UID - 386 - - - CF$UID - 387 - - - - - $class - - CF$UID - 66 - - NS.string - Architectures||ADDITIONAL_SDKS - - - $class - - CF$UID - 66 - - NS.string - Architectures||ARCHS - - - $class - - CF$UID - 66 - - NS.string - Architectures||SDKROOT - - - $class - - CF$UID - 66 - - NS.string - Architectures||SUPPORTED_PLATFORMS - - - $class - - CF$UID - 66 - - NS.string - Architectures||VALID_ARCHS - - - $class - - CF$UID - 66 - - NS.string - Build Locations||SYMROOT - - - $class - - CF$UID - 66 - - NS.string - Build Locations||OBJROOT - - - $class - - CF$UID - 66 - - NS.string - Build Locations||SHARED_PRECOMPS_DIR - - - $class - - CF$UID - 66 - - NS.string - Build Options||BUILD_VARIANTS - - - $class - - CF$UID - 66 - - NS.string - Build Options||GCC_VERSION - - - $class - - CF$UID - 66 - - NS.string - Build Options||ENABLE_OPENMP_SUPPORT - - - $class - - CF$UID - 66 - - NS.string - Build Options||GENERATE_PROFILING_CODE - - - $class - - CF$UID - 66 - - NS.string - Build Options||PRECOMPS_INCLUDE_HEADERS_FROM_BUILT_PRODUCTS_DIR - - - $class - - CF$UID - 66 - - NS.string - Build Options||RUN_CLANG_STATIC_ANALYZER - - - $class - - CF$UID - 66 - - NS.string - Build Options||SCAN_ALL_SOURCE_FILES_FOR_INCLUDES - - - $class - - CF$UID - 66 - - NS.string - Build Options||VALIDATE_PRODUCT - - - $class - - CF$UID - 66 - - NS.string - Code Signing||CODE_SIGN_ENTITLEMENTS - - - $class - - CF$UID - 66 - - NS.string - Code Signing||CODE_SIGN_IDENTITY - - - $class - - CF$UID - 66 - - NS.string - Code Signing||CODE_SIGN_RESOURCE_RULES_PATH - - - $class - - CF$UID - 66 - - NS.string - Code Signing||OTHER_CODE_SIGN_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Deployment||STRIPFLAGS - - - $class - - CF$UID - 66 - - NS.string - Deployment||ALTERNATE_GROUP - - - $class - - CF$UID - 66 - - NS.string - Deployment||ALTERNATE_OWNER - - - $class - - CF$UID - 66 - - NS.string - Deployment||ALTERNATE_MODE - - - $class - - CF$UID - 66 - - NS.string - Deployment||ALTERNATE_PERMISSIONS_FILES - - - $class - - CF$UID - 66 - - NS.string - Deployment||COMBINE_HIDPI_IMAGES - - - $class - - CF$UID - 66 - - NS.string - Deployment||DEPLOYMENT_LOCATION - - - $class - - CF$UID - 66 - - NS.string - Deployment||DEPLOYMENT_POSTPROCESSING - - - $class - - CF$UID - 66 - - NS.string - Deployment||INSTALL_GROUP - - - $class - - CF$UID - 66 - - NS.string - Deployment||INSTALL_OWNER - - - $class - - CF$UID - 66 - - NS.string - Deployment||INSTALL_MODE_FLAG - - - $class - - CF$UID - 66 - - NS.string - Deployment||DSTROOT - - - $class - - CF$UID - 66 - - NS.string - Deployment||INSTALL_PATH - - - $class - - CF$UID - 66 - - NS.string - Deployment||MACOSX_DEPLOYMENT_TARGET - - - $class - - CF$UID - 66 - - NS.string - Deployment||SKIP_INSTALL - - - $class - - CF$UID - 66 - - NS.string - Deployment||STRIP_INSTALLED_PRODUCT - - - $class - - CF$UID - 66 - - NS.string - Deployment||STRIP_STYLE - - - $class - - CF$UID - 66 - - NS.string - Deployment||SEPARATE_STRIP - - - $class - - CF$UID - 66 - - NS.string - Kernel Module||MODULE_NAME - - - $class - - CF$UID - 66 - - NS.string - Kernel Module||MODULE_START - - - $class - - CF$UID - 66 - - NS.string - Kernel Module||MODULE_STOP - - - $class - - CF$UID - 66 - - NS.string - Kernel Module||MODULE_VERSION - - - $class - - CF$UID - 66 - - NS.string - Linking||BUNDLE_LOADER - - - $class - - CF$UID - 66 - - NS.string - Linking||DYLIB_COMPATIBILITY_VERSION - - - $class - - CF$UID - 66 - - NS.string - Linking||DYLIB_CURRENT_VERSION - - - $class - - CF$UID - 66 - - NS.string - Linking||DEAD_CODE_STRIPPING - - - $class - - CF$UID - 66 - - NS.string - Linking||LINKER_DISPLAYS_MANGLED_NAMES - - - $class - - CF$UID - 66 - - NS.string - Linking||LD_NO_PIE - - - $class - - CF$UID - 66 - - NS.string - Linking||PRESERVE_DEAD_CODE_INITS_AND_TERMS - - - $class - - CF$UID - 66 - - NS.string - Linking||LD_DYLIB_INSTALL_NAME - - - $class - - CF$UID - 66 - - NS.string - Linking||EXPORTED_SYMBOLS_FILE - - - $class - - CF$UID - 66 - - NS.string - Linking||INIT_ROUTINE - - - $class - - CF$UID - 66 - - NS.string - Linking||LINK_WITH_STANDARD_LIBRARIES - - - $class - - CF$UID - 66 - - NS.string - Linking||MACH_O_TYPE - - - $class - - CF$UID - 66 - - NS.string - Linking||LD_OPENMP_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Linking||ORDER_FILE - - - $class - - CF$UID - 66 - - NS.string - Linking||OTHER_LDFLAGS - - - $class - - CF$UID - 66 - - NS.string - Linking||GENERATE_MASTER_OBJECT_FILE - - - $class - - CF$UID - 66 - - NS.string - Linking||PRELINK_LIBS - - - $class - - CF$UID - 66 - - NS.string - Linking||KEEP_PRIVATE_EXTERNS - - - $class - - CF$UID - 66 - - NS.string - Linking||LD_RUNPATH_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Linking||SEPARATE_SYMBOL_EDIT - - - $class - - CF$UID - 66 - - NS.string - Linking||PRELINK_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Linking||SECTORDER_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Linking||UNEXPORTED_SYMBOLS_FILE - - - $class - - CF$UID - 66 - - NS.string - Linking||WARNING_LDFLAGS - - - $class - - CF$UID - 66 - - NS.string - Linking||LD_GENERATE_MAP_FILE - - - $class - - CF$UID - 66 - - NS.string - Packaging||APPLY_RULES_IN_COPY_FILES - - - $class - - CF$UID - 66 - - NS.string - Packaging||EXECUTABLE_EXTENSION - - - $class - - CF$UID - 66 - - NS.string - Packaging||EXECUTABLE_PREFIX - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_EXPAND_BUILD_SETTINGS - - - $class - - CF$UID - 66 - - NS.string - Packaging||GENERATE_PKGINFO_FILE - - - $class - - CF$UID - 66 - - NS.string - Packaging||FRAMEWORK_VERSION - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_FILE - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_OTHER_PREPROCESSOR_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_OUTPUT_FORMAT - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_PREPROCESSOR_DEFINITIONS - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_PREFIX_HEADER - - - $class - - CF$UID - 66 - - NS.string - Packaging||INFOPLIST_PREPROCESS - - - $class - - CF$UID - 66 - - NS.string - Packaging||COPYING_PRESERVES_HFS_DATA - - - $class - - CF$UID - 66 - - NS.string - Packaging||PRIVATE_HEADERS_FOLDER_PATH - - - $class - - CF$UID - 66 - - NS.string - Packaging||PRODUCT_NAME - - - $class - - CF$UID - 66 - - NS.string - Packaging||PLIST_FILE_OUTPUT_FORMAT - - - $class - - CF$UID - 66 - - NS.string - Packaging||PUBLIC_HEADERS_FOLDER_PATH - - - $class - - CF$UID - 66 - - NS.string - Packaging||STRINGS_FILE_OUTPUT_ENCODING - - - $class - - CF$UID - 66 - - NS.string - Packaging||WRAPPER_EXTENSION - - - $class - - CF$UID - 66 - - NS.string - Search Paths||ALWAYS_SEARCH_USER_PATHS - - - $class - - CF$UID - 66 - - NS.string - Search Paths||FRAMEWORK_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Search Paths||HEADER_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Search Paths||LIBRARY_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Search Paths||REZ_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Search Paths||EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES - - - $class - - CF$UID - 66 - - NS.string - Search Paths||INCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES - - - $class - - CF$UID - 66 - - NS.string - Search Paths||USER_HEADER_SEARCH_PATHS - - - $class - - CF$UID - 66 - - NS.string - Unit Testing||OTHER_TEST_FLAGS - - - $class - - CF$UID - 66 - - NS.string - Unit Testing||TEST_AFTER_BUILD - - - $class - - CF$UID - 66 - - NS.string - Unit Testing||TEST_HOST - - - $class - - CF$UID - 66 - - NS.string - Unit Testing||TEST_RIG - - - $class - - CF$UID - 66 - - NS.string - Versioning||CURRENT_PROJECT_VERSION - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSION_INFO_FILE - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSION_INFO_EXPORT_DECL - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSION_INFO_PREFIX - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSION_INFO_SUFFIX - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSIONING_SYSTEM - - - $class - - CF$UID - 66 - - NS.string - Versioning||VERSION_INFO_BUILDER - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_FAST_OBJC_DISPATCH - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_SSE3_EXTENSIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_SSE41_EXTENSIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_SSE42_EXTENSIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_STRICT_ALIASING - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_GENERATE_DEBUGGING_SYMBOLS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_DYNAMIC_NO_PIC - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_INLINES_ARE_PRIVATE_EXTERN - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_KERNEL_DEVELOPMENT - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||LLVM_LTO - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_REUSE_STRINGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_NO_COMMON_BLOCKS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_ENABLE_OBJC_GC - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_FAST_MATH - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_THREADSAFE_STATICS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Code Generation||GCC_UNROLL_LOOPS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_CHAR_IS_UNSIGNED_CHAR - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_ASM_KEYWORD - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_C_LANGUAGE_STANDARD - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_INPUT_FILETYPE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_CPP_EXCEPTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_CPP_RTTI - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_LINK_WITH_DYNAMIC_LIBRARIES - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_OBJC_EXCEPTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_TRIGRAPHS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_FLOATING_POINT_LIBRARY_CALLS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_USE_INDIRECT_FUNCTION_CALLS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_USE_REGISTER_FUNCTION_CALLS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_INCREASE_PRECOMPILED_HEADER_SHARING - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_CW_ASM_SYNTAX - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||OTHER_CFLAGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||OTHER_CPLUSPLUSFLAGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_PRECOMPILE_PREFIX_HEADER - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_PREFIX_HEADER - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_BUILTIN_FUNCTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_ENABLE_PASCAL_STRINGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_FORCE_CPU_SUBTYPE_ALL - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_SHORT_ENUMS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Language||GCC_USE_STANDARD_INCLUDE_SEARCHING - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Preprocessing||GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_CHECK_SWITCH_STATEMENTS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_FOUR_CHARACTER_CONSTANTS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_SHADOW - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_64_TO_32_BIT_CONVERSION - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_INHIBIT_ALL_WARNINGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_RETURN_TYPE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_MISSING_PARENTHESES - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_MISSING_PROTOTYPES - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_MISSING_NEWLINE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_NON_VIRTUAL_DESTRUCTOR - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||WARNING_CFLAGS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_PEDANTIC - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_POINTER_SIGNEDNESS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_SIGN_COMPARE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_STRICT_SELECTOR_MATCH - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_TREAT_WARNINGS_AS_ERRORS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_TYPECHECK_CALLS_TO_PRINTF - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNDECLARED_SELECTOR - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNINITIALIZED_AUTOS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNKNOWN_PRAGMAS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNUSED_FUNCTION - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNUSED_LABEL - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNUSED_PARAMETER - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNUSED_VALUE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_UNUSED_VARIABLE - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS - - - $class - - CF$UID - 66 - - NS.string - LLVM compiler 2.1 - Warnings||GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO - - - $class - - CF$UID - 95 - - NS.objects - - - 0 - 1 - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 393 - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 394 - - - NS.objects - - - CF$UID - 395 - - - CF$UID - 396 - - - CF$UID - 402 - - - CF$UID - 403 - - - CF$UID - 413 - - - - Xcode3ProjectEditorPreviousProjectEditorClass - Xcode3ProjectEditor_Xcode3BuildPhasesEditor - Xcode3BuildSettingsEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 397 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 398 - - - CF$UID - 400 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 399 - - - - 170 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 401 - - - - 970 - Xcode3BuildPhasesEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 404 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 405 - - selection - - CF$UID - 407 - - timestamp - - CF$UID - 406 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/ - 364646667.83658397 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - CF$UID - 408 - - - NS.objects - - - CF$UID - 409 - - - CF$UID - 410 - - - CF$UID - 411 - - - - Xcode3BuildPhasesEditorLocations - Xcode3BuildPhasesEditor - testexe - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 412 - - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 414 - - - CF$UID - 415 - - - CF$UID - 416 - - - CF$UID - 417 - - - CF$UID - 418 - - - CF$UID - 419 - - - CF$UID - 420 - - - NS.objects - - - CF$UID - 421 - - - CF$UID - 422 - - - CF$UID - 423 - - - CF$UID - 427 - - - CF$UID - 428 - - - CF$UID - 429 - - - CF$UID - 430 - - - - kXcode3BuildPhasesEditorScrollPointKey - Xcode3BuildPhasesEditorFilterKey - Xcode3BuildPhasesEditorDisclosedNamesKey2.0 - 90E6FC2415BC0C3400A88421 - 90E6FC2615BC0C3400A88421 - 90E6FC2715BC0C3400A88421 - 90E6FC2515BC0C3400A88421 - {0, 0} - - - $class - - CF$UID - 426 - - NS.objects - - - CF$UID - 424 - - - CF$UID - 425 - - - - Link Binary With Libraries - Target Dependencies - - $classes - - NSMutableSet - NSSet - NSObject - - $classname - NSMutableSet - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 432 - - - CF$UID - 434 - - - CF$UID - 436 - - - CF$UID - 438 - - - CF$UID - 440 - - - CF$UID - 442 - - - NS.objects - - - CF$UID - 444 - - - CF$UID - 451 - - - CF$UID - 454 - - - CF$UID - 457 - - - CF$UID - 460 - - - CF$UID - 463 - - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 433 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/test.cpp - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 435 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/GNUmakefile - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 437 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Darwin64.s - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 439 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 441 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/testexe/testexe/main.cpp - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 443 - - - - $class - - CF$UID - 66 - - NS.string - file://localhost/Users/ochafik/.Trash/testexe/main.cpp - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 449 - - - CF$UID - 450 - - - CF$UID - 15 - - - CF$UID - 421 - - - - PrimaryDocumentTimestamp - PrimaryDocumentVisibleCharacterRange - HideAllIssues - PrimaryDocumentSelectedCharacterRange - 364645728.62637401 - {0, 1237} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 452 - - - CF$UID - 453 - - - CF$UID - 15 - - - CF$UID - 421 - - - - 364645800.41909498 - {0, 2052} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 455 - - - CF$UID - 456 - - - CF$UID - 15 - - - CF$UID - 421 - - - - 364645353.171031 - {0, 1930} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 458 - - - CF$UID - 459 - - - CF$UID - 15 - - - CF$UID - 421 - - - - 364645781.36390299 - {0, 1334} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 461 - - - CF$UID - 462 - - - CF$UID - 15 - - - CF$UID - 421 - - - - 364645433.66865599 - {0, 282} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 445 - - - CF$UID - 446 - - - CF$UID - 447 - - - CF$UID - 448 - - - NS.objects - - - CF$UID - 464 - - - CF$UID - 465 - - - CF$UID - 15 - - - CF$UID - 421 - - - - 364645473.88430601 - {0, 282} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 467 - - - CF$UID - 468 - - - NS.objects - - - CF$UID - 469 - - - CF$UID - 470 - - - - IDEDeviceLocation - IDEDeviceArchitecture - dvtdevice-local-computer:localhost - x86_64 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 472 - - - NS.objects - - - CF$UID - 473 - - - - IDENameString - BridJ - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 475 - - - CF$UID - 476 - - - CF$UID - 477 - - - NS.objects - - - CF$UID - 478 - - - CF$UID - 503 - - - CF$UID - 131 - - - - IDEActivityReportCompletionSummaryStringSegments - IDEActivityReportOptions - IDEActivityReportTitle - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 479 - - - CF$UID - 486 - - - CF$UID - 490 - - - CF$UID - 494 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 480 - - - CF$UID - 481 - - - CF$UID - 482 - - - NS.objects - - - CF$UID - 483 - - - CF$UID - 484 - - - CF$UID - 485 - - - - IDEActivityReportStringSegmentPriority - IDEActivityReportStringSegmentBackSeparator - IDEActivityReportStringSegmentStringValue - 2 - - Build - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 480 - - - CF$UID - 481 - - - CF$UID - 482 - - - NS.objects - - - CF$UID - 487 - - - CF$UID - 488 - - - CF$UID - 489 - - - - 4 - : - BridJ - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 480 - - - CF$UID - 481 - - - CF$UID - 482 - - - NS.objects - - - CF$UID - 491 - - - CF$UID - 492 - - - CF$UID - 493 - - - - 1 - │ - - $class - - CF$UID - 48 - - NS.data - - YnBsaXN0MDDUAQIDBAUGOzxYJHZlcnNpb25YJG9iamVjdHNZJGFy - Y2hpdmVyVCR0b3ASAAGGoK0HCA8QGhscJCUrMTQ3VSRudWxs0wkK - CwwNDlxOU0F0dHJpYnV0ZXNWJGNsYXNzWE5TU3RyaW5ngAOADIAC - WVN1Y2NlZWRlZNMKERITFBdXTlMua2V5c1pOUy5vYmplY3RzgAui - FRaABIAFohgZgAaACVZOU0ZvbnRXTlNDb2xvctQKHR4fICEiI1ZO - U05hbWVWTlNTaXplWE5TZkZsYWdzgAiAByNAJgAAAAAAABENEF8Q - EUx1Y2lkYUdyYW5kZS1Cb2xk0iYnKClaJGNsYXNzbmFtZVgkY2xh - c3Nlc1ZOU0ZvbnSiKCpYTlNPYmplY3TTCiwtLi8wXE5TQ29sb3JT - cGFjZVdOU1doaXRlgAoQA0IwANImJzIzV05TQ29sb3KiMirSJic1 - NlxOU0RpY3Rpb25hcnmiNSrSJic4OV8QEk5TQXR0cmlidXRlZFN0 - cmluZ6I6Kl8QEk5TQXR0cmlidXRlZFN0cmluZ18QD05TS2V5ZWRB - cmNoaXZlctE9PlRyb290gAEACAARABoAIwAtADIANwBFAEsAUgBf - AGYAbwBxAHMAdQB/AIYAjgCZAJsAngCgAKIApQCnAKkAsAC4AMEA - yADPANgA2gDcAOUA6AD8AQEBDAEVARwBHwEoAS8BPAFEAUYBSAFL - AVABWAFbAWABbQFwAXUBigGNAaIBtAG3AbwAAAAAAAACAQAAAAAA - AAA/AAAAAAAAAAAAAAAAAAABvg== - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 480 - - - CF$UID - 495 - - - CF$UID - 496 - - - CF$UID - 482 - - - CF$UID - 497 - - - CF$UID - 498 - - - NS.objects - - - CF$UID - 499 - - - CF$UID - 390 - - - CF$UID - 500 - - - CF$UID - 502 - - - CF$UID - 390 - - - CF$UID - 390 - - - - IDEActivityReportStringSegmentType - IDEActivityReportStringSegmentDate - IDEActivityReportStringSegmentDateStyle - IDEActivityReportStringSegmentTimeStyle - 3 - - $class - - CF$UID - 501 - - NS.time - 364646662.83509398 - - - $classes - - NSDate - NSObject - - $classname - NSDate - - Today at 11:44 - 234 - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 3 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 506 - - - CF$UID - 507 - - - CF$UID - 34 - - - CF$UID - 24 - - - CF$UID - 30 - - - CF$UID - 28 - - - CF$UID - 32 - - - CF$UID - 26 - - - CF$UID - 36 - - - CF$UID - 508 - - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 405 - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 125 - - - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 144 - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 510 - - - CF$UID - 511 - - - CF$UID - 512 - - - CF$UID - 513 - - - CF$UID - 514 - - - CF$UID - 515 - - - CF$UID - 516 - - - CF$UID - 517 - - - NS.objects - - - CF$UID - 518 - - - CF$UID - 720 - - - CF$UID - 721 - - - CF$UID - 15 - - - CF$UID - 3 - - - CF$UID - 510 - - - CF$UID - 528 - - - CF$UID - 15 - - - - IDEWorkspaceTabController_9436B520-7912-40B0-BAD2-B184266BD629 - IDEWindowFrame - IDEOrderedWorkspaceTabControllers - IDEWindowInFullscreenMode - IDEWorkspaceWindowControllerUniqueIdentifier - IDEActiveWorkspaceTabController - IDEWindowToolbarIsVisible - IDEWindowTabBarIsVisible - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 519 - - - CF$UID - 520 - - - CF$UID - 521 - - - CF$UID - 522 - - - CF$UID - 523 - - - CF$UID - 524 - - - CF$UID - 525 - - - CF$UID - 526 - - - NS.objects - - - CF$UID - 527 - - - CF$UID - 528 - - - CF$UID - 529 - - - CF$UID - 641 - - - CF$UID - 647 - - - CF$UID - 711 - - - CF$UID - 15 - - - CF$UID - 389 - - - - IDETabLabel - IDEShowNavigator - IDEEditorArea - IDEWorkspaceTabControllerUtilityAreaSplitView - IDENavigatorArea - IDEWorkspaceTabControllerDesignAreaSplitView - IDEShowUtilities - AssistantEditorsLayout - testexe.xcodeproj - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 530 - - - CF$UID - 531 - - - CF$UID - 532 - - - CF$UID - 533 - - - CF$UID - 534 - - - CF$UID - 535 - - - CF$UID - 536 - - - CF$UID - 537 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 538 - - - CF$UID - 563 - - - CF$UID - 528 - - - CF$UID - 389 - - - CF$UID - 620 - - - CF$UID - 628 - - - CF$UID - 629 - - - - ShowDebuggerArea - IDEEDitorArea_DebugArea - IDEEditorMode_Standard - IDEShowEditor - EditorMode - DebuggerSplitView - DefaultPersistentRepresentations - layoutTree - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 539 - - - CF$UID - 540 - - - CF$UID - 541 - - - CF$UID - 542 - - - CF$UID - 543 - - - CF$UID - 544 - - - NS.objects - - - CF$UID - 390 - - - CF$UID - 545 - - - CF$UID - 547 - - - CF$UID - 390 - - - CF$UID - 555 - - - CF$UID - 561 - - - - LayoutFocusMode - console - IDEDebuggerAreaSplitView - LayoutMode - IDEDebugArea_SplitView - variables - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 546 - - - NS.objects - - - CF$UID - 389 - - - - ConsoleFilterMode - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 548 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 549 - - - CF$UID - 552 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 550 - - - CF$UID - 551 - - - - VariablesView - 570 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 553 - - - CF$UID - 554 - - - - ConsoleArea - 569 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 556 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 557 - - - CF$UID - 559 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 550 - - - CF$UID - 558 - - - - 570 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 553 - - - CF$UID - 560 - - - - 569 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 562 - - - NS.objects - - - CF$UID - 390 - - - - VariablesViewSelectedScope - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 564 - - - NS.objects - - - CF$UID - 565 - - - - EditorLayout_PersistentRepresentation - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 566 - - - NS.objects - - - CF$UID - 567 - - - - Main - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 568 - - - CF$UID - 569 - - - CF$UID - 570 - - - NS.objects - - - CF$UID - 571 - - - CF$UID - 389 - - - CF$UID - 618 - - - - EditorLayout_StateSavingStateDictionaries - EditorLayout_Selected - EditorLayout_Geometry - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 572 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 573 - - - CF$UID - 574 - - - CF$UID - 575 - - - CF$UID - 576 - - - CF$UID - 577 - - - CF$UID - 578 - - - CF$UID - 579 - - - NS.objects - - - CF$UID - 580 - - - CF$UID - 581 - - - CF$UID - 593 - - - CF$UID - 585 - - - CF$UID - 585 - - - CF$UID - 615 - - - CF$UID - 616 - - - - FileDataType - ArchivableRepresentation - EditorState - NavigableItemName - DocumentNavigableItemName - DocumentExtensionIdentifier - DocumentURL - com.apple.xcode.project - - $class - - CF$UID - 592 - - DocumentLocation - - CF$UID - 590 - - DomainIdentifier - - CF$UID - 582 - - IdentifierPath - - CF$UID - 583 - - IndexOfDocumentIdentifier - - CF$UID - 589 - - - Xcode.IDENavigableItemDomain.WorkspaceStructure - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 584 - - - CF$UID - 587 - - - - - $class - - CF$UID - 586 - - Identifier - - CF$UID - 585 - - - testexe.xcodeproj - - $classes - - IDEArchivableStringIndexPair - NSObject - - $classname - IDEArchivableStringIndexPair - - - $class - - CF$UID - 586 - - Identifier - - CF$UID - 588 - - - BridJ - 9223372036854775807 - - $class - - CF$UID - 591 - - documentURL - - CF$UID - 78 - - timestamp - - CF$UID - 0 - - - - $classes - - DVTDocumentLocation - NSObject - - $classname - DVTDocumentLocation - - - $classes - - IDENavigableItemArchivableRepresentation - NSObject - - $classname - IDENavigableItemArchivableRepresentation - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 393 - - - CF$UID - 108 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 394 - - - NS.objects - - - CF$UID - 594 - - - CF$UID - 595 - - - CF$UID - 601 - - - CF$UID - 602 - - - CF$UID - 610 - - - - Xcode3BuildSettingsEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 596 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 597 - - - CF$UID - 599 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 598 - - - - 170 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 600 - - - - 970 - Xcode3BuildPhasesEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 603 - - - - - $class - - CF$UID - 105 - - documentURL - - CF$UID - 405 - - selection - - CF$UID - 605 - - timestamp - - CF$UID - 604 - - - 364646667.83960998 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 128 - - - CF$UID - 129 - - - CF$UID - 606 - - - NS.objects - - - CF$UID - 607 - - - CF$UID - 410 - - - CF$UID - 608 - - - - Xcode3BuildPhasesEditorLocations - Xcode3BuildPhasesEditor - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 609 - - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 414 - - - CF$UID - 415 - - - CF$UID - 416 - - - CF$UID - 417 - - - CF$UID - 418 - - - CF$UID - 419 - - - CF$UID - 420 - - - NS.objects - - - CF$UID - 421 - - - CF$UID - 422 - - - CF$UID - 423 - - - CF$UID - 611 - - - CF$UID - 612 - - - CF$UID - 613 - - - CF$UID - 614 - - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - Xcode.Xcode3ProjectSupport.EditorDocument.Xcode3Project - - $class - - CF$UID - 23 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 617 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/ - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 619 - - - - {{0, 0}, {1140, 876}} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 621 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 622 - - - CF$UID - 625 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 623 - - - CF$UID - 624 - - - - IDEEditor - 203 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 626 - - - CF$UID - 627 - - - - IDEDebuggerArea - 115 - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 640 - - geniusEditorContextNode - - CF$UID - 0 - - primaryEditorContextNode - - CF$UID - 630 - - rootLayoutTreeNode - - CF$UID - 637 - - - - $class - - CF$UID - 639 - - children - - CF$UID - 0 - - contentType - 1 - documentArchivableRepresentation - - CF$UID - 631 - - orientation - 0 - parent - - CF$UID - 637 - - - - $class - - CF$UID - 592 - - DocumentLocation - - CF$UID - 590 - - DomainIdentifier - - CF$UID - 582 - - IdentifierPath - - CF$UID - 632 - - IndexOfDocumentIdentifier - - CF$UID - 636 - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 633 - - - CF$UID - 634 - - - - - $class - - CF$UID - 586 - - Identifier - - CF$UID - 585 - - - - $class - - CF$UID - 586 - - Identifier - - CF$UID - 635 - - - BridJ - 9223372036854775807 - - $class - - CF$UID - 639 - - children - - CF$UID - 638 - - contentType - 0 - documentArchivableRepresentation - - CF$UID - 0 - - orientation - 0 - parent - - CF$UID - 0 - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 630 - - - - - $classes - - IDEWorkspaceTabControllerLayoutTreeNode - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTreeNode - - - $classes - - IDEWorkspaceTabControllerLayoutTree - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTree - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 642 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 643 - - - CF$UID - 645 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 644 - - - - 652 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 118 - - - CF$UID - 646 - - - - 224 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 648 - - - CF$UID - 649 - - - CF$UID - 650 - - - CF$UID - 651 - - - NS.objects - - - CF$UID - 652 - - - CF$UID - 648 - - - CF$UID - 670 - - - CF$UID - 680 - - - - Xcode.IDEKit.Navigator.Structure - SelectedNavigator - Xcode.IDEKit.Navigator.Logs - Xcode.IDEKit.Navigator.Issues - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 653 - - - CF$UID - 654 - - - CF$UID - 655 - - - CF$UID - 656 - - - CF$UID - 657 - - - CF$UID - 658 - - - CF$UID - 659 - - - NS.objects - - - CF$UID - 660 - - - CF$UID - 15 - - - CF$UID - 661 - - - CF$UID - 15 - - - CF$UID - 15 - - - CF$UID - 663 - - - CF$UID - 666 - - - - IDEVisibleRect - IDEUnsavedDocumentFilteringEnabled - IDENavigatorExpandedItemsBeforeFilteringSet - IDERecentDocumentFilteringEnabled - IDESCMStatusFilteringEnabled - IDESelectedObjects - IDEExpandedItemsSet - {{0, 0}, {259, 832}} - - $class - - CF$UID - 662 - - NS.objects - - - - $classes - - NSSet - NSObject - - $classname - NSSet - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 664 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 665 - - - CF$UID - 585 - - - - BridJ - - $class - - CF$UID - 662 - - NS.objects - - - CF$UID - 667 - - - CF$UID - 668 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 665 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 665 - - - CF$UID - 669 - - - - test.xcodeproj - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 671 - - - CF$UID - 672 - - - CF$UID - 673 - - - CF$UID - 674 - - - NS.objects - - - CF$UID - 675 - - - CF$UID - 676 - - - CF$UID - 15 - - - CF$UID - 679 - - - - IDELogNavigatorExpandedItemsStateKey - IDELogNavigatorSelectedObjectsStateKey - IDELogNavigatorRecentFilterStateKey - IDELogNavigatorVisibleRectStateKey - - $class - - CF$UID - 95 - - NS.objects - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 677 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 678 - - - - Build BridJ : 11:41:50 - {{0, 0}, {259, 832}} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 681 - - - CF$UID - 682 - - - CF$UID - 683 - - - CF$UID - 684 - - - CF$UID - 685 - - - CF$UID - 686 - - - CF$UID - 687 - - - CF$UID - 688 - - - CF$UID - 689 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 690 - - - CF$UID - 691 - - - CF$UID - 692 - - - CF$UID - 693 - - - CF$UID - 15 - - - CF$UID - 709 - - - CF$UID - 15 - - - CF$UID - 710 - - - - IDEErrorFilteringEnabled - IDEVisibleRect - IDECollapsedFiles - IDEExpandedIssues - IDESelectedNavigables - IDEShowsByType - IDECollapsedTypes - IDERecentFilteringEnabled - IDECollapsedGroups - {{0, 0}, {259, 810}} - - $class - - CF$UID - 426 - - NS.objects - - - - $class - - CF$UID - 426 - - NS.objects - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 694 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 695 - - - CF$UID - 699 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 696 - - - CF$UID - 697 - - - NS.objects - - - CF$UID - 131 - - - CF$UID - 698 - - - - id - ty - g - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 696 - - - CF$UID - 697 - - - NS.objects - - - CF$UID - 700 - - - CF$UID - 708 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 701 - - - CF$UID - 702 - - - CF$UID - 703 - - - CF$UID - 704 - - - NS.objects - - - CF$UID - 705 - - - CF$UID - 706 - - - CF$UID - 707 - - - CF$UID - 705 - - - - fullMessage - subissues - type - shortMessage - Cp: android_arm32_arm_androidndk_release/*.dylib: No such file or directory - - $class - - CF$UID - 95 - - NS.objects - - - Shell Script Invocation Error - i - - $class - - CF$UID - 426 - - NS.objects - - - - $class - - CF$UID - 426 - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 113 - - - NS.objects - - - CF$UID - 712 - - - - - $class - - CF$UID - 95 - - NS.objects - - - CF$UID - 713 - - - CF$UID - 715 - - - CF$UID - 717 - - - - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 523 - - - CF$UID - 714 - - - - 260 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 521 - - - CF$UID - 716 - - - - 1140 - - $class - - CF$UID - 92 - - NS.keys - - - CF$UID - 116 - - - CF$UID - 117 - - - NS.objects - - - CF$UID - 718 - - - CF$UID - 719 - - - - IDEUtilitiesArea - 260 - {{142, 31}, {1400, 952}} - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 510 - - - - - $top - - State - - CF$UID - 1 - - - $version - 100000 - - diff --git a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/BridJ.xcscheme b/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/BridJ.xcscheme deleted file mode 100644 index 896da8e84..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/BridJ.xcscheme +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist b/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 339c27869..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/BridJ.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - BridJ.xcscheme - - orderHint - 0 - - - SuppressBuildableAutocreation - - 90E6FBE615BC0B7F00A88421 - - primary - - - - - diff --git a/libraries/BridJ/src/main/cpp/bridj/CallbackHandler.c b/libraries/BridJ/src/main/cpp/bridj/CallbackHandler.c deleted file mode 100644 index 991262b52..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/CallbackHandler.c +++ /dev/null @@ -1,153 +0,0 @@ -#include "HandlersCommon.h" - -#if defined(DC__OS_Win32) && !defined(DC__OS_Win64) -#define JNI_CALL_MODE DC_CALL_C_X86_WIN32_STD -#else -#define JNI_CALL_MODE DC_CALL_C_DEFAULT -#endif - -void __cdecl CToJavaCallHandler_Sub(CallTempStruct* call, NativeToJavaCallbackCallInfo* info, DCArgs* args, DCValue* result) -{ - dcMode(call->vm, JNI_CALL_MODE); - //dcReset(call->vm); - - if (!info->fCallbackInstance) - { - throwException(call->env, "Trying to call a null callback instance !"); - return; - } - - dcArgPointer(call->vm, (DCpointer)call->env); - dcArgPointer(call->vm, info->fCallbackInstance); - dcArgPointer(call->vm, info->fInfo.fMethodID); - - if (info->fIsObjCBlock) - dcbArgPointer(args); // consume the pointer to the block instance ; TODO use it to reuse native callbacks !!! - - if (info->fIsGenericCallback) { - followArgsGenericJavaCallback(call, args, info->fInfo.nParams, info->fInfo.fParamTypes) - && - followCallGenericJavaCallback(call, info->fInfo.fReturnType, result, (void*)(*call->env)->CallObjectMethod); - } else { - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_TRUE, JNI_TRUE) - && - followCall(call, info->fInfo.fReturnType, result, info->fJNICallFunction, JNI_TRUE, JNI_FALSE); - } - -} - -char __cdecl CToJavaCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - CallTempStruct* call; - jthrowable exc; - NativeToJavaCallbackCallInfo* info = (NativeToJavaCallbackCallInfo*)userdata; - JNIEnv *env = GetEnv(); - initCallHandler(NULL, &call, env, &info->fInfo); - - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(env, call); - - CToJavaCallHandler_Sub(call, info, args, result); - - END_TRY(info->fInfo.fEnv, call); - - exc = (*env)->ExceptionOccurred(env); - if (exc) { - (*env)->ExceptionDescribe(env); - printStackTrace(env, exc); - //(*env)->ExceptionClear(env); - } - - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; - -} - -void __cdecl CPPToJavaCallHandler_Sub(CallTempStruct* call, NativeToJavaCallbackCallInfo* info, DCArgs* args, DCValue* result) -{ - void* cppObject; - jobject javaObject; - - dcMode(call->vm, JNI_CALL_MODE); - //dcReset(call->vm); - - if (info->fCallbackInstance) - { - throwException(call->env, "Not expecting a callback instance here !"); - return; - } - - cppObject = dcbArgPointer(args); - javaObject = getJavaObjectForNativePointer(call->env, cppObject); - dcArgPointer(call->vm, (DCpointer)call->env); - dcArgPointer(call->vm, javaObject); - dcArgPointer(call->vm, info->fInfo.fMethodID); - - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_TRUE, JNI_TRUE) - && - followCall(call, info->fInfo.fReturnType, result, info->fJNICallFunction, JNI_TRUE, JNI_FALSE); - -} -char __cdecl CPPToJavaCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - CallTempStruct* call; - jthrowable exc; - NativeToJavaCallbackCallInfo* info = (NativeToJavaCallbackCallInfo*)userdata; - JNIEnv *env = GetEnv(); - initCallHandler(NULL, &call, env, &info->fInfo); - - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(env, call); - - CPPToJavaCallHandler_Sub(call, info, args, result); - - END_TRY(info->fInfo.fEnv, call); - - exc = (*env)->ExceptionOccurred(env); - if (exc) { - (*env)->ExceptionDescribe(env); - printStackTrace(env, exc); - //(*env)->ExceptionClear(env); - // TODO rethrow in native world ? - } - - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} - -void __cdecl JavaToCCallHandler_Sub(CallTempStruct* call, JavaToNativeCallbackCallInfo* info, jobject instance, DCArgs* args, DCValue* result) -{ - void* callbackPtr; - - dcMode(call->vm, info->fInfo.fDCMode); - //dcReset(call->vm); - - callbackPtr = getNativeObjectPointer(call->env, instance, NULL); - - // printf("doJavaToCCallHandler(callback = %d) !!!\n", callback); - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_FALSE, JNI_FALSE) - && - followCall(call, info->fInfo.fReturnType, result, callbackPtr, JNI_FALSE, JNI_FALSE); -} -char __cdecl JavaToCCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - CallTempStruct* call; - JavaToNativeCallbackCallInfo* info = (JavaToNativeCallbackCallInfo*)userdata; - jobject instance = initCallHandler(args, &call, NULL, &info->fInfo); - - // printf("JavaToCCallHandler !!!\n"); - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(env, call); - - JavaToCCallHandler_Sub(call, info, instance, args, result); - - END_TRY(info->fInfo.fEnv, call); - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} diff --git a/libraries/BridJ/src/main/cpp/bridj/CppHandler.c b/libraries/BridJ/src/main/cpp/bridj/CppHandler.c deleted file mode 100644 index 8139d2afd..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/CppHandler.c +++ /dev/null @@ -1,134 +0,0 @@ -#include "HandlersCommon.h" - -void callSinglePointerArgVoidFunction(JNIEnv* env, void* constructor, void* thisPtr, int callMode) -{ - CallTempStruct* call; - initCallHandler(NULL, &call, env, NULL); - - dcMode(call->vm, callMode); - //dcReset(call->vm); - - dcArgPointer(call->vm, thisPtr); - dcCallVoid(call->vm, constructor); - - cleanupCallHandler(call); -} - -void* getNthVirtualMethodFromThis(JNIEnv* env, void* thisPtr, size_t virtualTableOffset, size_t virtualIndex) { - // Get virtual pointer table - void* ret; - void** vptr = (void**)*((void**)thisPtr); - if (!vptr) { - throwException(env, "Null virtual pointer table !"); - return NULL; - } - ret = (void*)vptr[virtualIndex]; - if (!ret) - throwException(env, "Failed to get the method pointer from the virtual table !"); - //THROW_EXCEPTION(env, "Failed to get the method pointer from the virtual table ! Virtual index = %lld, vtable ptr = 0x%llx", (long long int)virtualIndex, (long long unsigned int)PTR_TO_JLONG(vptr)); - - return ret; -} - -void JavaToVirtualMethodCallHandler_Sub(CallTempStruct* call, VirtualMethodCallInfo* info, jobject instance, DCArgs* args, DCValue* result) -{ - void* callbackFn; - void* thisPtr; - int nParams = info->fInfo.nParams; - ValueType *pParamTypes = info->fInfo.fParamTypes; - - dcMode(call->vm, info->fInfo.fDCMode); - //dcReset(call->vm); - - if (info->fHasThisPtrArg) { - if (nParams == 0 || *pParamTypes != eSizeTValue) { - throwException(call->env, "A C++ method must be bound with a method having a first argument of type long !"); - return; - } - thisPtr = dcbArgPointer(args); - if (!thisPtr) { - throwException(call->env, "Calling a method on a NULL C++ class pointer !"); - return; - } - nParams--; - pParamTypes++; - - } else { - thisPtr = getNativeObjectPointer(call->env, instance, info->fClass); - if (!thisPtr) { - throwException(call->env, "Failed to get the pointer to the target C++ instance of the method invocation !"); - return; - } - - //nParams--; - //pParamTypes++; - - } - - callbackFn = getNthVirtualMethodFromThis(call->env, thisPtr, info->fVirtualTableOffset, info->fVirtualIndex); - if (!callbackFn) { - throwException(call->env, "Virtual method pointer found in virtual table is NULL !"); - return; - } - - dcArgPointer(call->vm, thisPtr); - - followArgs(call, args, nParams, pParamTypes, JNI_FALSE, JNI_FALSE) - && - followCall(call, info->fInfo.fReturnType, result, callbackFn, JNI_FALSE, JNI_FALSE); - -} -char __cdecl JavaToVirtualMethodCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - VirtualMethodCallInfo* info = (VirtualMethodCallInfo*)userdata; - CallTempStruct* call; - jobject instance = initCallHandler(args, &call, NULL, &info->fInfo); - - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(call->env, call); - - JavaToVirtualMethodCallHandler_Sub(call, info, instance, args, result); - - END_TRY(info->fInfo.fEnv, call); - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} - -void JavaToCPPMethodCallHandler_Sub(CallTempStruct* call, FunctionCallInfo* info, jobject instance, DCArgs* args, DCValue* result) -{ - void* thisPtr; - - dcMode(call->vm, info->fInfo.fDCMode); - //dcReset(call->vm); - - thisPtr = getNativeObjectPointer(call->env, instance, info->fClass); - if (!thisPtr) { - throwException(call->env, "Failed to get the pointer to the target C++ instance of the method invocation !"); - return; - } - dcArgPointer(call->vm, thisPtr); - - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_FALSE, JNI_FALSE) - && - followCall(call, info->fInfo.fReturnType, result, info->fForwardedSymbol, JNI_FALSE, JNI_FALSE); -} -char __cdecl JavaToCPPMethodCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - FunctionCallInfo* info = (FunctionCallInfo*)userdata; - CallTempStruct* call; - jobject instance = initCallHandler(args, &call, NULL, &info->fInfo); - - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(call->env, call); - - JavaToCPPMethodCallHandler_Sub(call, info, instance, args, result); - - END_TRY(info->fInfo.fEnv, call); - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} - diff --git a/libraries/BridJ/src/main/cpp/bridj/Exceptions.c b/libraries/BridJ/src/main/cpp/bridj/Exceptions.c deleted file mode 100644 index 95f198ab4..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Exceptions.c +++ /dev/null @@ -1,195 +0,0 @@ -#include "bridj.hpp" -#include "jni.h" -#include "JNI.h" - -#include "Exceptions.h" - -#include -#include - -#ifdef _WIN32 -#include "windows.h" -#endif - -// http://msdn.microsoft.com/en-us/library/ms679356(VS.85).aspx - -extern jclass gLastErrorClass; -extern jmethodID gThrowNewLastErrorMethod; - -extern jclass gSignalErrorClass; -extern jmethodID gSignalErrorThrowMethod; - -extern jclass gWindowsErrorClass; -extern jmethodID gWindowsErrorThrowMethod; - -void throwException(JNIEnv* env, const char* message) { - if ((*env)->ExceptionCheck(env)) - return; // there is already a pending exception - (*env)->ExceptionClear(env); - (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/RuntimeException"), message ? message : "No message (TODO)"); -} - -void clearLastError(JNIEnv* env) { - errno = 0; -} - -#ifdef __GNUC__ -void throwSignalError(JNIEnv* env, int signal, int signalCode, jlong address) { - initMethods(env); - (*env)->CallStaticVoidMethod(env, gSignalErrorClass, gSignalErrorThrowMethod, signal, signalCode, address); -} -#else -void throwWindowsError(JNIEnv* env, int code, jlong info, jlong address) { - initMethods(env); - (*env)->CallStaticVoidMethod(env, gWindowsErrorClass, gWindowsErrorThrowMethod, code, info, address); -} -#endif - -#ifdef _WIN32 -jstring formatWin32ErrorMessage(JNIEnv* env, int errorCode) -{ - jstring message = NULL; - // http://msdn.microsoft.com/en-us/library/ms680582(v=vs.85).aspx - LPVOID lpMsgBuf; - int res; - res = FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - errorCode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR) &lpMsgBuf, - 0, - NULL - ); - if (res) { - message = (*env)->NewStringUTF(env, (LPCSTR)lpMsgBuf); - LocalFree(lpMsgBuf); - } else { -#define MESSAGE_BUF_SIZE 2048 - char lpMsgBuf[MESSAGE_BUF_SIZE + 1]; - //sprintf(lpMsgBuf, "Last Error Code = %d", errorCode); - message = (*env)->NewStringUTF(env, lpMsgBuf); - } - return message; -} -#endif - -void throwIfLastError(JNIEnv* env) { - int errorCode = 0; - int en = errno; - jstring message = NULL; - initMethods(env); - -#ifdef _WIN32 - errorCode = GetLastError(); - if (errorCode) - message = formatWin32ErrorMessage(env, errorCode); - -#endif - if (!errorCode) { - errorCode = en; - if (errorCode) { - const char* msg = strerror(errorCode); - message = msg ? (*env)->NewStringUTF(env, msg) : NULL; - } - } - if (errorCode) - (*env)->CallStaticVoidMethod(env, gLastErrorClass, gThrowNewLastErrorMethod, errorCode, message); -} - -jboolean assertThrow(JNIEnv* env, jboolean value, const char* message) { - if (!value) - throwException(env, message); - return value; -} - -//#if defined(ENABLE_PROTECTED_MODE) - -#ifdef __GNUC__ - -//Signals gSignals; - - -void TrapSignals(Signals* s) -{ - struct sigaction act; - memset(&act, 0, sizeof(struct sigaction)); - act.sa_sigaction = UnixExceptionHandler; - act.sa_flags = SA_SIGINFO | SA_NOCLDSTOP | SA_NOCLDWAIT; - -#define TRAP_SIG(sig) \ - sigaction(sig, &act, &s->fOld ## sig); - - TRAP_SIG(SIGSEGV) - TRAP_SIG(SIGBUS) - TRAP_SIG(SIGFPE) - TRAP_SIG(SIGCHLD) - TRAP_SIG(SIGILL) - TRAP_SIG(SIGABRT) - //TRAP_SIG(SIGTRAP) -} -void RestoreSignals(Signals* s) { - #define UNTRAP_SIG(sig) \ - sigaction(sig, &s->fOld ## sig, NULL); - - UNTRAP_SIG(SIGSEGV) - UNTRAP_SIG(SIGBUS) - UNTRAP_SIG(SIGFPE) - UNTRAP_SIG(SIGCHLD) - UNTRAP_SIG(SIGILL) - UNTRAP_SIG(SIGABRT) - //UNTRAP_SIG(SIGTRAP) -} - -void InitProtection() { - //TrapSignals(&gSignals); -} - -void CleanupProtection() { - //RestoreSignals(&gSignals); -} - -//void UnixExceptionHandler(int sig) { -void UnixExceptionHandler(int sig, siginfo_t* si, void * ctx) -{ - JNIEnv* env = GetEnv(); - CallTempStruct* call = getCurrentTempCallStruct(env); - if (!call) - return; - - call->signal = sig; - call->signalCode = si->si_code; - call->signalAddress = PTR_TO_JLONG(si->si_addr); - - longjmp(call->exceptionContext, sig); -} - -#else - -int WinExceptionFilter(LPEXCEPTION_POINTERS ex) { - switch (ex->ExceptionRecord->ExceptionCode) { - case 0x40010005: // Control+C - case 0x80000003: // Breakpoint - return EXCEPTION_CONTINUE_SEARCH; - } - return EXCEPTION_EXECUTE_HANDLER; -} -void WinExceptionHandler(JNIEnv* env, LPEXCEPTION_POINTERS ex) { - int code = ex->ExceptionRecord->ExceptionCode; - jlong info; - void* address; - - if ((code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR) && ex->ExceptionRecord->NumberParameters >= 2) { - info = ex->ExceptionRecord->ExceptionInformation[0]; - address = (void*)ex->ExceptionRecord->ExceptionInformation[1]; - } else { - info = 0; - address = ex->ExceptionRecord->ExceptionAddress; - } - - throwWindowsError(env, code, info, PTR_TO_JLONG(address)); -} - -//#endif //defined(ENABLE_PROTECTED_MODE) - -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/Exceptions.h b/libraries/BridJ/src/main/cpp/bridj/Exceptions.h deleted file mode 100644 index 00beb5c55..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Exceptions.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once -#ifndef _BRIDJ_EXCEPTIONS_H -#define _BRIDJ_EXCEPTIONS_H - -#include - -#define ENABLE_PROTECTED_MODE -#if defined(ENABLE_PROTECTED_MODE) - -#include "bridj.hpp" -//#include "Protected.h" -extern jboolean gProtected; - -#if defined(__GNUC__) - -void throwSignalError(JNIEnv* env, int signal, int signalCode, jlong address); - -static inline jboolean DoTrapSignals(CallTempStruct* call) { - //call->signal = call->signalCode = 0; - //call->signalAddress = 0; - TrapSignals(&call->signals); - return JNI_TRUE; -} - -#define BEGIN_TRY_BASE(env, call, prot) \ - if (!prot || !DoTrapSignals(call) || (call->signal = setjmp(call->exceptionContext)) == 0) \ - { - -#define END_TRY_BASE(env, call, prot, ifProt) \ - } else { \ - throwSignalError(env, call->signal, call->signalCode, call->signalAddress); \ - } \ - if (prot) { \ - RestoreSignals(&call->signals); \ - ifProt \ - } - -#define BEGIN_TRY(env, call) BEGIN_TRY_BASE(env, call, gProtected) - -#define BEGIN_TRY_CALL(env) \ - { \ - jboolean _protected = gProtected; \ - { \ - CallTempStruct* call = _protected ? getTempCallStruct(env) : NULL; \ - BEGIN_TRY_BASE(env, call, _protected); - -#define END_TRY(env, call) END_TRY_BASE(env, call, gProtected, ) - -#define END_TRY_CALL(env) \ - END_TRY_BASE(env, call, _protected, releaseTempCallStruct(env, call);) \ - } \ - } - -#else - -// WINDOWS -#define BEGIN_TRY(env, call) \ - { \ - LPEXCEPTION_POINTERS exceptionPointers = NULL; \ - __try \ - { - -#define END_TRY(env, call) \ - } \ - __except (gProtected ? WinExceptionFilter(exceptionPointers = GetExceptionInformation()) : EXCEPTION_CONTINUE_SEARCH) \ - { \ - WinExceptionHandler(env, exceptionPointers); \ - } \ - } - -#define BEGIN_TRY_CALL(env) BEGIN_TRY(env,) -#define END_TRY_CALL(env) END_TRY(env, ) - -#endif - -#else - -#define BEGIN_TRY(env, call) { -#define END_TRY(env, call) } - -#define BEGIN_TRY_CALL(env) { -#define END_TRY_CALL(env) } - -#endif // defined(ENABLE_PROTECTED_MODE) - -void clearLastError(JNIEnv* env); -void throwIfLastError(JNIEnv* env); - -#endif // _BRIDJ_EXCEPTIONS_H diff --git a/libraries/BridJ/src/main/cpp/bridj/FunctionHandler.c b/libraries/BridJ/src/main/cpp/bridj/FunctionHandler.c deleted file mode 100644 index ee496ca25..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/FunctionHandler.c +++ /dev/null @@ -1,38 +0,0 @@ -#include "HandlersCommon.h" - -void __cdecl JavaToFunctionCallHandler_Sub(CallTempStruct* call, FunctionCallInfo* info, DCArgs* args, DCValue* result) -{ - dcMode(call->vm, info->fInfo.fDCMode); - //dcReset(call->vm); - - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_FALSE, JNI_FALSE) - && - followCall(call, info->fInfo.fReturnType, result, info->fForwardedSymbol, JNI_FALSE, JNI_FALSE); - -} -char __cdecl JavaToFunctionCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - FunctionCallInfo* info = (FunctionCallInfo*)userdata; - CallTempStruct* call; - JNIEnv* env; - initCallHandler(args, &call, NULL, &info->fInfo); - env = call->env; - - call->pCallIOs = info->fInfo.fCallIOs; - - BEGIN_TRY(env, call); - - if (info->fCheckLastError) - clearLastError(info->fInfo.fEnv); - - JavaToFunctionCallHandler_Sub(call, info, args, result); - - if (info->fCheckLastError) - throwIfLastError(info->fInfo.fEnv); - - END_TRY(info->fInfo.fEnv, call); - - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} diff --git a/libraries/BridJ/src/main/cpp/bridj/GNUmakefile b/libraries/BridJ/src/main/cpp/bridj/GNUmakefile deleted file mode 100644 index 028e4a7c2..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/GNUmakefile +++ /dev/null @@ -1,142 +0,0 @@ -#////////////////////////////////////////////////////////////////////////////// -# -# Copyright (c) 2007,2009 Daniel Adler , -# Tassilo Philipp -# -# Permission to use, copy, modify, and distribute this software for any -# purpose with or without fee is hereby granted, provided that the above -# copyright notice and this permission notice appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -# -#////////////////////////////////////////////////////////////////////////////// - -#BUILD_CONFIG=debug - -LD=gcc -CXX=gcc - -COMPILE_PIC = 1 - -TOP = $(DYNCALL_HOME)/dyncall -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/prolog.gmake - -TARGET_DLL = bridj -INSTALL_LIB = 1 - -# uses some dyncall headers - no other dependencies. - -CPPFLAGS += -I$(DYNCALL_HOME)/dyncall -CPPFLAGS += -I$(DYNCALL_HOME)/dyncall/dyncall -CPPFLAGS += -I$(DYNCALL_HOME)/dyncall/dyncallback -CPPFLAGS += -I$(DYNCALL_HOME)/dyncall/dynload - -UNITS += Exceptions -UNITS += JNI -UNITS += Platform -UNITS += Pointer - -UNITS += HandlersCommon -UNITS += GenericJavaCallbackHandlers -UNITS += CallbackHandler -UNITS += CppHandler -UNITS += FunctionHandler -#UNITS += StructHandler -UNITS += CallbackHandler -UNITS += ThreadLocal -ifdef BUILD_OS_darwin -UNITS += ObjCHandler ObjCProxy ObjCBlocks -endif -ifdef BUILD_OS_iphoneos -UNITS += ObjCHandler ObjCProxy ObjCBlocks -endif -UNITS += RawNativeForwardCallback -#ifdef BUILD_TOOL_gcc -UNITS += RawNativeForwardCallback_arch -#endif - -ifndef BUILD_OS_darwin -CPPFLAGS += -Werror -CPPFLAGS += -D_DARWIN_C_SOURCE -endif - -CPPFLAGS += -std=c99 -#CFLAGS += -msse2 -msseregparm -#CFLAGS += -g - -# Lower requirement for GLIBC version number (2.2.5) : -# objdump -p src/main/resources/org/bridj/lib/linux_x64/bridj.so | fgrep 'Version References:' -A 100 -CPPFLAGS += -U_FORTIFY_SOURCE - -ifndef BUILD_OS_sunos -CPPFLAGS += -fno-stack-protector -funsafe-loop-optimizations -endif - -#LDFLAGS += -Wl,--as-needed -#LDFLAGS += -static-libgcc -Wl,-Bstatic -libc - -ifdef BUILD_OS_darwin -CPPFLAGS += -I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/ -CPPFLAGS += -DBRIDJ_OBJC_SUPPORT -LDFLAGS += -ldl -framework Foundation -all_load -endif - -ifdef BUILD_OS_iphoneos -CPPFLAGS += -I/Users/ochafik/src/jamvm/src -CPPFLAGS += -DBRIDJ_OBJC_SUPPORT -LDFLAGS += -ldl -framework Foundation -all_load -endif - -ifndef BUILD_OS_android -ifndef BUILD_ARCH_arm -LDFLAGS += -lpthread -endif -endif - -ifdef BUILD_OS_linux -CPPFLAGS += -D_GNU_SOURCE -CPPFLAGS += -I/usr/lib/jvm/java-6-sun/include/ -CPPFLAGS += -I/usr/lib/jvm/java-6-sun/include/linux -CPPFLAGS += -I/usr/lib/jvm/java-6-openjdk/include/ -CPPFLAGS += -I/usr/lib/jvm/java-6-openjdk/include/linux -endif - -ifdef BUILD_OS_sunos -# http://gcc.gnu.org/onlinedocs/gcc/Solaris-2-Options.html -CPPFLAGS += -D__EXTENSIONS__ -CPPFLAGS += -I/usr/jdk/instances/jdk1.5.0/include -CPPFLAGS += -I/usr/jdk/instances/jdk1.5.0/include/solaris -LDFLAGS += -mimpure-text -LDFLAGS += -L/opt/csw/gcc4/lib -endif - -ifdef BUILD_OS_darwin -CPPFLAGS += -mmacosx-version-min=10.4 -LDFLAGS += -mmacosx-version-min=10.4 -endif - -ifdef BUILD_CONFIG_debug -CPPFLAGS += -O0 -g -else -CPPFLAGS += -O3 -endif - -#LINK_LIBS += stdc++ - -#CPPFLAGS += -DJNICALL=__cdecl -DJNIEXPORT=__cdecl - -#CPPFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -#LDFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden - -LINK_DIRS += $(DYNCALL_HOME)/dyncall/dyncall/$(BUILD_DIR) -LINK_DIRS += $(DYNCALL_HOME)/dyncall/dynload/$(BUILD_DIR) -LINK_DIRS += $(DYNCALL_HOME)/dyncall/dyncallback/$(BUILD_DIR) -LINK_LIBS += dyncall_s dynload_s dyncallback_s - -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/epilog.gmake diff --git a/libraries/BridJ/src/main/cpp/bridj/GenericJavaCallbackHandlers.c b/libraries/BridJ/src/main/cpp/bridj/GenericJavaCallbackHandlers.c deleted file mode 100644 index ab2c264b2..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/GenericJavaCallbackHandlers.c +++ /dev/null @@ -1,200 +0,0 @@ -#include "HandlersCommon.h" -#include -#include "JNI.h" - -extern jclass gObjectClass; -extern jclass gCLongClass; -extern jclass gSizeTClass; - -jboolean followArgsGenericJavaCallback(CallTempStruct* call, DCArgs* args, int nTypes, ValueType* pTypes) -{ - JNIEnv* env = call->env; - int iParam; - jobjectArray arr; - - initMethods(env); - - arr = (*env)->NewObjectArray(env, nTypes, gObjectClass, NULL); - - for (iParam = 0; iParam < nTypes; iParam++) { - ValueType type = pTypes[iParam]; - jobject arg = NULL; - switch (type) { - case eIntFlagSet: - arg = BoxInt(env, (jint)getFlagValue(env, (jobject)dcbArgPointer(args))); - break; - case eIntValue: - arg = BoxInt(env, dcbArgInt(args)); - break; - case eTimeTObjectValue: - case eSizeTObjectValue: - case eCLongObjectValue: - arg = dcbArgPointer(args); - break; - - #define ARG_UNBOXED_INTEGRAL(type, capitalized) \ - { \ - type v; \ - if (sizeof(type) == 4) \ - v = (type)dcbArgInt(args); \ - else \ - v = (type)dcbArgLongLong(args); \ - arg = Box ## capitalized(env, v); \ - break; \ - } - - case eCLongValue: - ARG_UNBOXED_INTEGRAL(long, CLong); - break; - case eSizeTValue: - ARG_UNBOXED_INTEGRAL(size_t, SizeT); - break; - case eLongValue: - arg = BoxLong(env, dcbArgLongLong(args)); - break; - case eShortValue: - arg = BoxShort(env, dcbArgShort(args)); - break; - case eBooleanValue: - case eByteValue: - arg = BoxByte(env, dcbArgChar(args)); - break; - case eFloatValue: - arg = BoxFloat(env, dcbArgFloat(args)); - break; - case eDoubleValue: - arg = BoxDouble(env, dcbArgDouble(args)); - break; - case ePointerValue: - { - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - void* ptr = dcbArgPointer(args); - arg = createPointerFromIO(env, ptr, callIO); - } - break; - case eWCharValue: - switch (sizeof(wchar_t)) { - case 1: - arg = BoxChar(env, dcbArgChar(args)); - break; - case 2: - arg = BoxChar(env, dcbArgShort(args)); - break; - case 4: - arg = BoxInt(env, dcbArgInt(args)); - break; - default: - throwException(env, "Invalid wchar_t size for argument !"); - return JNI_FALSE; - } - break; - default: - throwException(env, "Invalid argument value type !"); - return JNI_FALSE; - - } - (*env)->SetObjectArrayElement(env, arr, iParam, arg); - } - dcArgPointer(call->vm, arr); - - if ((*env)->ExceptionCheck(env)) - return JNI_FALSE; - return JNI_TRUE; -} - -jboolean followCallGenericJavaCallback(CallTempStruct* call, ValueType returnType, DCValue* result, void* callback) -{ - JNIEnv* env = call->env; - jobject ret = dcCallPointer(call->vm, callback); - HACK_REFETCH_ENV(); - if ((*env)->ExceptionCheck(env)) - return JNI_FALSE; - - switch (returnType) { - case eIntValue: - result->i = UnboxInt(env, ret); - break; - case eLongValue: - result->l = UnboxLong(env, ret); - break; - case eShortValue: - result->s = UnboxShort(env, ret); - break; - case eByteValue: - result->c = UnboxByte(env, ret); - break; - case eFloatValue: - result->f = UnboxFloat(env, ret); - break; - case eDoubleValue: - result->d = UnboxDouble(env, ret); - break; - case eBooleanValue: - result->c = UnboxBoolean(env, ret); - break; - #define RETURN_UNBOXED_INTEGRAL(type, capitalized) \ - { \ - jlong v; \ - if ((*env)->IsInstanceOf(env, ret, g ## capitalized ## Class)) \ - v = Unbox ## capitalized(env, ret); \ - else \ - v = UnboxLong(env, ret); \ - if (sizeof(type) == 4) \ - result->i = (jint)v; \ - else \ - result->L = (jlong)v; \ - } - #define RETURN_BOXED_INTEGRAL(type, capitalized) \ - { \ - if ((*env)->IsInstanceOf(env, ret, g ## capitalized ##Class)) \ - result->p = ret; \ - else \ - result->p = Box ## capitalized(env, (type)UnboxLong(env, ret)); \ - } - case eCLongValue: - RETURN_UNBOXED_INTEGRAL(long, CLong) - break; - case eCLongObjectValue: - RETURN_BOXED_INTEGRAL(long, CLong); - break; - case eSizeTValue: - RETURN_UNBOXED_INTEGRAL(size_t, SizeT); - break; - case eSizeTObjectValue: - RETURN_BOXED_INTEGRAL(size_t, SizeT); - break; - case eTimeTObjectValue: - RETURN_BOXED_INTEGRAL(time_t, TimeT); - break; - case eVoidValue: - assert(ret == NULL); - break; - case eIntFlagSet: - result->i = (jint)getFlagValue(env, ret); - break; - case ePointerValue: - result->p = ret ? getPointerPeer(env, (void*)ret) : NULL; - call->pCallIOs++; - break; - case eWCharValue: - switch (sizeof(wchar_t)) { - case 1: - result->c = (char)UnboxChar(env, ret); - break; - case 2: - result->s = (short)UnboxChar(env, ret); - break; - case 4: - result->i = UnboxInt(env, ret); - break; - default: - throwException(env, "Invalid wchar_t size !"); - return JNI_FALSE; - } - break; - default: - throwException(env, "Invalid return value type !"); - return JNI_FALSE; - } - return JNI_TRUE; -} diff --git a/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.c b/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.c deleted file mode 100644 index 3387eda06..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.c +++ /dev/null @@ -1,345 +0,0 @@ -#include "HandlersCommon.h" -#include "JNI.h" - -jboolean followArgs(CallTempStruct* call, DCArgs* args, int nTypes, ValueType* pTypes, jboolean toJava, jboolean isVarArgs) -{ - JNIEnv* env = call->env; - int iParam; - //printf("ARGS : %d args\n", (int)nTypes); - for (iParam = 0; iParam < nTypes; iParam++) { - ValueType type = pTypes[iParam]; - switch (type) { - case eIntFlagSet: - { - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - if (toJava) { - int flags = dcbArgInt(args); - jobject obj = createPointerFromIO(env, JLONG_TO_PTR ((jlong)flags), callIO); - dcArgPointer(call->vm, obj); - } else { - int arg = (jint)getFlagValue(env, (jobject)dcbArgPointer(args)); - if (isVarArgs) - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); - else - dcArgInt(call->vm, arg); - } - } - break; - case eIntValue: - { - int arg = dcbArgInt(args); - if (isVarArgs) - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); - else - dcArgInt(call->vm, arg); - } - break; - #define ARG_BOXED_INTEGRAL(type, capitalized) \ - { \ - if (toJava) { \ - type arg = (sizeof(type) == 4) ? (type)dcbArgInt(args) : (type)dcbArgLongLong(args); \ - dcArgPointer(call->vm, Box ## capitalized(env, arg)); \ - } else { \ - jobject parg = dcbArgPointer(args); \ - jlong arg = Unbox ## capitalized(env, parg); \ - if (isVarArgs) \ - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); \ - else if (sizeof(type) == 4) \ - dcArgInt(call->vm, (jint)arg); \ - else \ - dcArgLongLong(call->vm, (jlong)arg); \ - } \ - } - #define ARG_UNBOXED_INTEGRAL(type, capitalized) \ - { \ - if (toJava) { \ - type arg = (sizeof(type) == 4) ? (type)dcbArgInt(args) : (type)dcbArgLongLong(args); \ - dcArgLongLong(call->vm, (jlong)arg); \ - } else { \ - jlong arg = dcbArgLongLong(args); \ - if (isVarArgs) \ - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); \ - else if (sizeof(type) == 4) \ - dcArgInt(call->vm, (jint)arg); \ - else \ - dcArgLongLong(call->vm, (jlong)arg); \ - } \ - } - case eCLongValue: - ARG_UNBOXED_INTEGRAL(long, CLong); - break; - case eSizeTValue: - ARG_UNBOXED_INTEGRAL(size_t, SizeT); - break; - case eCLongObjectValue: - ARG_BOXED_INTEGRAL(long, CLong); - break; - case eSizeTObjectValue: - ARG_BOXED_INTEGRAL(size_t, SizeT); - break; - case eTimeTObjectValue: - ARG_BOXED_INTEGRAL(time_t, TimeT); - break; - case eLongValue: - dcArgLongLong(call->vm, dcbArgLongLong(args)); - break; - case eShortValue: - { - short arg = dcbArgShort(args); - if (isVarArgs) - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); - else - dcArgShort(call->vm, arg); - } - break; - case eBooleanValue: - case eByteValue: - { - char arg = dcbArgChar(args); - if (isVarArgs) - dcArgPointer(call->vm, (void*)(ptrdiff_t)arg); - else - dcArgChar(call->vm, arg); - } - break; - case eFloatValue: - { - float arg = dcbArgFloat(args); - if (isVarArgs) - dcArgDouble(call->vm, arg); - else - dcArgFloat(call->vm, arg); - } - break; - case eDoubleValue: - dcArgDouble(call->vm, dcbArgDouble(args)); - break; - case ePointerValue: - { - void* ptr = dcbArgPointer(args); - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - if (toJava) - { - ptr = createPointerFromIO(env, ptr, callIO); - } else { - ptr = ptr ? getPointerPeer(env, ptr) : NULL; - // printf("ARG POINTER = %d\n", ptr); - } - dcArgPointer(call->vm, ptr); - } - break; - case eWCharValue: - switch (sizeof(wchar_t)) { - case 1: - dcArgChar(call->vm, dcbArgChar(args)); - break; - case 2: - dcArgShort(call->vm, dcbArgShort(args)); - break; - case 4: - dcArgInt(call->vm, dcbArgInt(args)); - break; - default: - throwException(env, "Invalid wchar_t size for argument !"); - return JNI_FALSE; - } - break; - case eNativeObjectValue: { - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - DCstruct* s = getStructFromIO(env, callIO); - void* pStruct = getNativeObjectPointerWithIO(env, dcbArgPointer(args), callIO); - if (!s) { - throwException(env, "Failed to get low-level struct representation !"); - return JNI_FALSE; - } - if (!pStruct) { - throwException(env, "Struct by value cannot be null !"); - return JNI_FALSE; - } - dcArgStruct(call->vm, s, pStruct); - break; - } - case eEllipsis: { - if (toJava) { - throwException(env, "Calling Java ellipsis is not supported yet !"); - return JNI_FALSE; - } else { - jobjectArray arr = (jobjectArray)dcbArgPointer(args); - jsize n = (*env)->GetArrayLength(env, arr), i; - - for (i = 0; i < n; i++) { - jobject arg = (*env)->GetObjectArrayElement(env, arr, i); - #define TEST_INSTANCEOF(cl, st) \ - if ((*env)->IsInstanceOf(env, arg, cl)) st; - - if (arg == NULL) - dcArgPointer(call->vm, getPointerPeer(env, (void*)NULL)); - else - // As per the C standard for varargs, all ints are promoted to ptrdiff_t and float is promoted to double : - TEST_INSTANCEOF(gIntClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)UnboxInt(env, arg))) - else - TEST_INSTANCEOF(gLongClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)UnboxLong(env, arg))) - else - TEST_INSTANCEOF(gShortClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)UnboxShort(env, arg))) - else - TEST_INSTANCEOF(gByteClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)UnboxByte(env, arg))) - else - TEST_INSTANCEOF(gBooleanClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)(char)UnboxBoolean(env, arg))) - else - TEST_INSTANCEOF(gCharClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)(short)UnboxChar(env, arg))) - else - TEST_INSTANCEOF(gDoubleClass, dcArgDouble(call->vm, UnboxDouble(env, arg))) - else - TEST_INSTANCEOF(gFloatClass, dcArgDouble(call->vm, UnboxFloat(env, arg))) - else - TEST_INSTANCEOF(gCLongClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)(long)UnboxCLong(env, arg))) - else - TEST_INSTANCEOF(gSizeTClass, dcArgPointer(call->vm, (void*)(ptrdiff_t)UnboxSizeT(env, arg))) - else - TEST_INSTANCEOF(gPointerClass, dcArgPointer(call->vm, getPointerPeer(env, (void*)arg))) - else { - throwException(env, "Invalid value type in ellipsis"); - return JNI_FALSE; - } - } - } - break; - } - default: - throwException(env, "Invalid argument value type !"); - return JNI_FALSE; - } - } - if ((*env)->ExceptionCheck(env)) - return JNI_FALSE; - return JNI_TRUE; -} - -jboolean followCall(CallTempStruct* call, ValueType returnType, DCValue* result, void* callback, jboolean bCallingJava, jboolean forceVoidReturn) -{ - JNIEnv* env = call->env; - switch (returnType) { -#define CALL_CASE(valueType, capCase, hiCase, uni) \ - case valueType: \ - result->uni = dcCall ## capCase(call->vm, callback); \ - break; - CALL_CASE(eIntValue, Int, INT, i) - CALL_CASE(eLongValue, LongLong, LONGLONG, l) - CALL_CASE(eShortValue, Short, SHORT, s) - CALL_CASE(eFloatValue, Float, FLOAT, f) - CALL_CASE(eDoubleValue, Double, DOUBLE, d) - case eBooleanValue: - CALL_CASE(eByteValue, Char, CHAR, c) - case eCLongValue: - result->L = (jlong)dcCallLong(call->vm, callback); - break; - case eSizeTValue: - result->L = (size_t)dcCallPointer(call->vm, callback); - break; - - #define CALL_BOXED_INTEGRAL(type, capitalized) \ - if (bCallingJava) { \ - time_t tt = Unbox ## capitalized(env, dcCallPointer(call->vm, callback)); \ - if (sizeof(type) == 4) \ - result->i = (jint)tt; \ - else \ - result->l = (jlong)tt; \ - } else { \ - type tt = (sizeof(type) == 4) ? (type)dcCallInt(call->vm, callback) : (type)dcCallLongLong(call->vm, callback); \ - result->p = Box ## capitalized(env, tt); \ - } - - case eCLongObjectValue: - CALL_BOXED_INTEGRAL(long, CLong); - break; - case eSizeTObjectValue: - CALL_BOXED_INTEGRAL(size_t, SizeT); - break; - case eTimeTObjectValue: - CALL_BOXED_INTEGRAL(time_t, TimeT); - break; - case eVoidValue: - dcCallVoid(call->vm, callback); - break; - case eIntFlagSet: - { - int flags = dcCallInt(call->vm, callback); - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - jobject obj = createPointerFromIO(env, JLONG_TO_PTR ((jlong)flags), callIO); - - result->p = obj; - } - break; - case ePointerValue: - { - void* ptr = dcCallPointer(call->vm, callback); - if (bCallingJava) - result->p = ptr ? getPointerPeer(env, ptr) : NULL; - //result->p = ptr; - else - { - jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL; - //printf("RETURNED POINTER = %d\n", ptr); - result->p = createPointerFromIO(env, ptr, callIO); - } - } - break; - case eWCharValue: - switch (sizeof(wchar_t)) { - case 1: - result->c = dcCallChar(call->vm, callback); - break; - case 2: - result->s = dcCallShort(call->vm, callback); - break; - case 4: - result->i = dcCallInt(call->vm, callback); - break; - default: - throwException(env, "Invalid wchar_t size !"); - return JNI_FALSE; - } - break; - default: - if (forceVoidReturn) - { - dcCallVoid(call->vm, callback); - break; - } - throwException(env, "Invalid return value type !"); - return JNI_FALSE; - } - HACK_REFETCH_ENV(); - if (bCallingJava && (*env)->ExceptionCheck(env)) - return JNI_FALSE; - return JNI_TRUE; -} - -jobject initCallHandler(DCArgs* args, CallTempStruct** callOut, JNIEnv* env, CommonCallbackInfo* info) -{ - jobject instance = NULL; - CallTempStruct* call = NULL; - - if (args) { - env = (JNIEnv*)dcbArgPointer(args); // first arg = Java env - instance = dcbArgPointer(args); // skip second arg = jclass or jobject - } - if (env) { - //initMethods(env); - *callOut = call = getTempCallStruct(env); - call->env = env; - } else - *callOut = NULL; - - if (gLog && call && info) - logCall(call->env, info->fMethod); - - return instance; -} - -void cleanupCallHandler(CallTempStruct* call) -{ - dcReset(call->vm); - releaseTempCallStruct(call->env, call); -} - diff --git a/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.h b/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.h deleted file mode 100644 index 9cdb45ebd..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/HandlersCommon.h +++ /dev/null @@ -1,13 +0,0 @@ -#include "bridj.hpp" -#include -#include "Exceptions.h" - -jboolean followArgs(CallTempStruct* call, DCArgs* args, int nTypes, ValueType* pTypes, jboolean toJava, jboolean isVarArgs); - -jboolean followCall(CallTempStruct* call, ValueType returnType, DCValue* result, void* callback, jboolean bCallingJava, jboolean forceVoidReturn); - -jobject initCallHandler(DCArgs* args, CallTempStruct** callOut, JNIEnv* env, CommonCallbackInfo* info); -void cleanupCallHandler(CallTempStruct* call); - -jboolean followArgsGenericJavaCallback(CallTempStruct* call, DCArgs* args, int nTypes, ValueType* pTypes) ; -jboolean followCallGenericJavaCallback(CallTempStruct* call, ValueType returnType, DCValue* result, void* callback); diff --git a/libraries/BridJ/src/main/cpp/bridj/JNI.c b/libraries/BridJ/src/main/cpp/bridj/JNI.c deleted file mode 100644 index e53a0130c..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/JNI.c +++ /dev/null @@ -1,1314 +0,0 @@ -#include "org_bridj_JNI.h" -#include "JNI.h" - -#include "dyncallback/dyncall_callback.h" -#include "dynload/dynload.h" -#include "RawNativeForwardCallback.h" - -#include "bridj.hpp" -#include -#include -#include -#include -#include "Exceptions.h" -#include - -#pragma warning(disable: 4152) -#pragma warning(disable: 4189) // local variable initialized but unreferenced // TODO remove this ! -#pragma warning(disable:4055) // cast from data pointer to function pointer - -jboolean gLog = JNI_FALSE; -jboolean gProtected = JNI_FALSE; - -jclass gObjectClass = NULL; -jclass gPointerClass = NULL; -//jclass gFlagSetClass = NULL; -jclass gValuedEnumClass = NULL; -jclass gBridJClass = NULL; -jclass gCallIOClass = NULL; -jclass gLastErrorClass = NULL; -jclass gRunnableClass = NULL; -jmethodID gRunnableRunMethod = NULL; -jmethodID gAddressMethod = NULL; -jmethodID gGetPeerMethod = NULL; -jmethodID gCreatePeerMethod = NULL; -jmethodID gGetValuedEnumValueMethod = NULL; -jmethodID gGetJavaObjectFromNativePeerMethod = NULL; -//jmethodID gNewFlagSetMethod = NULL; -jmethodID gThrowNewLastErrorMethod = NULL; -jmethodID gGetCallIOsMethod = NULL; -jmethodID gGetCallIOStructMethod = NULL; -jmethodID gCallIOGetPeerMethod = NULL; -jmethodID gNewCallIOInstance = NULL; -jmethodID gLogCallMethod = NULL; -jfieldID gLogCallsField = NULL; -jfieldID gProtectedModeField = NULL; - -jclass gMethodCallInfoClass = NULL; -jfieldID gFieldId_javaSignature = NULL; -jfieldID gFieldId_dcSignature = NULL; -jfieldID gFieldId_paramsValueTypes = NULL; -jfieldID gFieldId_returnValueType = NULL; -jfieldID gFieldId_forwardedPointer = NULL; -jfieldID gFieldId_virtualIndex = NULL; -jfieldID gFieldId_virtualTableOffset = NULL; -jfieldID gFieldId_javaCallback = NULL; -jfieldID gFieldId_isGenericCallback = NULL; -jfieldID gFieldId_isObjCBlock = NULL; -jfieldID gFieldId_direct = NULL; -jfieldID gFieldId_startsWithThis = NULL; -jfieldID gFieldId_isCPlusPlus = NULL; -jfieldID gFieldId_isStatic = NULL; -jfieldID gFieldId_bNeedsThisPointer = NULL; -jfieldID gFieldId_bThrowLastError = NULL; -jfieldID gFieldId_dcCallingConvention = NULL; -jfieldID gFieldId_symbolName = NULL; -jfieldID gFieldId_nativeClass = NULL; -jfieldID gFieldId_methodName = NULL; -jfieldID gFieldId_method = NULL; -jfieldID gFieldId_declaringClass = NULL; - -#ifdef __GNUC__ -jclass gSignalErrorClass = NULL; -jmethodID gSignalErrorThrowMethod = NULL; -#else -jclass gWindowsErrorClass = NULL; -jmethodID gWindowsErrorThrowMethod = NULL; -#endif - -/*jclass gCLongClass = NULL; -jclass gSizeTClass = NULL; -jmethodID gCLongValueMethod = NULL; -jmethodID gSizeTValueMethod = NULL; -jlong UnboxCLong(JNIEnv* env, jobject v) { - return (*env)->CallLongMethod(env, v, gCLongValueMethod); -} -jlong UnboxSizeT(JNIEnv* env, jobject v) { \ - return (*env)->CallLongMethod(env, v, gSizeTValueMethod); -}*/ - -#define BOX_METHOD_IMPL(prim, shortName, methShort, type, letter) \ -jclass g ## shortName ## Class = NULL; \ -jmethodID g ## shortName ## ValueOfMethod = NULL; \ -jmethodID g ## shortName ## ValueMethod = NULL; \ -jobject Box ## shortName(JNIEnv* env, type v) { \ - return (*env)->CallStaticObjectMethod(env, g ## shortName ## Class, g ## shortName ## ValueOfMethod, (jlong)v); \ -} \ -type Unbox ## shortName(JNIEnv* env, jobject v) { \ - HACK_REFETCH_ENV(); \ - return (type)(*env)->Call ## methShort ## Method(env, v, g ## shortName ## ValueMethod); \ -} -// - -BOX_METHOD_IMPL("org/bridj/TimeT", TimeT, Long, time_t, "J"); -BOX_METHOD_IMPL("org/bridj/SizeT", SizeT, Long, jlong, "J"); -BOX_METHOD_IMPL("org/bridj/CLong", CLong, Long, long, "J"); -BOX_METHOD_IMPL("java/lang/Integer", Int, Int, jint, "I"); -BOX_METHOD_IMPL("java/lang/Long", Long, Long, jlong, "J"); -BOX_METHOD_IMPL("java/lang/Short", Short, Short, jshort, "S"); -BOX_METHOD_IMPL("java/lang/Byte", Byte, Byte, jbyte, "B"); -BOX_METHOD_IMPL("java/lang/Boolean", Boolean, Boolean, jboolean, "Z"); -BOX_METHOD_IMPL("java/lang/Character", Char, Char, jchar, "C"); -BOX_METHOD_IMPL("java/lang/Float", Float, Float, jfloat, "F"); -BOX_METHOD_IMPL("java/lang/Double", Double, Double, jdouble, "D"); - -int main() {} - -void printStackTrace(JNIEnv* env, jthrowable ex) { - jthrowable cause; - jclass thClass = (*env)->FindClass(env, "java/lang/Throwable"); - jmethodID printMeth = (*env)->GetMethodID(env, thClass, "printStackTrace", "()V"); - jmethodID causeMeth = (*env)->GetMethodID(env, thClass, "getCause", "()Ljava/lang/Throwable;"); - if (!ex) { - jclass exClass = (*env)->FindClass(env, "java/lang/RuntimeException"); - jmethodID initMeth = (*env)->GetMethodID(env, exClass, "", "()V"); - ex = (jthrowable)(*env)->NewObject(env, exClass, initMeth); - } - (*env)->CallVoidMethod(env, (jobject)ex, printMeth); - cause = (jthrowable)(*env)->CallObjectMethod(env, ex, causeMeth); - if (cause) - printStackTrace(env, cause); -} - -JavaVM* gJVM = NULL; -#define JNI_VERSION JNI_VERSION_1_4 - -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* jvm, void* x) { - gJVM = jvm; - return JNI_VERSION; -} - -JNIEnv* GetEnv() { - JNIEnv* env = NULL; - if ((*gJVM)->GetEnv(gJVM, (void*)&env, JNI_VERSION) != JNI_OK) { - if ((*gJVM)->AttachCurrentThreadAsDaemon(gJVM, (void*)&env, NULL) != JNI_OK) { - printf("BridJ: Cannot attach current JVM thread !\n"); - return NULL; - } - } - return env; -} - -void InitProtection(); -void initPlatformMethods(JNIEnv* env); - -void initMethods(JNIEnv* env) { - //InitProtection(); - - if (!gAddressMethod) - { - gObjectClass = FIND_GLOBAL_CLASS("java/lang/Object"); - gRunnableClass = FIND_GLOBAL_CLASS("java/lang/Runnable"); - - #define INIT_PRIM(prim, shortName, methShort, type, letter) \ - g ## shortName ## Class = FIND_GLOBAL_CLASS(prim); \ - g ## shortName ## ValueMethod = (*env)->GetMethodID(env, g ## shortName ## Class, #type "Value", "()" letter); \ - g ## shortName ## ValueOfMethod = (*env)->GetStaticMethodID(env, g ## shortName ## Class, "valueOf", "(" letter ")L" prim ";"); - - INIT_PRIM("org/bridj/SizeT", SizeT, Long, long, "J"); - INIT_PRIM("org/bridj/TimeT", TimeT, Long, long, "J"); - INIT_PRIM("org/bridj/CLong", CLong, Long, long, "J"); - INIT_PRIM("java/lang/Integer", Int, Int, int, "I"); - INIT_PRIM("java/lang/Long", Long, Long, long, "J"); - INIT_PRIM("java/lang/Short", Short, Short, short, "S"); - INIT_PRIM("java/lang/Byte", Byte, Byte, byte, "B"); - INIT_PRIM("java/lang/Boolean", Boolean, Boolean, boolean, "Z"); - INIT_PRIM("java/lang/Character", Char, Char, char, "C"); - INIT_PRIM("java/lang/Float", Float, Float, float, "F"); - INIT_PRIM("java/lang/Double", Double, Double, double, "D"); - - gBridJClass = FIND_GLOBAL_CLASS("org/bridj/BridJ"); - //gFlagSetClass = FIND_GLOBAL_CLASS("org/bridj/FlagSet"); - gValuedEnumClass = FIND_GLOBAL_CLASS("org/bridj/ValuedEnum"); - //gStructFieldsIOClass = FIND_GLOBAL_CLASS("org/bridj/StructFieldsIO"); - gPointerClass = FIND_GLOBAL_CLASS("org/bridj/Pointer"); - gMethodCallInfoClass = FIND_GLOBAL_CLASS("org/bridj/MethodCallInfo"); - gCallIOClass = FIND_GLOBAL_CLASS("org/bridj/CallIO"); - gLastErrorClass = FIND_GLOBAL_CLASS("org/bridj/LastError"); - - gRunnableRunMethod = (*env)->GetMethodID(env, gRunnableClass, "run", "()V"); - //gGetTempCallStruct = (*env)->GetStaticMethodID(env, gBridJClass, "getTempCallStruct", "()J"); - //gReleaseTempCallStruct = (*env)->GetStaticMethodID(env, gBridJClass, "releaseTempCallStruct", "(J)V"); - gGetValuedEnumValueMethod = (*env)->GetMethodID(env, gValuedEnumClass, "value", "()J"); - gGetJavaObjectFromNativePeerMethod = (*env)->GetStaticMethodID(env, gBridJClass, "getJavaObjectFromNativePeer", "(J)" OBJECT_SIG); - //gNewFlagSetMethod = (*env)->GetStaticMethodID(env, gFlagSetClass, "fromValue", "(J" CLASS_SIG ")Lorg/bridj/FlagSet;"); - gAddressMethod = (*env)->GetStaticMethodID(env, gPointerClass, "getAddress", "(Lorg/bridj/NativeObject;" CLASS_SIG ")J"); - gGetPeerMethod = (*env)->GetMethodID(env, gPointerClass, "getPeer", "()J"); - gCreatePeerMethod = (*env)->GetStaticMethodID(env, gPointerClass, "pointerToAddress", "(JLjava/lang/Class;)" POINTER_SIG); - gThrowNewLastErrorMethod = (*env)->GetStaticMethodID(env, gLastErrorClass, "throwNewInstance", "(I" STRING_SIG ")V"); - gGetCallIOsMethod = (*env)->GetMethodID(env, gMethodCallInfoClass, "getCallIOs", "()[Lorg/bridj/CallIO;"); - gNewCallIOInstance = (*env)->GetMethodID(env, gCallIOClass, "newInstance", "(J)" OBJECT_SIG); - gGetCallIOStructMethod = (*env)->GetMethodID(env, gCallIOClass, "getDCStruct", "()J"); - gCallIOGetPeerMethod = (*env)->GetMethodID(env, gCallIOClass, "getPeer", "(" OBJECT_SIG ")J"); - - gLogCallMethod = (*env)->GetStaticMethodID(env, gBridJClass, "logCall", "(" METHOD_SIG ")V"); - gLogCallsField = (*env)->GetStaticFieldID(env, gBridJClass, "logCalls", "Z"); - gProtectedModeField = (*env)->GetStaticFieldID(env, gBridJClass, "protectedMode", "Z"); - -#ifdef __GNUC__ - gSignalErrorClass = FIND_GLOBAL_CLASS("org/bridj/SignalError"); - gSignalErrorThrowMethod = (*env)->GetStaticMethodID(env, gSignalErrorClass, "throwNew", "(IIJ)V"); -#else - gWindowsErrorClass = FIND_GLOBAL_CLASS("org/bridj/WindowsError"); - gWindowsErrorThrowMethod = (*env)->GetStaticMethodID(env, gWindowsErrorClass, "throwNew", "(IJJ)V"); -#endif - -#define GETFIELD_ID(out, name, sig) \ - if (!(gFieldId_ ## out = (*env)->GetFieldID(env, gMethodCallInfoClass, name, sig))) \ - throwException(env, "Failed to get the field " #name " in MethodCallInfo !"); - - - GETFIELD_ID(javaSignature , "javaSignature" , STRING_SIG ); - GETFIELD_ID(dcSignature , "dcSignature" , STRING_SIG ); - GETFIELD_ID(symbolName , "symbolName" , STRING_SIG ); - GETFIELD_ID(nativeClass , "nativeClass" , "J" ); - GETFIELD_ID(methodName , "methodName" , STRING_SIG ); - GETFIELD_ID(method , "method" , METHOD_SIG ); - GETFIELD_ID(declaringClass , "declaringClass" , CLASS_SIG ); - GETFIELD_ID(paramsValueTypes , "paramsValueTypes" , "[I" ); - GETFIELD_ID(returnValueType , "returnValueType" , "I" ); - GETFIELD_ID(forwardedPointer , "forwardedPointer" , "J" ); - GETFIELD_ID(virtualIndex , "virtualIndex" , "I" ); - GETFIELD_ID(virtualTableOffset , "virtualTableOffset" , "I" ); - //GETFIELD_ID(javaCallback , "javaCallback" , "Lorg/bridj/Callback;" ); - GETFIELD_ID(javaCallback , "javaCallback" , OBJECT_SIG ); - GETFIELD_ID(isGenericCallback , "isGenericCallback" , "Z" ); - GETFIELD_ID(isObjCBlock , "isObjCBlock" , "Z" ); - GETFIELD_ID(direct , "direct" , "Z" ); - GETFIELD_ID(isCPlusPlus , "isCPlusPlus" , "Z" ); - GETFIELD_ID(isStatic , "isStatic" , "Z" ); - GETFIELD_ID(startsWithThis , "startsWithThis" , "Z" ); - GETFIELD_ID(bNeedsThisPointer , "bNeedsThisPointer" , "Z" ); - GETFIELD_ID(bThrowLastError , "bThrowLastError" , "Z" ); - GETFIELD_ID(dcCallingConvention, "dcCallingConvention" , "I" ); - - gLog = (*env)->GetStaticBooleanField(env, gBridJClass, gLogCallsField); - gProtected = (*env)->GetStaticBooleanField(env, gBridJClass, gProtectedModeField); - - initPlatformMethods(env); - } -} - -jlong getFlagValue(JNIEnv *env, jobject valuedEnum) -{ - initMethods(env); - return valuedEnum ? (*env)->CallLongMethod(env, valuedEnum, gGetValuedEnumValueMethod) : 0; -} - -/* -jobject newFlagSet(JNIEnv *env, jlong value, jobject enumClass) -{ - env = GetEnv(); - //initMethods(env); - return (*env)->CallStaticObjectMethod(env, gFlagSetClass, gNewFlagSetMethod, value, enumClass); -} -*/ - -//void main() {} -jmethodID GetMethodIDOrFail(JNIEnv* env, jclass declaringClass, const char* methName, const char* javaSig) -{ - jmethodID id = (*env)->GetStaticMethodID(env, declaringClass, methName, javaSig); - if (!id) { - (*env)->ExceptionClear(env); - id = (*env)->GetMethodID(env, declaringClass, methName, javaSig); - } - if (!id) - throwException(env, "Couldn't find this method !"); - - return id; -} - - -jobject createPointerFromIO(JNIEnv *env, void* ptr, jobject callIO) { - jobject instance; - jlong addr; - if (!callIO) - return NULL; - initMethods(env); - addr = PTR_TO_JLONG(ptr); - instance = (*env)->CallObjectMethod(env, callIO, gNewCallIOInstance, addr); - return instance; -} -DCstruct* getStructFromIO(JNIEnv *env, jobject callIO) { - jlong peer = (*env)->CallLongMethod(env, callIO, gGetCallIOStructMethod); - return (DCstruct*)JLONG_TO_PTR(peer); -} -DCstruct* getNativeObjectPointerWithIO(JNIEnv *env, jobject instance, jobject callIO) { - jlong peer = (*env)->CallLongMethod(env, callIO, gCallIOGetPeerMethod, instance); - return (DCstruct*)JLONG_TO_PTR(peer); -} - -void* getPointerPeer(JNIEnv *env, jobject pointer) { - initMethods(env); - return pointer ? JLONG_TO_PTR((*env)->CallLongMethod(env, pointer, gGetPeerMethod)) : NULL; -} - -void* getNativeObjectPointer(JNIEnv *env, jobject instance, jclass targetClass) { - initMethods(env); - return JLONG_TO_PTR((*env)->CallStaticLongMethod(env, gPointerClass, gAddressMethod, instance, targetClass)); -} - - -jobject getJavaObjectForNativePointer(JNIEnv *env, void* nativeObject) { - initMethods(env); - return (*env)->CallStaticObjectMethod(env, gBridJClass, gGetJavaObjectFromNativePeerMethod, PTR_TO_JLONG(nativeObject)); -} - -JNIEXPORT void JNICALL Java_org_bridj_Platform_init(JNIEnv *env, jclass clazz) -{ - initThreadLocal(env); - //initMethods(env); -} - -#include "../../../../target/generated-resources/org/bridj/Init.c" - -jlong JNICALL Java_org_bridj_JNI_getEnv(JNIEnv *env, jclass clazz) -{ - return PTR_TO_JLONG(env); -} - -jlong JNICALL Java_org_bridj_JNI_getJVM(JNIEnv *env, jclass clazz) -{ - return PTR_TO_JLONG(gJVM); -} - -jobject JNICALL Java_org_bridj_JNI_refToObject(JNIEnv *env, jclass clazz, jlong refPeer) -{ - return JLONG_TO_PTR(refPeer); -} - -void logCall(JNIEnv *env, jobject method) { - initMethods(env); - (*env)->CallStaticObjectMethod(env, gBridJClass, gLogCallMethod, method); -} - -jlong JNICALL Java_org_bridj_JNI_newGlobalRef(JNIEnv *env, jclass clazz, jobject obj) -{ - return obj ? PTR_TO_JLONG(GLOBAL_REF(obj)) : 0; -} - -void JNICALL Java_org_bridj_JNI_deleteGlobalRef(JNIEnv *env, jclass clazz, jlong ref) -{ - if (ref) - DEL_GLOBAL_REF((jobject)JLONG_TO_PTR(ref)); -} -jlong JNICALL Java_org_bridj_JNI_newWeakGlobalRef(JNIEnv *env, jclass clazz, jobject obj) -{ - return obj ? PTR_TO_JLONG(WEAK_GLOBAL_REF(obj)) : 0; -} - -void JNICALL Java_org_bridj_JNI_deleteWeakGlobalRef(JNIEnv *env, jclass clazz, jlong ref) -{ - if (ref) - DEL_WEAK_GLOBAL_REF((jobject)JLONG_TO_PTR(ref)); -} -void JNICALL Java_org_bridj_JNI_callSinglePointerArgVoidFunction(JNIEnv *env, jclass clazz, jlong constructor, jlong thisPtr, jint callMode) -{ - callSinglePointerArgVoidFunction(env, JLONG_TO_PTR(constructor), JLONG_TO_PTR(thisPtr), callMode); -} - -jlong JNICALL Java_org_bridj_JNI_getDirectBufferAddress(JNIEnv *env, jobject jthis, jobject buffer) { - jlong ret; - ret = !buffer ? 0 : PTR_TO_JLONG((*env)->GetDirectBufferAddress(env, buffer)); - return ret; -} -jlong JNICALL Java_org_bridj_JNI_getDirectBufferCapacity(JNIEnv *env, jobject jthis, jobject buffer) { - jlong ret; - ret = !buffer ? 0 : (*env)->GetDirectBufferCapacity(env, buffer); - return ret; -} - -#if defined(DC_UNIX) -//char* dlerror(); -#else -jstring formatWin32ErrorMessage(JNIEnv* env, int errorCode); -#endif - -#if defined(DC_WINDOWS) -wchar_t* ConvertStringToWide(JNIEnv* env, jstring javaString) { - const char* utfStr = GET_CHARS(javaString); - int len = (*env)->GetStringLength(env, javaString); - wchar_t* wideStr = (wchar_t*)malloc((len + 1) * sizeof(wchar_t)); - wideStr[len] = L'\0'; - MultiByteToWideChar(CP_UTF8, 0, utfStr, -1, wideStr, len); - RELEASE_CHARS(javaString, utfStr); - return wideStr; -} -#endif - -#if defined(DC_UNIX) -#include "dlfcn.h" -#endif - -jlong JNICALL Java_org_bridj_JNI_loadLibrary(JNIEnv *env, jclass clazz, jstring pathStr) -{ - jlong ret = 0; -#if defined(DC_WINDOWS) - wchar_t* widePath = ConvertStringToWide(env, pathStr); - const char* path = (char*)(void*)widePath; - //int pathStrLength = (*env)->GetStringLength(env, pathStr); - //wchar_t* widePath = (wchar_t*)malloc((pathStrLength + 1) * sizeof(wchar_t)); - //widePath[pathStrLength] = L'\0'; - //MultiByteToWideChar(CP_UTF8, 0, rawPath, -1, widePath, pathStrLength); - //ret = PTR_TO_JLONG((DLLib*) LoadLibraryW(widePath)); -#else - const char* rawPath = GET_CHARS(pathStr); - const char* path = rawPath; - //ret = PTR_TO_JLONG(dlLoadLibrary(path)); -#endif - ret = PTR_TO_JLONG(dlLoadLibrary(path)); - if (!ret) { -#if defined(DC_UNIX) - printf("# BridJ: dlopen error when loading %s : %s\n", path, dlerror()); -#elif defined(DC_WINDOWS) - jstring message = formatWin32ErrorMessage(env, GetLastError()); - wchar_t* msg = ConvertStringToWide(env, message); - //const char* msg = GET_CHARS(message); - wprintf(L"# BridJ: LoadLibrary error when loading %s : %s\n", widePath, msg); - //RELEASE_CHARS(message, msg); -#endif - } -#if defined(DC_WINDOWS) - free(widePath); -#else - RELEASE_CHARS(pathStr, rawPath); -#endif - return ret; -} - -void JNICALL Java_org_bridj_JNI_freeLibrary(JNIEnv *env, jclass clazz, jlong libHandle) -{ - dlFreeLibrary((DLLib*)JLONG_TO_PTR(libHandle)); -} - -jlong JNICALL Java_org_bridj_JNI_loadLibrarySymbols(JNIEnv *env, jclass clazz, jstring libPath) -{ - DLSyms* pSyms = NULL; - const char* libPathStr; - wchar_t* widePath; - - // Force protection (override global protection switch) - jboolean gProtected = JNI_TRUE; - BEGIN_TRY_CALL(env); - -#if defined(DC_WINDOWS) - widePath = ConvertStringToWide(env, libPath); - libPathStr = (char*)(void*)widePath; - pSyms = dlSymsInit(libPathStr); - free(widePath); -#else - libPathStr = GET_CHARS(libPath); - pSyms = dlSymsInit(libPathStr); - RELEASE_CHARS(libPath, libPathStr); -#endif - END_TRY_CALL(env); - return PTR_TO_JLONG(pSyms); - -} -void JNICALL Java_org_bridj_JNI_freeLibrarySymbols(JNIEnv *env, jclass clazz, jlong symbolsHandle) -{ - DLSyms* pSyms = (DLSyms*)JLONG_TO_PTR(symbolsHandle); - //BEGIN_TRY_CALL(env); - dlSymsCleanup(pSyms); - //END_TRY_CALL(env); -} - -jarray JNICALL Java_org_bridj_JNI_getLibrarySymbols(JNIEnv *env, jclass clazz, jlong libHandle, jlong symbolsHandle) -{ - // Force protection (override global protection switch) - jboolean gProtected = JNI_TRUE; - jclass stringClass; - jarray ret = NULL; - DLSyms* pSyms = (DLSyms*)JLONG_TO_PTR(symbolsHandle); - int count, i; - //BEGIN_TRY_CALL(env); - if (!pSyms) - return NULL; - - count = dlSymsCount(pSyms); - //printf("getLibrarySymbols has %d symbols\n", (int)count); - stringClass = (*env)->FindClass(env, "java/lang/String"); - ret = (*env)->NewObjectArray(env, count, stringClass, 0); - for (i = 0; i < count; i++) { - const char* name = dlSymsName(pSyms, i); - if (!name) - continue; - (*env)->SetObjectArrayElement(env, ret, i, (*env)->NewStringUTF(env, name)); - } - //END_TRY_CALL(env); - return ret; -} - - -jstring JNICALL Java_org_bridj_JNI_findSymbolName(JNIEnv *env, jclass clazz, jlong libHandle, jlong symbolsHandle, jlong address) -{ - const char* name = dlSymsNameFromValue((DLSyms*)JLONG_TO_PTR(symbolsHandle), JLONG_TO_PTR(address)); - return name ? (*env)->NewStringUTF(env, name) : NULL; -} - -jlong JNICALL Java_org_bridj_JNI_findSymbolInLibrary(JNIEnv *env, jclass clazz, jlong libHandle, jstring nameStr) -{ - const char* name; - void* ptr; - if (!nameStr) - return 0; - - name = GET_CHARS(nameStr); - - ptr = dlFindSymbol((DLLib*)JLONG_TO_PTR(libHandle), name); - RELEASE_CHARS(nameStr, name); - return PTR_TO_JLONG(ptr); -} - -jobject JNICALL Java_org_bridj_JNI_newDirectByteBuffer(JNIEnv *env, jobject jthis, jlong peer, jlong length) { - jobject ret; - ret = (*env)->NewDirectByteBuffer(env, JLONG_TO_PTR(peer), length); - return ret; -} - -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_createCallTempStruct(JNIEnv* env, jclass clazz) { - CallTempStruct* s = MALLOC_STRUCT(CallTempStruct); - s->vm = dcNewCallVM(1024); - return PTR_TO_JLONG(s); -} -JNIEXPORT void JNICALL Java_org_bridj_JNI_deleteCallTempStruct(JNIEnv* env, jclass clazz, jlong handle) { - CallTempStruct* s = (CallTempStruct*)JLONG_TO_PTR(handle); - dcFree(s->vm); - free(s); -} - -char getDCReturnType(JNIEnv* env, ValueType returnType) -{ - switch (returnType) { -#define RET_TYPE_CASE(valueType, hiCase) \ - case valueType: \ - return DC_SIGCHAR_ ## hiCase; - case eIntFlagSet: - RET_TYPE_CASE(eIntValue, INT) - RET_TYPE_CASE(eLongValue, LONGLONG) - RET_TYPE_CASE(eShortValue, SHORT) - RET_TYPE_CASE(eFloatValue, FLOAT) - RET_TYPE_CASE(eDoubleValue, DOUBLE) - case eBooleanValue: - RET_TYPE_CASE(eByteValue, CHAR) - case eCLongObjectValue: - case eSizeTObjectValue: - case eTimeTObjectValue: - return DC_SIGCHAR_POINTER; - case eCLongValue: - return DC_SIGCHAR_LONGLONG; - case eSizeTValue: - return DC_SIGCHAR_LONGLONG; - case eVoidValue: - return DC_SIGCHAR_VOID; - case ePointerValue: - return DC_SIGCHAR_POINTER; - case eWCharValue: - switch (sizeof(wchar_t)) { - case 1: - return DC_SIGCHAR_CHAR; - case 2: - return DC_SIGCHAR_SHORT; - case 4: - return DC_SIGCHAR_INT; - default: - throwException(env, "wchar_t size not supported yet !"); - return DC_SIGCHAR_VOID; - } - // TODO - case eNativeObjectValue: - return DC_SIGCHAR_POINTER; - default: - throwException(env, "Return ValueType not supported yet !"); - return DC_SIGCHAR_VOID; - } -} - - -void registerJavaFunction(JNIEnv* env, jclass declaringClass, const char* methName, const char* methSig, void (*callback)()) -{ - JNINativeMethod meth; - if (!callback) { - throwException(env, "No callback !"); - return; - } - if (!methName) { - throwException(env, "No methodName !"); - return; - } - if (!methSig) { - throwException(env, "No methodSignature !"); - return; - } - if (!declaringClass) { - throwException(env, "No declaringClass !"); - return; - } - - meth.fnPtr = callback; - meth.name = (char*)methName; - meth.signature = (char*)methSig; - (*env)->RegisterNatives(env, declaringClass, &meth, 1); - -} - -void initCommonCallInfo( - struct CommonCallbackInfo* info, - JNIEnv *env, - jclass declaringClass, - jstring methodName, - jstring javaSignature, - jint callMode, - jint nParams, - jint returnValueType, - jintArray paramsValueTypes, - jobjectArray callIOs, - jboolean registerJava, - jobject method -) { - const char* javaSig, *methName; - javaSig = (char*)GET_CHARS(javaSignature); - methName = (char*)GET_CHARS(methodName); - - info->fEnv = env; - info->fDCMode = callMode; - info->fReturnType = (ValueType)returnValueType; - info->nParams = nParams; - if (nParams) { - info->fParamTypes = (ValueType*)malloc(nParams * sizeof(jint)); - (*env)->GetIntArrayRegion(env, paramsValueTypes, 0, nParams, (jint*)info->fParamTypes); - } else { - info->fParamTypes = NULL; - } - info->fDCReturnType = getDCReturnType(env, info->fReturnType); - - if (callIOs) - { - jsize n = (*env)->GetArrayLength(env, callIOs), i; - if (n) - { - info->fCallIOs = (jobject*)malloc((n + 1) * sizeof(jobject)); - for (i = 0; i < n; i++) { - jobject obj = (*env)->GetObjectArrayElement(env, callIOs, i); - if (obj) - obj = GLOBAL_REF(obj); - info->fCallIOs[i] = obj; - } - info->fCallIOs[n] = NULL; - } - } else { - info->fCallIOs = NULL; - } - - if (registerJava) - registerJavaFunction(env, declaringClass, methName, javaSig, info->fDCCallback); - - info->fMethodID = GetMethodIDOrFail(env, declaringClass, methName, javaSig); - info->fMethod = GLOBAL_REF(method); - - - RELEASE_CHARS(javaSignature, javaSig); - RELEASE_CHARS(methodName, methName); -} - -void* getJNICallFunction(JNIEnv* env, ValueType valueType) { - switch (valueType) { - case eIntValue: - return (*env)->CallIntMethod; - case eTimeTObjectValue: - case eSizeTObjectValue: - case eCLongObjectValue: - return (*env)->CallObjectMethod; - case eSizeTValue: - case eCLongValue: - case eLongValue: - return (*env)->CallLongMethod; - case eFloatValue: - return (*env)->CallFloatMethod; - case eDoubleValue: - return (*env)->CallDoubleMethod; - case eBooleanValue: - return (*env)->CallBooleanMethod; - case eByteValue: - return (*env)->CallByteMethod; - case eShortValue: - return (*env)->CallShortMethod; - case eWCharValue: - return (*env)->CallCharMethod; - case eVoidValue: - return (*env)->CallVoidMethod; - case eNativeObjectValue: - case ePointerValue: - return (*env)->CallObjectMethod; - default: - throwException(env, "Unhandled type in getJNICallFunction !"); - return NULL; - } -} - - -void* getJNICallStaticFunction(JNIEnv* env, ValueType valueType) { - switch (valueType) { - case eIntValue: - return (*env)->CallStaticIntMethod; - case eTimeTObjectValue: - case eSizeTObjectValue: - case eCLongObjectValue: - return (*env)->CallStaticObjectMethod; - case eSizeTValue: - case eCLongValue: - case eLongValue: - return (*env)->CallStaticLongMethod; - case eFloatValue: - return (*env)->CallStaticFloatMethod; - case eDoubleValue: - return (*env)->CallStaticDoubleMethod; - case eBooleanValue: - return (*env)->CallStaticBooleanMethod; - case eByteValue: - return (*env)->CallStaticByteMethod; - case eShortValue: - return (*env)->CallStaticShortMethod; - case eWCharValue: - return (*env)->CallStaticCharMethod; - case eVoidValue: - return (*env)->CallStaticVoidMethod; - case eNativeObjectValue: - case ePointerValue: - return (*env)->CallStaticObjectMethod; - default: - throwException(env, "Unhandled type in getJNICallStaticFunction !"); - return NULL; - } -} - -#define NEW_STRUCTS(n, type, name) \ - struct type *name = NULL; \ - size_t sizeof ## name = n * sizeof(struct type); \ - name = (struct type*)malloc(sizeof ## name); \ - memset(name, 0, sizeof ## name); - - -void freeCommon(JNIEnv* env, CommonCallbackInfo* info) -{ - if (info->nParams && info->fParamTypes) { - free(info->fParamTypes); - } - - if (info->fCallIOs) - { - jobject* ptr = info->fCallIOs; - while (*ptr) { - DEL_GLOBAL_REF(*ptr); - ptr++; - } - free(info->fCallIOs); - } - - DEL_GLOBAL_REF(info->fMethod); - - if (info->fDCCallback) { - dcbFreeCallback((DCCallback*)info->fDCCallback); - } -} - -#define GetField_javaSignature() jstring javaSignature = (*env)->GetObjectField( env, methodCallInfo, gFieldId_javaSignature ) -#define GetField_dcSignature() jstring dcSignature = (*env)->GetObjectField( env, methodCallInfo, gFieldId_dcSignature ) -#define GetField_symbolName() jstring symbolName = (*env)->GetObjectField( env, methodCallInfo, gFieldId_symbolName ) -#define GetField_nativeClass() jlong nativeClass = (*env)->GetLongField( env, methodCallInfo, gFieldId_nativeClass ) -#define GetField_methodName() jstring methodName = (*env)->GetObjectField( env, methodCallInfo, gFieldId_methodName ) -#define GetField_method() jobject method = (*env)->GetObjectField( env, methodCallInfo, gFieldId_method ) -#define GetField_paramsValueTypes() jintArray paramsValueTypes = (*env)->GetObjectField( env, methodCallInfo, gFieldId_paramsValueTypes ) -#define GetField_javaCallback() jobject javaCallback = (*env)->GetObjectField( env, methodCallInfo, gFieldId_javaCallback ) -#define GetField_isGenericCallback() jboolean isGenericCallback = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_isGenericCallback ) -#define GetField_isObjCBlock() jboolean isObjCBlock = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_isObjCBlock ) -#define GetField_forwardedPointer() jlong forwardedPointer = (*env)->GetLongField( env, methodCallInfo, gFieldId_forwardedPointer ) -#define GetField_returnValueType() jint returnValueType = (*env)->GetIntField( env, methodCallInfo, gFieldId_returnValueType ) -#define GetField_virtualIndex() jint virtualIndex = (*env)->GetIntField( env, methodCallInfo, gFieldId_virtualIndex ) -#define GetField_virtualTableOffset() jint virtualTableOffset = (*env)->GetIntField( env, methodCallInfo, gFieldId_virtualTableOffset ) -#define GetField_dcCallingConvention() jint dcCallingConvention = (*env)->GetIntField( env, methodCallInfo, gFieldId_dcCallingConvention ) -#define GetField_direct() jboolean direct = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_direct ) -#define GetField_isCPlusPlus() jboolean isCPlusPlus = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_isCPlusPlus ) -#define GetField_isStatic() jboolean isStatic = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_isStatic ) -#define GetField_startsWithThis() jboolean startsWithThis = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_startsWithThis ) -#define GetField_bNeedsThisPointer() jboolean bNeedsThisPointer = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_bNeedsThisPointer ) -#define GetField_bThrowLastError() jboolean bThrowLastError = (*env)->GetBooleanField( env, methodCallInfo, gFieldId_bThrowLastError ) -#define GetField_declaringClass() jstring declaringClass = (jclass)(*env)->GetObjectField(env, methodCallInfo, gFieldId_declaringClass ) -#define GetField_nParams() jsize nParams = (*env)->GetArrayLength( env, paramsValueTypes ) -#define GetField_callIOs() jobjectArray callIOs = (*env)->CallObjectMethod( env, methodCallInfo, gGetCallIOsMethod ) - - -#define BEGIN_INFOS_LOOP(type) \ - jsize i, n = (*env)->GetArrayLength(env, methodCallInfos); \ - NEW_STRUCTS(n, type, infos); \ - initMethods(env); \ - for (i = 0; i < n; i++) \ - { \ - type* info = &infos[i]; \ - jobject methodCallInfo = (*env)->GetObjectArrayElement(env, methodCallInfos, i); - -#define END_INFOS_LOOP() } - -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_createCToJavaCallback( - JNIEnv *env, - jclass clazz, - jobject methodCallInfo -) { - initMethods(env); - { - struct NativeToJavaCallbackCallInfo* info = NULL; - { - const char* dcSig; - - GetField_javaSignature() ; - GetField_dcSignature() ; - GetField_symbolName() ; - GetField_nativeClass() ; - GetField_methodName() ; - GetField_method() ; - GetField_paramsValueTypes() ; - GetField_javaCallback() ; - GetField_isGenericCallback() ; - GetField_isObjCBlock() ; - //GetField_forwardedPointer() ; - GetField_returnValueType() ; - //GetField_virtualIndex() ; - //GetField_virtualTableOffset() ; - GetField_dcCallingConvention() ; - //GetField_direct() ; - //GetField_startsWithThis() ; - //GetField_bNeedsThisPointer() ; - GetField_isCPlusPlus() ; - GetField_declaringClass() ; - GetField_nParams() ; - GetField_callIOs() ; - - { - info = MALLOC_STRUCT(NativeToJavaCallbackCallInfo); - memset(info, 0, sizeof(struct NativeToJavaCallbackCallInfo)); - - // TODO DIRECT C++ virtual thunk - dcSig = GET_CHARS(dcSignature); - - info->fInfo.fDCCallback = dcbNewCallback(dcSig, isCPlusPlus ? CPPToJavaCallHandler : CToJavaCallHandler, info); - info->fCallbackInstance = WEAK_GLOBAL_REF(javaCallback); - info->fIsGenericCallback = isGenericCallback; - info->fIsObjCBlock = isObjCBlock; - - info->fJNICallFunction = getJNICallFunction(env, (ValueType)returnValueType); - - RELEASE_CHARS(dcSignature, dcSig); - - initCommonCallInfo(&info->fInfo, env, declaringClass, methodName, javaSignature, dcCallingConvention, nParams, returnValueType, paramsValueTypes, callIOs, JNI_FALSE, method); - } - } - return PTR_TO_JLONG(info); - } -} -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getActualCToJavaCallback( - JNIEnv *env, - jclass clazz, - jlong handle -) { - struct NativeToJavaCallbackCallInfo* info = (struct NativeToJavaCallbackCallInfo*)JLONG_TO_PTR(handle); - return PTR_TO_JLONG(info->fInfo.fDCCallback); -} -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeCToJavaCallback( - JNIEnv *env, - jclass clazz, - jlong handle -) { - struct NativeToJavaCallbackCallInfo* info = (struct NativeToJavaCallbackCallInfo*)JLONG_TO_PTR(handle); - DEL_WEAK_GLOBAL_REF(info->fCallbackInstance); - freeCommon(env, &info->fInfo); - free(info); -} - - -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaToCCallbacks( - JNIEnv *env, - jclass clazz, - jobjectArray methodCallInfos -) { - initMethods(env); - { - BEGIN_INFOS_LOOP(JavaToNativeCallbackCallInfo) - - GetField_javaSignature() ; - GetField_dcSignature() ; - //GetField_symbolName() ; - //GetField_nativeClass() ; - GetField_methodName() ; - GetField_method() ; - GetField_paramsValueTypes() ; - //GetField_javaCallback() ; - //GetField_forwardedPointer() ; - GetField_returnValueType() ; - //GetField_virtualIndex() ; - //GetField_virtualTableOffset() ; - GetField_dcCallingConvention() ; - //GetField_direct() ; - //GetField_startsWithThis() ; - //GetField_bNeedsThisPointer() ; - GetField_declaringClass() ; - GetField_nParams() ; - GetField_callIOs() ; - - { - //void* callback; - const char* dcSig; - - // TODO DIRECT C++ virtual thunk - dcSig = GET_CHARS(dcSignature); - info->fInfo.fDCCallback = dcbNewCallback(dcSig, JavaToCCallHandler/* NativeToJavaCallHandler*/, info); - RELEASE_CHARS(dcSignature, dcSig); - - initCommonCallInfo(&info->fInfo, env, declaringClass, methodName, javaSignature, dcCallingConvention, nParams, returnValueType, paramsValueTypes, callIOs, JNI_TRUE, method); - } - END_INFOS_LOOP() - return PTR_TO_JLONG(infos); - } -} -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeJavaToCCallbacks( - JNIEnv *env, - jclass clazz, - jlong handle, - jint size -) { - JavaToNativeCallbackCallInfo* infos = (JavaToNativeCallbackCallInfo*)JLONG_TO_PTR(handle); - jint i; - if (!infos) - return; - for (i = 0; i < size; i++) { - freeCommon(env, &infos[i].fInfo); - } - free(infos); -} - -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToCFunctions( - JNIEnv *env, - jclass clazz, - jobjectArray methodCallInfos -) { - initMethods(env); - { - BEGIN_INFOS_LOOP(FunctionCallInfo) - - GetField_javaSignature() ; - GetField_dcSignature() ; - GetField_symbolName() ; - GetField_methodName() ; - GetField_method() ; - GetField_paramsValueTypes() ; - GetField_forwardedPointer() ; - GetField_returnValueType() ; - GetField_dcCallingConvention() ; - GetField_direct() ; - GetField_isCPlusPlus() ; - GetField_isStatic() ; - GetField_startsWithThis() ; - GetField_declaringClass() ; - GetField_bThrowLastError() ; - GetField_nParams() ; - GetField_callIOs() ; - - { - info->fForwardedSymbol = JLONG_TO_PTR(forwardedPointer); - if (isCPlusPlus && !isStatic && declaringClass) - info->fClass = GLOBAL_REF(declaringClass); - - info->fCheckLastError = bThrowLastError; - -#ifndef NO_DIRECT_CALLS - if (direct && !gProtected && forwardedPointer) - info->fInfo.fDCCallback = (DCCallback*)dcRawCallAdapterSkipTwoArgs((void (*)())info->fForwardedSymbol, dcCallingConvention); -#endif - if (!info->fInfo.fDCCallback) { - const char* ds = GET_CHARS(dcSignature); - //info->fInfo.fDCCallback = dcbNewCallback(ds, JavaToFunctionCallHandler, info); - info->fInfo.fDCCallback = dcbNewCallback(ds, isCPlusPlus && !isStatic ? JavaToCPPMethodCallHandler : JavaToFunctionCallHandler, info); - RELEASE_CHARS(dcSignature, ds); - } - initCommonCallInfo(&info->fInfo, env, declaringClass, methodName, javaSignature, dcCallingConvention, nParams, returnValueType, paramsValueTypes, callIOs, JNI_TRUE, method); - } - END_INFOS_LOOP() - return PTR_TO_JLONG(infos); - } -} -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeCFunctionBindings( - JNIEnv *env, - jclass clazz, - jlong handle, - jint size -) { - FunctionCallInfo* infos = (FunctionCallInfo*)JLONG_TO_PTR(handle); - jint i; - if (!infos) - return; - for (i = 0; i < size; i++) { - if (infos[i].fClass) - DEL_GLOBAL_REF(infos[i].fClass); - freeCommon(env, &infos[i].fInfo); - } - free(infos); -} -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToObjCMethods( - JNIEnv *env, - jclass clazz, - jobjectArray methodCallInfos -) { -#ifdef BRIDJ_OBJC_SUPPORT - initMethods(env); - { - BEGIN_INFOS_LOOP(JavaToObjCCallInfo) - - GetField_javaSignature() ; - GetField_dcSignature() ; - GetField_symbolName() ; - GetField_nativeClass() ; - GetField_methodName() ; - GetField_method() ; - GetField_paramsValueTypes() ; - //GetField_javaCallback() ; - //GetField_forwardedPointer() ; - GetField_returnValueType() ; - //GetField_virtualIndex() ; - //GetField_virtualTableOffset() ; - GetField_dcCallingConvention() ; - //GetField_direct() ; - //GetField_startsWithThis() ; - //GetField_bNeedsThisPointer() ; - GetField_declaringClass() ; - GetField_nParams() ; - GetField_callIOs() ; - - { - const char* ds, *methName; - - // TODO DIRECT ObjC thunk - methName = (char*)GET_CHARS(symbolName); - //ds = GET_CHARS(dcSignature); - - info->fInfo.fDCCallback = dcbNewCallback(ds, JavaToObjCCallHandler, info); - info->fSelector = sel_registerName(methName); - info->fNativeClass = nativeClass; - - //RELEASE_CHARS(dcSignature, ds); - RELEASE_CHARS(symbolName, methName); - - - initCommonCallInfo(&info->fInfo, env, declaringClass, methodName, javaSignature, dcCallingConvention, nParams, returnValueType, paramsValueTypes, callIOs, JNI_TRUE, method); - } - END_INFOS_LOOP() - return PTR_TO_JLONG(infos); - } -#else - return 0; -#endif -} - -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeObjCMethodBindings( - JNIEnv *env, - jclass clazz, - jlong handle, - jint size -) { -#ifdef BRIDJ_OBJC_SUPPORT - JavaToObjCCallInfo* infos = (JavaToObjCCallInfo*)JLONG_TO_PTR(handle); - jint i; - if (!infos) - return; - for (i = 0; i < size; i++) { - freeCommon(env, &infos[i].fInfo); - } - free(infos); -#endif -} - - -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToVirtualMethods( - JNIEnv *env, - jclass clazz, - jobjectArray methodCallInfos -) { - initMethods(env); - { - BEGIN_INFOS_LOOP(VirtualMethodCallInfo) - - GetField_javaSignature() ; - GetField_dcSignature() ; - GetField_symbolName() ; - GetField_methodName() ; - GetField_method() ; - GetField_paramsValueTypes() ; - GetField_returnValueType() ; - GetField_virtualIndex() ; - GetField_virtualTableOffset() ; - GetField_dcCallingConvention() ; - GetField_startsWithThis() ; - //GetField_bNeedsThisPointer() ; - GetField_declaringClass() ; - GetField_nParams() ; - GetField_callIOs() ; - - { - const char* ds; - - info->fClass = GLOBAL_REF(declaringClass); - info->fHasThisPtrArg = startsWithThis; - info->fVirtualIndex = virtualIndex; - info->fVirtualTableOffset = virtualTableOffset; - - // TODO DIRECT C++ virtual thunk - ds = GET_CHARS(dcSignature); - info->fInfo.fDCCallback = dcbNewCallback(ds, JavaToVirtualMethodCallHandler, info); - RELEASE_CHARS(dcSignature, ds); - - - initCommonCallInfo(&info->fInfo, env, declaringClass, methodName, javaSignature, dcCallingConvention, nParams, returnValueType, paramsValueTypes, callIOs, JNI_TRUE, method); - } - END_INFOS_LOOP() - return PTR_TO_JLONG(infos); - } -} -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeVirtualMethodBindings( - JNIEnv *env, - jclass clazz, - jlong handle, - jint size -) { - VirtualMethodCallInfo* infos = (VirtualMethodCallInfo*)JLONG_TO_PTR(handle); - jint i; - if (!infos) - return; - for (i = 0; i < size; i++) { - DEL_GLOBAL_REF(infos[i].fClass); - freeCommon(env, &infos[i].fInfo); - } - free(infos); -} - -jlong JNICALL Java_org_bridj_JNI_mallocNulled(JNIEnv *env, jclass clazz, jlong size) -{ - size_t len = (size_t)size; - void* p = malloc(len); - if (p) - memset(p, 0, len); - return PTR_TO_JLONG(p); -} -jlong JNICALL Java_org_bridj_JNI_mallocNulledAligned(JNIEnv *env, jclass clazz, jlong size, jint alignment) -{ -#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) - size_t len = (size_t)size; - void* p; - if (posix_memalign(&p, alignment, len)) - return 0; - if (p) - memset(p, 0, len); - return PTR_TO_JLONG(p); -#else - return 0; -#endif -} - -jlong JNICALL Java_org_bridj_JNI_malloc(JNIEnv *env, jclass clazz, jlong size) -{ - jlong r = 0; - BEGIN_TRY_CALL(env); - r = PTR_TO_JLONG(malloc((size_t)size)); - END_TRY_CALL(env); - return r; -} -jlong JNICALL Java_org_bridj_JNI_strlen(JNIEnv *env, jclass clazz, jlong ptr) -{ - jlong r = 0; - BEGIN_TRY_CALL(env); - r = strlen(JLONG_TO_PTR(ptr)); - END_TRY_CALL(env); - return r; -} -jlong JNICALL Java_org_bridj_JNI_wcslen(JNIEnv *env, jclass clazz, jlong ptr) -{ - jlong r = 0; - BEGIN_TRY_CALL(env); - r = wcslen(JLONG_TO_PTR(ptr)); - END_TRY_CALL(env); - return r; -} -void JNICALL Java_org_bridj_JNI_free(JNIEnv *env, jclass clazz, jlong ptr) -{ - BEGIN_TRY_CALL(env); - free(JLONG_TO_PTR(ptr)); - END_TRY_CALL(env); -} -void JNICALL Java_org_bridj_JNI_memcpy(JNIEnv *env, jclass clazz, jlong dest, jlong src, jlong size) -{ - BEGIN_TRY_CALL(env); - memcpy(JLONG_TO_PTR(dest), JLONG_TO_PTR(src), (size_t)size); - END_TRY_CALL(env); -} -void JNICALL Java_org_bridj_JNI_memmove(JNIEnv *env, jclass clazz, jlong dest, jlong src, jlong size) -{ - BEGIN_TRY_CALL(env); - memmove(JLONG_TO_PTR(dest), JLONG_TO_PTR(src), (size_t)size); - END_TRY_CALL(env); -} -jlong JNICALL Java_org_bridj_JNI_memchr(JNIEnv *env, jclass clazz, jlong ptr, jbyte value, jlong size) -{ - jlong r = 0; - BEGIN_TRY_CALL(env); - r = PTR_TO_JLONG(memchr(JLONG_TO_PTR(ptr), value, (size_t)size)); - END_TRY_CALL(env); - return r; -} -jint JNICALL Java_org_bridj_JNI_memcmp(JNIEnv *env, jclass clazz, jlong ptr1, jlong ptr2, jlong size) -{ - jint r = 0; - BEGIN_TRY_CALL(env); - r = memcmp(JLONG_TO_PTR(ptr1), JLONG_TO_PTR(ptr2), (size_t)size); - END_TRY_CALL(env); - return r; -} -void JNICALL Java_org_bridj_JNI_memset(JNIEnv *env, jclass clazz, jlong ptr, jbyte value, jlong size) -{ - BEGIN_TRY_CALL(env); - PTR_TO_JLONG(memset(JLONG_TO_PTR(ptr), value, (size_t)size)); - END_TRY_CALL(env); -} - -jlong JNICALL Java_org_bridj_JNI_memmem(JNIEnv *env, jclass clazz, jlong haystack, jlong haystackLength, jlong needle, jlong needleLength) -{ - const char* pHaystack = JLONG_TO_PTR(haystack); - const char* pNeedle = JLONG_TO_PTR(needle); - - if (needleLength > haystackLength) - return 0; - if (!pHaystack || !pNeedle) - return 0; - -#ifndef memmem - { - jlong n = haystackLength - needleLength, i; - char needleStart = *pNeedle; - for (i = 0; i <= n; i++) { - const char* position = pHaystack + i; - if (*position == needleStart) { - if (memcmp(position, pNeedle, (size_t)needleLength) == 0) - return PTR_TO_JLONG(position); - } - } - return 0; - } -#else - return memmem(pHaystack, (size_t)haystackLength, pNeedle, (size_t)needleLength); -#endif -} - - -jlong JNICALL Java_org_bridj_JNI_memmem_1last(JNIEnv *env, jclass clazz, jlong haystack, jlong haystackLength, jlong needle, jlong needleLength) -{ - const char* pHaystack = JLONG_TO_PTR(haystack); - const char* pNeedle = JLONG_TO_PTR(needle); - - if (needleLength > haystackLength) - return 0; - if (!pHaystack || !pNeedle) - return 0; - - { - jlong n = haystackLength - needleLength, i; - char needleStart = *pNeedle; - for (i = n; i >= n; i--) { - const char* position = pHaystack + i; - if (*position == needleStart) { - if (memcmp(position, pNeedle, (size_t)needleLength) == 0) - return PTR_TO_JLONG(position); - } - } - return 0; - } -} - -#include "PrimDefs_int.h" -#include "JNI_prim.h" - -#include "PrimDefs_long.h" -#include "JNI_prim.h" - -#include "PrimDefs_short.h" -#include "JNI_prim.h" - -#include "PrimDefs_byte.h" -#include "JNI_prim.h" - -#include "PrimDefs_char.h" -#include "JNI_prim.h" - -#include "PrimDefs_boolean.h" -#include "JNI_prim.h" - -#include "PrimDefs_float.h" -#include "JNI_prim.h" - -#include "PrimDefs_double.h" -#include "JNI_prim.h" diff --git a/libraries/BridJ/src/main/cpp/bridj/JNI.h b/libraries/BridJ/src/main/cpp/bridj/JNI.h deleted file mode 100644 index 5384f61bc..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/JNI.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _BRIDJ_JNI_H -#define _BRIDJ_JNI_H - -#include - -#define GLOBAL_REF(v) (*env)->NewGlobalRef(env, v) -#define DEL_GLOBAL_REF(v) (*env)->DeleteGlobalRef(env, v) -#define WEAK_GLOBAL_REF(v) (*env)->NewWeakGlobalRef(env, v) -#define DEL_WEAK_GLOBAL_REF(v) (*env)->DeleteWeakGlobalRef(env, v) -#define FIND_GLOBAL_CLASS(name) GLOBAL_REF((*env)->FindClass(env, name)) -#define OBJECT_SIG "Ljava/lang/Object;" -#define STRING_SIG "Ljava/lang/String;" -#define CLASS_SIG "Ljava/lang/Class;" -#define TYPE_SIG "Ljava/lang/reflect/Type;" -#define METHOD_SIG "Ljava/lang/reflect/Method;" - -#define POINTER_SIG "Lorg/bridj/Pointer;" -#define CALLIO_SIG "Lorg/bridj/CallIO;" - - -void initMethods(JNIEnv* env); - -#endif // _BRIDJ_JNI_H diff --git a/libraries/BridJ/src/main/cpp/bridj/JNI_prim.h b/libraries/BridJ/src/main/cpp/bridj/JNI_prim.h deleted file mode 100644 index 9181eb31d..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/JNI_prim.h +++ /dev/null @@ -1,160 +0,0 @@ -#ifndef CONCAT_2 - #define CONCAT_2_(a, b) a##b - #define CONCAT_2(a, b) CONCAT_2_(a, b) - #define CONCAT_3_(a, b, c) a##b##c - #define CONCAT_3(a, b, c) CONCAT_3_(a, b, c) -#endif - -#ifndef SUPPORTS_UNALIGNED_ACCESS -static jprimName CONCAT_2(unaligned_get_1, primName)(JNIEnv* env, jclass clazz, jlong peer, jprimName (JNICALL *getter)(JNIEnv*, jclass, jlong)) { -#if 1 - throwException(env, "Unaligned pointer access !"); - return (jprimName)0; -#else - int i; - union { char bytes[primSize]; jprimName prim; } aligned; - char* ptr = (char*)JLONG_TO_PTR(peer); - for (i = 0; i < primSize; i++) - aligned.bytes[i] = *(ptr++); - - return getter(env, clazz, PTR_TO_JLONG(&aligned.bytes)); -#endif -} -#endif // ifndef SUPPORTS_UNALIGNED_ACCESS - -#ifndef SUPPORTS_UNALIGNED_ACCESS -static void CONCAT_2(unaligned_set_1, primName)(JNIEnv* env, jclass clazz, jlong peer, jprimName value, void (JNICALL *setter)(JNIEnv*, jclass, jlong, jprimName)) { - int i; - char* ptr; - union { char bytes[primSize]; jprimName prim; } aligned; - setter(env, clazz, PTR_TO_JLONG(&aligned.bytes), value); - - ptr = (char*)JLONG_TO_PTR(peer); - for (i = 0; i < primSize; i++) - *(ptr++) = aligned.bytes[i]; -} -#endif // ifndef SUPPORTS_UNALIGNED_ACCESS - -#ifdef REORDER_VALUE_BYTES -jprimName JNICALL CONCAT_3(Java_org_bridj_JNI_get_1, primName, _1disordered)(JNIEnv* env, jclass clazz, jlong peer) { -#ifndef SUPPORTS_UNALIGNED_ACCESS -#ifdef alignmentMask - if (peer & alignmentMask) - return CONCAT_2(unaligned_get_1, primName)(env, clazz, peer, CONCAT_3(Java_org_bridj_JNI_get_1, primName, _1disordered)); -#endif -#endif - //return ((((jprimName)((jprimName*)peer)[0]) << 16) | ((jprimName*)peer)[1]); - { - TEMP_REORDER_VAR_TYPE tempVal = REORDER_VALUE_BYTES(peer); - return *(jprimName*)&tempVal; - } -} -#endif // ifdef REORDER_VALUE_BYTES - -jprimName JNICALL CONCAT_2(Java_org_bridj_JNI_get_1, primName)(JNIEnv *env, jclass clazz, jlong peer) { - jprimName ret = (jprimName)0; -#ifndef SUPPORTS_UNALIGNED_ACCESS -#ifdef alignmentMask - if (peer & alignmentMask) - return CONCAT_2(unaligned_get_1, primName)(env, clazz, peer, CONCAT_2(Java_org_bridj_JNI_get_1, primName)); -#endif -#endif - BEGIN_TRY_CALL(env); - ret = *(jprimName*)((char*)JLONG_TO_PTR(peer)); - END_TRY_CALL(env); - return ret; -} -void JNICALL CONCAT_2(Java_org_bridj_JNI_set_1, primName)(JNIEnv *env, jclass clazz, jlong peer, jprimName value) { -#ifndef SUPPORTS_UNALIGNED_ACCESS -#ifdef alignmentMask - if (peer & alignmentMask) { - CONCAT_2(unaligned_set_1, primName)(env, clazz, peer, value, CONCAT_2(Java_org_bridj_JNI_set_1, primName)); - return; - } -#endif -#endif - BEGIN_TRY_CALL(env); - *(jprimName*)((char*)JLONG_TO_PTR(peer)) = value; - END_TRY_CALL(env); -} - -#ifdef REORDER_VALUE_BYTES -void JNICALL CONCAT_3(Java_org_bridj_JNI_set_1, primName, _1disordered)(JNIEnv* env, jclass clazz, jlong peer, jprimName value) { -#ifndef SUPPORTS_UNALIGNED_ACCESS -#ifdef alignmentMask - if (peer & alignmentMask) { - CONCAT_2(unaligned_set_1, primName)(env, clazz, peer, value, CONCAT_3(Java_org_bridj_JNI_set_1, primName, _1disordered)); - return; - } -#endif -#endif - { - TEMP_REORDER_VAR_TYPE tempVal; - BEGIN_TRY_CALL(env); - tempVal = REORDER_VALUE_BYTES(&value); - *(jprimName*)((char*)JLONG_TO_PTR(peer)) = *(jprimName*)&tempVal; - END_TRY_CALL(env); - } -} -#endif // ifdef REORDER_VALUE_BYTES - -jprimArray JNICALL CONCAT_3(Java_org_bridj_JNI_get_1, primName, _1array)(JNIEnv *env, jclass clazz, jlong peer, jint length) { - jprimArray array = NULL; - BEGIN_TRY_CALL(env); - array = (jprimArray)JLONG_TO_PTR((*env)->CONCAT_3(New, primJNICapName, Array)(env, length)); - (*env)->CONCAT_3(Set, primJNICapName, ArrayRegion)(env, array, 0, (jsize)length, (jprimName*)((char*)JLONG_TO_PTR(peer))); - END_TRY_CALL(env); - return array; -} -void JNICALL CONCAT_3(Java_org_bridj_JNI_set_1, primName, _1array)(JNIEnv *env, jclass clazz, jlong peer, jprimArray values, jint valuesOffset, jint length) { - BEGIN_TRY_CALL(env); - (*env)->CONCAT_3(Get, primJNICapName, ArrayRegion)(env, values, (jsize)valuesOffset, (jsize)length, (jprimName*)((char*)JLONG_TO_PTR(peer))); - END_TRY_CALL(env); -} - -#ifdef REORDER_VALUE_BYTES -jprimArray JNICALL CONCAT_3(Java_org_bridj_JNI_get_1, primName, _1array_1disordered)(JNIEnv *env, jclass clazz, jlong peer, jint length) { - jint i; - jprimArray array = NULL; - jprimName* nativeArray; - TEMP_REORDER_VAR_TYPE tempVal; - BEGIN_TRY_CALL(env); - array = (jprimArray)JLONG_TO_PTR((*env)->CONCAT_3(New, primJNICapName, Array)(env, length)); - nativeArray = (jprimName*)((char*)JLONG_TO_PTR(peer)); - for (i = 0; i < length; i++) { - tempVal = REORDER_VALUE_BYTES(&nativeArray[i]); - (*env)->CONCAT_3(Set, primJNICapName, ArrayRegion)(env, array, i, 1, (jprimName*)&tempVal); - } - END_TRY_CALL(env); - return array; -} -void JNICALL CONCAT_3(Java_org_bridj_JNI_set_1, primName, _1array_1disordered)(JNIEnv *env, jclass clazz, jlong peer, jprimArray values, jint valuesOffset, jint length) { - jint i; - jprimName* nativeArray; - TEMP_REORDER_VAR_TYPE tempVal; - BEGIN_TRY_CALL(env); - nativeArray = (jprimName*)((char*)JLONG_TO_PTR(peer)); - for (i = 0; i < length; i++) { - (*env)->CONCAT_3(Get, primJNICapName, ArrayRegion)(env, values, valuesOffset + i, 1, (jprimName*)&tempVal); - tempVal = REORDER_VALUE_BYTES(&tempVal); - nativeArray[i] = *(jprimName*)&tempVal; - } - END_TRY_CALL(env); -} -#endif // ifdef REORDER_VALUE_BYTES - -JNIEXPORT jlong JNICALL CONCAT_3(Java_org_bridj_JNI_get, primJNICapName, ArrayElements)(JNIEnv *env, jclass clazz, jprimArray array, jbooleanArray aIsCopy) -{ - jboolean tr = JNI_TRUE; - jboolean *pIsCopy = aIsCopy ? (*env)->GetBooleanArrayElements(env, aIsCopy, &tr) : NULL; - jlong ret = PTR_TO_JLONG((*env)->CONCAT_3(Get, primJNICapName, ArrayElements)(env, array, pIsCopy)); - if (aIsCopy) - (*env)->ReleaseBooleanArrayElements(env, aIsCopy, pIsCopy, JNI_COMMIT); - return ret; -} - -JNIEXPORT void JNICALL CONCAT_3(Java_org_bridj_JNI_release, primJNICapName, ArrayElements)(JNIEnv *env, jclass clazz, jprimArray array, jlong pointer, jint mode) -{ - (*env)->CONCAT_3(Release, primJNICapName, ArrayElements)(env, array, (jprimName*)JLONG_TO_PTR(pointer), mode); -} - diff --git a/libraries/BridJ/src/main/cpp/bridj/Make.sh b/libraries/BridJ/src/main/cpp/bridj/Make.sh deleted file mode 100755 index d1bddcbb4..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Make.sh +++ /dev/null @@ -1,158 +0,0 @@ -#!/bin/bash - -# Avoid locale in diff : -LANG=C - -SRC_HOME=${SRC_HOME:-~/src} -BIN_HOME=${BIN_HOME:-~/bin} - -#BUILD_CONFIG=debug sh MakeAll.sh clean -export MAKE_CMD=make -if [[ "`which gmake`" != "" ]] ; then - export MAKE_CMD=gmake ; -fi - -if [[ "$DEBUG" == "1" ]] ; then - export OUT_PATTERN=debug ; -else - export OUT_PATTERN=release ; -fi - -CURR="`pwd`" -LD=gcc -COMPILE_PIC=1 -BUILD_DIR= - -function fail() { - echo "#" - echo "# ERROR: $@" - echo "#" - exit 1 -} - -#echo BUILD_DIR = $BUILD_DIR -#echo BUILD_CONFIG = $BUILD_CONFIG -#echo LINK_DIRS = $LINK_DIRS - -#echo $DYNCALL_HOME/dyncall/$BUILD_DIR - -#svn diff $SRC_HOME/dyncall/dyncall > dyncall.diff -svn diff $DYNCALL_HOME/dyncall | sed "s/${DYNCALL_HOME//\//\\/}\///" > dyncall.diff -#svn diff $SRC_HOME/dyncall/dyncall | sed "s/${HOME//\//\\/}\/src\/dyncall\///" | sed -E 's/^(---|\+\+\+)(.*)\(([^)]+)\)/\1\2/' > dyncall.diff - -echo "# Configuring dyncall" -cd "$DYNCALL_HOME/dyncall" || fail "Cannot go to DYNCALL_HOME = $DYNCALL_HOME" - -TARGET=${TARGET:-default} -ANDROID_NDK_HOME=${ANDROID_NDK_HOME:-$BIN_HOME/android-ndk-r5c} - -case $TARGET in - android) - NEEDS_TEST=0 - SHAREDLIB_SUFFIX=so - - if [[ ! -d "$ANDROID_NDK_HOME" ]] - then - fail "ANDROID_NDK_HOME not set and $ANDROID_NDK_HOME does not exist" - fi - - ANDROID_PREBUILT_DIR=$ANDROID_NDK_HOME/toolchains/arm-linux-androideabi-4.4.3/prebuilt - - if [[ ! -d "$ANDROID_PREBUILT_DIR" ]] - then - fail "Cannot find $ANDROID_PREBUILT_DIR" - fi - - sh ./configure --with-androidndk=$ANDROID_PREBUILT_DIR/`ls $ANDROID_PREBUILT_DIR | grep -`/bin/arm-linux-androideabi- --target-arm-arm --with-sysroot=$ANDROID_NDK_HOME/platforms/android-9/arch-arm || fail "Failed to configure Android/arm build" - ;; - android-emulator) - NEEDS_TEST=0 - sh ./configure --tool-androidndk --target-x86 || fail "Failed to configure Android/x86 build" - ;; - ios) - #export PATH=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:$PATH - #export C_INCLUDE_PATH=/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/include - #export LIBRARY_PATH=/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/lib - #export CC="gcc -arch arm" - #export CPPFLAGS - NEEDS_TEST=1 - export PATH=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:$PATH - sh ./configure --target-iphoneos --with-iphonesdk=4.3 || fail "Failed to configure iOS build" - ;; - default) - NEEDS_TEST=1 - export PATH=/Developer-old/usr/bin:$PATH - if [[ -d /System/Library/Frameworks/ && ! -d /Applications/MobilePhone.app ]] ; then - # Avoid LC_DYLD_INFO (https://discussions.apple.com/thread/3197542?start=0&tstart=0) - export MACOSX_DEPLOYMENT_TARGET=10.4 - sh ./configure --target-universal || fail "Failed to configure MacOS X Universal build" - else - sh ./configure || fail "Failed to configure default build" - fi - ;; - *) - fail "Unknown TARGET : $TARGET - Valid targets are android, android-emulator and default" - ;; -esac - -if [[ -z "$SHAREDLIB_SUFFIX" ]] ; then - if [[ -d /System/Library/Frameworks/ ]] ; then - SHAREDLIB_SUFFIX=dylib ; - else - SHAREDLIB_SUFFIX=so ; - fi ; -fi - -echo "# Making dyncall with '$MAKE_CMD $@'" -$MAKE_CMD $@ || fail "Failed to make dyncall" - -echo "# Making BridJ" -cd "$CURR" -$MAKE_CMD $@ || fail "Failed to make BridJ" - -if [[ "$NEEDS_TEST" == "1" ]] ; then - echo "# Making test library" - cd "../../../test/cpp/test" - $MAKE_CMD $@ || fail "Failed to make BridJ's test library" ; - - echo "# Making dependsOnTest library" - cd "../../../test/cpp/dependsOnTest" - $MAKE_CMD $@ || fail "Failed to make BridJ's dependsOnTest library" ; -fi - -cd "$CURR" - -if [[ -d build_out ]] ; then - cd build_out - - for D in `ls . | grep _$OUT_PATTERN` ; do - ARCH_NAME="`echo $D| sed "s/_gcc_$OUT_PATTERN//"| sed "s/_androidndk_$OUT_PATTERN//"`" - if [[ "$ARCH_NAME" == "android_arm32_arm" ]] ; then - RES_SUB="lib/armeabi" ; - else - RES_SUB="org/bridj/lib/$ARCH_NAME" ; - fi - MAIN_OUT="../../../resources/$RES_SUB" - - echo ARCH_NAME: $ARCH_NAME - echo RES_SUB: $RES_SUB - TEST_OUT="../../../../test/resources/$RES_SUB" - - mkdir -p $MAIN_OUT - cp $D/*.$SHAREDLIB_SUFFIX $MAIN_OUT - - if [[ "$NEEDS_TEST" == "1" ]] ; then - mkdir -p $TEST_OUT - cp ../../../../test/cpp/test/build_out/$D/*.$SHAREDLIB_SUFFIX $TEST_OUT - cp ../../../../test/cpp/dependsOnTest/build_out/$D/*.$SHAREDLIB_SUFFIX $TEST_OUT - - nm $TEST_OUT/*.so > $TEST_OUT/test.so.nm - nm $TEST_OUT/*.dylib > $TEST_OUT/test.dylib.nm ; - fi - - echo "Done for $D" ; - # svn add $MAIN_OUT - # svn add $TEST_OUT ; - done ; -fi diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCBlocks.m b/libraries/BridJ/src/main/cpp/bridj/ObjCBlocks.m deleted file mode 100644 index 07590029e..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCBlocks.m +++ /dev/null @@ -1,42 +0,0 @@ -#include "HandlersCommon.h" - -#ifdef BRIDJ_OBJC_SUPPORT -#include -#include -#include "bridj.hpp" - -/* -http://cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html -http://www.opensource.apple.com/source/libclosure/libclosure-38/BlockImplementation.txt -*/ -typedef struct Block_literal { - void* isa; - int flags; - int reserved; - void (*invoke)(void *, ...); - void* descriptor; -} Block_literal; - -const void* createObjCBlock() { - void (^block)() = ^{ - // do nothing - }; - return Block_copy(block); -} -jlong Java_org_bridj_objc_ObjCJNI_getObjCBlockFunctionPointer(JNIEnv* env, jclass cl, jlong jblock) -{ - Block_literal* block = (Block_literal*)JLONG_TO_PTR(jblock); - return PTR_TO_JLONG(block->invoke); -} -jlong Java_org_bridj_objc_ObjCJNI_createObjCBlockWithFunctionPointer(JNIEnv* env, jclass cl, jlong fptr) -{ - Block_literal* block = (Block_literal*)createObjCBlock(); - block->invoke = JLONG_TO_PTR(fptr); - return PTR_TO_JLONG(block); -} -void releaseObjCBlock(const void* block) { - Block_release(block); -} - -#endif - diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCHandler.c b/libraries/BridJ/src/main/cpp/bridj/ObjCHandler.c deleted file mode 100644 index 5e74cd97d..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCHandler.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "HandlersCommon.h" - -#ifdef BRIDJ_OBJC_SUPPORT -#include - -char __cdecl JavaToObjCCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata) -{ - JavaToObjCCallInfo* info = (JavaToObjCCallInfo*)userdata; - CallTempStruct* call; - jobject instance = initCallHandler(args, &call, NULL, &info->fInfo); - JNIEnv* env = call->env; - BEGIN_TRY(env, call); - - call->pCallIOs = info->fInfo.fCallIOs; - - void* targetId = info->fNativeClass ? JLONG_TO_PTR(info->fNativeClass) : getNativeObjectPointer(env, instance, NULL); - void* callback = //objc_msgSend_stret;// - objc_msgSend; - -#if defined(DC__Arch_Intel_x86) - switch (info->fInfo.fReturnType) { - case eDoubleValue: - case eFloatValue: - callback = objc_msgSend_fpret; - break; - } -#endif - - dcMode(call->vm, info->fInfo.fDCMode); - //dcReset(call->vm); - - dcArgPointer(call->vm, targetId); - dcArgPointer(call->vm, info->fSelector); - - followArgs(call, args, info->fInfo.nParams, info->fInfo.fParamTypes, JNI_FALSE, JNI_TRUE)// TODO isVarArgs ?? - && - followCall(call, info->fInfo.fReturnType, result, callback, JNI_FALSE, JNI_FALSE); - - END_TRY(info->fInfo.fEnv, call); - cleanupCallHandler(call); - - return info->fInfo.fDCReturnType; -} -#endif - diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h b/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h deleted file mode 100644 index 8a8d59353..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#ifndef _OBJC_PROXY_H -#define _OBJC_PROXY_H - -#include - -#import - -@interface ObjCProxy : NSObject - - { - jobject javaInstance; - } - - - (id) initWithEnv: (JNIEnv*)env javaInstance: (jobject)theJavaInstance; - - - dealloc; - - - (void)forwardInvocation:(NSInvocation *) anInvocation; - - - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector; - -@end - -id newObjCProxy(JNIEnv* env, jobject javaInstance); - -#endif // _OBJC_PROXY_H diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h.bug b/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h.bug deleted file mode 100644 index 15d72a055..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.h.bug +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#ifndef _OBJC_PROXY_H -#define _OBJC_PROXY_H - -#include - -#import - -// http://borkware.com/rants/agentm/elegant-delegation/ - -@interface ObjCProxy : NSObject // NSProxy - - { - jobject javaInstance; - } - - - (id) initWithEnv: (JNIEnv*)env javaInstance: (jobject)theJavaInstance; - - - dealloc; - - - (void)forwardInvocation: (NSInvocation*)anInvocation; - - - (NSMethodSignature*)methodSignatureForSelector: (SEL)aSelector; - - // NSProxy : - - //- (BOOL)respondsTo: (SEL)aSelector; - - //- (NSString*)description; - /* - - (id)performSelector: (SEL)aSelector; - - - (void)doesNotRecognizeSelector:(SEL)aSelector; - - - (BOOL) conformsTo: (Protocol *)aProtocolObject; - + (BOOL) conformsTo: (Protocol *)aProtocolObject; - */ -@end - -id newObjCProxy(JNIEnv* env, jobject javaInstance); - -#endif // _OBJC_PROXY_H diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m b/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m deleted file mode 100644 index 72071af64..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m +++ /dev/null @@ -1,103 +0,0 @@ -#include "JNI.h" -#include "org_bridj_JNI.h" -#include "bridj.hpp" - -#import "ObjCProxy.h" - -jclass gObjCProxyClass = NULL; -jclass gNSInvocationClass = NULL; -jclass gSELClass = NULL; - -jmethodID gObjCProxyMethodSignatureForSelector = NULL; -jmethodID gObjCProxyForwardInvocation = NULL; -jobject gNSInvocationCallIO = NULL; -jobject gSELCallIO = NULL; -jobject gObjCProxyCallIO = NULL; - -jclass gCallIOUtilsClass = NULL; -jmethodID gCallIOUtilsCreatePointerCallIO = NULL; -jmethodID gCallIOUtilsCreatePointerCallIOToTargetType = NULL; - -jobject getCallIOToTargetType(JNIEnv* env, jobject tpe) { - return (*env)->CallStaticObjectMethod(env, gCallIOUtilsClass, gCallIOUtilsCreatePointerCallIOToTargetType, tpe); -} -jobject getCallIO(JNIEnv* env, jclass cl) { - return (*env)->CallStaticObjectMethod(env, gCallIOUtilsClass, gCallIOUtilsCreatePointerCallIO, cl); -} -void initObjCProxy(JNIEnv* env) { - if (gObjCProxyClass) - return; - - gObjCProxyClass = FIND_GLOBAL_CLASS("org/bridj/objc/ObjCProxy"); - gObjCProxyMethodSignatureForSelector = (*env)->GetMethodID(env, - gObjCProxyClass, - "methodSignatureForSelector", - "(Lorg/bridj/objc/SEL;)" POINTER_SIG - ); - gObjCProxyForwardInvocation = (*env)->GetMethodID(env, - gObjCProxyClass, - "forwardInvocation", - "(" POINTER_SIG ")V" //"(" OBJECT_SIG "Lorg/bridj/objc/SEL;" POINTER_SIG "V" - ); - gCallIOUtilsClass = FIND_GLOBAL_CLASS("org/bridj/CallIO$Utils"); - gCallIOUtilsCreatePointerCallIO = (*env)->GetStaticMethodID(env, - gCallIOUtilsClass, - "createPointerCallIO", - "(" TYPE_SIG ")" CALLIO_SIG - ); - gCallIOUtilsCreatePointerCallIOToTargetType = (*env)->GetStaticMethodID(env, - gCallIOUtilsClass, - "createPointerCallIOToTargetType", - "(" TYPE_SIG ")" CALLIO_SIG - ); - - gNSInvocationClass = FIND_GLOBAL_CLASS("org/bridj/objc/NSInvocation"); - gSELClass = FIND_GLOBAL_CLASS("org/bridj/objc/SEL"); - - gSELCallIO = GLOBAL_REF(getCallIO(env, gSELClass)); - gNSInvocationCallIO = GLOBAL_REF(getCallIOToTargetType(env, gNSInvocationClass)); - gObjCProxyCallIO = GLOBAL_REF(getCallIOToTargetType(env, gObjCProxyClass)); -} - -@implementation ObjCProxy - -- (id) initWithEnv: (JNIEnv*)env javaInstance: (jobject)theJavaInstance { - self = [super init]; - if (self) - javaInstance = GLOBAL_REF(theJavaInstance); - - return self; -} - -- dealloc { - JNIEnv* env = GetEnv(); - (*env)->DeleteGlobalRef(env, javaInstance); - [super dealloc]; -} - -- (void)forwardInvocation: (NSInvocation*)invocation { - JNIEnv* env = GetEnv(); - jobject ptr = createPointerFromIO(env, invocation, gNSInvocationCallIO); - (*env)->CallVoidMethod(env, javaInstance, gObjCProxyForwardInvocation, ptr); -} - -- (NSMethodSignature*)methodSignatureForSelector: (SEL)sel { - JNIEnv* env = GetEnv(); - jobject sig = (*env)->CallObjectMethod(env, javaInstance, gObjCProxyMethodSignatureForSelector, createPointerFromIO(env, sel, gSELCallIO)); - if (!sig) - return [super methodSignatureForSelector: sel]; - return (NSMethodSignature*)getPointerPeer(env, sig); -} - -- (BOOL)respondsToSelector: (SEL)sel { - return [self methodSignatureForSelector: sel] != nil; -} - -@end - -jobject Java_org_bridj_objc_ObjCJNI_createObjCProxyPeer(JNIEnv* env, jclass cl, jobject javaInstance) -{ - initObjCProxy(env); - id proxyInstance = [[ObjCProxy alloc] initWithEnv: env javaInstance: javaInstance]; - return createPointerFromIO(env, proxyInstance, gObjCProxyCallIO); -} diff --git a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m.bug b/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m.bug deleted file mode 100644 index e1deb69f9..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ObjCProxy.m.bug +++ /dev/null @@ -1,134 +0,0 @@ -#include "JNI.h" -#include "org_bridj_JNI.h" -#include "bridj.hpp" - -#import "ObjCProxy.h" - -jclass gObjCProxyClass = NULL; -jclass gNSInvocationClass = NULL; -jclass gSELClass = NULL; - -jmethodID gObjCProxyMethodSignatureForSelector = NULL; -jmethodID gObjCProxyForwardInvocation = NULL; -jobject gNSInvocationCallIO = NULL; -jobject gSELCallIO = NULL; -jobject gObjCProxyCallIO = NULL; - -jclass gCallIOUtilsClass = NULL; -jmethodID gCallIOUtilsCreatePointerCallIO = NULL; -jmethodID gCallIOUtilsCreatePointerCallIOToTargetType = NULL; - -jobject getCallIOToTargetType(JNIEnv* env, jobject tpe) { - return (*env)->CallStaticObjectMethod(env, gCallIOUtilsClass, gCallIOUtilsCreatePointerCallIOToTargetType, tpe); -} -jobject getCallIO(JNIEnv* env, jclass cl) { - return (*env)->CallStaticObjectMethod(env, gCallIOUtilsClass, gCallIOUtilsCreatePointerCallIO, cl); -} -void initObjCProxy(JNIEnv* env) { - if (gObjCProxyClass) - return; - - gObjCProxyClass = FIND_GLOBAL_CLASS("org/bridj/objc/ObjCProxy"); - gObjCProxyMethodSignatureForSelector = (*env)->GetMethodID(env, - gObjCProxyClass, - "methodSignatureForSelector", - "(Lorg/bridj/objc/SEL;)" POINTER_SIG - ); - gObjCProxyForwardInvocation = (*env)->GetMethodID(env, - gObjCProxyClass, - "forwardInvocation", - "(" POINTER_SIG ")V" //"(" OBJECT_SIG "Lorg/bridj/objc/SEL;" POINTER_SIG "V" - ); - gCallIOUtilsClass = FIND_GLOBAL_CLASS("org/bridj/CallIO$Utils"); - gCallIOUtilsCreatePointerCallIO = (*env)->GetStaticMethodID(env, - gCallIOUtilsClass, - "createPointerCallIO", - "(" TYPE_SIG ")" CALLIO_SIG - ); - gCallIOUtilsCreatePointerCallIOToTargetType = (*env)->GetStaticMethodID(env, - gCallIOUtilsClass, - "createPointerCallIOToTargetType", - "(" TYPE_SIG ")" CALLIO_SIG - ); - - gNSInvocationClass = FIND_GLOBAL_CLASS("org/bridj/objc/NSInvocation"); - gSELClass = FIND_GLOBAL_CLASS("org/bridj/objc/SEL"); - - gSELCallIO = GLOBAL_REF(getCallIO(env, gSELClass)); - gNSInvocationCallIO = GLOBAL_REF(getCallIOToTargetType(env, gNSInvocationClass)); - gObjCProxyCallIO = GLOBAL_REF(getCallIOToTargetType(env, gObjCProxyClass)); -} - -@implementation ObjCProxy - -- (id) initWithEnv: (JNIEnv*)env javaInstance: (jobject)theJavaInstance { - self = [super init]; - if (self) - javaInstance = GLOBAL_REF(theJavaInstance); - - return self; -} - -- dealloc { - JNIEnv* env = GetEnv(); - (*env)-> DeleteGlobalRef(env, javaInstance); - [super dealloc]; -} - -- (void)forwardInvocation: (NSInvocation*)invocation { - //NSLog(@"forwardInvocation"); - JNIEnv* env = GetEnv(); - jobject ptr = createPointerFromIO(env, invocation, gNSInvocationCallIO); - (*env)->CallVoidMethod(env, javaInstance, gObjCProxyForwardInvocation, ptr); -} - - -- (void)doesNotRecognizeSelector:(SEL)sel { - //NSLog(@"doesNotRecognizeSelector: %@", NSStringFromSelector(sel)); -} - -- (NSMethodSignature*)methodSignatureForSelector: (SEL)sel { - //NSLog(@"methodSignatureForSelector ?"); - JNIEnv* env = GetEnv(); - jobject sig = (*env)->CallObjectMethod(env, javaInstance, gObjCProxyMethodSignatureForSelector, createPointerFromIO(env, sel, gSELCallIO)); - if (!sig) - //return nil;// - return [super methodSignatureForSelector: sel]; - return (NSMethodSignature*)getPointerPeer(env, sig); -} - - -/* -- (BOOL)respondsTo: (SEL)sel { - return ![self respondsToSelector: sel]; -} -- (id)performSelector: (SEL)sel { - //NSLog(@"performSelector"); - return [super performSelector: sel]; -} - - -- (BOOL)respondsToSelector: (SEL)sel { - //NSLog(@"respondsToSelector ?"); - return [self methodSignatureForSelector: sel] != nil; -} - -- (BOOL) conformsTo: (Protocol *)aProtocolObject { - //NSLog(@"-conformsTo protocol ?"); - return YES;//[super conformsTo: aProtocolObject]; -} - -+ (BOOL) conformsTo: (Protocol *)aProtocolObject { - //NSLog(@"+conformsTo protocol ?"); - return YES;//[super conformsTo: aProtocolObject]; -} -*/ - -@end - -jobject Java_org_bridj_objc_ObjCJNI_createObjCProxyPeer(JNIEnv* env, jclass cl, jobject javaInstance) -{ - initObjCProxy(env); - id proxyInstance = [[ObjCProxy alloc] initWithEnv: env javaInstance: javaInstance]; - return createPointerFromIO(env, proxyInstance, gObjCProxyCallIO); -} diff --git a/libraries/BridJ/src/main/cpp/bridj/Platform.c b/libraries/BridJ/src/main/cpp/bridj/Platform.c deleted file mode 100644 index 0ad3d247f..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Platform.c +++ /dev/null @@ -1,75 +0,0 @@ -#include "org_bridj_Platform.h" -#include "JNI.h" - -#include "bridj.hpp" -#include - -#define STRING_SIG "Ljava/lang/String;" -#define NEW_STRING(x) (*env)->NewStringUTF(env, x) - -//jclass gPlatform_utsnameClass = NULL; -//jmethodID gPlatform_utsnameConstr = NULL; - -void initPlatformMethods(JNIEnv *env) -{ - /*gPlatform_utsnameClass = FIND_GLOBAL_CLASS("org/bridj/Platform$utsname"); - gPlatform_utsnameConstr = (*env)->GetMethodID(env, gPlatform_utsnameClass, "", - "(" STRING_SIG STRING_SIG STRING_SIG STRING_SIG STRING_SIG ")V" - );*/ -} - - -#define JNI_SIZEOF(type, escType) \ -jint JNICALL Java_org_bridj_Platform_sizeOf_1 ## escType(JNIEnv *env, jclass clazz) { return sizeof(type); } - -#define JNI_SIZEOF_t(type) JNI_SIZEOF(type ## _t, type ## _1t) - -JNI_SIZEOF_t(size) -JNI_SIZEOF_t(time) -JNI_SIZEOF_t(wchar) -JNI_SIZEOF_t(ptrdiff) -JNI_SIZEOF(long, long) - - -JNIEXPORT jint JNICALL Java_org_bridj_Platform_getMaxDirectMappingArgCount(JNIEnv *env, jclass clazz) { -#if defined(_WIN64) - return 16; -#elif defined(DC__OS_Darwin) && defined(DC__Arch_AMD64) - return 4;//16; -#elif defined(DC__OS_Linux) && defined(DC__Arch_AMD64) - return 4; -#elif defined(_WIN32) - return 8; -#else - return -1; -#endif -} - -/* -#ifdef _WIN32 -jobject JNICALL Java_org_bridj_Platform_uname(JNIEnv *env, jclass clazz) { - return NULL; -} -#else - -#include -jobject JNICALL Java_org_bridj_Platform_uname(JNIEnv *env, jclass clazz) -{ - initMethods(env); - - struct utsname name; - uname(&name); - return (*env)->NewObject( - env, - gPlatform_utsnameClass, - gPlatform_utsnameConstr, - NEW_STRING(name.sysname), - NEW_STRING(name.nodename), - NEW_STRING(name.release), - NEW_STRING(name.version), - NEW_STRING(name.machine) - ); -} -#endif -*/ - diff --git a/libraries/BridJ/src/main/cpp/bridj/Pointer.c b/libraries/BridJ/src/main/cpp/bridj/Pointer.c deleted file mode 100644 index d032ec665..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Pointer.c +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include -#include -#include "Exceptions.h" -#include "org_bridj_Pointer.h" -#include - -#ifndef __GNUC__ -#pragma warning(disable: 4715) -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/Pointer_prim.h b/libraries/BridJ/src/main/cpp/bridj/Pointer_prim.h deleted file mode 100644 index 2db0bb591..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Pointer_prim.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef CONCAT_2 - #define CONCAT_2_(a, b) a##b - #define CONCAT_2(a, b) CONCAT_2_(a, b) - #define CONCAT_3_(a, b, c) a##b##c - #define CONCAT_3(a, b, c) CONCAT_3_(a, b, c) -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_boolean.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_boolean.h deleted file mode 100644 index 6846cc7fb..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_boolean.h +++ /dev/null @@ -1,8 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName boolean -#define jprimName jboolean -#define jprimArray jbooleanArray -#define primJNICapName Boolean -#define primCapName Bool -#define wrapperName Boolean -#define primSize 1 diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_byte.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_byte.h deleted file mode 100644 index ce7f50f4a..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_byte.h +++ /dev/null @@ -1,9 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName byte -#define jprimName jbyte -#define jprimArray jbyteArray -#define primJNICapName Byte -#define primCapName Byte -#define wrapperName Byte -#define bufferName ByteBuffer -#define primSize 1 diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_char.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_char.h deleted file mode 100644 index a5ba2e455..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_char.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName char -#define jprimName jchar -#define jprimArray jcharArray -#define primJNICapName Char -#define primCapName Char -#define wrapperName Character -#define bufferName CharBuffer -#define primSize 2 -#define alignmentMask 1 -#define TEMP_REORDER_VAR_TYPE jshort - -//#ifdef BIG_ENDIAN -//#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jshort(peer, 0, 1) -//#else -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jshort(peer, 1, 0) -//#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_double.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_double.h deleted file mode 100644 index 0174bde58..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_double.h +++ /dev/null @@ -1,18 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName double -#define jprimName jdouble -#define jprimArray jdoubleArray -#define primJNICapName Double -#define primCapName Double -#define wrapperName Double -#define bufferName DoubleBuffer -#define primSize 8 -#define alignmentMask 7 - -#define TEMP_REORDER_VAR_TYPE jlong - -//#ifdef BIG_ENDIAN -//#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jlong(peer, 0, 1, 2, 3, 4, 5, 6, 7) -//#else -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jlong(peer, 7, 6, 5, 4, 3, 2, 1, 0) -//#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_float.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_float.h deleted file mode 100644 index 2150214fa..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_float.h +++ /dev/null @@ -1,15 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName float -#define jprimName jfloat -#define jprimArray jfloatArray -#define primJNICapName Float -#define primCapName Float -#define wrapperName Float -#define bufferName FloatBuffer -#define primSize 4 -#define alignmentMask 3 - -#define TEMP_REORDER_VAR_TYPE jint - -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jint(peer, 3, 2, 1, 0) - diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_int.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_int.h deleted file mode 100644 index 98d932656..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_int.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName int -#define jprimName jint -#define jprimArray jintArray -#define primJNICapName Int -#define primCapName Int -#define wrapperName Integer -#define bufferName IntBuffer -#define primSize 4 -#define alignmentMask 3 -#define TEMP_REORDER_VAR_TYPE jint - -//#ifdef BIG_ENDIAN -//#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jint(peer, 0, 1, 2, 3) -//#else -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jint(peer, 3, 2, 1, 0) -//#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_long.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_long.h deleted file mode 100644 index b3f258ed3..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_long.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName long -#define jprimName jlong -#define jprimArray jlongArray -#define primJNICapName Long -#define primCapName Long -#define wrapperName Long -#define bufferName LongBuffer -#define primSize 8 -#define alignmentMask 7 -#define TEMP_REORDER_VAR_TYPE jlong - -//#ifdef BIG_ENDIAN -//#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jlong(peer, 0, 1, 2, 3, 4, 5, 6, 7) -//#else -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jlong(peer, 7, 6, 5, 4, 3, 2, 1, 0) -//#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_short.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_short.h deleted file mode 100644 index d78cc19d7..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_short.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "PrimDefs_undef.h" -#define primName short -#define jprimName jshort -#define jprimArray jshortArray -#define primJNICapName Short -#define primCapName Short -#define wrapperName Short -#define bufferName ShortBuffer -#define primSize 2 -#define alignmentMask 1 -#define TEMP_REORDER_VAR_TYPE jshort - -//#ifdef BIG_ENDIAN -//#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jshort(peer, 0, 1) -//#else -#define REORDER_VALUE_BYTES(peer) REORDER_VALUE_BYTES_jshort(peer, 1, 0) -//#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_undef.h b/libraries/BridJ/src/main/cpp/bridj/PrimDefs_undef.h deleted file mode 100644 index 691c097d3..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/PrimDefs_undef.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifdef primName - #undef primName -#endif - -#ifdef halfJPrimName - #undef halfJPrimName -#endif - -#ifdef primCapName - #undef primCapName -#endif - -#ifdef wrapperName - #undef wrapperName -#endif - -#ifdef bufferName - #undef bufferName -#endif - -#ifdef primSize - #undef primSize -#endif - -#ifdef jprimName - #undef jprimName -#endif - -#ifdef jprimArray - #undef jprimArray -#endif - -#ifdef primJNICapName - #undef primJNICapName -#endif - -#ifdef alignmentMask - #undef alignmentMask -#endif - -#ifdef REORDER_VALUE_BYTES - #undef REORDER_VALUE_BYTES -#endif - -#ifdef REORDER_VALUE_BYTES_ - #undef REORDER_VALUE_BYTES_ -#endif - -#ifdef REORDER_VALUE_BYTES - #undef REORDER_VALUE_BYTES -#endif - -#ifdef TEMP_REORDER_VAR_TYPE - #undef TEMP_REORDER_VAR_TYPE -#endif - -#ifndef __GNUC__ -#ifndef BIG_ENDIAN -#define BIG_ENDIAN -#endif -#endif - -#ifndef REORDER_VALUE_BYTES_jshort -#define REORDER_VALUE_BYTES_jshort(peer, lowerIndex, upperIndex) \ - ((((jshort)((unsigned char*)JLONG_TO_PTR(peer))[upperIndex]) << 8) | ((unsigned char*)JLONG_TO_PTR(peer))[lowerIndex]) -#endif - -#ifndef REORDER_VALUE_BYTES_jint -#define REORDER_VALUE_BYTES_jint(peer, idx0, idx1, idx2, idx3) \ - ( \ - (((jint)((unsigned char*)JLONG_TO_PTR(peer))[idx3]) << 24) | \ - (((jint)((unsigned char*)JLONG_TO_PTR(peer))[idx2]) << 16) | \ - (((jint)((unsigned char*)JLONG_TO_PTR(peer))[idx1]) << 8) | \ - ((unsigned char*)JLONG_TO_PTR(peer))[idx0] \ - ) -#endif - -#ifndef REORDER_VALUE_BYTES_jlong -#define REORDER_VALUE_BYTES_jlong(peer, idx0, idx1, idx2, idx3, idx4, idx5, idx6, idx7) \ - ( \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx7]) << 56) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx6]) << 48) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx5]) << 40) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx4]) << 32) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx3]) << 24) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx2]) << 16) | \ - (((jlong)((unsigned char*)JLONG_TO_PTR(peer))[idx1]) << 8) | \ - ((unsigned char*)JLONG_TO_PTR(peer))[idx0] \ - ) -#endif - diff --git a/libraries/BridJ/src/main/cpp/bridj/Protected.h b/libraries/BridJ/src/main/cpp/bridj/Protected.h deleted file mode 100644 index 96eb49e4f..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/Protected.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#ifndef _BRIDJ_PROTECTED_H -#define _BRIDJ_PROTECTED_H - -#include - -#if defined(__GNUC__) - -#include -#include - -typedef struct Signals { - struct sigaction fOldSIGSEGV; - struct sigaction fOldSIGBUS; - struct sigaction fOldSIGFPE; - struct sigaction fOldSIGCHLD; - struct sigaction fOldSIGABRT; - struct sigaction fOldSIGILL; - struct sigaction fOldSIGTRAP; -} Signals; - -void TrapSignals(Signals* s); -void RestoreSignals(Signals* s); -//void UnixExceptionHandler(int sig); -void UnixExceptionHandler(int, siginfo_t*, void*); - -#else - -// WINDOWS -#include - -void WinExceptionHandler(JNIEnv* env, LPEXCEPTION_POINTERS ex); -int WinExceptionFilter(LPEXCEPTION_POINTERS ex); - -#endif - -#endif // _BRIDJ_PROTECTED_H diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.c b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.c deleted file mode 100644 index 16d5f47f0..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.c +++ /dev/null @@ -1,61 +0,0 @@ - -#include "RawNativeForwardCallback.h" - -#ifdef _WIN64 -#include "dyncallback/dyncall_callback_x64.h" -#include "dyncallback/dyncall_args_x64.h" -#else -#ifdef _WIN32 -#include "dyncallback/dyncall_callback_x86.h" -#include "dyncallback/dyncall_args_x86.h" -#endif -#endif - -#include "dyncallback/dyncall_alloc_wx.h" -#include "dyncallback/dyncall_thunk.h" -#include "dyncall/dyncall_signature.h" - -#pragma warning(disable: 4152) // casting a function pointer as a data pointer - -//extern "C" { -extern void dcRawCallAdapterSkipTwoArgs64(); -extern void dcRawCallAdapterSkipTwoArgs32_cdecl(); -//} - -#if (defined(DC__OS_Linux) || defined(DC__OS_Darwin)) && defined(DC__Arch_AMD64) || defined(_WIN64) -#define DIRECT_SKIP_TWO_ARGS dcRawCallAdapterSkipTwoArgs64 -#elif defined(_WIN32) -#define DIRECT_SKIP_TWO_ARGS dcRawCallAdapterSkipTwoArgs32_cdecl -#endif - -#ifndef DIRECT_SKIP_TWO_ARGS -struct DCAdapterCallback -{ -}; -#else -struct DCAdapterCallback -{ - DCThunk thunk; // offset 0, size 24 - void (*handler)(); -}; -#endif - -DCAdapterCallback* dcRawCallAdapterSkipTwoArgs(void (*handler)(), int callMode) -{ -#ifndef DIRECT_SKIP_TWO_ARGS - return NULL; -#else - int err; - DCAdapterCallback* pcb; - if (callMode != DC_CALL_C_DEFAULT) - return NULL; - - err = dcAllocWX(sizeof(DCAdapterCallback), (void**) &pcb); - if (err != 0) - return 0; - - dcbInitThunk(&pcb->thunk, DIRECT_SKIP_TWO_ARGS); - pcb->handler = handler; - return pcb; -#endif -} diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.h b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.h deleted file mode 100644 index 37da3f27e..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef RawNativeForwardCallback_H -#define RawNativeForwardCallback_H - -#include "../dyncallback/dyncall_callback.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct DCAdapterCallback DCAdapterCallback; - -#ifdef _WIN32 -__declspec(dllexport) -#else -DC_API -#endif -DCAdapterCallback* dcRawCallAdapterSkipTwoArgs(void (*handler)(), int callMode); - -#ifdef __cplusplus -} -#endif - -#endif // DYNCALL_CALLBACK_H - diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Darwin64.s b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Darwin64.s deleted file mode 100644 index 1dc03c67b..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Darwin64.s +++ /dev/null @@ -1,102 +0,0 @@ -/* - Package: dyncall - Library: dyncallback - File: dyncallback/dyncall_callback_x64_apple.s - Description: Callback Thunk - Implementation for x64 (Apple as assembly) - License: - - Copyright (c) 2007-2009 Daniel Adler , - Tassilo Philipp - - Permission to use, copy, modify, and distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -*/ - -.intel_syntax -.text - -/* sizes */ - -.set DCThunk_size , 24 -.set DCArgs_size , 128 -.set DCValue_size , 8 - -/* frame local variable offsets relative to %rbp*/ - -.set FRAME_arg0 , 16 -.set FRAME_return , 8 -.set FRAME_parent , 0 -.set FRAME_DCArgs ,-128 -.set FRAME_DCValue ,-136 - -/* struct DCCallback */ - -.set CTX_thunk , 0 -.set CTX_handler , 24 -.set CTX_userdata , 32 -.set DCCallback_size , 40 -.set STACK_offset , 48//80 // TODO FIXME - -//.globl _dcCallbackThunkEntry -//_dcCallbackThunkEntry: - -.globl _dcRawCallAdapterSkipTwoArgs64 -_dcRawCallAdapterSkipTwoArgs64: - - pushq %rbp - movq %rbp, %rsp - - // Up to 6 ints and/or 8 floats are passed through registers - // To support a max of 16 args (& 2 skipped ones), we hence need to copy a worst case of 10 values from the stack - sub %rsp, 10 * 8 - - push rcx // shadow-push rcx - add %rsp, 8 - - // TODO FIXME - mov %rsi, %rbp - add %rsi, STACK_offset // source of stack args - mov %rdi, %rsp // destination - mov %rcx, 10 // size to copy - rep movsq // copy! - - sub %rsp, 8 - pop rcx - - // integer parameters - mov %rdi , %rdx # parameter 0 - mov %rsi , %rcx # parameter 1 - mov %rdx , %r8 # parameter 2 - mov %rcx , %r9 # parameter 3 - mov %r8, [%rbp + STACK_offset] - mov %r9, [%rbp + STACK_offset + 8] - - // float parameters - //movapd %xmm0 , %xmm2 # float parameter 0 - //movapd %xmm1 , %xmm3 # float parameter 1 - //movapd %xmm2 , %xmm4 # float parameter 2 - //movapd %xmm3 , %xmm5 # float parameter 3 - //movapd %xmm4 , %xmm6 # float parameter 4 - //movapd %xmm5 , %xmm7 # float parameter 5 - //movd %xmm6 , %r8 # float parameter 6 - //movd %xmm7 , %r9 # float parameter 7 - - call [%rax+CTX_handler] - - //movd %xmm0, %rax - -.return: - mov %rsp, %rbp - pop %rbp - ret - diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Linux64.s b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Linux64.s deleted file mode 100644 index 5528e08fa..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_Linux64.s +++ /dev/null @@ -1,83 +0,0 @@ -/* - Package: dyncall - Library: dyncallback - File: dyncallback/dyncall_callback_x64_apple.s - Description: Callback Thunk - Implementation for x64 (Apple as assembly) - License: - - Copyright (c) 2007-2009 Daniel Adler , - Tassilo Philipp - - Permission to use, copy, modify, and distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -*/ - -.intel_syntax -.text - -/* sizes */ - -.set DCThunk_size , 24 -.set DCArgs_size , 128 -.set DCValue_size , 8 - -/* frame local variable offsets relative to %rbp*/ - -.set FRAME_arg0 , 16 -.set FRAME_return , 8 -.set FRAME_parent , 0 -.set FRAME_DCArgs ,-128 -.set FRAME_DCValue ,-136 - -/* struct DCCallback */ - -.set CTX_thunk , 0 -.set CTX_handler , 24 -.set CTX_userdata , 32 -.set DCCallback_size , 40 - -//.globl _dcCallbackThunkEntry -//_dcCallbackThunkEntry: - -.globl dcRawCallAdapterSkipTwoArgs64 -dcRawCallAdapterSkipTwoArgs64: - - pushq %rbp - movq %rbp, %rsp - - // float parameters - //movq %xmm0 , %xmm2 # float parameter 0 - //movq %xmm1 , %xmm3 # float parameter 1 - //movq %xmm2 , %xmm4 # float parameter 2 - //movq %xmm3 , %xmm5 # float parameter 3 - - //movd %xmm0 , %rdx # float parameter 0 - //movd %xmm1 , %rcx # float parameter 1 - //movd %xmm2 , %r8 # float parameter 2 - //movd %xmm3 , %r9 # float parameter 3 - - // integer parameters - mov %rdi , %rdx # parameter 0 - mov %rsi , %rcx # parameter 1 - mov %rdx , %r8 # parameter 2 - mov %rcx , %r9 # parameter 3 - - call [%rax+CTX_handler] - - //movd %xmm0, %rax - -.return: - mov %rsp, %rbp - pop %rbp - ret - diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN32_masm.asm b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN32_masm.asm deleted file mode 100644 index b3f9816a0..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN32_masm.asm +++ /dev/null @@ -1,34 +0,0 @@ -;////////////////////////////////////////////////////////////////////////////// -;/// -;/// Copyright (c) 2009-2010 Olivier Chafik -;/// -;////////////////////////////////////////////////////////////////////////////// - -.386 -.MODEL FLAT -.CODE - -CTX_phandler = 16 - -_dcRawCallAdapterSkipTwoArgs32_cdecl PROC ; EXPORT - - OPTION PROLOGUE:NONE, EPILOGUE:NONE - - ; http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/toc.html - ; remove JNIEnv *env and jobject *this - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - push dword ptr[esp + 4 * 10] - call dword ptr[eax + CTX_phandler] ; call function - add esp, 4 * 8 - - ret - -_dcRawCallAdapterSkipTwoArgs32_cdecl ENDP - -END \ No newline at end of file diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN64_masm.asm b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN64_masm.asm deleted file mode 100644 index 3461fa91d..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_WIN64_masm.asm +++ /dev/null @@ -1,64 +0,0 @@ -;////////////////////////////////////////////////////////////////////////////// -;/// -;/// Copyright (c) 2009-2010 Olivier Chafik -;/// -;////////////////////////////////////////////////////////////////////////////// - -.CODE - -; struct DCCallback -CTX_thunk = 0 -CTX_handler = 24 -CTX_userdata = 32 -DCCallback_size = 40 -STACK_offset = 48 -;ZERO_IREG_ISMS = - -dcRawCallAdapterSkipTwoArgs64 PROC ; EXPORT - - OPTION PROLOGUE:NONE, EPILOGUE:NONE - - push rbp - mov rbp, rsp ; aligns stack to 16 - push rbx - push rsi - push rdi - - ; Copy 16 args from stack (including spill for 3rd and 4th args) - sub rsp, 14 * 8 + 8 ; allocate stack space for 14 args (& align stack) - mov rsi, rbp - add rsi, 48 ; source = extra args on the stack - mov rcx, 14 ; 14 arguments - mov rdi, rsp ; destination = stack - rep movsq ; copy by 8 bytes - - ; Allocate spill for 1st and 2nd args - sub rsp, 2 * 8 - - ; Shift / copy the 4 first integral arguments in registers - mov rcx, r8 - mov rdx, r9 - mov r8, [rbp + STACK_offset] - mov r9, [rbp + STACK_offset + 8] - - ; Shift / copy the 4 first float arguments in registers - movapd xmm0, xmm2 - movapd xmm1, xmm3 - movd xmm2, r8 - movd xmm3, r9 - - call qword ptr[rax+CTX_handler] - - add rsp, 16 * 8 + 8 ; pop spills + args + dealign - - pop rdi - pop rsi - pop rbx - pop rbp - ;add rsp, 8 - - ret - -dcRawCallAdapterSkipTwoArgs64 ENDP - -END diff --git a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_arch.S b/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_arch.S deleted file mode 100644 index 7c25d16cc..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback_arch.S +++ /dev/null @@ -1,24 +0,0 @@ -#include "dyncall_macros.h" - -#if defined(DC__OS_Darwin) -# if defined(DC__Arch_Intel_x86) - //TODO -# elif defined(DC__Arch_AMD64) -# include "RawNativeForwardCallback_Darwin64.s" -# endif -#elif defined(DC__OS_Linux) -# if defined(DC__Arch_Intel_x86) - //TODO -# elif defined(DC__Arch_AMD64) -# include "RawNativeForwardCallback_Linux64.s" -# elif defined(DC__Arch_PowerPC) - -# endif -#else -# if defined(DC__Arch_Intel_x86) - //TODO -# elif defined(DC__Arch_AMD64) - //TODO -# endif -#endif - diff --git a/libraries/BridJ/src/main/cpp/bridj/ThreadLocal.c b/libraries/BridJ/src/main/cpp/bridj/ThreadLocal.c deleted file mode 100644 index f06ed1eac..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/ThreadLocal.c +++ /dev/null @@ -1,176 +0,0 @@ -#include "bridj.hpp" -#include -#include "Exceptions.h" -#include - -extern jclass gBridJClass; -//extern jmethodID gGetTempCallStruct; -//extern jmethodID gReleaseTempCallStruct; -void freeCurrentThreadLocalData(); - -typedef struct CallTempStructNode { - struct CallTempStruct fCallTempStruct; - struct CallTempStructNode* fPrevious; - struct CallTempStructNode* fNext; - jboolean fUsed; -} CallTempStructNode; - -void InitCallTempStruct(CallTempStruct* s) { - s->vm = dcNewCallVM(1024); -} -CallTempStructNode* NewNode(CallTempStructNode* pPrevious) { - //printf("### Creating new temp node...\n"); - CallTempStructNode* pNode = MALLOC_STRUCT(CallTempStructNode); - memset(pNode, 0, sizeof(CallTempStructNode)); - InitCallTempStruct(&pNode->fCallTempStruct); - //pNode->fCallTempStruct.vm = dcNewCallVM(1024); - if (pPrevious) { - pPrevious->fNext = pNode; - pNode->fPrevious = pPrevious; - } - return pNode; -} - -void FreeCallTempStruct(CallTempStruct* s) { - dcFree(s->vm); -} - - -void FreeNodes(CallTempStructNode* pNode) { - while (pNode) { - CallTempStructNode* pNext = pNode->fNext; - FreeCallTempStruct(&pNode->fCallTempStruct); - free(pNode); - pNode = pNext; - } -} - -#if defined(DC__OS_Win64) || defined(DC__OS_Win32) - -#include - -DWORD gTlsIndex = TLS_OUT_OF_INDEXES; -#define GET_THREAD_LOCAL_DATA() ((CallTempStructNode*)TlsGetValue(gTlsIndex)) -#define SET_THREAD_LOCAL_DATA(data) TlsSetValue(gTlsIndex, data); - -void initThreadLocal(JNIEnv* env) { - gTlsIndex = TlsAlloc(); - if (gTlsIndex == TLS_OUT_OF_INDEXES) { - throwException(env, "Failed to initialize the thread-local mechanism !"); - return; - } -} - -BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) -{ - switch (fdwReason) - { - case DLL_PROCESS_ATTACH: - break; - case DLL_THREAD_ATTACH: - break; - case DLL_THREAD_DETACH: - freeCurrentThreadLocalData(); - break; - case DLL_PROCESS_DETACH: - if (gTlsIndex != TLS_OUT_OF_INDEXES) { - freeCurrentThreadLocalData(); - TlsFree(gTlsIndex); - } - break; - default: - break; - } - - return TRUE; - UNREFERENCED_PARAMETER(hinstDLL); - UNREFERENCED_PARAMETER(lpvReserved); -} - -#else - -#include - -pthread_key_t gTlsKey; -#define GET_THREAD_LOCAL_DATA() ((CallTempStructNode*)pthread_getspecific(gTlsKey)) -#define SET_THREAD_LOCAL_DATA(data) pthread_setspecific(gTlsKey, data); - -void destroyThreadLocal(void* data) { - FreeNodes((CallTempStructNode*)data); -} -void initThreadLocal(JNIEnv* env) { - pthread_key_create(&gTlsKey, destroyThreadLocal); -} - -/* -CallTempStruct* getTempCallStruct(JNIEnv* env) { - jlong handle = (*env)->CallStaticLongMethod(env, gBridJClass, gGetTempCallStruct); - return (CallTempStruct*)JLONG_TO_PTR(handle); -} -void releaseTempCallStruct(JNIEnv* env, CallTempStruct* s) { - //s->env = NULL; - jlong h = PTR_TO_JLONG(s); - (*env)->CallStaticVoidMethod(env, gBridJClass, gReleaseTempCallStruct, h); -}*/ - -#endif - -#if 1 -CallTempStruct* getTempCallStruct(JNIEnv* env) { - CallTempStructNode* pNode = (CallTempStructNode*)GET_THREAD_LOCAL_DATA(); - if (!pNode) { - pNode = NewNode(NULL); - SET_THREAD_LOCAL_DATA(pNode); - } - - if (pNode->fUsed) { - if (!pNode->fNext) - pNode->fNext = NewNode(pNode); - - pNode = pNode->fNext; - SET_THREAD_LOCAL_DATA(pNode); - } - pNode->fUsed = JNI_TRUE; - return &pNode->fCallTempStruct; -} - -CallTempStruct* getCurrentTempCallStruct(JNIEnv* env) { - CallTempStructNode* pNode = (CallTempStructNode*)GET_THREAD_LOCAL_DATA(); - if (!pNode || !pNode->fUsed) - return NULL; - - return &pNode->fCallTempStruct; -} - -void releaseTempCallStruct(JNIEnv* env, CallTempStruct* s) { - CallTempStructNode* pNode = (CallTempStructNode*)GET_THREAD_LOCAL_DATA(); - if (!pNode || &pNode->fCallTempStruct != s) { - throwException(env, "Invalid thread-local status : critical bug !"); - return; - } - pNode->fUsed = JNI_FALSE; - if (pNode->fPrevious) - SET_THREAD_LOCAL_DATA(pNode->fPrevious); -} - -void freeCurrentThreadLocalData() { - CallTempStructNode* pNode = (CallTempStructNode*)GET_THREAD_LOCAL_DATA(); - FreeNodes(pNode); - SET_THREAD_LOCAL_DATA(NULL); -} -#else - -CallTempStruct* getTempCallStruct(JNIEnv* env) { - CallTempStruct* s = MALLOC_STRUCT(CallTempStruct); - InitCallTempStruct(s); - return s; -} - -void releaseTempCallStruct(JNIEnv* env, CallTempStruct* s) { - FreeCallTempStruct(s); - free(s); -} - -void freeCurrentThreadLocalData() { -} -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/bridj.hpp b/libraries/BridJ/src/main/cpp/bridj/bridj.hpp deleted file mode 100644 index 709deb9fd..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/bridj.hpp +++ /dev/null @@ -1,236 +0,0 @@ -#ifndef BRIDJ_H -#define BRIDJ_H - -#ifndef BRIDJ_API -#define BRIDJ_API -#endif - -#pragma warning(error: 4061) -#pragma warning(disable: 4127) -#pragma warning(disable: 4100) // unreferenced formal parameter -#pragma warning(disable: 4706) // assignment inside a conditional expression -#pragma warning(disable: 4054) // casting a function pointer to a data pointer -#pragma warning(disable: 4996) - -#ifndef _WIN32 -#define __cdecl -#endif - -#ifdef _WIN32 -#define SUPPORTS_UNALIGNED_ACCESS -#endif - -#if defined(_WIN64) || (!defined (DC__OS_Darwin) && !defined(DC__OS_Linux) && !defined(_WIN32)) -//#define NO_DIRECT_CALLS // TODO REMOVE ME !!! (issues with stack alignment on COM calls ?) -#endif - -#include "dyncallback/dyncall_callback.h" -#include -#include - -#if defined(__GNUC__) -#include -#endif - - -#ifdef _MSC_VER -# define THREAD_STATIC __declspec(thread) static -#else -# define THREAD_STATIC static -//TODO http://www.opengroup.org/onlinepubs/009695399/functions/pthread_key_create.html -//static __thread -#endif - -#define MAX(x, y) (x < y ? y : x) -#define PTR_TO_JLONG(ptr) ((jlong)(size_t)(ptr)) -#define JLONG_TO_PTR(jl) ((void*)(size_t)(jl)) -#define MALLOC_STRUCT(type) ((struct type*)malloc(sizeof(struct type))) -#define MALLOC_STRUCT_ARRAY(type, size) ((struct type*)malloc(sizeof(struct type) * size)) - -#define STRING_SIG "Ljava/lang/String;" - -#define Modifier_ABSTRACT 1024 -#define Modifier_FINAL 16 -#define Modifier_INTERFACE 512 -#define Modifier_NATIVE 256 -#define Modifier_PRIVATE 2 -#define Modifier_PROTECTED 4 -#define Modifier_PUBLIC 1 -#define Modifier_STATIC 8 -#define Modifier_STRICT 2048 -#define Modifier_SYNCHRONIZED 32 -#define Modifier_TRANSIENT 128 -#define Modifier_VOLATILE 64 - -extern jboolean gLog; - -#include "Protected.h" - -typedef enum ValueType { - eVoidValue = 0, - eWCharValue, - eCLongValue, - eCLongObjectValue, - eSizeTValue, - eSizeTObjectValue, - eIntValue, - eShortValue, - eByteValue, - eBooleanValue, - eLongValue, - eDoubleValue, - eFloatValue, - ePointerValue, - eEllipsis, - eIntFlagSet, - eNativeObjectValue, - eTimeTObjectValue -} ValueType; - -typedef struct CallTempStruct { - DCCallVM* vm; - JNIEnv *env; - jobject* pCallIOs; -#if defined(__GNUC__) - jmp_buf exceptionContext; - Signals signals; - int signal, signalCode; - jlong signalAddress; -#endif -} CallTempStruct; - -typedef struct CommonCallbackInfo { - int nParams; - char fDCReturnType; - enum ValueType fReturnType; - enum ValueType* fParamTypes; - int fDCMode; - jobject* fCallIOs; - void* fDCCallback; - JNIEnv* fEnv; - jmethodID fMethodID; - jobject fMethod; -} CommonCallbackInfo; - -typedef struct VirtualMethodCallInfo { - struct CommonCallbackInfo fInfo; - jclass fClass; - jboolean fHasThisPtrArg; - int fVirtualIndex; - int fVirtualTableOffset; -} VirtualMethodCallInfo; - -typedef struct FunctionCallInfo { - struct CommonCallbackInfo fInfo; - jclass fClass; - void* fForwardedSymbol; - jboolean fCheckLastError; -} FunctionCallInfo, CPPMethodCallInfo; - -#ifdef BRIDJ_OBJC_SUPPORT -#include - -typedef struct JavaToObjCCallInfo { - struct CommonCallbackInfo fInfo; - SEL fSelector; - jlong fNativeClass; -} JavaToObjCCallInfo; - -char __cdecl JavaToObjCCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -#endif - -typedef struct StructFieldInfo { - struct CommonCallbackInfo fInfo; - void* fJNICallFunction; - jint fFieldIndex; -} StructFieldInfo; - - -typedef struct NativeToJavaCallbackCallInfo { - struct CommonCallbackInfo fInfo; - void* fJNICallFunction; - jobject fCallbackInstance; - jboolean fIsGenericCallback; - jboolean fIsObjCBlock; -} NativeToJavaCallbackCallInfo; - -typedef struct JavaToNativeCallbackCallInfo { - struct CommonCallbackInfo fInfo; -} JavaToNativeCallbackCallInfo; - -char __cdecl JavaToFunctionCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl JavaToCPPMethodCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl JavaToVirtualMethodCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl JavaToCCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl CToJavaCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl CPPToJavaCallHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); -char __cdecl StructHandler(DCCallback* callback, DCArgs* args, DCValue* result, void* userdata); - -extern jclass gPointerClass; - -#define BOX_METHOD_DECL(prim, shortName, methShort, type, letter) \ -extern jclass g ## shortName ## Class; \ -jobject Box ## shortName(JNIEnv* env, type v); \ -type Unbox ## shortName(JNIEnv* env, jobject v); - -BOX_METHOD_DECL("org/bridj/TimeT", TimeT, Long, time_t, "J"); -BOX_METHOD_DECL("org/bridj/SizeT", SizeT, Long, jlong, "J"); -BOX_METHOD_DECL("org/bridj/CLong", CLong, Long, long, "J"); -BOX_METHOD_DECL("java/lang/Integer", Int, Int, jint, "I"); -BOX_METHOD_DECL("java/lang/Long", Long, Long, jlong, "J"); -BOX_METHOD_DECL("java/lang/Short", Short, Short, jshort, "S"); -BOX_METHOD_DECL("java/lang/Byte", Byte, Byte, jbyte, "B"); -BOX_METHOD_DECL("java/lang/Boolean", Boolean, Boolean, jboolean, "Z"); -BOX_METHOD_DECL("java/lang/Character", Char, Char, jchar, "C"); -BOX_METHOD_DECL("java/lang/Float", Float, Float, jfloat, "F"); -BOX_METHOD_DECL("java/lang/Double", Double, Double, jdouble, "D"); - -void* getNativeObjectPointer(JNIEnv* env, jobject instance, jclass targetClass); -void* getPointerPeer(JNIEnv *env, jobject pointer); -jobject getJavaObjectForNativePointer(JNIEnv *env, void* nativeObject); -jobject createPointerFromIO(JNIEnv *env, void* ptr, jobject callIO); -DCstruct* getStructFromIO(JNIEnv *env, jobject callIO); -DCstruct* getNativeObjectPointerWithIO(JNIEnv *env, jobject instance, jobject callIO); - -void callSinglePointerArgVoidFunction(JNIEnv *env, void* constructor, void* thisPtr, int callMode); -jlong getFlagValue(JNIEnv *env, jobject flagSet); - -JNIEnv* GetEnv(); - -#define THROW_EXCEPTION(env, message, ...) \ -{ \ - char err[256]; \ - sprintf(err, message, ##__VA_ARGS__); \ - throwException(env, err); \ -} - -void throwException(JNIEnv* env, const char* message); -jboolean assertThrow(JNIEnv* env, jboolean value, const char* message); -void printStackTrace(JNIEnv* env, jthrowable ex); -void logCall(JNIEnv *env, jobject method); - -void initThreadLocal(JNIEnv* env); -CallTempStruct* getTempCallStruct(JNIEnv* env); -CallTempStruct* getCurrentTempCallStruct(JNIEnv* env); -void releaseTempCallStruct(JNIEnv* env, CallTempStruct* s); -void cleanupCallHandler(CallTempStruct* call); - -#define GET_CHARS(javaStr) (javaStr ? (*env)->GetStringUTFChars(env, javaStr, NULL) : NULL) -#define RELEASE_CHARS(javaStr, cStr) if (javaStr) (*env)->ReleaseStringUTFChars(env, javaStr, cStr) - -#define FORCE_CRASH() \ - {\ - char* p = (char*)NULL;\ - for (int i = 0; i < 1000; i++)\ - *p = *p + 1;\ - } - -#if defined(_WIN32) && !defined(_WIN64) -#define HACK_REFETCH_ENV() env = GetEnv(); -#else -#define HACK_REFETCH_ENV() -#endif - - -#endif - diff --git a/libraries/BridJ/src/main/cpp/bridj/dyncall.diff b/libraries/BridJ/src/main/cpp/bridj/dyncall.diff deleted file mode 100644 index 13c0e4d6a..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/dyncall.diff +++ /dev/null @@ -1,362 +0,0 @@ -Index: dyncall/buildsys/gmake/os/darwin.gmake -=================================================================== ---- dyncall/buildsys/gmake/os/darwin.gmake (revision 1377) -+++ dyncall/buildsys/gmake/os/darwin.gmake (working copy) -@@ -23,7 +23,8 @@ - LIBTOOL_STATIC=libtool -static -o $@ $^ - - ifdef BUILD_ARCH_universal --TARGET_ARCH?=-arch i386 -arch ppc -arch x86_64 -+#TARGET_ARCH?=-arch i386 -arch ppc -arch x86_64 -+TARGET_ARCH?=-arch x86_64 -arch i386 - endif - - ifdef BUILD_ARCH_ppc32 -Index: dyncall/buildsys/gmake/tool/gcc.gmake -=================================================================== ---- dyncall/buildsys/gmake/tool/gcc.gmake (revision 1377) -+++ dyncall/buildsys/gmake/tool/gcc.gmake (working copy) -@@ -86,6 +86,13 @@ - - # $(CC) -MM -MT $@ $(CPPFLAGS) $(CFLAGS) $< > $(BUILD_DIR)/$*.d - -+# --- Compile Objective-C --------------------------------------------------------------- -+ -+$(BUILD_DIR)/%.o: %.m -+ $(COMPILE.c) $< $(OUTPUT_OPTION) -+ -+# $(CC) -MM -MT $@ $(CPPFLAGS) $(CFLAGS) $< > $(BUILD_DIR)/$*.d -+ - # --- Compile C++ ------------------------------------------------------------- - - $(BUILD_DIR)/%.o: %.cpp -Index: dyncall/dynload/dynload_windows.c -=================================================================== ---- dyncall/dynload/dynload_windows.c (revision 1377) -+++ dyncall/dynload/dynload_windows.c (working copy) -@@ -40,7 +40,9 @@ - DLLib* dlLoadLibrary(const char* libPath) - { - if (libPath != NULL) { -- return (DLLib*) LoadLibraryA(libPath); -+ return (DLLib*) LoadLibraryW((wchar_t*)(void*)libPath); -+ // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx -+ // return (DLLib*) LoadLibraryExA(libPath, NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_DEFAULT_DIRS); - /*return (DLLib*) LoadLibraryA(libPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);*/ - } else { - return (DLLib*) GetModuleHandle(NULL); -Index: dyncall/dynload/dynload_syms_mach-o.c -=================================================================== ---- dyncall/dynload/dynload_syms_mach-o.c (revision 1377) -+++ dyncall/dynload/dynload_syms_mach-o.c (working copy) -@@ -28,6 +28,7 @@ - dynamic symbol resolver for Mach-O - - */ -+#include "../autovar/autovar_ARCH.h" - - #include "dynload.h" - #include "dynload_alloc.h" -@@ -39,15 +40,16 @@ - - #if defined(ARCH_X64) - #define MACH_HEADER_TYPE mach_header_64 -+#define MACH_MAGIC MH_MAGIC_64 - #define SEGMENT_COMMAND segment_command_64 - #define NLIST_TYPE nlist_64 - #else - #define MACH_HEADER_TYPE mach_header -+#define MACH_MAGIC MH_MAGIC - #define SEGMENT_COMMAND segment_command - #define NLIST_TYPE nlist - #endif - -- - struct DLLib_ - { - char* libPath; -@@ -57,12 +59,140 @@ - - struct DLSyms_ - { -+ const char** decompressedSymbols; - const char* pStringTable; - const struct NLIST_TYPE* pSymbolTable; - uint32_t symbolCount; - }; - -+int isSameMacImageName(const char* libPath, const char* systemLibPath) { -+ if (!libPath || !systemLibPath) -+ return 0; -+ -+ if (!strcmp(libPath, systemLibPath)) -+ return 1; -+ -+ if (strstr(libPath, "/libc.") && strstr(systemLibPath, "/libSystem.")) -+ return 1; -+ -+ return 0; -+} - -+/// -+/// LEB128 DECODING (http://en.wikipedia.org/wiki/LEB128) -+/// -+unsigned long long decode_leb128(const unsigned char** ppIn) { -+ const unsigned char* pIn = *ppIn; -+ unsigned char input; -+ unsigned long long decoded = 0; -+ int shift = 0; -+ do { -+ input = *pIn++; -+ decoded |= (((unsigned long long)(input & 0x7f)) << shift); -+ shift += 7; -+ } while (input & 0x80); -+ -+ *ppIn = pIn; -+ return decoded; -+} -+ -+/// -+/// DUMMY APPENDABLE STRING -+/// -+typedef struct _DCString { -+ char* buffer; -+ size_t capacity; -+} DCString; -+void initString(DCString* s, size_t capacity) { -+ if (!s) -+ return; -+ -+ s->buffer = dlAllocMem((s->capacity = capacity) + 1); -+ s->buffer[0] = '\0'; -+} -+void appendString(DCString* s, const char* suffix) { -+ if (!s) -+ return; -+ -+ size_t suffixLen = strlen(suffix), sLen = strlen(s->buffer); -+ if (suffixLen + sLen > s->capacity) { -+ char* old = s->buffer; -+ initString(s, (suffixLen + sLen) * 3 / 2); -+ strcpy(s->buffer, old); -+ dlFreeMem(old); -+ } -+ strcpy(s->buffer + sLen, suffix); -+} -+void freeString(DCString* s) { -+ if (s->buffer) { -+ dlFreeMem(s->buffer); -+ s->buffer = NULL; -+ s->capacity = 0; -+ } -+} -+ -+/// -+/// MACHO COMPRESSED SYMBOLS TRIE VISITATION -+/// -+typedef void (*SymbolOutputFunction)(const char* symbol, size_t index, void* payload); -+ -+#define MAX_DEPTH 256 -+ -+size_t visitTrie( -+ const unsigned char* start, -+ const unsigned char* current, -+ const unsigned char* end, -+ DCString* prefix, -+ SymbolOutputFunction output, size_t indexOffset, void* payload, int depth) -+{ -+ size_t count = 0; -+ if (current < end && depth < MAX_DEPTH) { -+ unsigned char term_size = *current++; -+ if (term_size != 0) { -+ //const unsigned char* pos = current; -+ //unsigned long long flags = decode_leb128(&pos); -+ //unsigned long long addr = decode_leb128(&pos); -+ { -+ if (prefix && output) -+ output(prefix->buffer, indexOffset, payload); -+ -+ indexOffset++; -+ count++; -+ } -+ -+ current += term_size; -+ } -+ -+ unsigned char iSubNode, nSubNodes = *current++; -+ -+ size_t prefixLen = prefix ? strlen(prefix->buffer) : 0; -+ for (iSubNode = 0; iSubNode < nSubNodes; iSubNode++) { -+ unsigned long long subNodeOffset; -+ const char* suffix = (const char*)current; -+ current += strlen(suffix) + 1; -+ if (!(subNodeOffset = decode_leb128(¤t))) -+ continue; -+ -+ appendString(prefix, suffix); -+ size_t subCount = visitTrie(start, start + subNodeOffset, end, prefix, output, indexOffset, payload, depth + 1); -+ count += subCount; -+ indexOffset += subCount; -+ if (prefix) -+ prefix->buffer[prefixLen] = '\0'; -+ } -+ } -+ return count; -+} -+ -+/// Callback to harvest symbols visited in trie -+void CopyToNthString(const char* str, size_t index, void* payload) { -+ const char** pstr = (const char**)payload; -+ size_t len = strlen(str); -+ char* copy = dlAllocMem(len + 1); -+ strcpy(copy, str); -+ pstr[index] = copy; -+} -+ - DLSyms* dlSymsInit(const char* libPath) - { - DLSyms* pSyms = NULL; -@@ -70,27 +200,59 @@ - for (iImage = 0, nImages = _dyld_image_count(); iImage < nImages; iImage++) - { - const char* name = _dyld_get_image_name(iImage); -- if (name && !strcmp(name, libPath)) -+ if (isSameMacImageName(libPath, name)) - { - const struct MACH_HEADER_TYPE* pHeader = (const struct MACH_HEADER_TYPE*) _dyld_get_image_header(iImage); - const char* pBase = ((const char*)pHeader); -+ if (!pHeader) -+ return NULL; -+ -+ if (pHeader->magic != MACH_MAGIC) -+ return NULL; - if (pHeader->filetype != MH_DYLIB) - return NULL; -- if (pHeader->flags & MH_SPLIT_SEGS) -+ if (pHeader->flags & MH_SPLIT_SEGS || !(pHeader->flags & MH_DYLDLINK)) - return NULL; -- -- if (pHeader) -+ - { - uint32_t iCmd, nCmds = pHeader->ncmds; - const struct load_command* cmd = (const struct load_command*)(pBase + sizeof(struct MACH_HEADER_TYPE)); - - for (iCmd = 0; iCmd < nCmds; iCmd++) - { -- if (cmd->cmd == LC_SYMTAB) -- { -+ if (cmd->cmd == LC_DYLD_INFO_ONLY || cmd->cmd == LC_DYLD_INFO) { -+ const struct dyld_info_command* dcmd = (const struct dyld_info_command*)cmd; -+ const unsigned char* trie = (pBase + dcmd->export_off); -+ -+ pSyms = (DLSyms*)( dlAllocMem(sizeof(DLSyms)) ); -+ -+ // First, get the number of symbols -+ pSyms->symbolCount = visitTrie(trie, trie, trie + dcmd->export_size, NULL, NULL, 0, NULL, 0); -+ -+ if (pSyms->symbolCount) { -+ // Now revisit and copy symbols to their destination -+ DCString s; -+ size_t decompSize = pSyms->symbolCount * sizeof(char*) * 2; -+ pSyms->decompressedSymbols = dlAllocMem(decompSize); -+ memset(pSyms->decompressedSymbols, decompSize, 0); -+ initString(&s, 1024); -+ visitTrie(trie, trie, trie + dcmd->export_size, &s, CopyToNthString, 0, pSyms->decompressedSymbols, 0); -+ freeString(&s); -+ } -+ -+ return pSyms; -+ } -+ -+ if (cmd->cmd & LC_REQ_DYLD) { -+ return NULL; // "unknown load command required for execution"; -+ } -+ if (cmd->cmd == LC_SYMTAB) -+ { - const struct symtab_command* scmd = (const struct symtab_command*)cmd; - - pSyms = (DLSyms*)( dlAllocMem(sizeof(DLSyms)) ); -+ //memset(pSyms, sizeof(DLSyms), 0); -+ pSyms->decompressedSymbols = NULL; - pSyms->symbolCount = scmd->nsyms; - pSyms->pStringTable = pBase + scmd->stroff; - pSyms->pSymbolTable = (struct NLIST_TYPE*)(pBase + scmd->symoff); -@@ -100,7 +262,6 @@ - cmd = (const struct load_command*)(((char*)cmd) + cmd->cmdsize); - } - } -- break; - } - } - return NULL; -@@ -112,6 +273,18 @@ - if (!pSyms) - return; - -+ if (pSyms->decompressedSymbols) { -+ size_t i, n = pSyms->symbolCount; -+ for (i = 0; i < n; i++) { -+ char* str = pSyms->decompressedSymbols[i]; -+ if (str) { -+ dlFreeMem(str); -+ pSyms->decompressedSymbols[i] = NULL; -+ } -+ } -+ dlFreeMem(pSyms->decompressedSymbols); -+ pSyms->decompressedSymbols = NULL; -+ } - dlFreeMem(pSyms); - } - -@@ -132,6 +305,11 @@ - if (nl->n_un.n_strx <= 1) - return NULL; // would be empty string anyway - -+ if (!(nl->n_type & N_EXT) || (nl->n_type & N_PEXT)) -+ return NULL; // not a public external symbol -+ if (nl->n_type & N_STAB) -+ return NULL; -+ - //TODO skip more symbols based on nl->n_desc and nl->n_type ? - return nl; - } -@@ -139,6 +317,12 @@ - - const char* dlSymsName(DLSyms* pSyms, int index) - { -+ if (!pSyms || index >= pSyms->symbolCount) -+ return NULL; -+ -+ if (pSyms->decompressedSymbols) -+ return pSyms->decompressedSymbols[index]; -+ - const struct NLIST_TYPE* nl = get_nlist(pSyms, index); - if (!nl) - return NULL; -@@ -149,6 +333,12 @@ - - void* dlSymsValue(DLSyms* pSyms, int index) - { -+ if (!pSyms || index >= pSyms->symbolCount) -+ return NULL; -+ -+ if (pSyms->decompressedSymbols) -+ return NULL; // TODO use dlFindSymbol -+ - const struct NLIST_TYPE* nl = get_nlist(pSyms, index); - if (!nl) - return NULL; -Index: dyncall/dynload/dynload_unix.c -=================================================================== ---- dyncall/dynload/dynload_unix.c (revision 1377) -+++ dyncall/dynload/dynload_unix.c (working copy) -@@ -40,7 +40,7 @@ - - DLLib* dlLoadLibrary(const char* libPath) - { -- return (DLLib*)dlopen(libPath,RTLD_NOW|RTLD_GLOBAL); -+ return (DLLib*)dlopen(libPath,RTLD_LAZY|RTLD_GLOBAL); - } - - diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ.h deleted file mode 100644 index 3cf4642b3..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_BridJ */ - -#ifndef _Included_org_bridj_BridJ -#define _Included_org_bridj_BridJ -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_CastingType.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_CastingType.h deleted file mode 100644 index 209ee78f4..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_CastingType.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_BridJ_CastingType */ - -#ifndef _Included_org_bridj_BridJ_CastingType -#define _Included_org_bridj_BridJ_CastingType -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_Switch.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_Switch.h deleted file mode 100644 index 4fbf932d6..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_BridJ_Switch.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_BridJ_Switch */ - -#ifndef _Included_org_bridj_BridJ_Switch -#define _Included_org_bridj_BridJ_Switch -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_JNI.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_JNI.h deleted file mode 100644 index 341cebcbf..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_JNI.h +++ /dev/null @@ -1,941 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_JNI */ - -#ifndef _Included_org_bridj_JNI -#define _Included_org_bridj_JNI -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: org_bridj_JNI - * Method: getEnv - * Signature: ()J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getEnv - (JNIEnv *, jclass); - -/* - * Class: org_bridj_JNI - * Method: getJVM - * Signature: ()J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getJVM - (JNIEnv *, jclass); - -/* - * Class: org_bridj_JNI - * Method: refToObject - * Signature: (J)Ljava/lang/Object; - */ -JNIEXPORT jobject JNICALL Java_org_bridj_JNI_refToObject - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: loadLibrary - * Signature: (Ljava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_loadLibrary - (JNIEnv *, jclass, jstring); - -/* - * Class: org_bridj_JNI - * Method: freeLibrary - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeLibrary - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: loadLibrarySymbols - * Signature: (Ljava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_loadLibrarySymbols - (JNIEnv *, jclass, jstring); - -/* - * Class: org_bridj_JNI - * Method: freeLibrarySymbols - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeLibrarySymbols - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: findSymbolInLibrary - * Signature: (JLjava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_findSymbolInLibrary - (JNIEnv *, jclass, jlong, jstring); - -/* - * Class: org_bridj_JNI - * Method: getLibrarySymbols - * Signature: (JJ)[Ljava/lang/String; - */ -JNIEXPORT jobjectArray JNICALL Java_org_bridj_JNI_getLibrarySymbols - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: findSymbolName - * Signature: (JJJ)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_org_bridj_JNI_findSymbolName - (JNIEnv *, jclass, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: newGlobalRef - * Signature: (Ljava/lang/Object;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_newGlobalRef - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_JNI - * Method: deleteGlobalRef - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_deleteGlobalRef - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: newWeakGlobalRef - * Signature: (Ljava/lang/Object;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_newWeakGlobalRef - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_JNI - * Method: deleteWeakGlobalRef - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_deleteWeakGlobalRef - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: newDirectByteBuffer - * Signature: (JJ)Ljava/nio/ByteBuffer; - */ -JNIEXPORT jobject JNICALL Java_org_bridj_JNI_newDirectByteBuffer - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: getDirectBufferAddress - * Signature: (Ljava/nio/Buffer;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getDirectBufferAddress - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_JNI - * Method: getDirectBufferCapacity - * Signature: (Ljava/nio/Buffer;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getDirectBufferCapacity - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_JNI - * Method: getIntArrayElements - * Signature: ([I[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getIntArrayElements - (JNIEnv *, jclass, jintArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseIntArrayElements - * Signature: ([IJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseIntArrayElements - (JNIEnv *, jclass, jintArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_int - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_org_bridj_JNI_get_1int - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_int - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1int - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_int_array - * Signature: (JI)[I - */ -JNIEXPORT jintArray JNICALL Java_org_bridj_JNI_get_1int_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_int_array - * Signature: (J[III)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1int_1array - (JNIEnv *, jclass, jlong, jintArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_int_disordered - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_org_bridj_JNI_get_1int_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_int_disordered - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1int_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_int_array_disordered - * Signature: (JI)[I - */ -JNIEXPORT jintArray JNICALL Java_org_bridj_JNI_get_1int_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_int_array_disordered - * Signature: (J[III)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1int_1array_1disordered - (JNIEnv *, jclass, jlong, jintArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getLongArrayElements - * Signature: ([J[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getLongArrayElements - (JNIEnv *, jclass, jlongArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseLongArrayElements - * Signature: ([JJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseLongArrayElements - (JNIEnv *, jclass, jlongArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_long - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_get_1long - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_long - * Signature: (JJ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1long - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: get_long_array - * Signature: (JI)[J - */ -JNIEXPORT jlongArray JNICALL Java_org_bridj_JNI_get_1long_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_long_array - * Signature: (J[JII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1long_1array - (JNIEnv *, jclass, jlong, jlongArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_long_disordered - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_get_1long_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_long_disordered - * Signature: (JJ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1long_1disordered - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: get_long_array_disordered - * Signature: (JI)[J - */ -JNIEXPORT jlongArray JNICALL Java_org_bridj_JNI_get_1long_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_long_array_disordered - * Signature: (J[JII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1long_1array_1disordered - (JNIEnv *, jclass, jlong, jlongArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getShortArrayElements - * Signature: ([S[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getShortArrayElements - (JNIEnv *, jclass, jshortArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseShortArrayElements - * Signature: ([SJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseShortArrayElements - (JNIEnv *, jclass, jshortArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_short - * Signature: (J)S - */ -JNIEXPORT jshort JNICALL Java_org_bridj_JNI_get_1short - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_short - * Signature: (JS)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1short - (JNIEnv *, jclass, jlong, jshort); - -/* - * Class: org_bridj_JNI - * Method: get_short_array - * Signature: (JI)[S - */ -JNIEXPORT jshortArray JNICALL Java_org_bridj_JNI_get_1short_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_short_array - * Signature: (J[SII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1short_1array - (JNIEnv *, jclass, jlong, jshortArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_short_disordered - * Signature: (J)S - */ -JNIEXPORT jshort JNICALL Java_org_bridj_JNI_get_1short_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_short_disordered - * Signature: (JS)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1short_1disordered - (JNIEnv *, jclass, jlong, jshort); - -/* - * Class: org_bridj_JNI - * Method: get_short_array_disordered - * Signature: (JI)[S - */ -JNIEXPORT jshortArray JNICALL Java_org_bridj_JNI_get_1short_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_short_array_disordered - * Signature: (J[SII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1short_1array_1disordered - (JNIEnv *, jclass, jlong, jshortArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getByteArrayElements - * Signature: ([B[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getByteArrayElements - (JNIEnv *, jclass, jbyteArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseByteArrayElements - * Signature: ([BJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseByteArrayElements - (JNIEnv *, jclass, jbyteArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_byte - * Signature: (J)B - */ -JNIEXPORT jbyte JNICALL Java_org_bridj_JNI_get_1byte - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_byte - * Signature: (JB)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1byte - (JNIEnv *, jclass, jlong, jbyte); - -/* - * Class: org_bridj_JNI - * Method: get_byte_array - * Signature: (JI)[B - */ -JNIEXPORT jbyteArray JNICALL Java_org_bridj_JNI_get_1byte_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_byte_array - * Signature: (J[BII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1byte_1array - (JNIEnv *, jclass, jlong, jbyteArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getCharArrayElements - * Signature: ([C[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getCharArrayElements - (JNIEnv *, jclass, jcharArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseCharArrayElements - * Signature: ([CJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseCharArrayElements - (JNIEnv *, jclass, jcharArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_char - * Signature: (J)C - */ -JNIEXPORT jchar JNICALL Java_org_bridj_JNI_get_1char - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_char - * Signature: (JC)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1char - (JNIEnv *, jclass, jlong, jchar); - -/* - * Class: org_bridj_JNI - * Method: get_char_array - * Signature: (JI)[C - */ -JNIEXPORT jcharArray JNICALL Java_org_bridj_JNI_get_1char_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_char_array - * Signature: (J[CII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1char_1array - (JNIEnv *, jclass, jlong, jcharArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_char_disordered - * Signature: (J)C - */ -JNIEXPORT jchar JNICALL Java_org_bridj_JNI_get_1char_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_char_disordered - * Signature: (JC)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1char_1disordered - (JNIEnv *, jclass, jlong, jchar); - -/* - * Class: org_bridj_JNI - * Method: get_char_array_disordered - * Signature: (JI)[C - */ -JNIEXPORT jcharArray JNICALL Java_org_bridj_JNI_get_1char_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_char_array_disordered - * Signature: (J[CII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1char_1array_1disordered - (JNIEnv *, jclass, jlong, jcharArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getFloatArrayElements - * Signature: ([F[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getFloatArrayElements - (JNIEnv *, jclass, jfloatArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseFloatArrayElements - * Signature: ([FJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseFloatArrayElements - (JNIEnv *, jclass, jfloatArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_float - * Signature: (J)F - */ -JNIEXPORT jfloat JNICALL Java_org_bridj_JNI_get_1float - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_float - * Signature: (JF)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1float - (JNIEnv *, jclass, jlong, jfloat); - -/* - * Class: org_bridj_JNI - * Method: get_float_array - * Signature: (JI)[F - */ -JNIEXPORT jfloatArray JNICALL Java_org_bridj_JNI_get_1float_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_float_array - * Signature: (J[FII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1float_1array - (JNIEnv *, jclass, jlong, jfloatArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_float_disordered - * Signature: (J)F - */ -JNIEXPORT jfloat JNICALL Java_org_bridj_JNI_get_1float_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_float_disordered - * Signature: (JF)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1float_1disordered - (JNIEnv *, jclass, jlong, jfloat); - -/* - * Class: org_bridj_JNI - * Method: get_float_array_disordered - * Signature: (JI)[F - */ -JNIEXPORT jfloatArray JNICALL Java_org_bridj_JNI_get_1float_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_float_array_disordered - * Signature: (J[FII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1float_1array_1disordered - (JNIEnv *, jclass, jlong, jfloatArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getDoubleArrayElements - * Signature: ([D[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getDoubleArrayElements - (JNIEnv *, jclass, jdoubleArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseDoubleArrayElements - * Signature: ([DJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseDoubleArrayElements - (JNIEnv *, jclass, jdoubleArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_double - * Signature: (J)D - */ -JNIEXPORT jdouble JNICALL Java_org_bridj_JNI_get_1double - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_double - * Signature: (JD)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1double - (JNIEnv *, jclass, jlong, jdouble); - -/* - * Class: org_bridj_JNI - * Method: get_double_array - * Signature: (JI)[D - */ -JNIEXPORT jdoubleArray JNICALL Java_org_bridj_JNI_get_1double_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_double_array - * Signature: (J[DII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1double_1array - (JNIEnv *, jclass, jlong, jdoubleArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: get_double_disordered - * Signature: (J)D - */ -JNIEXPORT jdouble JNICALL Java_org_bridj_JNI_get_1double_1disordered - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_double_disordered - * Signature: (JD)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1double_1disordered - (JNIEnv *, jclass, jlong, jdouble); - -/* - * Class: org_bridj_JNI - * Method: get_double_array_disordered - * Signature: (JI)[D - */ -JNIEXPORT jdoubleArray JNICALL Java_org_bridj_JNI_get_1double_1array_1disordered - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_double_array_disordered - * Signature: (J[DII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1double_1array_1disordered - (JNIEnv *, jclass, jlong, jdoubleArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: getBooleanArrayElements - * Signature: ([Z[Z)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getBooleanArrayElements - (JNIEnv *, jclass, jbooleanArray, jbooleanArray); - -/* - * Class: org_bridj_JNI - * Method: releaseBooleanArrayElements - * Signature: ([ZJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_releaseBooleanArrayElements - (JNIEnv *, jclass, jbooleanArray, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: get_boolean - * Signature: (J)Z - */ -JNIEXPORT jboolean JNICALL Java_org_bridj_JNI_get_1boolean - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: set_boolean - * Signature: (JZ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1boolean - (JNIEnv *, jclass, jlong, jboolean); - -/* - * Class: org_bridj_JNI - * Method: get_boolean_array - * Signature: (JI)[Z - */ -JNIEXPORT jbooleanArray JNICALL Java_org_bridj_JNI_get_1boolean_1array - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: set_boolean_array - * Signature: (J[ZII)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_set_1boolean_1array - (JNIEnv *, jclass, jlong, jbooleanArray, jint, jint); - -/* - * Class: org_bridj_JNI - * Method: callSinglePointerArgVoidFunction - * Signature: (JJI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_callSinglePointerArgVoidFunction - (JNIEnv *, jclass, jlong, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: createCToJavaCallback - * Signature: (Lorg/bridj/MethodCallInfo;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_createCToJavaCallback - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_JNI - * Method: getActualCToJavaCallback - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_getActualCToJavaCallback - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: bindJavaMethodsToObjCMethods - * Signature: ([Lorg/bridj/MethodCallInfo;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToObjCMethods - (JNIEnv *, jclass, jobjectArray); - -/* - * Class: org_bridj_JNI - * Method: bindJavaToCCallbacks - * Signature: ([Lorg/bridj/MethodCallInfo;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaToCCallbacks - (JNIEnv *, jclass, jobjectArray); - -/* - * Class: org_bridj_JNI - * Method: bindJavaMethodsToCFunctions - * Signature: ([Lorg/bridj/MethodCallInfo;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToCFunctions - (JNIEnv *, jclass, jobjectArray); - -/* - * Class: org_bridj_JNI - * Method: bindJavaMethodsToVirtualMethods - * Signature: ([Lorg/bridj/MethodCallInfo;)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_bindJavaMethodsToVirtualMethods - (JNIEnv *, jclass, jobjectArray); - -/* - * Class: org_bridj_JNI - * Method: freeCToJavaCallback - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeCToJavaCallback - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: freeObjCMethodBindings - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeObjCMethodBindings - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: freeJavaToCCallbacks - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeJavaToCCallbacks - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: freeCFunctionBindings - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeCFunctionBindings - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: freeVirtualMethodBindings - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_freeVirtualMethodBindings - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: createCallTempStruct - * Signature: ()J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_createCallTempStruct - (JNIEnv *, jclass); - -/* - * Class: org_bridj_JNI - * Method: deleteCallTempStruct - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_deleteCallTempStruct - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: mallocNulled - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_mallocNulled - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: mallocNulledAligned - * Signature: (JI)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_mallocNulledAligned - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: org_bridj_JNI - * Method: malloc - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_malloc - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: free - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_free - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: strlen - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_strlen - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: wcslen - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_wcslen - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_JNI - * Method: memcpy - * Signature: (JJJ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_memcpy - (JNIEnv *, jclass, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: memmove - * Signature: (JJJ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_memmove - (JNIEnv *, jclass, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: memchr - * Signature: (JBJ)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_memchr - (JNIEnv *, jclass, jlong, jbyte, jlong); - -/* - * Class: org_bridj_JNI - * Method: memmem - * Signature: (JJJJ)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_memmem - (JNIEnv *, jclass, jlong, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: memmem_last - * Signature: (JJJJ)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_JNI_memmem_1last - (JNIEnv *, jclass, jlong, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: memcmp - * Signature: (JJJ)I - */ -JNIEXPORT jint JNICALL Java_org_bridj_JNI_memcmp - (JNIEnv *, jclass, jlong, jlong, jlong); - -/* - * Class: org_bridj_JNI - * Method: memset - * Signature: (JBJ)V - */ -JNIEXPORT void JNICALL Java_org_bridj_JNI_memset - (JNIEnv *, jclass, jlong, jbyte, jlong); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform.h deleted file mode 100644 index 918413199..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform.h +++ /dev/null @@ -1,71 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Platform */ - -#ifndef _Included_org_bridj_Platform -#define _Included_org_bridj_Platform -#ifdef __cplusplus -extern "C" { -#endif -#undef org_bridj_Platform_DELETE_OLD_BINARIES_AFTER_MILLIS -#define org_bridj_Platform_DELETE_OLD_BINARIES_AFTER_MILLIS 86400000LL -/* - * Class: org_bridj_Platform - * Method: init - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_org_bridj_Platform_init - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: sizeOf_size_t - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_sizeOf_1size_1t - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: sizeOf_time_t - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_sizeOf_1time_1t - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: sizeOf_wchar_t - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_sizeOf_1wchar_1t - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: sizeOf_ptrdiff_t - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_sizeOf_1ptrdiff_1t - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: sizeOf_long - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_sizeOf_1long - (JNIEnv *, jclass); - -/* - * Class: org_bridj_Platform - * Method: getMaxDirectMappingArgCount - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_org_bridj_Platform_getMaxDirectMappingArgCount - (JNIEnv *, jclass); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform_DeleteFiles.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform_DeleteFiles.h deleted file mode 100644 index 7a220d9a1..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Platform_DeleteFiles.h +++ /dev/null @@ -1,17 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Platform_DeleteFiles */ - -#ifndef _Included_org_bridj_Platform_DeleteFiles -#define _Included_org_bridj_Platform_DeleteFiles -#ifdef __cplusplus -extern "C" { -#endif -#undef org_bridj_Platform_DeleteFiles_TRY_DELETE_EVERY_MILLIS -#define org_bridj_Platform_DeleteFiles_TRY_DELETE_EVERY_MILLIS 50LL -#undef org_bridj_Platform_DeleteFiles_FAIL_AFTER_MILLIS -#define org_bridj_Platform_DeleteFiles_FAIL_AFTER_MILLIS 10000LL -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer.h deleted file mode 100644 index 03a3c40a8..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer */ - -#ifndef _Included_org_bridj_Pointer -#define _Included_org_bridj_Pointer -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_DisorderedPointer.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_DisorderedPointer.h deleted file mode 100644 index 8ebdcdfda..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_DisorderedPointer.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_DisorderedPointer */ - -#ifndef _Included_org_bridj_Pointer_DisorderedPointer -#define _Included_org_bridj_Pointer_DisorderedPointer -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_FreeReleaser.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_FreeReleaser.h deleted file mode 100644 index a82e2ff21..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_FreeReleaser.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_FreeReleaser */ - -#ifndef _Included_org_bridj_Pointer_FreeReleaser -#define _Included_org_bridj_Pointer_FreeReleaser -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_ListType.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_ListType.h deleted file mode 100644 index 00cfbee0a..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_ListType.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_ListType */ - -#ifndef _Included_org_bridj_Pointer_ListType -#define _Included_org_bridj_Pointer_ListType -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_OrderedPointer.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_OrderedPointer.h deleted file mode 100644 index 479edba57..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_OrderedPointer.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_OrderedPointer */ - -#ifndef _Included_org_bridj_Pointer_OrderedPointer -#define _Included_org_bridj_Pointer_OrderedPointer -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_Releaser.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_Releaser.h deleted file mode 100644 index 48f31e279..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_Releaser.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_Releaser */ - -#ifndef _Included_org_bridj_Pointer_Releaser -#define _Included_org_bridj_Pointer_Releaser -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_StringType.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_StringType.h deleted file mode 100644 index 7691506c8..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_Pointer_StringType.h +++ /dev/null @@ -1,13 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_Pointer_StringType */ - -#ifndef _Included_org_bridj_Pointer_StringType -#define _Included_org_bridj_Pointer_StringType -#ifdef __cplusplus -extern "C" { -#endif -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/bridj/org_bridj_objc_ObjCJNI.h b/libraries/BridJ/src/main/cpp/bridj/org_bridj_objc_ObjCJNI.h deleted file mode 100644 index 1a655e2eb..000000000 --- a/libraries/BridJ/src/main/cpp/bridj/org_bridj_objc_ObjCJNI.h +++ /dev/null @@ -1,45 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_bridj_objc_ObjCJNI */ - -#ifndef _Included_org_bridj_objc_ObjCJNI -#define _Included_org_bridj_objc_ObjCJNI -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: org_bridj_objc_ObjCJNI - * Method: createObjCProxyPeer - * Signature: (Lorg/bridj/objc/ObjCProxy;)Lorg/bridj/Pointer; - */ -JNIEXPORT jobject JNICALL Java_org_bridj_objc_ObjCJNI_createObjCProxyPeer - (JNIEnv *, jclass, jobject); - -/* - * Class: org_bridj_objc_ObjCJNI - * Method: createObjCBlockWithFunctionPointer - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_objc_ObjCJNI_createObjCBlockWithFunctionPointer - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_objc_ObjCJNI - * Method: getObjCBlockFunctionPointer - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_org_bridj_objc_ObjCJNI_getObjCBlockFunctionPointer - (JNIEnv *, jclass, jlong); - -/* - * Class: org_bridj_objc_ObjCJNI - * Method: releaseObjCBlock - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_org_bridj_objc_ObjCJNI_releaseObjCBlock - (JNIEnv *, jclass, jlong); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/libraries/BridJ/src/main/cpp/buildsys/GenerateJNIStubs.cmd b/libraries/BridJ/src/main/cpp/buildsys/GenerateJNIStubs.cmd deleted file mode 100644 index f32ab4932..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/GenerateJNIStubs.cmd +++ /dev/null @@ -1,5 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -"%JAVA_HOME%\bin\javah.exe" -d ..\bridj -classpath ..\..\..\..\target\classes org.bridj.JNI org.bridj.BridJ org.bridj.Pointer org.bridj.Platform - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.mode1v3 b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.mode1v3 deleted file mode 100644 index cc749ce79..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.mode1v3 +++ /dev/null @@ -1,1413 +0,0 @@ - - - - - ActivePerspectiveName - Project - AllowedModules - - - BundleLoadPath - - MaxInstances - n - Module - PBXSmartGroupTreeModule - Name - Groups and Files Outline View - - - BundleLoadPath - - MaxInstances - n - Module - PBXNavigatorGroup - Name - Editor - - - BundleLoadPath - - MaxInstances - n - Module - XCTaskListModule - Name - Task List - - - BundleLoadPath - - MaxInstances - n - Module - XCDetailModule - Name - File and Smart Group Detail Viewer - - - BundleLoadPath - - MaxInstances - 1 - Module - PBXBuildResultsModule - Name - Detailed Build Results Viewer - - - BundleLoadPath - - MaxInstances - 1 - Module - PBXProjectFindModule - Name - Project Batch Find Tool - - - BundleLoadPath - - MaxInstances - n - Module - XCProjectFormatConflictsModule - Name - Project Format Conflicts List - - - BundleLoadPath - - MaxInstances - n - Module - PBXBookmarksModule - Name - Bookmarks Tool - - - BundleLoadPath - - MaxInstances - n - Module - PBXClassBrowserModule - Name - Class Browser - - - BundleLoadPath - - MaxInstances - n - Module - PBXCVSModule - Name - Source Code Control Tool - - - BundleLoadPath - - MaxInstances - n - Module - PBXDebugBreakpointsModule - Name - Debug Breakpoints Tool - - - BundleLoadPath - - MaxInstances - n - Module - XCDockableInspector - Name - Inspector - - - BundleLoadPath - - MaxInstances - n - Module - PBXOpenQuicklyModule - Name - Open Quickly Tool - - - BundleLoadPath - - MaxInstances - 1 - Module - PBXDebugSessionModule - Name - Debugger - - - BundleLoadPath - - MaxInstances - 1 - Module - PBXDebugCLIModule - Name - Debug Console - - - BundleLoadPath - - MaxInstances - n - Module - XCSnapshotModule - Name - Snapshots Tool - - - BundlePath - /Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources - Description - DefaultDescriptionKey - DockingSystemVisible - - Extension - mode1v3 - FavBarConfig - - PBXProjectModuleGUID - 9007DF6010EE2B5900928CAE - XCBarModuleItemNames - - XCBarModuleItems - - - FirstTimeWindowDisplayed - - Identifier - com.apple.perspectives.project.mode1v3 - MajorVersion - 33 - MinorVersion - 0 - Name - Default - Notifications - - OpenEditors - - PerspectiveWidths - - -1 - -1 - - Perspectives - - - ChosenToolbarItems - - active-combo-popup - action - NSToolbarFlexibleSpaceItem - debugger-enable-breakpoints - build-and-go - com.apple.ide.PBXToolbarStopButton - get-info - NSToolbarFlexibleSpaceItem - com.apple.pbx.toolbar.searchfield - - ControllerClassBaseName - - IconName - WindowOfProjectWithEditor - Identifier - perspective.project - IsVertical - - Layout - - - BecomeActive - - ContentConfiguration - - PBXBottomSmartGroupGIDs - - 1C37FBAC04509CD000000102 - 1C37FAAC04509CD000000102 - 1C37FABC05509CD000000102 - 1C37FABC05539CD112110102 - E2644B35053B69B200211256 - 1C37FABC04509CD000100104 - 1CC0EA4004350EF90044410B - 1CC0EA4004350EF90041110B - - PBXProjectModuleGUID - 1CE0B1FE06471DED0097A5F4 - PBXProjectModuleLabel - Files - PBXProjectStructureProvided - yes - PBXSmartGroupTreeModuleColumnData - - PBXSmartGroupTreeModuleColumnWidthsKey - - 186 - - PBXSmartGroupTreeModuleColumnsKey_v4 - - MainColumn - - - PBXSmartGroupTreeModuleOutlineStateKey_v7 - - PBXSmartGroupTreeModuleOutlineStateExpansionKey - - 08FB7794FE84155DC02AAC07 - 9007E0D310EE3F1B00928CAE - 9007E0BD10EE3F0A00928CAE - 1C37FBAC04509CD000000102 - 1C37FAAC04509CD000000102 - 1C37FABC05509CD000000102 - - PBXSmartGroupTreeModuleOutlineStateSelectionKey - - - 5 - 1 - 0 - - - PBXSmartGroupTreeModuleOutlineStateVisibleRectKey - {{0, 0}, {186, 660}} - - PBXTopSmartGroupGIDs - - XCIncludePerspectivesSwitch - - XCSharingToken - com.apple.Xcode.GFSharingToken - - GeometryConfiguration - - Frame - {{0, 0}, {203, 678}} - GroupTreeTableConfiguration - - MainColumn - 186 - - RubberWindowFrame - 0 59 1280 719 0 0 1280 778 - - Module - PBXSmartGroupTreeModule - Proportion - 203pt - - - Dock - - - ContentConfiguration - - PBXProjectModuleGUID - 1CE0B20306471E060097A5F4 - PBXProjectModuleLabel - bridj.hpp - PBXSplitModuleInNavigatorKey - - Split0 - - PBXProjectModuleGUID - 1CE0B20406471E060097A5F4 - PBXProjectModuleLabel - bridj.hpp - _historyCapacity - 0 - bookmark - 901E70FF113A2AFF00F15234 - history - - 9007E11010EE3F5100928CAE - 903764CD111E0BC2004983BE - 903765BD111F89CB004983BE - 903765CB111F93E9004983BE - 905E200B1128C7E50036B0FA - 90FD149B11335059006462C7 - 90FD149E11335059006462C7 - 90FD149F11335059006462C7 - 90FD14A011335059006462C7 - 90FD14A111335059006462C7 - 90FD14AE11335079006462C7 - 90FD14F311376F9D006462C7 - 901E70FD113A2AFF00F15234 - 901E70FE113A2AFF00F15234 - - - SplitCount - 1 - - StatusBarVisibility - - - GeometryConfiguration - - Frame - {{0, 0}, {1072, 419}} - RubberWindowFrame - 0 59 1280 719 0 0 1280 778 - - Module - PBXNavigatorGroup - Proportion - 419pt - - - ContentConfiguration - - PBXProjectModuleGUID - 1CE0B20506471E060097A5F4 - PBXProjectModuleLabel - Detail - - GeometryConfiguration - - Frame - {{0, 424}, {1072, 254}} - RubberWindowFrame - 0 59 1280 719 0 0 1280 778 - - Module - XCDetailModule - Proportion - 254pt - - - Proportion - 1072pt - - - Name - Project - ServiceClasses - - XCModuleDock - PBXSmartGroupTreeModule - XCModuleDock - PBXNavigatorGroup - XCDetailModule - - TableOfContents - - 901E70F4113A173000F15234 - 1CE0B1FE06471DED0097A5F4 - 901E70F5113A173000F15234 - 1CE0B20306471E060097A5F4 - 1CE0B20506471E060097A5F4 - - ToolbarConfigUserDefaultsMinorVersion - 2 - ToolbarConfiguration - xcode.toolbar.config.defaultV3 - - - ControllerClassBaseName - - IconName - WindowOfProject - Identifier - perspective.morph - IsVertical - 0 - Layout - - - BecomeActive - 1 - ContentConfiguration - - PBXBottomSmartGroupGIDs - - 1C37FBAC04509CD000000102 - 1C37FAAC04509CD000000102 - 1C08E77C0454961000C914BD - 1C37FABC05509CD000000102 - 1C37FABC05539CD112110102 - E2644B35053B69B200211256 - 1C37FABC04509CD000100104 - 1CC0EA4004350EF90044410B - 1CC0EA4004350EF90041110B - - PBXProjectModuleGUID - 11E0B1FE06471DED0097A5F4 - PBXProjectModuleLabel - Files - PBXProjectStructureProvided - yes - PBXSmartGroupTreeModuleColumnData - - PBXSmartGroupTreeModuleColumnWidthsKey - - 186 - - PBXSmartGroupTreeModuleColumnsKey_v4 - - MainColumn - - - PBXSmartGroupTreeModuleOutlineStateKey_v7 - - PBXSmartGroupTreeModuleOutlineStateExpansionKey - - 29B97314FDCFA39411CA2CEA - 1C37FABC05509CD000000102 - - PBXSmartGroupTreeModuleOutlineStateSelectionKey - - - 0 - - - PBXSmartGroupTreeModuleOutlineStateVisibleRectKey - {{0, 0}, {186, 337}} - - PBXTopSmartGroupGIDs - - XCIncludePerspectivesSwitch - 1 - XCSharingToken - com.apple.Xcode.GFSharingToken - - GeometryConfiguration - - Frame - {{0, 0}, {203, 355}} - GroupTreeTableConfiguration - - MainColumn - 186 - - RubberWindowFrame - 373 269 690 397 0 0 1440 878 - - Module - PBXSmartGroupTreeModule - Proportion - 100% - - - Name - Morph - PreferredWidth - 300 - ServiceClasses - - XCModuleDock - PBXSmartGroupTreeModule - - TableOfContents - - 11E0B1FE06471DED0097A5F4 - - ToolbarConfiguration - xcode.toolbar.config.default.shortV3 - - - PerspectivesBarVisible - - ShelfIsVisible - - SourceDescription - file at '/Developer/Library/PrivateFrameworks/DevToolsInterface.framework/Resources/XCPerspectivesSpecificationMode1.xcperspec' - StatusbarIsVisible - - TimeStamp - 0.0 - ToolbarConfigUserDefaultsMinorVersion - 2 - ToolbarDisplayMode - 1 - ToolbarIsVisible - - ToolbarSizeMode - 1 - Type - Perspectives - UpdateMessage - The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'? - WindowJustification - 5 - WindowOrderList - - 9007DF5310EE2B1A00928CAE - 1CD10A99069EF8BA00B06720 - /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/Runtime/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj - - WindowString - 0 59 1280 719 0 0 1280 778 - WindowToolsV3 - - - FirstTimeWindowDisplayed - - Identifier - windowTool.build - IsVertical - - Layout - - - Dock - - - ContentConfiguration - - PBXProjectModuleGUID - 1CD0528F0623707200166675 - PBXProjectModuleLabel - - StatusBarVisibility - - - GeometryConfiguration - - Frame - {{0, 0}, {992, 213}} - RubberWindowFrame - 140 156 992 580 0 0 1280 778 - - Module - PBXNavigatorGroup - Proportion - 213pt - - - ContentConfiguration - - PBXProjectModuleGUID - XCMainBuildResultsModuleGUID - PBXProjectModuleLabel - Build Results - XCBuildResultsTrigger_Collapse - 1021 - XCBuildResultsTrigger_Open - 1011 - - GeometryConfiguration - - Frame - {{0, 218}, {992, 321}} - RubberWindowFrame - 140 156 992 580 0 0 1280 778 - - Module - PBXBuildResultsModule - Proportion - 321pt - - - Proportion - 539pt - - - Name - Build Results - ServiceClasses - - PBXBuildResultsModule - - StatusbarIsVisible - - TableOfContents - - 9007DF5310EE2B1A00928CAE - 901E70F6113A173000F15234 - 1CD0528F0623707200166675 - XCMainBuildResultsModuleGUID - - ToolbarConfiguration - xcode.toolbar.config.buildV3 - WindowContentMinSize - 486 300 - WindowString - 140 156 992 580 0 0 1280 778 - WindowToolGUID - 9007DF5310EE2B1A00928CAE - WindowToolIsVisible - - - - FirstTimeWindowDisplayed - - Identifier - windowTool.debugger - IsVertical - - Layout - - - Dock - - - ContentConfiguration - - Debugger - - HorizontalSplitView - - _collapsingFrameDimension - 0.0 - _indexOfCollapsedView - 0 - _percentageOfCollapsedView - 0.0 - isCollapsed - yes - sizes - - {{0, 0}, {316, 203}} - {{316, 0}, {378, 203}} - - - VerticalSplitView - - _collapsingFrameDimension - 0.0 - _indexOfCollapsedView - 0 - _percentageOfCollapsedView - 0.0 - isCollapsed - yes - sizes - - {{0, 0}, {694, 203}} - {{0, 203}, {694, 178}} - - - - LauncherConfigVersion - 8 - PBXProjectModuleGUID - 1C162984064C10D400B95A72 - PBXProjectModuleLabel - Debug - GLUTExamples (Underwater) - - GeometryConfiguration - - DebugConsoleVisible - None - DebugConsoleWindowFrame - {{200, 200}, {500, 300}} - DebugSTDIOWindowFrame - {{200, 200}, {500, 300}} - Frame - {{0, 0}, {694, 381}} - PBXDebugSessionStackFrameViewKey - - DebugVariablesTableConfiguration - - Name - 120 - Value - 85 - Summary - 148 - - Frame - {{316, 0}, {378, 203}} - RubberWindowFrame - 0 75 694 422 0 0 1280 778 - - RubberWindowFrame - 0 75 694 422 0 0 1280 778 - - Module - PBXDebugSessionModule - Proportion - 381pt - - - Proportion - 381pt - - - Name - Debugger - ServiceClasses - - PBXDebugSessionModule - - StatusbarIsVisible - - TableOfContents - - 1CD10A99069EF8BA00B06720 - 901E70F7113A173000F15234 - 1C162984064C10D400B95A72 - 901E70F8113A173000F15234 - 901E70F9113A173000F15234 - 901E70FA113A173000F15234 - 901E70FB113A173000F15234 - 901E70FC113A173000F15234 - - ToolbarConfiguration - xcode.toolbar.config.debugV3 - WindowString - 0 75 694 422 0 0 1280 778 - WindowToolGUID - 1CD10A99069EF8BA00B06720 - WindowToolIsVisible - - - - Identifier - windowTool.find - Layout - - - Dock - - - Dock - - - ContentConfiguration - - PBXProjectModuleGUID - 1CDD528C0622207200134675 - PBXProjectModuleLabel - <No Editor> - PBXSplitModuleInNavigatorKey - - Split0 - - PBXProjectModuleGUID - 1CD0528D0623707200166675 - - SplitCount - 1 - - StatusBarVisibility - 1 - - GeometryConfiguration - - Frame - {{0, 0}, {781, 167}} - RubberWindowFrame - 62 385 781 470 0 0 1440 878 - - Module - PBXNavigatorGroup - Proportion - 781pt - - - Proportion - 50% - - - BecomeActive - 1 - ContentConfiguration - - PBXProjectModuleGUID - 1CD0528E0623707200166675 - PBXProjectModuleLabel - Project Find - - GeometryConfiguration - - Frame - {{8, 0}, {773, 254}} - RubberWindowFrame - 62 385 781 470 0 0 1440 878 - - Module - PBXProjectFindModule - Proportion - 50% - - - Proportion - 428pt - - - Name - Project Find - ServiceClasses - - PBXProjectFindModule - - StatusbarIsVisible - 1 - TableOfContents - - 1C530D57069F1CE1000CFCEE - 1C530D58069F1CE1000CFCEE - 1C530D59069F1CE1000CFCEE - 1CDD528C0622207200134675 - 1C530D5A069F1CE1000CFCEE - 1CE0B1FE06471DED0097A5F4 - 1CD0528E0623707200166675 - - WindowString - 62 385 781 470 0 0 1440 878 - WindowToolGUID - 1C530D57069F1CE1000CFCEE - WindowToolIsVisible - 0 - - - Identifier - MENUSEPARATOR - - - FirstTimeWindowDisplayed - - Identifier - windowTool.debuggerConsole - IsVertical - - Layout - - - Dock - - - BecomeActive - - ContentConfiguration - - PBXProjectModuleGUID - 1C78EAAC065D492600B07095 - PBXProjectModuleLabel - Debugger Console - - GeometryConfiguration - - Frame - {{0, 0}, {650, 209}} - RubberWindowFrame - 492 505 650 250 0 0 1280 778 - - Module - PBXDebugCLIModule - Proportion - 209pt - - - Proportion - 209pt - - - Name - Debugger Console - ServiceClasses - - PBXDebugCLIModule - - StatusbarIsVisible - - TableOfContents - - 1C78EAAD065D492600B07095 - 903765C0111F89CB004983BE - 1C78EAAC065D492600B07095 - - ToolbarConfiguration - xcode.toolbar.config.consoleV3 - WindowString - 492 505 650 250 0 0 1280 778 - WindowToolGUID - 1C78EAAD065D492600B07095 - WindowToolIsVisible - - - - Identifier - windowTool.snapshots - Layout - - - Dock - - - Module - XCSnapshotModule - Proportion - 100% - - - Proportion - 100% - - - Name - Snapshots - ServiceClasses - - XCSnapshotModule - - StatusbarIsVisible - Yes - ToolbarConfiguration - xcode.toolbar.config.snapshots - WindowString - 315 824 300 550 0 0 1440 878 - WindowToolIsVisible - Yes - - - Identifier - windowTool.scm - Layout - - - Dock - - - ContentConfiguration - - PBXProjectModuleGUID - 1C78EAB2065D492600B07095 - PBXProjectModuleLabel - <No Editor> - PBXSplitModuleInNavigatorKey - - Split0 - - PBXProjectModuleGUID - 1C78EAB3065D492600B07095 - - SplitCount - 1 - - StatusBarVisibility - 1 - - GeometryConfiguration - - Frame - {{0, 0}, {452, 0}} - RubberWindowFrame - 743 379 452 308 0 0 1280 1002 - - Module - PBXNavigatorGroup - Proportion - 0pt - - - BecomeActive - 1 - ContentConfiguration - - PBXProjectModuleGUID - 1CD052920623707200166675 - PBXProjectModuleLabel - SCM - - GeometryConfiguration - - ConsoleFrame - {{0, 259}, {452, 0}} - Frame - {{0, 7}, {452, 259}} - RubberWindowFrame - 743 379 452 308 0 0 1280 1002 - TableConfiguration - - Status - 30 - FileName - 199 - Path - 197.0950012207031 - - TableFrame - {{0, 0}, {452, 250}} - - Module - PBXCVSModule - Proportion - 262pt - - - Proportion - 266pt - - - Name - SCM - ServiceClasses - - PBXCVSModule - - StatusbarIsVisible - 1 - TableOfContents - - 1C78EAB4065D492600B07095 - 1C78EAB5065D492600B07095 - 1C78EAB2065D492600B07095 - 1CD052920623707200166675 - - ToolbarConfiguration - xcode.toolbar.config.scm - WindowString - 743 379 452 308 0 0 1280 1002 - - - FirstTimeWindowDisplayed - - Identifier - windowTool.breakpoints - IsVertical - - Layout - - - Dock - - - ContentConfiguration - - PBXBottomSmartGroupGIDs - - 1C77FABC04509CD000000102 - - PBXProjectModuleGUID - 1CE0B1FE06471DED0097A5F4 - PBXProjectModuleLabel - Files - PBXProjectStructureProvided - no - PBXSmartGroupTreeModuleColumnData - - PBXSmartGroupTreeModuleColumnWidthsKey - - 168 - - PBXSmartGroupTreeModuleColumnsKey_v4 - - MainColumn - - - PBXSmartGroupTreeModuleOutlineStateKey_v7 - - PBXSmartGroupTreeModuleOutlineStateExpansionKey - - 1C77FABC04509CD000000102 - - PBXSmartGroupTreeModuleOutlineStateSelectionKey - - - 0 - - - PBXSmartGroupTreeModuleOutlineStateVisibleRectKey - {{0, 0}, {168, 350}} - - PBXTopSmartGroupGIDs - - XCIncludePerspectivesSwitch - - - GeometryConfiguration - - Frame - {{0, 0}, {185, 368}} - GroupTreeTableConfiguration - - MainColumn - 168 - - RubberWindowFrame - 157 346 744 409 0 0 1280 778 - - Module - PBXSmartGroupTreeModule - Proportion - 185pt - - - BecomeActive - - ContentConfiguration - - PBXProjectModuleGUID - 1CA1AED706398EBD00589147 - PBXProjectModuleLabel - Detail - - GeometryConfiguration - - Frame - {{190, 0}, {554, 368}} - RubberWindowFrame - 157 346 744 409 0 0 1280 778 - - Module - XCDetailModule - Proportion - 554pt - - - Proportion - 368pt - - - MajorVersion - 3 - MinorVersion - 0 - Name - Breakpoints - ServiceClasses - - PBXSmartGroupTreeModule - XCDetailModule - - StatusbarIsVisible - - TableOfContents - - 9037654B111E0EF1004983BE - 9037654C111E0EF1004983BE - 1CE0B1FE06471DED0097A5F4 - 1CA1AED706398EBD00589147 - - ToolbarConfiguration - xcode.toolbar.config.breakpointsV3 - WindowString - 157 346 744 409 0 0 1280 778 - WindowToolGUID - 9037654B111E0EF1004983BE - WindowToolIsVisible - - - - Identifier - windowTool.debugAnimator - Layout - - - Dock - - - Module - PBXNavigatorGroup - Proportion - 100% - - - Proportion - 100% - - - Name - Debug Visualizer - ServiceClasses - - PBXNavigatorGroup - - StatusbarIsVisible - 1 - ToolbarConfiguration - xcode.toolbar.config.debugAnimatorV3 - WindowString - 100 100 700 500 0 0 1280 1002 - - - Identifier - windowTool.bookmarks - Layout - - - Dock - - - Module - PBXBookmarksModule - Proportion - 100% - - - Proportion - 100% - - - Name - Bookmarks - ServiceClasses - - PBXBookmarksModule - - StatusbarIsVisible - 0 - WindowString - 538 42 401 187 0 0 1280 1002 - - - Identifier - windowTool.projectFormatConflicts - Layout - - - Dock - - - Module - XCProjectFormatConflictsModule - Proportion - 100% - - - Proportion - 100% - - - Name - Project Format Conflicts - ServiceClasses - - XCProjectFormatConflictsModule - - StatusbarIsVisible - 0 - WindowContentMinSize - 450 300 - WindowString - 50 850 472 307 0 0 1440 877 - - - Identifier - windowTool.classBrowser - Layout - - - Dock - - - BecomeActive - 1 - ContentConfiguration - - OptionsSetName - Hierarchy, all classes - PBXProjectModuleGUID - 1CA6456E063B45B4001379D8 - PBXProjectModuleLabel - Class Browser - NSObject - - GeometryConfiguration - - ClassesFrame - {{0, 0}, {374, 96}} - ClassesTreeTableConfiguration - - PBXClassNameColumnIdentifier - 208 - PBXClassBookColumnIdentifier - 22 - - Frame - {{0, 0}, {630, 331}} - MembersFrame - {{0, 105}, {374, 395}} - MembersTreeTableConfiguration - - PBXMemberTypeIconColumnIdentifier - 22 - PBXMemberNameColumnIdentifier - 216 - PBXMemberTypeColumnIdentifier - 97 - PBXMemberBookColumnIdentifier - 22 - - PBXModuleWindowStatusBarHidden2 - 1 - RubberWindowFrame - 385 179 630 352 0 0 1440 878 - - Module - PBXClassBrowserModule - Proportion - 332pt - - - Proportion - 332pt - - - Name - Class Browser - ServiceClasses - - PBXClassBrowserModule - - StatusbarIsVisible - 0 - TableOfContents - - 1C0AD2AF069F1E9B00FABCE6 - 1C0AD2B0069F1E9B00FABCE6 - 1CA6456E063B45B4001379D8 - - ToolbarConfiguration - xcode.toolbar.config.classbrowser - WindowString - 385 179 630 352 0 0 1440 878 - WindowToolGUID - 1C0AD2AF069F1E9B00FABCE6 - WindowToolIsVisible - 0 - - - Identifier - windowTool.refactoring - IncludeInToolsMenu - 0 - Layout - - - Dock - - - BecomeActive - 1 - GeometryConfiguration - - Frame - {0, 0}, {500, 335} - RubberWindowFrame - {0, 0}, {500, 335} - - Module - XCRefactoringModule - Proportion - 100% - - - Proportion - 100% - - - Name - Refactoring - ServiceClasses - - XCRefactoringModule - - WindowString - 200 200 500 356 0 0 1920 1200 - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.pbxuser b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.pbxuser deleted file mode 100644 index 6fc025699..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ochafik.pbxuser +++ /dev/null @@ -1,543 +0,0 @@ -// !$*UTF8*$! -{ - 08FB7793FE84155DC02AAC07 /* Project object */ = { - activeArchitecturePreference = i386; - activeBuildConfigurationName = Debug; - activeExecutable = 9007DFC210EE318300928CAE /* Java Maven Shaded Jar */; - activeTarget = D28A88AD04BDD90700651E21 /* bridj */; - addToTargets = ( - D28A88AD04BDD90700651E21 /* bridj */, - ); - breakpoints = ( - 90376584111E1159004983BE /* JNI.c:61 */, - 90376586111E115A004983BE /* JNI.c:60 */, - 90376588111E115D004983BE /* JNI.c:59 */, - ); - codeSenseManager = 9007DF0E10EE299F00928CAE /* Code sense */; - executables = ( - 9007DFC210EE318300928CAE /* Java Maven Shaded Jar */, - ); - perUserDictionary = { - "PBXConfiguration.PBXBreakpointsDataSource.v1:1CA1AED706398EBD00589147" = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXBreakpointsDataSource_BreakpointID; - PBXFileTableDataSourceColumnWidthsKey = ( - 20, - 20, - 198, - 20, - 99, - 99, - 29, - 20, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXBreakpointsDataSource_ActionID, - PBXBreakpointsDataSource_TypeID, - PBXBreakpointsDataSource_BreakpointID, - PBXBreakpointsDataSource_UseID, - PBXBreakpointsDataSource_LocationID, - PBXBreakpointsDataSource_ConditionID, - PBXBreakpointsDataSource_IgnoreCountID, - PBXBreakpointsDataSource_ContinueID, - ); - }; - PBXConfiguration.PBXFileTableDataSource3.PBXExecutablesDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXExecutablesDataSource_NameID; - PBXFileTableDataSourceColumnWidthsKey = ( - 22, - 300, - 458.58349609375, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXExecutablesDataSource_ActiveFlagID, - PBXExecutablesDataSource_NameID, - PBXExecutablesDataSource_CommentsID, - ); - }; - PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; - PBXFileTableDataSourceColumnWidthsKey = ( - 20, - 833, - 20, - 48, - 43, - 43, - 20, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXFileDataSource_FiletypeID, - PBXFileDataSource_Filename_ColumnID, - PBXFileDataSource_Built_ColumnID, - PBXFileDataSource_ObjectSize_ColumnID, - PBXFileDataSource_Errors_ColumnID, - PBXFileDataSource_Warnings_ColumnID, - PBXFileDataSource_Target_ColumnID, - ); - }; - PBXConfiguration.PBXTargetDataSource.PBXTargetDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; - PBXFileTableDataSourceColumnWidthsKey = ( - 20, - 531, - 60, - 20, - 48, - 43, - 43, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXFileDataSource_FiletypeID, - PBXFileDataSource_Filename_ColumnID, - PBXTargetDataSource_PrimaryAttribute, - PBXFileDataSource_Built_ColumnID, - PBXFileDataSource_ObjectSize_ColumnID, - PBXFileDataSource_Errors_ColumnID, - PBXFileDataSource_Warnings_ColumnID, - ); - }; - PBXPerProjectTemplateStateSaveDate = 289019693; - PBXWorkspaceStateSaveDate = 289019693; - }; - perUserProjectItems = { - 9007E11010EE3F5100928CAE /* PBXTextBookmark */ = 9007E11010EE3F5100928CAE /* PBXTextBookmark */; - 901E70FD113A2AFF00F15234 /* PBXTextBookmark */ = 901E70FD113A2AFF00F15234 /* PBXTextBookmark */; - 901E70FE113A2AFF00F15234 /* PBXTextBookmark */ = 901E70FE113A2AFF00F15234 /* PBXTextBookmark */; - 901E70FF113A2AFF00F15234 /* PBXTextBookmark */ = 901E70FF113A2AFF00F15234 /* PBXTextBookmark */; - 903764CD111E0BC2004983BE /* PBXTextBookmark */ = 903764CD111E0BC2004983BE /* PBXTextBookmark */; - 903765BD111F89CB004983BE /* PBXTextBookmark */ = 903765BD111F89CB004983BE /* PBXTextBookmark */; - 903765CB111F93E9004983BE /* PBXTextBookmark */ = 903765CB111F93E9004983BE /* PBXTextBookmark */; - 905E200B1128C7E50036B0FA /* PBXTextBookmark */ = 905E200B1128C7E50036B0FA /* PBXTextBookmark */; - 90FD149B11335059006462C7 /* PBXTextBookmark */ = 90FD149B11335059006462C7 /* PBXTextBookmark */; - 90FD149E11335059006462C7 /* PBXTextBookmark */ = 90FD149E11335059006462C7 /* PBXTextBookmark */; - 90FD149F11335059006462C7 /* PBXTextBookmark */ = 90FD149F11335059006462C7 /* PBXTextBookmark */; - 90FD14A011335059006462C7 /* PBXTextBookmark */ = 90FD14A011335059006462C7 /* PBXTextBookmark */; - 90FD14A111335059006462C7 /* PBXTextBookmark */ = 90FD14A111335059006462C7 /* PBXTextBookmark */; - 90FD14AE11335079006462C7 /* PBXTextBookmark */ = 90FD14AE11335079006462C7 /* PBXTextBookmark */; - 90FD14F311376F9D006462C7 /* PBXTextBookmark */ = 90FD14F311376F9D006462C7 /* PBXTextBookmark */; - }; - sourceControlManager = 9007DF0D10EE299F00928CAE /* Source Control */; - userBuildSettings = { - }; - }; - 9007DF0D10EE299F00928CAE /* Source Control */ = { - isa = PBXSourceControlManager; - fallbackIsa = XCSourceControlManager; - isSCMEnabled = 0; - scmConfiguration = { - repositoryNamesForRoots = { - "" = ""; - ../../../bridj = svn; - }; - }; - }; - 9007DF0E10EE299F00928CAE /* Code sense */ = { - isa = PBXCodeSenseManager; - indexTemplatePath = ""; - }; - 9007DFC210EE318300928CAE /* Java Maven Shaded Jar */ = { - isa = PBXExecutable; - activeArgIndices = ( - YES, - YES, - ); - argumentStrings = ( - "-cp \"/Users/ochafik/nativelibs4java/Runtime/Comp/target/nl4j-runtime-comp-0.1-shaded.jar\" ", - bridj.Main, - ); - autoAttachOnCrash = 1; - breakpointsEnabled = 1; - configStateDict = { - "PBXLSLaunchAction-0" = { - PBXLSLaunchAction = 0; - PBXLSLaunchStartAction = 1; - PBXLSLaunchStdioStyle = 2; - PBXLSLaunchStyle = 0; - class = PBXLSRunLaunchConfig; - commandLineArgs = ( - ); - displayName = "Executable Runner"; - environment = { - }; - identifier = com.apple.Xcode.launch.runConfig; - remoteHostInfo = ""; - startActionInfo = ""; - }; - "PBXLSLaunchAction-1" = { - PBXLSLaunchAction = 1; - PBXLSLaunchStartAction = 1; - PBXLSLaunchStdioStyle = 2; - PBXLSLaunchStyle = 0; - class = PBXGDB_LaunchConfig; - commandLineArgs = ( - ); - displayName = GDB; - environment = { - }; - identifier = com.apple.Xcode.launch.GDBMI_Config; - remoteHostInfo = ""; - startActionInfo = ""; - }; - }; - customDataFormattersEnabled = 1; - dataTipCustomDataFormattersEnabled = 1; - dataTipShowTypeColumn = 1; - dataTipSortType = 0; - debuggerPlugin = GDBDebugging; - disassemblyDisplayState = 0; - dylibVariantSuffix = ""; - enableDebugStr = 1; - environmentEntries = ( - { - active = YES; - name = DYLD_LIBRARY_PATH; - value = /Users/ochafik/nativelibs4java/Runtime/bridj/src/main/cpp/bridj/build_out/darwin_universal_gcc_debug; - }, - ); - executableSystemSymbolLevel = 0; - executableUserSymbolLevel = 0; - launchableReference = 9007DFC310EE318300928CAE /* java */; - libgmallocEnabled = 0; - name = "Java Maven Shaded Jar"; - savedGlobals = { - }; - showTypeColumn = 0; - sourceDirectories = ( - ); - startupPath = /Users/ochafik/nativelibs4java/Runtime/bridj/src/main/cpp/bridj/build_out/darwin_universal_gcc_debug; - }; - 9007DFC310EE318300928CAE /* java */ = { - isa = PBXFileReference; - lastKnownFileType = "compiled.mach-o.executable"; - name = java; - path = /usr/bin/java; - sourceTree = ""; - }; - 9007E0BE10EE3F0A00928CAE /* BSDmakefile */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 520}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 1075}"; - }; - }; - 9007E0C810EE3F0A00928CAE /* dynload.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 351}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{4, 984}"; - }; - }; - 9007E0CA10EE3F0A00928CAE /* dynload_macros.h */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 390}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 877}"; - }; - }; - 9007E0CB10EE3F0A00928CAE /* dynload_syms.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 377}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 880}"; - }; - }; - 9007E0CC10EE3F0A00928CAE /* dynload_syms_elf.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 5083}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 855}"; - }; - }; - 9007E0CD10EE3F0A00928CAE /* dynload_syms_pe32.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 1430}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 873}"; - }; - }; - 9007E0CE10EE3F0A00928CAE /* dynload_unix.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 728}}"; - sepNavSelRange = "{1151, 5}"; - sepNavVisRange = "{873, 354}"; - }; - }; - 9007E0F810EE3F1C00928CAE /* JavaToNativeCallHandler.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {789, 3887}}"; - sepNavSelRange = "{277, 0}"; - sepNavVisRange = "{67, 591}"; - }; - }; - 9007E0F910EE3F1C00928CAE /* bridj.hpp */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {1011, 1651}}"; - sepNavSelRange = "{3248, 0}"; - sepNavVisRange = "{0, 687}"; - }; - }; - 9007E0FC10EE3F1C00928CAE /* JNI.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {971, 9542}}"; - sepNavSelRange = "{1485, 0}"; - sepNavVisRange = "{1195, 759}"; - }; - }; - 9007E10710EE3F1C00928CAE /* RawNativeForwardCallback.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 728}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 526}"; - }; - }; - 9007E10810EE3F1C00928CAE /* RawNativeForwardCallback.h */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 264}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 359}"; - }; - }; - 9007E10910EE3F1C00928CAE /* RawNativeForwardCallback_WIN32_masm.asm */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 351}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 622}"; - }; - }; - 9007E11010EE3F5100928CAE /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0C810EE3F0A00928CAE /* dynload.c */; - name = "dynload.c: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 984; - vrLoc = 4; - }; - 901E70FD113A2AFF00F15234 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 90DC54281133337C00F33FC9 /* dynload_darwin.c */; - name = "dynload_darwin.c: 10"; - rLen = 0; - rLoc = 378; - rType = 0; - vrLen = 439; - vrLoc = 860; - }; - 901E70FE113A2AFF00F15234 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0F910EE3F1C00928CAE /* bridj.hpp */; - name = "bridj.hpp: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 687; - vrLoc = 0; - }; - 901E70FF113A2AFF00F15234 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0F910EE3F1C00928CAE /* bridj.hpp */; - name = "bridj.hpp: 121"; - rLen = 0; - rLoc = 3248; - rType = 0; - vrLen = 687; - vrLoc = 0; - }; - 903764CD111E0BC2004983BE /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E10910EE3F1C00928CAE /* RawNativeForwardCallback_WIN32_masm.asm */; - name = "RawNativeForwardCallback_WIN32_masm.asm: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 622; - vrLoc = 0; - }; - 90376584111E1159004983BE /* JNI.c:61 */ = { - isa = PBXFileBreakpoint; - actions = ( - ); - breakpointStyle = 0; - continueAfterActions = 0; - countType = 0; - delayBeforeContinue = 0; - fileReference = 9007E0FC10EE3F1C00928CAE /* JNI.c */; - functionName = "Java_com_nativelibs4java_runtime_JNI_findSymbolInLibrary()"; - hitCount = 0; - ignoreCount = 0; - lineNumber = 61; - modificationTime = 287280816.117092; - originalNumberOfMultipleMatches = 1; - state = 2; - }; - 90376586111E115A004983BE /* JNI.c:60 */ = { - isa = PBXFileBreakpoint; - actions = ( - ); - breakpointStyle = 0; - continueAfterActions = 0; - countType = 0; - delayBeforeContinue = 0; - fileReference = 9007E0FC10EE3F1C00928CAE /* JNI.c */; - functionName = "Java_com_nativelibs4java_runtime_JNI_findSymbolInLibrary()"; - hitCount = 0; - ignoreCount = 0; - lineNumber = 60; - modificationTime = 287280816.117148; - originalNumberOfMultipleMatches = 1; - state = 2; - }; - 90376588111E115D004983BE /* JNI.c:59 */ = { - isa = PBXFileBreakpoint; - actions = ( - ); - breakpointStyle = 0; - continueAfterActions = 0; - countType = 0; - delayBeforeContinue = 0; - fileReference = 9007E0FC10EE3F1C00928CAE /* JNI.c */; - functionName = "Java_com_nativelibs4java_runtime_JNI_findSymbolInLibrary()"; - hitCount = 0; - ignoreCount = 0; - lineNumber = 59; - modificationTime = 287280816.117161; - originalNumberOfMultipleMatches = 1; - state = 0; - }; - 903765BD111F89CB004983BE /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0FC10EE3F1C00928CAE /* JNI.c */; - name = "JNI.c: 45"; - rLen = 0; - rLoc = 1485; - rType = 0; - vrLen = 829; - vrLoc = 1267; - }; - 903765CB111F93E9004983BE /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E10710EE3F1C00928CAE /* RawNativeForwardCallback.c */; - name = "RawNativeForwardCallback.c: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 526; - vrLoc = 0; - }; - 905E200B1128C7E50036B0FA /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E10810EE3F1C00928CAE /* RawNativeForwardCallback.h */; - name = "RawNativeForwardCallback.h: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 359; - vrLoc = 0; - }; - 90DC54271133337000F33FC9 /* dynload_syms_darwin.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {749, 1989}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRange = "{0, 786}"; - }; - }; - 90DC54281133337C00F33FC9 /* dynload_darwin.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {1011, 910}}"; - sepNavSelRange = "{378, 0}"; - sepNavVisRange = "{860, 439}"; - }; - }; - 90FD149B11335059006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0F810EE3F1C00928CAE /* JavaToNativeCallHandler.c */; - name = "JavaToNativeCallHandler.c: 11"; - rLen = 0; - rLoc = 277; - rType = 0; - vrLen = 591; - vrLoc = 67; - }; - 90FD149E11335059006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0BE10EE3F0A00928CAE /* BSDmakefile */; - name = "BSDmakefile: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 1075; - vrLoc = 0; - }; - 90FD149F11335059006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0CB10EE3F0A00928CAE /* dynload_syms.c */; - name = "dynload_syms.c: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 880; - vrLoc = 0; - }; - 90FD14A011335059006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0CC10EE3F0A00928CAE /* dynload_syms_elf.c */; - name = "dynload_syms_elf.c: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 855; - vrLoc = 0; - }; - 90FD14A111335059006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0CD10EE3F0A00928CAE /* dynload_syms_pe32.c */; - name = "dynload_syms_pe32.c: 1"; - rLen = 0; - rLoc = 0; - rType = 0; - vrLen = 873; - vrLoc = 0; - }; - 90FD14AC11335069006462C7 /* dynload_darwin.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {1011, 949}}"; - sepNavSelRange = "{378, 0}"; - sepNavVisRange = "{860, 452}"; - }; - }; - 90FD14AD11335069006462C7 /* dynload_syms_darwin.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {1011, 1872}}"; - sepNavSelRange = "{1124, 0}"; - sepNavVisRange = "{1039, 663}"; - }; - }; - 90FD14AE11335079006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 9007E0CE10EE3F0A00928CAE /* dynload_unix.c */; - name = "dynload_unix.c: 40"; - rLen = 5; - rLoc = 1151; - rType = 0; - vrLen = 354; - vrLoc = 873; - }; - 90FD14F311376F9D006462C7 /* PBXTextBookmark */ = { - isa = PBXTextBookmark; - fRef = 90FD14AD11335069006462C7 /* dynload_syms_darwin.c */; - name = "dynload_syms_darwin.c: 41"; - rLen = 0; - rLoc = 1124; - rType = 0; - vrLen = 663; - vrLoc = 1039; - }; - D28A88AD04BDD90700651E21 /* bridj */ = { - activeExec = 0; - }; -} diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.pbxproj b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.pbxproj deleted file mode 100644 index 35210e5dd..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.pbxproj +++ /dev/null @@ -1,574 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXFileReference section */ - 9007E03F10EE3F0A00928CAE /* BSDmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = BSDmakefile; sourceTree = ""; }; - 9007E04210EE3F0A00928CAE /* dyncall_alloc_wx.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_alloc_wx.o; sourceTree = ""; }; - 9007E04310EE3F0A00928CAE /* dyncall_args.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_args.o; sourceTree = ""; }; - 9007E04410EE3F0A00928CAE /* dyncall_callback.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callback.o; sourceTree = ""; }; - 9007E04510EE3F0A00928CAE /* dyncall_callback_arch.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callback_arch.o; sourceTree = ""; }; - 9007E04610EE3F0A00928CAE /* dyncall_thunk.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_thunk.o; sourceTree = ""; }; - 9007E04710EE3F0A00928CAE /* libdyncallback_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdyncallback_s.a; sourceTree = ""; }; - 9007E04910EE3F0A00928CAE /* dyncall_alloc_wx.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_alloc_wx.o; sourceTree = ""; }; - 9007E04A10EE3F0A00928CAE /* dyncall_args.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_args.o; sourceTree = ""; }; - 9007E04B10EE3F0A00928CAE /* dyncall_callback.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callback.o; sourceTree = ""; }; - 9007E04C10EE3F0A00928CAE /* dyncall_callback_arch.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callback_arch.o; sourceTree = ""; }; - 9007E04D10EE3F0A00928CAE /* dyncall_thunk.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_thunk.o; sourceTree = ""; }; - 9007E04E10EE3F0A00928CAE /* libdyncallback_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdyncallback_s.a; sourceTree = ""; }; - 9007E04F10EE3F0A00928CAE /* dyncall_alloc_wx.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_alloc_wx.c; sourceTree = ""; }; - 9007E05010EE3F0A00928CAE /* dyncall_alloc_wx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_alloc_wx.h; sourceTree = ""; }; - 9007E05110EE3F0A00928CAE /* dyncall_alloc_wx_malloc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_alloc_wx_malloc.c; sourceTree = ""; }; - 9007E05210EE3F0A00928CAE /* dyncall_alloc_wx_mmap.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_alloc_wx_mmap.c; sourceTree = ""; }; - 9007E05310EE3F0A00928CAE /* dyncall_alloc_wx_win32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_alloc_wx_win32.c; sourceTree = ""; }; - 9007E05410EE3F0A00928CAE /* dyncall_args.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_args.c; sourceTree = ""; }; - 9007E05510EE3F0A00928CAE /* dyncall_args.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_args.h; sourceTree = ""; }; - 9007E05610EE3F0A00928CAE /* dyncall_args_ppc32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_args_ppc32.c; sourceTree = ""; }; - 9007E05710EE3F0A00928CAE /* dyncall_args_ppc32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_args_ppc32.h; sourceTree = ""; }; - 9007E05810EE3F0A00928CAE /* dyncall_args_x64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_args_x64.c; sourceTree = ""; }; - 9007E05910EE3F0A00928CAE /* dyncall_args_x64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_args_x64.h; sourceTree = ""; }; - 9007E05A10EE3F0A00928CAE /* dyncall_args_x86.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_args_x86.c; sourceTree = ""; }; - 9007E05B10EE3F0A00928CAE /* dyncall_args_x86.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_args_x86.h; sourceTree = ""; }; - 9007E05C10EE3F0A00928CAE /* dyncall_callback.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callback.c; sourceTree = ""; }; - 9007E05D10EE3F0A00928CAE /* dyncall_callback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callback.h; sourceTree = ""; }; - 9007E05E10EE3F0A00928CAE /* dyncall_callback_arch.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_arch.S; sourceTree = ""; }; - 9007E05F10EE3F0A00928CAE /* dyncall_callback_ppc32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callback_ppc32.c; sourceTree = ""; }; - 9007E06010EE3F0A00928CAE /* dyncall_callback_ppc32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callback_ppc32.h; sourceTree = ""; }; - 9007E06110EE3F0A00928CAE /* dyncall_callback_ppc32_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_ppc32_apple.s; sourceTree = ""; }; - 9007E06210EE3F0A00928CAE /* dyncall_callback_x64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callback_x64.c; sourceTree = ""; }; - 9007E06310EE3F0A00928CAE /* dyncall_callback_x64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callback_x64.h; sourceTree = ""; }; - 9007E06410EE3F0A00928CAE /* dyncall_callback_x64_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_x64_apple.s; sourceTree = ""; }; - 9007E06510EE3F0A00928CAE /* dyncall_callback_x64_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_x64_gas.s; sourceTree = ""; }; - 9007E06610EE3F0A00928CAE /* dyncall_callback_x64_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = dyncall_callback_x64_masm.asm; sourceTree = ""; }; - 9007E06710EE3F0A00928CAE /* dyncall_callback_x86.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callback_x86.c; sourceTree = ""; }; - 9007E06810EE3F0A00928CAE /* dyncall_callback_x86.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callback_x86.h; sourceTree = ""; }; - 9007E06910EE3F0A00928CAE /* dyncall_callback_x86_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_x86_apple.s; sourceTree = ""; }; - 9007E06A10EE3F0A00928CAE /* dyncall_callback_x86_gas.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_callback_x86_gas.S; sourceTree = ""; }; - 9007E06B10EE3F0A00928CAE /* dyncall_callback_x86_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = dyncall_callback_x86_masm.asm; sourceTree = ""; }; - 9007E06C10EE3F0A00928CAE /* dyncall_thunk.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_thunk.c; sourceTree = ""; }; - 9007E06D10EE3F0A00928CAE /* dyncall_thunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_thunk.h; sourceTree = ""; }; - 9007E06E10EE3F0A00928CAE /* dyncall_thunk_arm9_arm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_thunk_arm9_arm.c; sourceTree = ""; }; - 9007E06F10EE3F0A00928CAE /* dyncall_thunk_arm9_arm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_thunk_arm9_arm.h; sourceTree = ""; }; - 9007E07010EE3F0A00928CAE /* dyncall_thunk_ppc32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_thunk_ppc32.c; sourceTree = ""; }; - 9007E07110EE3F0A00928CAE /* dyncall_thunk_ppc32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_thunk_ppc32.h; sourceTree = ""; }; - 9007E07210EE3F0A00928CAE /* dyncall_thunk_x64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_thunk_x64.c; sourceTree = ""; }; - 9007E07310EE3F0A00928CAE /* dyncall_thunk_x64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_thunk_x64.h; sourceTree = ""; }; - 9007E07410EE3F0A00928CAE /* dyncall_thunk_x86.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_thunk_x86.c; sourceTree = ""; }; - 9007E07510EE3F0A00928CAE /* dyncall_thunk_x86.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_thunk_x86.h; sourceTree = ""; }; - 9007E07610EE3F0A00928CAE /* GNUmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GNUmakefile; sourceTree = ""; }; - 9007E07710EE3F0A00928CAE /* Nmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Nmakefile; sourceTree = ""; }; - 9007E07810EE3F0A00928CAE /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; }; - 9007E07910EE3F0A00928CAE /* TODO */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = TODO; sourceTree = ""; }; - 9007E07B10EE3F0A00928CAE /* BSDmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = BSDmakefile; sourceTree = ""; }; - 9007E07E10EE3F0A00928CAE /* dyncall_api.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_api.o; sourceTree = ""; }; - 9007E07F10EE3F0A00928CAE /* dyncall_call.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_call.o; sourceTree = ""; }; - 9007E08010EE3F0A00928CAE /* dyncall_callf.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callf.o; sourceTree = ""; }; - 9007E08110EE3F0A00928CAE /* dyncall_callvm.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callvm.o; sourceTree = ""; }; - 9007E08210EE3F0A00928CAE /* dyncall_vector.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_vector.o; sourceTree = ""; }; - 9007E08310EE3F0A00928CAE /* libdyncall_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdyncall_s.a; sourceTree = ""; }; - 9007E08510EE3F0A00928CAE /* dyncall_api.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_api.o; sourceTree = ""; }; - 9007E08610EE3F0A00928CAE /* dyncall_call.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_call.o; sourceTree = ""; }; - 9007E08710EE3F0A00928CAE /* dyncall_callf.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callf.o; sourceTree = ""; }; - 9007E08810EE3F0A00928CAE /* dyncall_callvm.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_callvm.o; sourceTree = ""; }; - 9007E08910EE3F0A00928CAE /* dyncall_vector.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dyncall_vector.o; sourceTree = ""; }; - 9007E08A10EE3F0A00928CAE /* libdyncall_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdyncall_s.a; sourceTree = ""; }; - 9007E08B10EE3F0A00928CAE /* dyncall.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall.h; sourceTree = ""; }; - 9007E08C10EE3F0A00928CAE /* dyncall_alloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_alloc.h; sourceTree = ""; }; - 9007E08D10EE3F0A00928CAE /* dyncall_api.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_api.c; sourceTree = ""; }; - 9007E08E10EE3F0A00928CAE /* dyncall_call.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call.S; sourceTree = ""; }; - 9007E08F10EE3F0A00928CAE /* dyncall_call_arm9_arm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_arm9_arm.h; sourceTree = ""; }; - 9007E09010EE3F0A00928CAE /* dyncall_call_arm9_arm_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_arm9_arm_gas.s; sourceTree = ""; }; - 9007E09110EE3F0A00928CAE /* dyncall_call_arm9_thumb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_arm9_thumb.h; sourceTree = ""; }; - 9007E09210EE3F0A00928CAE /* dyncall_call_arm9_thumb_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_arm9_thumb_gas.s; sourceTree = ""; }; - 9007E09310EE3F0A00928CAE /* dyncall_call_mips32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_mips32.h; sourceTree = ""; }; - 9007E09410EE3F0A00928CAE /* dyncall_call_mips32_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_mips32_gas.s; sourceTree = ""; }; - 9007E09510EE3F0A00928CAE /* dyncall_call_ppc32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_ppc32.h; sourceTree = ""; }; - 9007E09610EE3F0A00928CAE /* dyncall_call_ppc32_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_ppc32_apple.s; sourceTree = ""; }; - 9007E09710EE3F0A00928CAE /* dyncall_call_ppc32_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_ppc32_gas.s; sourceTree = ""; }; - 9007E09810EE3F0A00928CAE /* dyncall_call_x64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_x64.h; sourceTree = ""; }; - 9007E09910EE3F0A00928CAE /* dyncall_call_x64_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_x64_apple.s; sourceTree = ""; }; - 9007E09A10EE3F0A00928CAE /* dyncall_call_x64_gas.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_x64_gas.s; sourceTree = ""; }; - 9007E09B10EE3F0A00928CAE /* dyncall_call_x64_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = dyncall_call_x64_masm.asm; sourceTree = ""; }; - 9007E09C10EE3F0A00928CAE /* dyncall_call_x86.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_call_x86.h; sourceTree = ""; }; - 9007E09D10EE3F0A00928CAE /* dyncall_call_x86_apple.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_x86_apple.s; sourceTree = ""; }; - 9007E09E10EE3F0A00928CAE /* dyncall_call_x86_gas.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = dyncall_call_x86_gas.S; sourceTree = ""; }; - 9007E09F10EE3F0A00928CAE /* dyncall_call_x86_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = dyncall_call_x86_masm.asm; sourceTree = ""; }; - 9007E0A010EE3F0A00928CAE /* dyncall_call_x86_nasm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = dyncall_call_x86_nasm.asm; sourceTree = ""; }; - 9007E0A110EE3F0A00928CAE /* dyncall_callf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callf.c; sourceTree = ""; }; - 9007E0A210EE3F0A00928CAE /* dyncall_callf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callf.h; sourceTree = ""; }; - 9007E0A310EE3F0A00928CAE /* dyncall_callvm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm.c; sourceTree = ""; }; - 9007E0A410EE3F0A00928CAE /* dyncall_callvm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm.h; sourceTree = ""; }; - 9007E0A510EE3F0A00928CAE /* dyncall_callvm_arm9_arm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_arm9_arm.c; sourceTree = ""; }; - 9007E0A610EE3F0A00928CAE /* dyncall_callvm_arm9_arm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_arm9_arm.h; sourceTree = ""; }; - 9007E0A710EE3F0A00928CAE /* dyncall_callvm_arm9_thumb.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_arm9_thumb.c; sourceTree = ""; }; - 9007E0A810EE3F0A00928CAE /* dyncall_callvm_arm9_thumb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_arm9_thumb.h; sourceTree = ""; }; - 9007E0A910EE3F0A00928CAE /* dyncall_callvm_mips32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_mips32.c; sourceTree = ""; }; - 9007E0AA10EE3F0A00928CAE /* dyncall_callvm_mips32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_mips32.h; sourceTree = ""; }; - 9007E0AB10EE3F0A00928CAE /* dyncall_callvm_ppc32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_ppc32.c; sourceTree = ""; }; - 9007E0AC10EE3F0A00928CAE /* dyncall_callvm_ppc32.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_ppc32.h; sourceTree = ""; }; - 9007E0AD10EE3F0A00928CAE /* dyncall_callvm_x64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_x64.c; sourceTree = ""; }; - 9007E0AE10EE3F0A00928CAE /* dyncall_callvm_x64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_x64.h; sourceTree = ""; }; - 9007E0AF10EE3F0A00928CAE /* dyncall_callvm_x86.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_callvm_x86.c; sourceTree = ""; }; - 9007E0B010EE3F0A00928CAE /* dyncall_callvm_x86.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_callvm_x86.h; sourceTree = ""; }; - 9007E0B110EE3F0A00928CAE /* dyncall_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_config.h; sourceTree = ""; }; - 9007E0B210EE3F0A00928CAE /* dyncall_macros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_macros.h; sourceTree = ""; }; - 9007E0B310EE3F0A00928CAE /* dyncall_signature.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_signature.h; sourceTree = ""; }; - 9007E0B410EE3F0A00928CAE /* dyncall_types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_types.h; sourceTree = ""; }; - 9007E0B510EE3F0A00928CAE /* dyncall_value.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_value.h; sourceTree = ""; }; - 9007E0B610EE3F0A00928CAE /* dyncall_vector.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dyncall_vector.c; sourceTree = ""; }; - 9007E0B710EE3F0A00928CAE /* dyncall_vector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dyncall_vector.h; sourceTree = ""; }; - 9007E0B810EE3F0A00928CAE /* GNUmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GNUmakefile; sourceTree = ""; }; - 9007E0B910EE3F0A00928CAE /* Makefile.psp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Makefile.psp; sourceTree = ""; }; - 9007E0BA10EE3F0A00928CAE /* Nmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Nmakefile; sourceTree = ""; }; - 9007E0BB10EE3F0A00928CAE /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; }; - 9007E0BC10EE3F0A00928CAE /* TODO */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = TODO; sourceTree = ""; }; - 9007E0BE10EE3F0A00928CAE /* BSDmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = BSDmakefile; sourceTree = ""; }; - 9007E0C110EE3F0A00928CAE /* dynload.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dynload.o; sourceTree = ""; }; - 9007E0C210EE3F0A00928CAE /* dynload_syms.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dynload_syms.o; sourceTree = ""; }; - 9007E0C310EE3F0A00928CAE /* libdynload_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdynload_s.a; sourceTree = ""; }; - 9007E0C510EE3F0A00928CAE /* dynload.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dynload.o; sourceTree = ""; }; - 9007E0C610EE3F0A00928CAE /* dynload_syms.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = dynload_syms.o; sourceTree = ""; }; - 9007E0C710EE3F0A00928CAE /* libdynload_s.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libdynload_s.a; sourceTree = ""; }; - 9007E0C810EE3F0A00928CAE /* dynload.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload.c; sourceTree = ""; }; - 9007E0C910EE3F0A00928CAE /* dynload.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dynload.h; sourceTree = ""; }; - 9007E0CA10EE3F0A00928CAE /* dynload_macros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dynload_macros.h; sourceTree = ""; }; - 9007E0CB10EE3F0A00928CAE /* dynload_syms.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_syms.c; sourceTree = ""; }; - 9007E0CC10EE3F0A00928CAE /* dynload_syms_elf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_syms_elf.c; sourceTree = ""; }; - 9007E0CD10EE3F0A00928CAE /* dynload_syms_pe32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_syms_pe32.c; sourceTree = ""; }; - 9007E0CE10EE3F0A00928CAE /* dynload_unix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_unix.c; sourceTree = ""; }; - 9007E0CF10EE3F0A00928CAE /* dynload_win32.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_win32.c; sourceTree = ""; }; - 9007E0D010EE3F0A00928CAE /* GNUmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GNUmakefile; sourceTree = ""; }; - 9007E0D110EE3F0A00928CAE /* Nmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Nmakefile; sourceTree = ""; }; - 9007E0D210EE3F0A00928CAE /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; }; - 9007E0D910EE3F1B00928CAE /* JavaToNativeCallHandler.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = JavaToNativeCallHandler.o; sourceTree = ""; }; - 9007E0DA10EE3F1B00928CAE /* JNI.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = JNI.o; sourceTree = ""; }; - 9007E0DC10EE3F1B00928CAE /* libbridj.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; path = libbridj.dylib; sourceTree = ""; }; - 9007E0DD10EE3F1B00928CAE /* libtest.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; path = libtest.dylib; sourceTree = ""; }; - 9007E0E010EE3F1B00928CAE /* Pointer.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = Pointer.o; sourceTree = ""; }; - 9007E0E110EE3F1B00928CAE /* RawNativeForwardCallback.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = RawNativeForwardCallback.o; sourceTree = ""; }; - 9007E0E610EE3F1B00928CAE /* JavaToNativeCallHandler.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = JavaToNativeCallHandler.o; sourceTree = ""; }; - 9007E0E710EE3F1B00928CAE /* JNI.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = JNI.o; sourceTree = ""; }; - 9007E0E910EE3F1B00928CAE /* libbridj.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; path = libbridj.dylib; sourceTree = ""; }; - 9007E0ED10EE3F1B00928CAE /* Pointer.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = Pointer.o; sourceTree = ""; }; - 9007E0EE10EE3F1B00928CAE /* RawNativeForwardCallback.o */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.objfile"; path = RawNativeForwardCallback.o; sourceTree = ""; }; - 9007E0F710EE3F1C00928CAE /* GNUmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GNUmakefile; sourceTree = ""; }; - 9007E0F810EE3F1C00928CAE /* JavaToNativeCallHandler.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = JavaToNativeCallHandler.c; sourceTree = ""; }; - 9007E0F910EE3F1C00928CAE /* bridj.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bridj.hpp; sourceTree = ""; }; - 9007E0FC10EE3F1C00928CAE /* JNI.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = JNI.c; sourceTree = ""; }; - 9007E10610EE3F1C00928CAE /* Pointer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Pointer.c; sourceTree = ""; }; - 9007E10710EE3F1C00928CAE /* RawNativeForwardCallback.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = RawNativeForwardCallback.c; sourceTree = ""; }; - 9007E10810EE3F1C00928CAE /* RawNativeForwardCallback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RawNativeForwardCallback.h; sourceTree = ""; }; - 9007E10910EE3F1C00928CAE /* RawNativeForwardCallback_WIN32_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = RawNativeForwardCallback_WIN32_masm.asm; sourceTree = ""; }; - 9007E10A10EE3F1C00928CAE /* RawNativeForwardCallback_WIN64_masm.asm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm.asm; path = RawNativeForwardCallback_WIN64_masm.asm; sourceTree = ""; }; - 90DC54271133337000F33FC9 /* dynload_syms_darwin.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_syms_darwin.c; sourceTree = ""; }; - 90DC54281133337C00F33FC9 /* dynload_darwin.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_darwin.c; sourceTree = ""; }; - 90FD14AC11335069006462C7 /* dynload_darwin.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_darwin.c; sourceTree = ""; }; - 90FD14AD11335069006462C7 /* dynload_syms_darwin.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dynload_syms_darwin.c; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXGroup section */ - 08FB7794FE84155DC02AAC07 /* bridj */ = { - isa = PBXGroup; - children = ( - 9007E0D310EE3F1B00928CAE /* bridj */, - 9007E03E10EE3F0A00928CAE /* dyncallback */, - 9007E07A10EE3F0A00928CAE /* dyncall */, - 9007E0BD10EE3F0A00928CAE /* dynload */, - ); - name = bridj; - sourceTree = ""; - }; - 9007E03E10EE3F0A00928CAE /* dyncallback */ = { - isa = PBXGroup; - children = ( - 9007E03F10EE3F0A00928CAE /* BSDmakefile */, - 9007E04010EE3F0A00928CAE /* build_out */, - 9007E04F10EE3F0A00928CAE /* dyncall_alloc_wx.c */, - 9007E05010EE3F0A00928CAE /* dyncall_alloc_wx.h */, - 9007E05110EE3F0A00928CAE /* dyncall_alloc_wx_malloc.c */, - 9007E05210EE3F0A00928CAE /* dyncall_alloc_wx_mmap.c */, - 9007E05310EE3F0A00928CAE /* dyncall_alloc_wx_win32.c */, - 9007E05410EE3F0A00928CAE /* dyncall_args.c */, - 9007E05510EE3F0A00928CAE /* dyncall_args.h */, - 9007E05610EE3F0A00928CAE /* dyncall_args_ppc32.c */, - 9007E05710EE3F0A00928CAE /* dyncall_args_ppc32.h */, - 9007E05810EE3F0A00928CAE /* dyncall_args_x64.c */, - 9007E05910EE3F0A00928CAE /* dyncall_args_x64.h */, - 9007E05A10EE3F0A00928CAE /* dyncall_args_x86.c */, - 9007E05B10EE3F0A00928CAE /* dyncall_args_x86.h */, - 9007E05C10EE3F0A00928CAE /* dyncall_callback.c */, - 9007E05D10EE3F0A00928CAE /* dyncall_callback.h */, - 9007E05E10EE3F0A00928CAE /* dyncall_callback_arch.S */, - 9007E05F10EE3F0A00928CAE /* dyncall_callback_ppc32.c */, - 9007E06010EE3F0A00928CAE /* dyncall_callback_ppc32.h */, - 9007E06110EE3F0A00928CAE /* dyncall_callback_ppc32_apple.s */, - 9007E06210EE3F0A00928CAE /* dyncall_callback_x64.c */, - 9007E06310EE3F0A00928CAE /* dyncall_callback_x64.h */, - 9007E06410EE3F0A00928CAE /* dyncall_callback_x64_apple.s */, - 9007E06510EE3F0A00928CAE /* dyncall_callback_x64_gas.s */, - 9007E06610EE3F0A00928CAE /* dyncall_callback_x64_masm.asm */, - 9007E06710EE3F0A00928CAE /* dyncall_callback_x86.c */, - 9007E06810EE3F0A00928CAE /* dyncall_callback_x86.h */, - 9007E06910EE3F0A00928CAE /* dyncall_callback_x86_apple.s */, - 9007E06A10EE3F0A00928CAE /* dyncall_callback_x86_gas.S */, - 9007E06B10EE3F0A00928CAE /* dyncall_callback_x86_masm.asm */, - 9007E06C10EE3F0A00928CAE /* dyncall_thunk.c */, - 9007E06D10EE3F0A00928CAE /* dyncall_thunk.h */, - 9007E06E10EE3F0A00928CAE /* dyncall_thunk_arm9_arm.c */, - 9007E06F10EE3F0A00928CAE /* dyncall_thunk_arm9_arm.h */, - 9007E07010EE3F0A00928CAE /* dyncall_thunk_ppc32.c */, - 9007E07110EE3F0A00928CAE /* dyncall_thunk_ppc32.h */, - 9007E07210EE3F0A00928CAE /* dyncall_thunk_x64.c */, - 9007E07310EE3F0A00928CAE /* dyncall_thunk_x64.h */, - 9007E07410EE3F0A00928CAE /* dyncall_thunk_x86.c */, - 9007E07510EE3F0A00928CAE /* dyncall_thunk_x86.h */, - 9007E07610EE3F0A00928CAE /* GNUmakefile */, - 9007E07710EE3F0A00928CAE /* Nmakefile */, - 9007E07810EE3F0A00928CAE /* README.txt */, - 9007E07910EE3F0A00928CAE /* TODO */, - ); - name = dyncallback; - path = ../../../../../../../../../../../../../../src/dyncall/dyncall/dyncallback; - sourceTree = SOURCE_ROOT; - }; - 9007E04010EE3F0A00928CAE /* build_out */ = { - isa = PBXGroup; - children = ( - 9007E04110EE3F0A00928CAE /* darwin_universal_gcc_debug */, - 9007E04810EE3F0A00928CAE /* darwin_universal_gcc_release */, - ); - path = build_out; - sourceTree = ""; - }; - 9007E04110EE3F0A00928CAE /* darwin_universal_gcc_debug */ = { - isa = PBXGroup; - children = ( - 9007E04210EE3F0A00928CAE /* dyncall_alloc_wx.o */, - 9007E04310EE3F0A00928CAE /* dyncall_args.o */, - 9007E04410EE3F0A00928CAE /* dyncall_callback.o */, - 9007E04510EE3F0A00928CAE /* dyncall_callback_arch.o */, - 9007E04610EE3F0A00928CAE /* dyncall_thunk.o */, - 9007E04710EE3F0A00928CAE /* libdyncallback_s.a */, - ); - path = darwin_universal_gcc_debug; - sourceTree = ""; - }; - 9007E04810EE3F0A00928CAE /* darwin_universal_gcc_release */ = { - isa = PBXGroup; - children = ( - 9007E04910EE3F0A00928CAE /* dyncall_alloc_wx.o */, - 9007E04A10EE3F0A00928CAE /* dyncall_args.o */, - 9007E04B10EE3F0A00928CAE /* dyncall_callback.o */, - 9007E04C10EE3F0A00928CAE /* dyncall_callback_arch.o */, - 9007E04D10EE3F0A00928CAE /* dyncall_thunk.o */, - 9007E04E10EE3F0A00928CAE /* libdyncallback_s.a */, - ); - path = darwin_universal_gcc_release; - sourceTree = ""; - }; - 9007E07A10EE3F0A00928CAE /* dyncall */ = { - isa = PBXGroup; - children = ( - 9007E07B10EE3F0A00928CAE /* BSDmakefile */, - 9007E07C10EE3F0A00928CAE /* build_out */, - 9007E08B10EE3F0A00928CAE /* dyncall.h */, - 9007E08C10EE3F0A00928CAE /* dyncall_alloc.h */, - 9007E08D10EE3F0A00928CAE /* dyncall_api.c */, - 9007E08E10EE3F0A00928CAE /* dyncall_call.S */, - 9007E08F10EE3F0A00928CAE /* dyncall_call_arm9_arm.h */, - 9007E09010EE3F0A00928CAE /* dyncall_call_arm9_arm_gas.s */, - 9007E09110EE3F0A00928CAE /* dyncall_call_arm9_thumb.h */, - 9007E09210EE3F0A00928CAE /* dyncall_call_arm9_thumb_gas.s */, - 9007E09310EE3F0A00928CAE /* dyncall_call_mips32.h */, - 9007E09410EE3F0A00928CAE /* dyncall_call_mips32_gas.s */, - 9007E09510EE3F0A00928CAE /* dyncall_call_ppc32.h */, - 9007E09610EE3F0A00928CAE /* dyncall_call_ppc32_apple.s */, - 9007E09710EE3F0A00928CAE /* dyncall_call_ppc32_gas.s */, - 9007E09810EE3F0A00928CAE /* dyncall_call_x64.h */, - 9007E09910EE3F0A00928CAE /* dyncall_call_x64_apple.s */, - 9007E09A10EE3F0A00928CAE /* dyncall_call_x64_gas.s */, - 9007E09B10EE3F0A00928CAE /* dyncall_call_x64_masm.asm */, - 9007E09C10EE3F0A00928CAE /* dyncall_call_x86.h */, - 9007E09D10EE3F0A00928CAE /* dyncall_call_x86_apple.s */, - 9007E09E10EE3F0A00928CAE /* dyncall_call_x86_gas.S */, - 9007E09F10EE3F0A00928CAE /* dyncall_call_x86_masm.asm */, - 9007E0A010EE3F0A00928CAE /* dyncall_call_x86_nasm.asm */, - 9007E0A110EE3F0A00928CAE /* dyncall_callf.c */, - 9007E0A210EE3F0A00928CAE /* dyncall_callf.h */, - 9007E0A310EE3F0A00928CAE /* dyncall_callvm.c */, - 9007E0A410EE3F0A00928CAE /* dyncall_callvm.h */, - 9007E0A510EE3F0A00928CAE /* dyncall_callvm_arm9_arm.c */, - 9007E0A610EE3F0A00928CAE /* dyncall_callvm_arm9_arm.h */, - 9007E0A710EE3F0A00928CAE /* dyncall_callvm_arm9_thumb.c */, - 9007E0A810EE3F0A00928CAE /* dyncall_callvm_arm9_thumb.h */, - 9007E0A910EE3F0A00928CAE /* dyncall_callvm_mips32.c */, - 9007E0AA10EE3F0A00928CAE /* dyncall_callvm_mips32.h */, - 9007E0AB10EE3F0A00928CAE /* dyncall_callvm_ppc32.c */, - 9007E0AC10EE3F0A00928CAE /* dyncall_callvm_ppc32.h */, - 9007E0AD10EE3F0A00928CAE /* dyncall_callvm_x64.c */, - 9007E0AE10EE3F0A00928CAE /* dyncall_callvm_x64.h */, - 9007E0AF10EE3F0A00928CAE /* dyncall_callvm_x86.c */, - 9007E0B010EE3F0A00928CAE /* dyncall_callvm_x86.h */, - 9007E0B110EE3F0A00928CAE /* dyncall_config.h */, - 9007E0B210EE3F0A00928CAE /* dyncall_macros.h */, - 9007E0B310EE3F0A00928CAE /* dyncall_signature.h */, - 9007E0B410EE3F0A00928CAE /* dyncall_types.h */, - 9007E0B510EE3F0A00928CAE /* dyncall_value.h */, - 9007E0B610EE3F0A00928CAE /* dyncall_vector.c */, - 9007E0B710EE3F0A00928CAE /* dyncall_vector.h */, - 9007E0B810EE3F0A00928CAE /* GNUmakefile */, - 9007E0B910EE3F0A00928CAE /* Makefile.psp */, - 9007E0BA10EE3F0A00928CAE /* Nmakefile */, - 9007E0BB10EE3F0A00928CAE /* README.txt */, - 9007E0BC10EE3F0A00928CAE /* TODO */, - ); - name = dyncall; - path = ../../../../../../../../../../../../../../src/dyncall/dyncall/dyncall; - sourceTree = SOURCE_ROOT; - }; - 9007E07C10EE3F0A00928CAE /* build_out */ = { - isa = PBXGroup; - children = ( - 9007E07D10EE3F0A00928CAE /* darwin_universal_gcc_debug */, - 9007E08410EE3F0A00928CAE /* darwin_universal_gcc_release */, - ); - path = build_out; - sourceTree = ""; - }; - 9007E07D10EE3F0A00928CAE /* darwin_universal_gcc_debug */ = { - isa = PBXGroup; - children = ( - 9007E07E10EE3F0A00928CAE /* dyncall_api.o */, - 9007E07F10EE3F0A00928CAE /* dyncall_call.o */, - 9007E08010EE3F0A00928CAE /* dyncall_callf.o */, - 9007E08110EE3F0A00928CAE /* dyncall_callvm.o */, - 9007E08210EE3F0A00928CAE /* dyncall_vector.o */, - 9007E08310EE3F0A00928CAE /* libdyncall_s.a */, - ); - path = darwin_universal_gcc_debug; - sourceTree = ""; - }; - 9007E08410EE3F0A00928CAE /* darwin_universal_gcc_release */ = { - isa = PBXGroup; - children = ( - 9007E08510EE3F0A00928CAE /* dyncall_api.o */, - 9007E08610EE3F0A00928CAE /* dyncall_call.o */, - 9007E08710EE3F0A00928CAE /* dyncall_callf.o */, - 9007E08810EE3F0A00928CAE /* dyncall_callvm.o */, - 9007E08910EE3F0A00928CAE /* dyncall_vector.o */, - 9007E08A10EE3F0A00928CAE /* libdyncall_s.a */, - ); - path = darwin_universal_gcc_release; - sourceTree = ""; - }; - 9007E0BD10EE3F0A00928CAE /* dynload */ = { - isa = PBXGroup; - children = ( - 90FD14AC11335069006462C7 /* dynload_darwin.c */, - 90FD14AD11335069006462C7 /* dynload_syms_darwin.c */, - 90DC54281133337C00F33FC9 /* dynload_darwin.c */, - 90DC54271133337000F33FC9 /* dynload_syms_darwin.c */, - 9007E0BE10EE3F0A00928CAE /* BSDmakefile */, - 9007E0BF10EE3F0A00928CAE /* build_out */, - 9007E0C810EE3F0A00928CAE /* dynload.c */, - 9007E0C910EE3F0A00928CAE /* dynload.h */, - 9007E0CA10EE3F0A00928CAE /* dynload_macros.h */, - 9007E0CB10EE3F0A00928CAE /* dynload_syms.c */, - 9007E0CC10EE3F0A00928CAE /* dynload_syms_elf.c */, - 9007E0CD10EE3F0A00928CAE /* dynload_syms_pe32.c */, - 9007E0CE10EE3F0A00928CAE /* dynload_unix.c */, - 9007E0CF10EE3F0A00928CAE /* dynload_win32.c */, - 9007E0D010EE3F0A00928CAE /* GNUmakefile */, - 9007E0D110EE3F0A00928CAE /* Nmakefile */, - 9007E0D210EE3F0A00928CAE /* README.txt */, - ); - name = dynload; - path = ../../../../../../../../../../../../../../src/dyncall/dyncall/dynload; - sourceTree = SOURCE_ROOT; - }; - 9007E0BF10EE3F0A00928CAE /* build_out */ = { - isa = PBXGroup; - children = ( - 9007E0C010EE3F0A00928CAE /* darwin_universal_gcc_debug */, - 9007E0C410EE3F0A00928CAE /* darwin_universal_gcc_release */, - ); - path = build_out; - sourceTree = ""; - }; - 9007E0C010EE3F0A00928CAE /* darwin_universal_gcc_debug */ = { - isa = PBXGroup; - children = ( - 9007E0C110EE3F0A00928CAE /* dynload.o */, - 9007E0C210EE3F0A00928CAE /* dynload_syms.o */, - 9007E0C310EE3F0A00928CAE /* libdynload_s.a */, - ); - path = darwin_universal_gcc_debug; - sourceTree = ""; - }; - 9007E0C410EE3F0A00928CAE /* darwin_universal_gcc_release */ = { - isa = PBXGroup; - children = ( - 9007E0C510EE3F0A00928CAE /* dynload.o */, - 9007E0C610EE3F0A00928CAE /* dynload_syms.o */, - 9007E0C710EE3F0A00928CAE /* libdynload_s.a */, - ); - path = darwin_universal_gcc_release; - sourceTree = ""; - }; - 9007E0D310EE3F1B00928CAE /* bridj */ = { - isa = PBXGroup; - children = ( - 9007E0D510EE3F1B00928CAE /* build_out */, - 9007E0F710EE3F1C00928CAE /* GNUmakefile */, - 9007E0F810EE3F1C00928CAE /* JavaToNativeCallHandler.c */, - 9007E0F910EE3F1C00928CAE /* bridj.hpp */, - 9007E0FC10EE3F1C00928CAE /* JNI.c */, - 9007E10610EE3F1C00928CAE /* Pointer.c */, - 9007E10710EE3F1C00928CAE /* RawNativeForwardCallback.c */, - 9007E10810EE3F1C00928CAE /* RawNativeForwardCallback.h */, - 9007E10910EE3F1C00928CAE /* RawNativeForwardCallback_WIN32_masm.asm */, - 9007E10A10EE3F1C00928CAE /* RawNativeForwardCallback_WIN64_masm.asm */, - ); - name = bridj; - path = ../../../bridj; - sourceTree = SOURCE_ROOT; - }; - 9007E0D510EE3F1B00928CAE /* build_out */ = { - isa = PBXGroup; - children = ( - 9007E0D610EE3F1B00928CAE /* darwin_universal_gcc_debug */, - 9007E0E310EE3F1B00928CAE /* darwin_universal_gcc_release */, - ); - path = build_out; - sourceTree = ""; - }; - 9007E0D610EE3F1B00928CAE /* darwin_universal_gcc_debug */ = { - isa = PBXGroup; - children = ( - 9007E0D910EE3F1B00928CAE /* JavaToNativeCallHandler.o */, - 9007E0DA10EE3F1B00928CAE /* JNI.o */, - 9007E0DC10EE3F1B00928CAE /* libbridj.dylib */, - 9007E0DD10EE3F1B00928CAE /* libtest.dylib */, - 9007E0E010EE3F1B00928CAE /* Pointer.o */, - 9007E0E110EE3F1B00928CAE /* RawNativeForwardCallback.o */, - ); - path = darwin_universal_gcc_debug; - sourceTree = ""; - }; - 9007E0E310EE3F1B00928CAE /* darwin_universal_gcc_release */ = { - isa = PBXGroup; - children = ( - 9007E0E610EE3F1B00928CAE /* JavaToNativeCallHandler.o */, - 9007E0E710EE3F1B00928CAE /* JNI.o */, - 9007E0E910EE3F1B00928CAE /* libbridj.dylib */, - 9007E0ED10EE3F1B00928CAE /* Pointer.o */, - 9007E0EE10EE3F1B00928CAE /* RawNativeForwardCallback.o */, - ); - path = darwin_universal_gcc_release; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXLegacyTarget section */ - D28A88AD04BDD90700651E21 /* bridj */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "$(ACTION)"; - buildConfigurationList = 1DEB918F08733D9F0010E9CD /* Build configuration list for PBXLegacyTarget "bridj" */; - buildPhases = ( - ); - buildToolPath = /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/Runtime/BridJ/BuildNative; - buildWorkingDirectory = /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/Runtime/BridJ; - dependencies = ( - ); - name = bridj; - passBuildSettingsInEnvironment = 0; - productName = bridj; - }; -/* End PBXLegacyTarget section */ - -/* Begin PBXProject section */ - 08FB7793FE84155DC02AAC07 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 1DEB919308733D9F0010E9CD /* Build configuration list for PBXProject "JDyncall" */; - compatibilityVersion = "Xcode 3.2"; - hasScannedForEncodings = 1; - mainGroup = 08FB7794FE84155DC02AAC07 /* bridj */; - projectDirPath = ""; - projectRoots = ( - "", - ../../../bridj, - ); - targets = ( - D28A88AD04BDD90700651E21 /* bridj */, - ); - }; -/* End PBXProject section */ - -/* Begin XCBuildConfiguration section */ - 1DEB919008733D9F0010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUILD_CONFIG = debug; - DYNCALL_HOME = /Users/ochafik/src/dyncall; - }; - name = Debug; - }; - 1DEB919108733D9F0010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DYNCALL_HOME = /Users/ochafik/src/dyncall; - }; - name = Release; - }; - 1DEB919408733D9F0010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = YES; - PREBINDING = NO; - SDKROOT = macosx10.6; - }; - name = Debug; - }; - 1DEB919508733D9F0010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - PREBINDING = NO; - SDKROOT = macosx10.6; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1DEB918F08733D9F0010E9CD /* Build configuration list for PBXLegacyTarget "bridj" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB919008733D9F0010E9CD /* Debug */, - 1DEB919108733D9F0010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1DEB919308733D9F0010E9CD /* Build configuration list for PBXProject "JDyncall" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB919408733D9F0010E9CD /* Debug */, - 1DEB919508733D9F0010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 08FB7793FE84155DC02AAC07 /* Project object */; -} diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 46529335c..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index edf63b432..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate +++ /dev/null @@ -1,2985 +0,0 @@ - - - - - $archiver - NSKeyedArchiver - $objects - - $null - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 2 - - - CF$UID - 3 - - - NS.objects - - - CF$UID - 4 - - - CF$UID - 124 - - - - IDEWorkspaceDocument - E7C51A93-7D3A-415A-9AB1-6207FE669BDB - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 5 - - - CF$UID - 6 - - - CF$UID - 7 - - - CF$UID - 8 - - - CF$UID - 9 - - - CF$UID - 10 - - - CF$UID - 11 - - - CF$UID - 12 - - - CF$UID - 13 - - - CF$UID - 14 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 16 - - - CF$UID - 79 - - - CF$UID - 80 - - - CF$UID - 85 - - - CF$UID - 88 - - - CF$UID - 119 - - - CF$UID - 120 - - - CF$UID - 15 - - - CF$UID - 15 - - - - BreakpointsActivated - DefaultEditorStatesForURLs - DebuggingWindowBehavior - ActiveRunDestination - ActiveScheme - LastCompletedPersistentSchemeBasedActivityReport - DocumentWindows - RecentEditorDocumentURLs - AppFocusInMiniDebugging - MiniDebuggingConsole - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 17 - - - CF$UID - 18 - - - CF$UID - 19 - - - NS.objects - - - CF$UID - 20 - - - CF$UID - 56 - - - CF$UID - 67 - - - - Xcode.Xcode3ProjectSupport.EditorDocument.Xcode3Project - Xcode.IDEKit.EditorDocument.SourceCode - Xcode.IDEKit.EditorDocument.LogDocument - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 21 - - - NS.objects - - - CF$UID - 25 - - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 22 - - - - $class - - CF$UID - 23 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ - - - $classes - - NSMutableString - NSString - NSObject - - $classname - NSMutableString - - - $classes - - NSURL - NSObject - - $classname - NSURL - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 26 - - - CF$UID - 27 - - - CF$UID - 28 - - - CF$UID - 29 - - - NS.objects - - - CF$UID - 30 - - - CF$UID - 43 - - - CF$UID - 44 - - - CF$UID - 55 - - - - Xcode3ProjectEditor.sourceList.splitview - Xcode3ProjectEditorPreviousTargetEditorClass - Xcode3ProjectEditorSelectedDocumentLocations - Xcode3ProjectEditor_Xcode3InfoEditor - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 32 - - - - DVTSplitViewItems - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 33 - - - CF$UID - 39 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 36 - - - CF$UID - 37 - - - - DVTIdentifier - DVTViewMagnitude - - 162 - - $classes - - NSDictionary - NSObject - - $classname - NSDictionary - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 36 - - - CF$UID - 40 - - - - 978 - - $classes - - NSMutableArray - NSArray - NSObject - - $classname - NSMutableArray - - - $classes - - NSMutableDictionary - NSDictionary - NSObject - - $classname - NSMutableDictionary - - Xcode3InfoEditor - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 45 - - - - - $class - - CF$UID - 53 - - documentURL - - CF$UID - 46 - - selection - - CF$UID - 48 - - timestamp - - CF$UID - 47 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/ - 364652088.77702302 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 49 - - - CF$UID - 50 - - - NS.objects - - - CF$UID - 51 - - - CF$UID - 52 - - - - Editor - Target - Xcode3InfoEditor - bridj - - $classes - - Xcode3ProjectDocumentLocation - DVTDocumentLocation - NSObject - - $classname - Xcode3ProjectDocumentLocation - - - $classes - - NSArray - NSObject - - $classname - NSArray - - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 57 - - - NS.objects - - - CF$UID - 59 - - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 58 - - - - $class - - CF$UID - 23 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/GNUmakefile - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 60 - - - CF$UID - 61 - - - CF$UID - 62 - - - CF$UID - 63 - - - NS.objects - - - CF$UID - 64 - - - CF$UID - 65 - - - CF$UID - 15 - - - CF$UID - 66 - - - - PrimaryDocumentTimestamp - PrimaryDocumentVisibleCharacterRange - HideAllIssues - PrimaryDocumentSelectedCharacterRange - 364645643.32302099 - {0, 2052} - {0, 0} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 68 - - - NS.objects - - - CF$UID - 70 - - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 69 - - - x-xcode-log://30F1CAEB-B5A3-4E20-A047-0FC5A54612F0 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 71 - - - NS.objects - - - CF$UID - 72 - - - - SelectedDocumentLocations - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 73 - - - - - $class - - CF$UID - 78 - - documentURL - - CF$UID - 69 - - expandTranscript - - indexPath - - CF$UID - 74 - - timestamp - - CF$UID - 0 - - - - $class - - CF$UID - 77 - - NSIndexPathData - - CF$UID - 75 - - NSIndexPathLength - 2 - - - $class - - CF$UID - 76 - - NS.data - - AAE= - - - - $classes - - NSMutableData - NSData - NSObject - - $classname - NSMutableData - - - $classes - - NSIndexPath - NSObject - - $classname - NSIndexPath - - - $classes - - IDELogDocumentLocation - DVTDocumentLocation - NSObject - - $classname - IDELogDocumentLocation - - 0 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 81 - - - CF$UID - 82 - - - NS.objects - - - CF$UID - 83 - - - CF$UID - 84 - - - - IDEDeviceLocation - IDEDeviceArchitecture - dvtdevice-local-computer:localhost - x86_64 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 86 - - - NS.objects - - - CF$UID - 87 - - - - IDENameString - bridj - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 89 - - - CF$UID - 90 - - - CF$UID - 91 - - - NS.objects - - - CF$UID - 92 - - - CF$UID - 118 - - - CF$UID - 52 - - - - IDEActivityReportCompletionSummaryStringSegments - IDEActivityReportOptions - IDEActivityReportTitle - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 93 - - - CF$UID - 100 - - - CF$UID - 104 - - - CF$UID - 108 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 94 - - - CF$UID - 95 - - - CF$UID - 96 - - - NS.objects - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - - IDEActivityReportStringSegmentPriority - IDEActivityReportStringSegmentBackSeparator - IDEActivityReportStringSegmentStringValue - 2 - - Build - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 94 - - - CF$UID - 95 - - - CF$UID - 96 - - - NS.objects - - - CF$UID - 101 - - - CF$UID - 102 - - - CF$UID - 103 - - - - 4 - : - bridj - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 94 - - - CF$UID - 95 - - - CF$UID - 96 - - - NS.objects - - - CF$UID - 105 - - - CF$UID - 106 - - - CF$UID - 107 - - - - 1 - │ - - $class - - CF$UID - 76 - - NS.data - - YnBsaXN0MDDUAQIDBAUGOzxYJHZlcnNpb25YJG9iamVjdHNZJGFy - Y2hpdmVyVCR0b3ASAAGGoK0HCA8QGhscJCUrMTQ3VSRudWxs0wkK - CwwNDlxOU0F0dHJpYnV0ZXNWJGNsYXNzWE5TU3RyaW5ngAOADIAC - VkZhaWxlZNMKERITFBdXTlMua2V5c1pOUy5vYmplY3RzgAuiFRaA - BIAFohgZgAaACVZOU0ZvbnRXTlNDb2xvctQKHR4fICEiI1ZOU05h - bWVWTlNTaXplWE5TZkZsYWdzgAiAByNAJgAAAAAAABENEF8QEUx1 - Y2lkYUdyYW5kZS1Cb2xk0iYnKClaJGNsYXNzbmFtZVgkY2xhc3Nl - c1ZOU0ZvbnSiKCpYTlNPYmplY3TTCiwtLi8wXE5TQ29sb3JTcGFj - ZVVOU1JHQoAKEAFGMSAwIDAA0iYnMjNXTlNDb2xvcqIyKtImJzU2 - XE5TRGljdGlvbmFyeaI1KtImJzg5XxASTlNBdHRyaWJ1dGVkU3Ry - aW5nojoqXxASTlNBdHRyaWJ1dGVkU3RyaW5nXxAPTlNLZXllZEFy - Y2hpdmVy0T0+VHJvb3SAAQAIABEAGgAjAC0AMgA3AEUASwBSAF8A - ZgBvAHEAcwB1AHwAgwCLAJYAmACbAJ0AnwCiAKQApgCtALUAvgDF - AMwA1QDXANkA4gDlAPkA/gEJARIBGQEcASUBLAE5AT8BQQFDAUoB - TwFXAVoBXwFsAW8BdAGJAYwBoQGzAbYBuwAAAAAAAAIBAAAAAAAA - AD8AAAAAAAAAAAAAAAAAAAG9 - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 94 - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 96 - - - CF$UID - 111 - - - CF$UID - 112 - - - NS.objects - - - CF$UID - 113 - - - CF$UID - 114 - - - CF$UID - 115 - - - CF$UID - 117 - - - CF$UID - 114 - - - CF$UID - 114 - - - - IDEActivityReportStringSegmentType - IDEActivityReportStringSegmentDate - IDEActivityReportStringSegmentDateStyle - IDEActivityReportStringSegmentTimeStyle - 3 - 1 - - $class - - CF$UID - 116 - - NS.time - 364645637.78372401 - - - $classes - - NSDate - NSObject - - $classname - NSDate - - Today at 11:27 - 234 - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 3 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 68 - - - CF$UID - 121 - - - CF$UID - 122 - - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 46 - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 123 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/GNUmakefile - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 125 - - - CF$UID - 126 - - - CF$UID - 127 - - - CF$UID - 128 - - - CF$UID - 129 - - - CF$UID - 130 - - - CF$UID - 131 - - - CF$UID - 132 - - - NS.objects - - - CF$UID - 133 - - - CF$UID - 134 - - - CF$UID - 135 - - - CF$UID - 15 - - - CF$UID - 3 - - - CF$UID - 127 - - - CF$UID - 144 - - - CF$UID - 15 - - - - IDEWindowFrame - IDEOrderedWorkspaceTabControllers - IDEWorkspaceTabController_6D3F388B-3B9E-4312-885F-A503507B592D - IDEWindowInFullscreenMode - IDEWorkspaceWindowControllerUniqueIdentifier - IDEActiveWorkspaceTabController - IDEWindowToolbarIsVisible - IDEWindowTabBarIsVisible - {{57, -181}, {1400, 952}} - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 127 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 136 - - - CF$UID - 137 - - - CF$UID - 138 - - - CF$UID - 139 - - - CF$UID - 140 - - - CF$UID - 141 - - - CF$UID - 142 - - - CF$UID - 143 - - - NS.objects - - - CF$UID - 79 - - - CF$UID - 144 - - - CF$UID - 145 - - - CF$UID - 146 - - - CF$UID - 152 - - - CF$UID - 195 - - - CF$UID - 15 - - - CF$UID - 204 - - - - AssistantEditorsLayout - IDEShowNavigator - IDETabLabel - IDEWorkspaceTabControllerUtilityAreaSplitView - IDENavigatorArea - IDEWorkspaceTabControllerDesignAreaSplitView - IDEShowUtilities - IDEEditorArea - - Build target bridj - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 147 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 148 - - - CF$UID - 150 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 36 - - - CF$UID - 149 - - - - 652 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 36 - - - CF$UID - 151 - - - - 224 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 153 - - - CF$UID - 154 - - - CF$UID - 155 - - - NS.objects - - - CF$UID - 156 - - - CF$UID - 155 - - - CF$UID - 179 - - - - Xcode.IDEKit.Navigator.Issues - SelectedNavigator - Xcode.IDEKit.Navigator.Structure - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 157 - - - CF$UID - 158 - - - CF$UID - 159 - - - CF$UID - 160 - - - CF$UID - 161 - - - CF$UID - 162 - - - CF$UID - 163 - - - CF$UID - 164 - - - CF$UID - 165 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 166 - - - CF$UID - 167 - - - CF$UID - 169 - - - CF$UID - 170 - - - CF$UID - 15 - - - CF$UID - 177 - - - CF$UID - 15 - - - CF$UID - 178 - - - - IDEErrorFilteringEnabled - IDEVisibleRect - IDECollapsedFiles - IDEExpandedIssues - IDESelectedNavigables - IDEShowsByType - IDECollapsedTypes - IDERecentFilteringEnabled - IDECollapsedGroups - {{0, 0}, {259, 810}} - - $class - - CF$UID - 168 - - NS.objects - - - - $classes - - NSMutableSet - NSSet - NSObject - - $classname - NSMutableSet - - - $class - - CF$UID - 168 - - NS.objects - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 171 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 172 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 173 - - - CF$UID - 174 - - - NS.objects - - - CF$UID - 175 - - - CF$UID - 176 - - - - id - ty - JDyncall project - g - - $class - - CF$UID - 168 - - NS.objects - - - - $class - - CF$UID - 168 - - NS.objects - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 180 - - - CF$UID - 181 - - - CF$UID - 182 - - - CF$UID - 183 - - - CF$UID - 184 - - - CF$UID - 185 - - - CF$UID - 186 - - - NS.objects - - - CF$UID - 187 - - - CF$UID - 15 - - - CF$UID - 188 - - - CF$UID - 15 - - - CF$UID - 15 - - - CF$UID - 190 - - - CF$UID - 193 - - - - IDEVisibleRect - IDEUnsavedDocumentFilteringEnabled - IDENavigatorExpandedItemsBeforeFilteringSet - IDERecentDocumentFilteringEnabled - IDESCMStatusFilteringEnabled - IDESelectedObjects - IDEExpandedItemsSet - {{0, 0}, {259, 832}} - - $class - - CF$UID - 189 - - NS.objects - - - - $classes - - NSSet - NSObject - - $classname - NSSet - - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 191 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 192 - - - - JDyncall - - $class - - CF$UID - 189 - - NS.objects - - - CF$UID - 194 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 192 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 196 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 197 - - - CF$UID - 199 - - - CF$UID - 201 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 140 - - - CF$UID - 198 - - - - 260 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 143 - - - CF$UID - 200 - - - - 1140 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 202 - - - CF$UID - 203 - - - - IDEUtilitiesArea - 260 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 205 - - - CF$UID - 206 - - - CF$UID - 207 - - - CF$UID - 208 - - - CF$UID - 209 - - - CF$UID - 210 - - - CF$UID - 211 - - - CF$UID - 212 - - - NS.objects - - - CF$UID - 213 - - - CF$UID - 225 - - - CF$UID - 251 - - - CF$UID - 144 - - - CF$UID - 79 - - - CF$UID - 276 - - - CF$UID - 284 - - - CF$UID - 15 - - - - layoutTree - IDEEditorMode_Standard - IDEEDitorArea_DebugArea - IDEShowEditor - EditorMode - DebuggerSplitView - DefaultPersistentRepresentations - ShowDebuggerArea - - $class - - CF$UID - 224 - - geniusEditorContextNode - - CF$UID - 0 - - primaryEditorContextNode - - CF$UID - 214 - - rootLayoutTreeNode - - CF$UID - 221 - - - - $class - - CF$UID - 223 - - children - - CF$UID - 0 - - contentType - 1 - documentArchivableRepresentation - - CF$UID - 215 - - orientation - 0 - parent - - CF$UID - 221 - - - - $class - - CF$UID - 220 - - DocumentLocation - - CF$UID - 218 - - DomainIdentifier - - CF$UID - 0 - - IdentifierPath - - CF$UID - 216 - - IndexOfDocumentIdentifier - - CF$UID - 217 - - - - $class - - CF$UID - 54 - - NS.objects - - - 9223372036854775807 - - $class - - CF$UID - 219 - - documentURL - - CF$UID - 69 - - timestamp - - CF$UID - 0 - - - - $classes - - DVTDocumentLocation - NSObject - - $classname - DVTDocumentLocation - - - $classes - - IDENavigableItemArchivableRepresentation - NSObject - - $classname - IDENavigableItemArchivableRepresentation - - - $class - - CF$UID - 223 - - children - - CF$UID - 222 - - contentType - 0 - documentArchivableRepresentation - - CF$UID - 0 - - orientation - 0 - parent - - CF$UID - 0 - - - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 214 - - - - - $classes - - IDEWorkspaceTabControllerLayoutTreeNode - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTreeNode - - - $classes - - IDEWorkspaceTabControllerLayoutTree - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTree - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 226 - - - NS.objects - - - CF$UID - 227 - - - - EditorLayout_PersistentRepresentation - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 228 - - - NS.objects - - - CF$UID - 229 - - - - Main - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 230 - - - CF$UID - 231 - - - CF$UID - 232 - - - NS.objects - - - CF$UID - 233 - - - CF$UID - 79 - - - CF$UID - 249 - - - - EditorLayout_StateSavingStateDictionaries - EditorLayout_Selected - EditorLayout_Geometry - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 234 - - - - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 235 - - - CF$UID - 236 - - - CF$UID - 237 - - - CF$UID - 238 - - - CF$UID - 239 - - - CF$UID - 240 - - - CF$UID - 241 - - - NS.objects - - - CF$UID - 242 - - - CF$UID - 243 - - - CF$UID - 245 - - - CF$UID - 246 - - - CF$UID - 247 - - - CF$UID - 19 - - - CF$UID - 248 - - - - FileDataType - ArchivableRepresentation - EditorState - NavigableItemName - DocumentNavigableItemName - DocumentExtensionIdentifier - DocumentURL - com.apple.dt.IDE.DebuggerLogContentType - - $class - - CF$UID - 220 - - DocumentLocation - - CF$UID - 218 - - DomainIdentifier - - CF$UID - 0 - - IdentifierPath - - CF$UID - 216 - - IndexOfDocumentIdentifier - - CF$UID - 244 - - - 9223372036854775807 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 71 - - - NS.objects - - - CF$UID - 72 - - - - - - - $class - - CF$UID - 24 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 69 - - - - $class - - CF$UID - 54 - - NS.objects - - - CF$UID - 250 - - - - {{0, 0}, {1140, 876}} - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 252 - - - CF$UID - 253 - - - CF$UID - 254 - - - CF$UID - 255 - - - CF$UID - 256 - - - CF$UID - 257 - - - NS.objects - - - CF$UID - 114 - - - CF$UID - 258 - - - CF$UID - 260 - - - CF$UID - 114 - - - CF$UID - 262 - - - CF$UID - 270 - - - - LayoutFocusMode - console - variables - LayoutMode - IDEDebugArea_SplitView - IDEDebuggerAreaSplitView - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 259 - - - NS.objects - - - CF$UID - 79 - - - - ConsoleFilterMode - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 261 - - - NS.objects - - - CF$UID - 114 - - - - VariablesViewSelectedScope - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 263 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 264 - - - CF$UID - 267 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 265 - - - CF$UID - 266 - - - - VariablesView - 572 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 268 - - - CF$UID - 269 - - - - ConsoleArea - 567 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 271 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 272 - - - CF$UID - 274 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 265 - - - CF$UID - 273 - - - - 572 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 268 - - - CF$UID - 275 - - - - 567 - - $class - - CF$UID - 42 - - NS.keys - - - CF$UID - 31 - - - NS.objects - - - CF$UID - 277 - - - - - $class - - CF$UID - 41 - - NS.objects - - - CF$UID - 278 - - - CF$UID - 281 - - - - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 279 - - - CF$UID - 280 - - - - IDEEditor - 203 - - $class - - CF$UID - 38 - - NS.keys - - - CF$UID - 34 - - - CF$UID - 35 - - - NS.objects - - - CF$UID - 282 - - - CF$UID - 283 - - - - IDEDebuggerArea - 115 - - $class - - CF$UID - 42 - - NS.keys - - NS.objects - - - - $top - - State - - CF$UID - 1 - - - $version - 100000 - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist deleted file mode 100644 index 20adbd38d..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/bridj.xcscheme b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/bridj.xcscheme deleted file mode 100644 index 84be6be80..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/bridj.xcscheme +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist b/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 9aedf3a63..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/XCode/JDyncall/JDyncall.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - bridj.xcscheme - - orderHint - 0 - - - SuppressBuildableAutocreation - - D28A88AD04BDD90700651E21 - - primary - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/CopyRulesIfNeeded.cmd b/libraries/BridJ/src/main/cpp/buildsys/vs2008/CopyRulesIfNeeded.cmd deleted file mode 100644 index 113108259..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/CopyRulesIfNeeded.cmd +++ /dev/null @@ -1,13 +0,0 @@ -@echo off -setlocal - -set FILE=masm64.rules -rem set TARGET_FILE=C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\%FILE% -rem if not exist "%TARGET_FILE%" copy "%FILE%" "%TARGET_FILE%" -if exist "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults" ( - if not exist "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\%FILE%" copy "%FILE%" "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults" -) -if exist "C:\Program Files\Microsoft Visual Studio 9.0\VC\VCProjectDefaults" ( - if not exist "C:\Program Files\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\%FILE%" copy "%FILE%" "C:\Program Files\Microsoft Visual Studio 9.0\VC\VCProjectDefaults" -) - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.cpp b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.cpp deleted file mode 100644 index c552d11ea..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// OtherLib.cpp : définit les fonctions exportées pour l'application DLL. -// - -#include "stdafx.h" -#include "OtherLib.h" - - -// Il s'agit d'un exemple de variable exportée -OTHERLIB_API int nOtherLib=0; - -// Il s'agit d'un exemple de fonction exportée. -OTHERLIB_API int fnOtherLib(int a, int b) -{ - return a + b; -} - -// Il s'agit du constructeur d'une classe qui a été exportée. -// consultez OtherLib.h pour la définition de la classe -COtherLib::COtherLib() -{ - return; -} diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.h b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.h deleted file mode 100644 index fd377bcfe..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.h +++ /dev/null @@ -1,22 +0,0 @@ -// Le bloc ifdef suivant est la façon standard de créer des macros qui facilitent l'exportation -// à partir d'une DLL. Tous les fichiers contenus dans cette DLL sont compilés avec le symbole OTHERLIB_EXPORTS -// défini sur la ligne de commande. Ce symbole ne doit pas être défini dans les projets -// qui utilisent cette DLL. De cette manière, les autres projets dont les fichiers sources comprennent ce fichier considèrent les fonctions -// OTHERLIB_API comme étant importées à partir d'une DLL, tandis que cette DLL considère les symboles -// définis avec cette macro comme étant exportés. -#ifdef OTHERLIB_EXPORTS -#define OTHERLIB_API __declspec(dllexport) -#else -#define OTHERLIB_API __declspec(dllimport) -#endif - -// Cette classe est exportée de OtherLib.dll -class OTHERLIB_API COtherLib { -public: - COtherLib(void); - // TODO : ajoutez ici vos méthodes. -}; - -extern OTHERLIB_API int nOtherLib; - -OTHERLIB_API int fnOtherLib(int, int); diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.vcproj deleted file mode 100644 index e75a48eb1..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/OtherLib.vcproj +++ /dev/null @@ -1,435 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/ReadMe.txt b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/ReadMe.txt deleted file mode 100644 index 5441b19fe..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/ReadMe.txt +++ /dev/null @@ -1,33 +0,0 @@ -======================================================================== - BIBLIOTHÈQUE DE LIENS DYNAMIQUES : Vue d'ensemble du projet OtherLib -======================================================================== - -AppWizard a créé cette DLL OtherLib pour vous. - -Ce fichier contient un résumé des éléments contenus dans chaque fichier qui -constitue votre application OtherLib. - - -OtherLib.vcproj - Il s'agit du fichier projet principal pour les projets VC++ générés à l'aide d'un Assistant Application. - Il contient des informations relatives à la version de Visual C++ qui a généré le fichier, - ainsi que des informations sur les plateformes, configurations et fonctionnalités du projet - d'un Assistant Application. - -OtherLib.cpp - Il s'agit du fichier source principal de la DLL. - -///////////////////////////////////////////////////////////////////////////// -Autres fichiers standard : - -StdAfx.h, StdAfx.cpp - Ces fichiers sont utilisés pour générer un fichier d'en-tête précompilé (PCH) - nommé OtherLib.pch et un fichier de types précompilés nommé StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Autres remarques : - -AppWizard utilise des commentaires "TODO:" pour indiquer les parties du code source où vous -devrez ajouter ou modifier du code. - -///////////////////////////////////////////////////////////////////////////// diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/dllmain.cpp b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/dllmain.cpp deleted file mode 100644 index c86a28578..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/dllmain.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// dllmain.cpp : Définit le point d'entrée pour l'application DLL. -#include "stdafx.h" - -BOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.cpp b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.cpp deleted file mode 100644 index 5cdf36741..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : fichier source incluant simplement les fichiers Include standard -// OtherLib.pch représente l'en-tête précompilé -// stdafx.obj contient les informations de type précompilées - -#include "stdafx.h" - -// TODO : faites référence aux en-têtes supplémentaires nécessaires dans STDAFX.H -// absents de ce fichier diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.h b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.h deleted file mode 100644 index 64843aa39..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/stdafx.h +++ /dev/null @@ -1,16 +0,0 @@ -// stdafx.h : fichier Include pour les fichiers Include système standard, -// ou les fichiers Include spécifiques aux projets qui sont utilisés fréquemment, -// et sont rarement modifiés -// - -#pragma once - -#include "targetver.h" - -#define WIN32_LEAN_AND_MEAN // Exclure les en-têtes Windows rarement utilisés -// Fichiers d'en-tête Windows : -#include - - - -// TODO : faites référence ici aux en-têtes supplémentaires nécessaires au programme diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/targetver.h b/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/targetver.h deleted file mode 100644 index 74b374591..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/OtherLib/targetver.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -// Les macros suivantes définissent la plateforme minimale requise. La plateforme minimale requise -// est la version de Windows, Internet Explorer etc. qui dispose des fonctionnalités nécessaires pour exécuter -// votre application. Les macros fonctionnent en activant toutes les fonctionnalités disponibles sur les versions de la plateforme jusqu'à la -// version spécifiée. - -// Modifiez les définitions suivantes si vous devez cibler une plateforme avant celles spécifiées ci-dessous. -// Reportez-vous à MSDN pour obtenir les dernières informations sur les valeurs correspondantes pour les différentes plateformes. -#ifndef WINVER // Spécifie que la plateforme minimale requise est Windows Vista. -#define WINVER 0x0600 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions de Windows. -#endif - -#ifndef _WIN32_WINNT // Spécifie que la plateforme minimale requise est Windows Vista. -#define _WIN32_WINNT 0x0600 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions de Windows. -#endif - -#ifndef _WIN32_WINDOWS // Spécifie que la plateforme minimale requise est Windows 98. -#define _WIN32_WINDOWS 0x0410 // Attribuez la valeur appropriée à cet élément pour cibler Windows Me ou version ultérieure. -#endif - -#ifndef _WIN32_IE // Spécifie que la plateforme minimale requise est Internet Explorer 7.0. -#define _WIN32_IE 0x0700 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions d'Internet Explorer. -#endif diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/RebuildAll.cmd b/libraries/BridJ/src/main/cpp/buildsys/vs2008/RebuildAll.cmd deleted file mode 100644 index ae4d217c5..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/RebuildAll.cmd +++ /dev/null @@ -1,5 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -call CleanAll.cmd nopause -call BuildAll.cmd diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/SetEnv.cmd b/libraries/BridJ/src/main/cpp/buildsys/vs2008/SetEnv.cmd deleted file mode 100644 index f0b64ec31..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/SetEnv.cmd +++ /dev/null @@ -1,9 +0,0 @@ -@echo off - -if "%DYNCALL_HOME%" == "" set DYNCALL_HOME=..\..\..\..\..\..\..\..\..\..\dyncall -if not exist "%DYNCALL_HOME%" set DYNCALL_HOME=c:\src\dyncall -if not exist "%DYNCALL_HOME%" set DYNCALL_HOME=f:\Experiments\tmp\dyncall -if not exist "%DYNCALL_HOME%" set DYNCALL_HOME=f:\Experiments\tmp\key\svn\dyncall -if not exist "%DYNCALL_HOME%" set DYNCALL_HOME=c:\Prog\dyncall - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj.sln b/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj.sln deleted file mode 100644 index 1cc8ec99d..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj.sln +++ /dev/null @@ -1,107 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bridj64", "bridj64\bridj64.vcproj", "{07387AE1-67E7-48C7-89E8-BBAE28200196}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bridj32", "bridj32\bridj32.vcproj", "{07387AE1-67E7-48C7-89E8-BBAE28200197}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test\test.vcproj", "{47AFB4D0-B124-40BC-A379-BA5AD59D5405}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dyncall64", "dyncall64\dyncall64.vcproj", "{39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dyncall32", "dyncall32\dyncall32.vcproj", "{DF67B85F-C8F8-4FB1-A701-867A9C835ABA}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dyncallback32", "dyncallback32\dyncallback32.vcproj", "{016DFB90-9945-4104-92B3-963230FCCC04}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dyncallback64", "dyncallback64\dyncallback64.vcproj", "{5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynload", "dynload\dynload.vcproj", "{124D59C2-1412-4F02-AE80-1ADA83166F83}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testexe", "testexe\testexe.vcproj", "{D7B787E4-63F3-4917-92F9-9ADE590E94BB}" - ProjectSection(ProjectDependencies) = postProject - {47AFB4D0-B124-40BC-A379-BA5AD59D5405} = {47AFB4D0-B124-40BC-A379-BA5AD59D5405} - {07387AE1-67E7-48C7-89E8-BBAE28200197} = {07387AE1-67E7-48C7-89E8-BBAE28200197} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OtherLib", "OtherLib\OtherLib.vcproj", "{4714A835-E46A-4CFC-BBFE-A00768792E21}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Debug|Win32.ActiveCfg = Debug|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Debug|x64.ActiveCfg = Debug|x64 - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Debug|x64.Build.0 = Debug|x64 - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Release|Win32.ActiveCfg = Release|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Release|x64.ActiveCfg = Release|x64 - {07387AE1-67E7-48C7-89E8-BBAE28200196}.Release|x64.Build.0 = Release|x64 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Debug|Win32.ActiveCfg = Debug|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Debug|Win32.Build.0 = Debug|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Debug|x64.ActiveCfg = Debug|x64 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Release|Win32.ActiveCfg = Release|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Release|Win32.Build.0 = Release|Win32 - {07387AE1-67E7-48C7-89E8-BBAE28200197}.Release|x64.ActiveCfg = Release|x64 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Debug|Win32.ActiveCfg = Debug|Win32 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Debug|Win32.Build.0 = Debug|Win32 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Debug|x64.ActiveCfg = Debug|x64 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Debug|x64.Build.0 = Debug|x64 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Release|Win32.ActiveCfg = Release|Win32 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Release|Win32.Build.0 = Release|Win32 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Release|x64.ActiveCfg = Release|x64 - {47AFB4D0-B124-40BC-A379-BA5AD59D5405}.Release|x64.Build.0 = Release|x64 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Debug|Win32.ActiveCfg = Debug|Win32 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Debug|x64.ActiveCfg = Debug|x64 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Debug|x64.Build.0 = Debug|x64 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Release|Win32.ActiveCfg = Release|Win32 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Release|x64.ActiveCfg = Release|x64 - {39E9E4FA-800A-4D71-A2A1-D5BE856B82BF}.Release|x64.Build.0 = Release|x64 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Debug|Win32.ActiveCfg = Debug|Win32 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Debug|Win32.Build.0 = Debug|Win32 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Debug|x64.ActiveCfg = Debug|x64 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Release|Win32.ActiveCfg = Release|Win32 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Release|Win32.Build.0 = Release|Win32 - {DF67B85F-C8F8-4FB1-A701-867A9C835ABA}.Release|x64.ActiveCfg = Release|x64 - {016DFB90-9945-4104-92B3-963230FCCC04}.Debug|Win32.ActiveCfg = Debug|Win32 - {016DFB90-9945-4104-92B3-963230FCCC04}.Debug|Win32.Build.0 = Debug|Win32 - {016DFB90-9945-4104-92B3-963230FCCC04}.Debug|x64.ActiveCfg = Debug|x64 - {016DFB90-9945-4104-92B3-963230FCCC04}.Release|Win32.ActiveCfg = Release|Win32 - {016DFB90-9945-4104-92B3-963230FCCC04}.Release|Win32.Build.0 = Release|Win32 - {016DFB90-9945-4104-92B3-963230FCCC04}.Release|x64.ActiveCfg = Release|x64 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Debug|Win32.ActiveCfg = Debug|Win32 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Debug|x64.ActiveCfg = Debug|x64 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Debug|x64.Build.0 = Debug|x64 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Release|Win32.ActiveCfg = Release|Win32 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Release|x64.ActiveCfg = Release|x64 - {5E5EF2B3-8BA6-4B21-8482-35CDFAE933D9}.Release|x64.Build.0 = Release|x64 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Debug|Win32.ActiveCfg = Debug|Win32 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Debug|Win32.Build.0 = Debug|Win32 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Debug|x64.ActiveCfg = Debug|x64 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Debug|x64.Build.0 = Debug|x64 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Release|Win32.ActiveCfg = Release|Win32 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Release|Win32.Build.0 = Release|Win32 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Release|x64.ActiveCfg = Release|x64 - {124D59C2-1412-4F02-AE80-1ADA83166F83}.Release|x64.Build.0 = Release|x64 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Debug|Win32.ActiveCfg = Debug|Win32 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Debug|Win32.Build.0 = Debug|Win32 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Debug|x64.ActiveCfg = Debug|x64 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Debug|x64.Build.0 = Debug|x64 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Release|Win32.ActiveCfg = Release|Win32 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Release|Win32.Build.0 = Release|Win32 - {D7B787E4-63F3-4917-92F9-9ADE590E94BB}.Release|x64.ActiveCfg = Release|x64 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Debug|Win32.ActiveCfg = Debug|Win32 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Debug|Win32.Build.0 = Debug|Win32 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Debug|x64.ActiveCfg = Debug|x64 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Debug|x64.Build.0 = Debug|x64 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Release|Win32.ActiveCfg = Release|Win32 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Release|Win32.Build.0 = Release|Win32 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Release|x64.ActiveCfg = Release|x64 - {4714A835-E46A-4CFC-BBFE-A00768792E21}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj32/bridj32.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj32/bridj32.vcproj deleted file mode 100644 index 614bd04d8..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj32/bridj32.vcproj +++ /dev/null @@ -1,548 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj64/bridj64.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj64/bridj64.vcproj deleted file mode 100644 index 367c41799..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/bridj64/bridj64.vcproj +++ /dev/null @@ -1,539 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall32/dyncall32.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall32/dyncall32.vcproj deleted file mode 100644 index 891985567..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall32/dyncall32.vcproj +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall64/dyncall64.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall64/dyncall64.vcproj deleted file mode 100644 index f843abc5f..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncall64/dyncall64.vcproj +++ /dev/null @@ -1,466 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback32/dyncallback32.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback32/dyncallback32.vcproj deleted file mode 100644 index 47fd29c1f..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback32/dyncallback32.vcproj +++ /dev/null @@ -1,457 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback64/dyncallback64.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback64/dyncallback64.vcproj deleted file mode 100644 index 12d527913..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dyncallback64/dyncallback64.vcproj +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dynload/dynload.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/dynload/dynload.vcproj deleted file mode 100644 index 0a778f75f..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/dynload/dynload.vcproj +++ /dev/null @@ -1,341 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/masm64.rules b/libraries/BridJ/src/main/cpp/buildsys/vs2008/masm64.rules deleted file mode 100644 index 9ae123c74..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/masm64.rules +++ /dev/null @@ -1,305 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/test/test.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/test/test.vcproj deleted file mode 100644 index 199427bb9..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/test/test.vcproj +++ /dev/null @@ -1,480 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/ReadMe.txt b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/ReadMe.txt deleted file mode 100644 index 0c1c38553..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/ReadMe.txt +++ /dev/null @@ -1,33 +0,0 @@ -======================================================================== - APPLICATION CONSOLE : Vue d'ensemble du projet testexe -======================================================================== - -AppWizard a créé cette application testexe pour vous. - -Ce fichier contient un résumé des éléments contenus dans chaque fichier qui -constitue votre application testexe. - - -testexe.vcproj - Il s'agit du fichier projet principal pour les projets VC++ générés à l'aide d'un Assistant Application. - Il contient des informations relatives à la version de Visual C++ qui a généré le fichier, - ainsi que des informations sur les plateformes, configurations et fonctionnalités du projet - d'un Assistant Application. - -testexe.cpp - Il s'agit du fichier source principal de l'application. - -///////////////////////////////////////////////////////////////////////////// -Autres fichiers standard : - -StdAfx.h, StdAfx.cpp - Ces fichiers sont utilisés pour générer un fichier d'en-tête précompilé (PCH) - nommé testexe.pch et un fichier de types précompilés nommé StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Autres remarques : - -AppWizard utilise des commentaires "TODO:" pour indiquer les parties du code source où vous -devrez ajouter ou modifier du code. - -///////////////////////////////////////////////////////////////////////////// diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.cpp b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.cpp deleted file mode 100644 index 4bf97a804..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : fichier source incluant simplement les fichiers Include standard -// testexe.pch représente l'en-tête précompilé -// stdafx.obj contient les informations de type précompilées - -#include "stdafx.h" - -// TODO : faites référence aux en-têtes supplémentaires nécessaires dans STDAFX.H -// absents de ce fichier diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.h b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.h deleted file mode 100644 index 11854661b..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.h +++ /dev/null @@ -1,15 +0,0 @@ -// stdafx.h : fichier Include pour les fichiers Include système standard, -// ou les fichiers Include spécifiques aux projets qui sont utilisés fréquemment, -// et sont rarement modifiés -// - -#pragma once - -#include "targetver.h" - -#include -#include - - - -// TODO : faites référence ici aux en-têtes supplémentaires nécessaires au programme diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/targetver.h b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/targetver.h deleted file mode 100644 index d676d5f1a..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/targetver.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -// Les macros suivantes définissent la plateforme minimale requise. La plateforme minimale requise -// est la version de Windows, Internet Explorer etc. qui dispose des fonctionnalités nécessaires pour exécuter -// votre application. Les macros fonctionnent en activant toutes les fonctionnalités disponibles sur les versions de la plateforme jusqu'à la -// version spécifiée. - -// Modifiez les définitions suivantes si vous devez cibler une plateforme avant celles spécifiées ci-dessous. -// Reportez-vous à MSDN pour obtenir les dernières informations sur les valeurs correspondantes pour les différentes plateformes. -#ifndef _WIN32_WINNT // Spécifie que la plateforme minimale requise est Windows Vista. -#define _WIN32_WINNT 0x0600 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions de Windows. -#endif - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp deleted file mode 100644 index 2f8d704ef..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp +++ /dev/null @@ -1,171 +0,0 @@ -//#include "stdafx.h" - -#include -#include - -#include "dynload/dynload.h" -#include "dyncall/dyncall.h" -#include "../../../bridj/RawNativeForwardCallback.h" - -int f() { - return 10; -} -int fVarArgs(int i, ...) { - printf("i = %d\n", i); - return i * 2; -} - -__declspec(dllimport) long test_incr_int(long value); - -void fOneInt(int a) { - printf("i = %d\n", a); -} -void fTwoInts(int a, int b) { - printf("i = %d, %d\n", a, b); -} -void fOneDouble(double a) { - printf("i = %f\n", a); -} - -/* -float forwardFloatCall(void* a, void* b, float (*adder)(void*, void*, void*, int, int, float, float), float value) { - return adder(NULL, NULL, NULL, 1, 1, -3, value); -} -float floatIncr(float value) { - return value * 8; -} - -char floatCbHandler(DCCallback* pcb, DCArgs* args, DCValue* result, void* userdata) { - dcbArgPointer(args); - dcbArgPointer(args); - dcbArgPointer(args); - dcbArgInt(args); - dcbArgInt(args); - dcbArgFloat(args); - float value = dcbArgFloat(args); - - - { - DCCallVM* vm = dcNewCallVM(1024); - dcReset(vm); - dcArgFloat(vm, value); - float res = dcCallFloat(vm, floatIncr); - result->f = res; - } - return DC_SIGCHAR_FLOAT; -} -float forwardCaller(void* cb, float value) { - DCCallVM* vm = dcNewCallVM(1024); - dcReset(vm); - - dcArgPointer(vm, NULL); - dcArgPointer(vm, NULL); - dcArgPointer(vm, cb); - dcArgFloat(vm, value); - float res = dcCallFloat(vm, forwardFloatCall); - dcFree(vm); - return res; -} -*/ -int f10int_impl(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n, int o, int p) { - printf("a = %d, b = %d, c = %d, d = %d, e = %d, f = %d, g = %d, h = %d, i = %d, j = %d, k = %d, l = %d, m = %d, n = %d, o = %d, p = %d\n", a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); - return a + j; -} - -void f4int_impl(int a, int b, int c, int d) { - printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d); -} - -void f3char_impl(char a, char b, char c) { - printf("a = %d, b = %d, c = %d\n", (int)a, (int)b, (int)c); -} - - -jdouble test_incr_double(jdouble value); -jlong test_incr_long(jlong value); -jfloat test_incr_float(jfloat value); - -int main(int argc, char* argv[]) -{ - /* - CK_INFO info; - ptrdiff_t offset = ((char*)&info.flags)-(char*)&info; - printf("sizeof(CK_INFO) = %d\n", sizeof(CK_INFO)); - printf("offset(CK_INFO.flags) = %d\n", offset); - DCCallback* cb = dcbNewCallback("pppiif)f", floatCbHandler, NULL); - float value = 1; - float incr = forwardCaller(cb, value); - //float incr = forwardFloatCall((float (*)(void*, void*, void*, int, int, float, float))cb, value); - printf("incr = %d\n", incr); - */ - { - typedef int (*pf)(void*, void*, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int); - pf f = (pf)dcRawCallAdapterSkipTwoArgs((void (*)())f10int_impl, DC_CALL_C_DEFAULT); - int ret = f((void*)16, (void*)32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - printf("ret %d\n", (int)ret); - } - { - typedef float (*pf)(void*, void*, float); - pf f = (pf)dcRawCallAdapterSkipTwoArgs((void (*)())test_incr_float, DC_CALL_C_DEFAULT); - float ret = f((void*)16, (void*)32, 10.0f); - printf("ret %d\n", (int)ret); - } - { - typedef double (*pf)(void*, void*, double); - pf f = (pf)dcRawCallAdapterSkipTwoArgs((void (*)())test_incr_double, DC_CALL_C_DEFAULT); - double ret = f((void*)16, (void*)32, 10.0); - printf("ret %d\n", (int)ret); - } - { - typedef jlong (*pf)(void*, void*, jlong); - pf f = (pf)dcRawCallAdapterSkipTwoArgs((void (*)())test_incr_long, DC_CALL_C_DEFAULT); - jlong ret = f((void*)16, (void*)32, 10LL); - printf("ret %d\n", (int)ret); - } - typedef void (*pf4)(void*, void*, int, int, int, int); - pf4 f4 = (pf4)dcRawCallAdapterSkipTwoArgs((void (*)())f4int_impl, DC_CALL_C_DEFAULT); - f4((void*)16, (void*)32, 1, 2, 3, 4); - - - typedef void (*pf3)(void*, void*, char, char, char); - pf3 f3 = (pf3)dcRawCallAdapterSkipTwoArgs((void (*)())f3char_impl, DC_CALL_C_DEFAULT); - f3((void*)16, (void*)32, (char)1, (char)2, (char)3); - - /* - int (*fSkipped)(void*, void*, int); - DCAdapterCallback* cb = dcRawCallAdapterSkipTwoArgs((void (*)())test_incr_int, DC_CALL_C_DEFAULT); - fSkipped = (int (*)(void*, void*, int))cb; - - int rrr = fSkipped((void*)1, (void*)2, 3); - int a = f(); - if (a != 0) { - printf("ok"); - }*/ - /* - int ret = CoInitialize(NULL); - void* instance; - - int s = sizeof(GUID); - char *cls = (char*)&CLSID_ShellWindows, *uid = (char*)&IID_IShellWindows; - //ret = CoCreateInstance(CLSID_ShellFSFolder, NULL, 0, IID_IShellFolder, &instance); - ret = CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_ALL, IID_IShellWindows, &instance); - - int ok = S_OK; - - DLLib* lib = dlLoadLibrary("Ole32.dll"); - void* fCoInitialize = dlFindSymbol(lib, "CoInitialize"); - DCCallVM* vm = dcNewCallVM(1024); - dcReset(vm); - - //dcMode(vm, DC_CALL_C_DEFAULT); - dcMode(vm, DC_CALL_C_X86_WIN32_STD); - dcArgInt(vm, 10); - ret = dcCallInt(vm, fVarArgs); - - dcMode(vm, DC_CALL_C_X86_WIN32_STD); - dcArgPointer(vm, NULL); - ret = dcCallInt(vm, fCoInitialize); - */ - return 0; -} - diff --git a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.vcproj b/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.vcproj deleted file mode 100644 index b08714675..000000000 --- a/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.vcproj +++ /dev/null @@ -1,403 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/main/demos/TaskbarListDemo.java b/libraries/BridJ/src/main/demos/TaskbarListDemo.java deleted file mode 100644 index fc9ae680d..000000000 --- a/libraries/BridJ/src/main/demos/TaskbarListDemo.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.demos; - -import org.bridj.JNI; -import org.bridj.Pointer; -import org.bridj.cpp.com.COMRuntime; -import org.bridj.cpp.com.IUnknown; -import org.bridj.cpp.com.shell.IShellWindows; -import org.bridj.cpp.com.shell.ITaskbarList3; -import org.bridj.jawt.JAWTUtils; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JRadioButton; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import org.bridj.Platform; - -/** - * On Windows 7, demonstrate the use of the ITaskbarList3 interface to control the taskbar progression visual indicator. - * @author Olivier - */ -public class TaskbarListDemo extends JFrame implements ActionListener, ChangeListener { - ITaskbarList3 list; - - int min = 0, max = 300, val = (min + max / 2); - JSlider slider; - - Pointer hwnd; - - public TaskbarListDemo() throws ClassNotFoundException { - super("TaskbarList Demo (" + (Platform.is64Bits() ? "64 bits" : "32 bits") + ")"); - - list = COMRuntime.newInstance(ITaskbarList3.class); - - getContentPane().add("Center", new JLabel("Hello Native Windows 7 World !")); - Box box = Box.createVerticalBox(); - - slider = new JSlider(min, max, val); - slider.addChangeListener(this); - box.add(slider); - - ButtonGroup group = new ButtonGroup(); - for (ITaskbarList3.TbpFlag state : ITaskbarList3.TbpFlag.values()) { - JRadioButton cb = new JRadioButton(state.name()); - group.add(cb); - cb.putClientProperty(ITaskbarList3.TbpFlag.class, state); - cb.setSelected(state == ITaskbarList3.TbpFlag.TBPF_NORMAL); - cb.addActionListener(this); - box.add(cb); - } - getContentPane().add("South", box); - - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - list.Release(); - } - - public void setVisible(boolean visible) { - super.setVisible(visible); - - long hwndVal = JAWTUtils.getNativePeerHandle(this);//TODO com.sun.jna.Native.getComponentID(this); - hwnd = Pointer.pointerToAddress(hwndVal); - list.SetProgressValue((Pointer)hwnd, slider.getValue(), slider.getMaximum()); - - } - @Override - public void stateChanged(ChangeEvent e) { - list.SetProgressValue((Pointer)hwnd, slider.getValue(), slider.getMaximum()); - } - @Override - public void actionPerformed(ActionEvent e) { - JRadioButton button = ((JRadioButton)e.getSource()); - if (button.isSelected()) { - ITaskbarList3.TbpFlag flag = (ITaskbarList3.TbpFlag)button.getClientProperty(ITaskbarList3.TbpFlag.class); - list.SetProgressValue((Pointer)hwnd, slider.getValue(), slider.getMaximum()); - list.SetProgressState((Pointer)hwnd, flag); - } - } - - public static void main(String[] args) throws Exception { - try { - - TaskbarListDemo f = new TaskbarListDemo(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.pack(); - f.setVisible(true); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } -} diff --git a/libraries/BridJ/src/main/demos/TestCPP.java b/libraries/BridJ/src/main/demos/TestCPP.java deleted file mode 100644 index 4ebb6d02b..000000000 --- a/libraries/BridJ/src/main/demos/TestCPP.java +++ /dev/null @@ -1,443 +0,0 @@ -package org.bridj.demos; - -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Callback; -import org.bridj.demangling.Demangler; -import org.bridj.JNI; -import org.bridj.NativeLibrary; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import org.bridj.demangling.Demangler.Symbol; -import org.bridj.ann.Array; -import org.bridj.ann.Convention; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; -import org.bridj.ann.Name; -import org.bridj.ann.Virtual; -import org.bridj.cpp.CPPObject; -import org.bridj.cpp.CPPRuntime; -import org.bridj.demangling.VC9Demangler; -import org.bridj.cpp.com.COMRuntime; -import org.bridj.cpp.com.IUnknown; -import org.bridj.cpp.com.shell.IShellFolder; -import org.bridj.cpp.com.shell.IShellWindows; -import org.bridj.cpp.com.shell.ITaskbarList3; -import org.bridj.demos.TaskbarListDemo; -import org.bridj.jawt.JAWTUtils; -import org.bridj.objc.NSAutoreleasePool; -//import org.bridj.objc.NSCalendar; -import org.bridj.objc.ObjCObject; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; -import java.util.Collections; - -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Callback; -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.NativeLibrary; -import org.bridj.Platform; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ValuedEnum; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html -//@Library("C:\\Users\\Olivier\\Prog\\nativelibs4java\\Runtime\\BridJ\\src\\test\\resources\\win64\\test.dll") -@Library("test") -@org.bridj.ann.Runtime(CPPRuntime.class) -public class TestCPP { -// static String libraryPath = //BridJ.getNativeLibraryFile("test").toString() -// Platform.isMacOSX() ? -// //"/Users/ochafik/nativelibs4java/Runtime/BridJ/src/test/resources/darwin_universal/libtest.dylib" -// "/Users/ochafik/nativelibs4java/Runtime/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_debug/libtest.dylib" : -// //"F:\\Experiments\\tmp\\key\\svn\\nativelibs4java\\Runtime\\BridJ\\src\\test\\resources\\win32\\test.dll" + -// "C:\\Users\\Olivier\\Prog\\nativelibs4java\\Runtime\\BridJ\\src\\main\\cpp\\buildsys\\vs2008\\x64\\Debug\\test.dll" -// ; - public enum Toto implements IntValuedEnum { - IBV_SYSFS_NAME_MAX(64), - IBV_SYSFS_PATH_MAX(256); - Toto(int value) { - this.value = value; - } - public final int value; - @java.lang.Override - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - static { - //BridJ.register(); - } - - static NativeLibrary library; - - - @Library("test") - @org.bridj.ann.Runtime(CRuntime.class) - public static class FunctionTest { - - public FunctionTest() { - BridJ.register(getClass()); - } - public native int testAddDyncall(int a, int b); - - public void add() { - int a = 10, b = 4, exp = a + b; - int res = testAddDyncall(a, b); - if (res != exp) - throw new RuntimeException("Got " + res + " (" + Integer.toHexString(res) + ") instead of " + exp + " (" + Integer.toHexString(exp)); - } - } -// @Array(Toto.IBV_SYSFS_NAME_MAX.value) - public static void print(String name, long addr, int n, int minI) { - System.out.println(name); - for (int i = -1; i < n; i++) { - long v = getPtr(addr + i * Pointer.SIZE); - Symbol sym = BridJ.getSymbolByAddress(v); - String sname = sym == null ? null : sym.getName(); - System.out.println("\tOffset " + i + ":\t" + hex(v) + " \t('" + sname + "')"); - if (v == 0 && i >= minI) - break; - } - System.out.println(); - } - public static native char test_incr_char(char value); - //public static native short test_incr_char(short value); - public static native int testAddDyncall(int a, int b); - - - public enum ETest implements ValuedEnum { - eFirst(0), - eSecond(1), - eThird(2); - - ETest(int value) { - this.value = value; - } - final int value; - public long value() { - return value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - - public static native ValuedEnum testEnum(ValuedEnum e); - - - static int[] createExpectedInts(int n) { - int[] expected = new int[n]; - for (int i = 0; i < n; i++) - expected[i] = (int)(i + 1); - return expected; - } - - - public static void testSetGetIntBuffer(int n) { - int[] expected = createExpectedInts(n); - Pointer p = Pointer.pointerToInts(expected); - long peer = p.getPeer(); - - Iterator it = p.iterator(); - for (int i = 0; i < n; i++) { - Integer obVal = it.next(); - int val = obVal; - if (val != expected[i]) - throw new RuntimeException("at position i = " + i); - } - } - - public static void main(String[] args) throws IOException { - try { - { - JFrame f = new JFrame(); - f.setVisible(true); - long hwndVal = JAWTUtils.getNativePeerHandle(f);//TODO com.sun.jna.Native.getComponentID(this); - System.out.println("#\n# hwndVal = " + hwndVal + "\n#"); - - BridJ.register(); - ValuedEnum t = testEnum(ETest.eFirst); - if (t != ETest.eFirst) - throw new RuntimeException(); - } - testSetGetIntBuffer(10); -// if (Platform.isMacOSX()) { -// new NSCalendar(); -// new NSAutoReleasePool(); -// } - -// NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new File("/System/Library/Frameworks/OpenCL.framework/OpenCL")); -// NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new File("/usr/lib/libobjc.dylib")); -// NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new File("/Users/ochafik/nativelibs4java/Runtime/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_debug/libtest.dylib")); - - -// Collection symbols = lib.getSymbols(); - BridJ.register(MyCallback.class); - BridJ.register(); - - int ra = testAddDyncall(10, 4); - if (ra != 14) - throw new RuntimeException("Expected 14, got " + ra); - ra = testAddDyncall(10, 4); - if (ra != 14) - throw new RuntimeException("Expected 14, got " + ra); - - testNativeTargetCallbacks(); - testJavaTargetCallbacks(); - - if (true) - return; - - long crea = Ctest.createTest(); - crea = Pointer.pointerToAddress(crea).getPointer().getPeer(); - print("Ctest.createTest()", crea, 10, 0); - Ctest test = new Ctest(); - //long thisPtr = test.$this.getPeer(); - //System.out.println(hex(thisPtr)); - print("Ctest.this", Pointer.pointerTo(test, Ctest.class).getPointer().getPeer(), 10, 2); - int res = test.testAdd(1, 2); - System.out.println("res = " + res); - res = test.testVirtualAdd(1, 2); - System.out.println("res = " + res); - - res = test.testVirtualAddStdCall(null, 1, 2); - System.out.println("res = " + res); - res = test.testAddStdCall(null, 1, 2); - System.out.println("res = " + res); - - TaskbarListDemo.main(null); - - IShellWindows win = COMRuntime.newInstance(IShellWindows.class); - IUnknown iu = win.QueryInterface(IUnknown.class); - if (iu == null) - throw new RuntimeException("Interface does not handle IUnknown !"); - win.Release(); - - try { - new FunctionTest().add(); - - MyStruct s = new MyStruct(); - s.a(10); - System.out.println("Created MyStruct and set it to 10"); - int a = Pointer.pointerTo(s).getInt(); - a = s.a(); - Pointer.pointerTo(s).setInt(10); - a = Pointer.pointerTo(s).getInt(); - a = s.a(); - if (s.a() != 10) - throw new RuntimeException("invalid value = " + a); - s.b(100.0); - if (s.b() != 100.0) - throw new RuntimeException("invalid value = " + a); - - } catch (Throwable ex) { - ex.printStackTrace(); - } - - - library = BridJ.getNativeLibrary("test"); - //NativeLibrary.load(libraryPath); - - new VC9Demangler(null, "?sinInt@@YANH@Z").parseSymbol(); - new VC9Demangler(null, "?forwardCall@@YAHP6AHHH@ZHH@Z").parseSymbol(); - - BridJ.register(); - - //new VC9Demangler(null, "??0Ctest2@@QEAA@XZ").parseSymbol(); - - for (Demangler.Symbol symbol : library.getSymbols()) { - String name = symbol.getName(); - long addr = symbol.getAddress(); - System.out.println(name + " = \t" + hex(addr)); - - if (name.startsWith("_ZTV") || name.startsWith("_ZTI") || name.startsWith("??_")) { - print("vtable", addr, 10, 1); - } else - System.out.println("'" + name + "'"); - } - - boolean is64 = Platform.is64Bits(); - - } catch (Throwable ex) { - ex.printStackTrace(); - } finally { - System.in.read(); - } - /*double dres = PerfLib.testASinB(1, 2); - res = PerfLib.testAddJNI(1, 2); - System.out.println("Done");*/ - } - - public static class MyStruct extends StructObject { - @Field(0) - public native int a(); - public native void a(int a); - - @Field(1) - public native double b(); - public native void b(double b); - } - - @Library("test") - static class Ctest extends CPPObject { - static { - BridJ.register();//Ctest.class); - } - -// @Constructor -// private static native void Ctest(@This long thisPtr); - - static native @Ptr long createTest(); - - - @Virtual - public native int testVirtualAdd(int a, int b); - -// protected static native int testAdd(@This long thisPtr, int a, int b); - public native int testAdd(int a, int b); - - - @Virtual - @Convention(Convention.Style.StdCall) - public native int testVirtualAddStdCall(Pointer ptr, int a, int b); - - @Convention(Convention.Style.StdCall) - public native int testAddStdCall(Pointer ptr, int a, int b); - -// public int testAdd(int a, int b) { -// //print("this", Pointer.getAddress(this, Ctest.class), 10, 10); -// //print("*this", $this.getPointer().getPeer(), 10, 10); -// return testAdd(Pointer.getAddress(this, Ctest.class), a, b); -// } - } - - static String hex(long v) { - return Long.toHexString(v); - /* - String s = Long.toString(v, 16); - while ((s.length() < 16)) - s = "0" + s; - return s;*/ - } - static long getPtr(long peer) { - Pointer ptr = Pointer.pointerToAddress(peer); - return ptr.getSizeT(); - } - - - public static void testJavaTargetCallbacks() { - int res; - - res = forwardCall(new MyCallback() { - @Override - public int doSomething(int a, int b) { - return a + b * 10; - } - }.toPointer(), 1, 2); - if (res != (1 + 2 * 10)) - throw new RuntimeException(); - - res = forwardCall(new MyCallback() { - @Override - public int doSomething(int a, int b) { - return a + b; - } - }.toPointer(), 1, 2); - if (res != (1 + 2)) - throw new RuntimeException(); - - } - - public static void testNativeTargetCallbacks() { - long rawadder = getAdder_raw(); - if (rawadder != 0) - System.out.println("Returned non null raw adder, cool (" + Long.toHexString(rawadder) + ") !"); - else - System.out.println("Returned null raw adder !"); - long longadder = getAdder_long(); - if (longadder != 0) - System.out.println("Returned non null longadder, cool (" + Long.toHexString(longadder) + ") !"); - else - System.out.println("Returned null longadder !"); - long getAdder_pvoid = getAdder_pvoid(); - if (getAdder_pvoid != 0) - System.out.println("Returned non null getAdder_pvoid, cool (" + Long.toHexString(getAdder_pvoid) + ") !"); - else - System.out.println("Returned null getAdder_pvoid !"); - Pointer ptr = getAdder(); - if (ptr == null) - throw new RuntimeException("getAdder returned null adder !!!"); - MyCallback adder = ptr.getNativeObject(MyCallback.class); - int res = adder.doSomething(1, 2); - - if (res != 3) - throw new RuntimeException("Expected 3, got "+ res); - } - - static native int forwardCall(Pointer cb, int a, int b); - static native Pointer getAdder(); - @Name("getAdder") - static native @Ptr long getAdder_raw(); - - static native @Ptr long getAdder_pvoid(); - static native long getAdder_long(); - - public static abstract class MyCallback extends Callback { - public abstract int doSomething(int a, int b); - } - -} - -/* - -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -class PerfLib { - static { - String f = BridJ.getNativeLibraryFile(BridJ.getNativeLibraryName(PerfLib.class)).toString(); - System.load(f); - } - public static class DynCallTest { - public DynCallTest() throws FileNotFoundException { - BridJ.register(getClass()); - } - public native int testAddDyncall(int a, int b); - public native int testASinB(int a, int b); - } - - public static class JNATest implements com.sun.jna.Library { - static { - try { - com.sun.jna.Native.register(JNI.extractEmbeddedLibraryResource("test").toString()); - } catch (Exception ex) { - throw new RuntimeException("Failed to initialize test JNA library", ex); - } - } - public static native int testAddJNA(int a, int b); - public static native int testASinB(int a, int b); - } - public static native int testAddJNI(int a, int b); - public static native double testASinB(int a, int b); -}*/ diff --git a/libraries/BridJ/src/main/demos/package-info.java b/libraries/BridJ/src/main/demos/package-info.java deleted file mode 100644 index 007eaf5e0..000000000 --- a/libraries/BridJ/src/main/demos/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ demos (won't make it to the final 1.0 version, demos will be split in their own package). -*/ -package org.bridj.demos; diff --git a/libraries/BridJ/src/main/java/org/bridj/AbstractBridJRuntime.java b/libraries/BridJ/src/main/java/org/bridj/AbstractBridJRuntime.java deleted file mode 100644 index edf40ee23..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/AbstractBridJRuntime.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import org.bridj.cpp.CPPRuntime; -import org.bridj.util.Utils; - -/** - * Base class for implementation of runtimes - * @author Olivier - */ -public abstract class AbstractBridJRuntime implements BridJRuntime { - //@Override - public void unregister(Type type) { - // TODO !!! - } - - //@Override - public Type getType(NativeObject instance) { - if (instance == null) - return null; - return Utils.getClass(instance.getClass()); - } - - protected java.lang.reflect.Constructor findConstructor(Class type, int constructorId, boolean onlyWithAnnotation) throws SecurityException, NoSuchMethodException { - for (java.lang.reflect.Constructor c : type.getDeclaredConstructors()) { - org.bridj.ann.Constructor ca = c.getAnnotation(org.bridj.ann.Constructor.class); - if (ca == null) - continue; - if (ca.value() == constructorId) - return c; - } - if (constructorId < 0)// && args.length == 0) - return type.getConstructor(); - Class sup = type.getSuperclass(); - if (sup != null) { - try { - java.lang.reflect.Constructor c = findConstructor(sup, constructorId, onlyWithAnnotation); - if (onlyWithAnnotation && c != null) - return c; - - Type[] params = c.getGenericParameterTypes(); - Constructor[] ccs = type.getDeclaredConstructors(); - for (java.lang.reflect.Constructor cc : ccs) { - Type[] ccparams = cc.getGenericParameterTypes(); - int overrideOffset = Utils.getEnclosedConstructorParametersOffset(cc); - if (isOverridenSignature(params, ccparams, overrideOffset)) - return cc; - } - } catch (Throwable th) { - th.printStackTrace(); - } - } - throw new NoSuchMethodException("Cannot find constructor with index " + constructorId); - } - public static boolean isOverridenSignature(Type[] parentSignature, Type[] overrideSignature, int overrideOffset) { - int n = parentSignature.length; - if (overrideSignature.length - overrideOffset != n) - return false; - for (int i = 0; i < n; i++) - if (!isOverride(parentSignature[i], overrideSignature[overrideOffset + i])) - return false; - return true; - } - protected static boolean isOverride(Type parentSignature, Type overrideSignature) { - return Utils.getClass(parentSignature).isAssignableFrom(Utils.getClass(overrideSignature)); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/AbstractIntegral.java b/libraries/BridJ/src/main/java/org/bridj/AbstractIntegral.java deleted file mode 100644 index 548151efa..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/AbstractIntegral.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -/** - * Base class for custom integral numbers - * @author Olivier - */ -class AbstractIntegral extends Number { - - protected final long value; - public AbstractIntegral(long value) { - this.value = value; - } - - private static final long HIGH_NEG = 0xffffffff00000000L; - public static int safeIntCast(long value) { - long high = value & HIGH_NEG; - if (high != 0 && high != HIGH_NEG) - //if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) - throw new RuntimeException("Value " + value + " = 0x" + Long.toHexString(value) + " is not within the int range"); - - return (int)(value & 0xffffffff); - } - - @Override - public int intValue() { - return safeIntCast(value); - } - - @Override - public long longValue() { - return value; - } - - @Override - public float floatValue() { - return value; - } - - @Override - public double doubleValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof AbstractIntegral)) - return false; - if (!o.getClass().equals(getClass())) - return false; - return value == ((AbstractIntegral)o).value; - } - - @Override - public int hashCode() { - return ((Long)value).hashCode(); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "(" + value + ")"; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/AndroidClassDefiner.java b/libraries/BridJ/src/main/java/org/bridj/AndroidClassDefiner.java deleted file mode 100644 index 0f308413c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/AndroidClassDefiner.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import org.bridj.util.ClassDefiner; -import com.android.dx.dex.cf.CfOptions; -import com.android.dx.dex.cf.CfTranslator; -import com.android.dx.dex.file.DexFile; -import com.android.dx.dex.DexOptions; -import dalvik.system.DexClassLoader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** - * - * @author ochafik - */ -class AndroidClassDefiner implements ClassDefiner { - - protected final File cacheDir; - protected final ClassLoader parentClassLoader; - public AndroidClassDefiner(File cacheDir, ClassLoader parentClassLoader) throws IOException { - this.cacheDir = cacheDir; - this.parentClassLoader = parentClassLoader; - } - - static void delete(File f) { - File[] fs = f.listFiles(); - if (fs != null) - for (File ff : fs) - delete(ff); - f.delete(); - } - - private static final byte[] dex(String className, byte[] classData) throws ClassFormatError { - try { - DexOptions dexOptions = new DexOptions(); - DexFile dxFile = new DexFile(dexOptions); - CfOptions cfOptions = new CfOptions(); - dxFile.add(CfTranslator.translate(className.replace('.', '/') + ".class", classData, cfOptions, dexOptions)); - StringWriter out = BridJ.debug ? new StringWriter() : null; - byte[] dexData = dxFile.toDex(out, false); - if (BridJ.debug) - BridJ.info("Dex output for class " + className + " : " + out); - return dexData; - } catch (IOException ex) { - throw new ClassFormatError("Unable to convert class data to Dalvik code using Dex : " + ex); - } - } - public Class defineClass(String className, byte[] classData) throws ClassFormatError { - byte[] dexData = dex(className, classData); - - File tempDir = null; - File apkFile = null; - try { - tempDir = File.createTempFile("bridj.", ".tmp", cacheDir).getAbsoluteFile(); - tempDir.delete(); - tempDir.mkdir(); - - apkFile = File.createTempFile("dynamic.", ".apk", tempDir).getAbsoluteFile(); - apkFile.getParentFile().mkdirs(); - - ZipOutputStream out = new ZipOutputStream(new FileOutputStream(apkFile)); - out.putNextEntry(new ZipEntry("classes.dex")); - out.write(dexData); - out.closeEntry(); - out.close(); - - // http://stackoverflow.com/questions/2903260/android-using-dexclassloader-to-load-apk-file - //PathClassLoader classLoader = new PathClassLoader(apkFile.toString(), getClass().getClassLoader()); - DexClassLoader classLoader = new DexClassLoader(apkFile.toString(), tempDir.toString(), null, parentClassLoader); - return classLoader.loadClass(className); - } catch (Throwable th) { - throw new RuntimeException("Failed with tempFile = " + apkFile + " : " + th, th); - } finally { - if (apkFile != null) - delete(apkFile); - - if (tempDir != null) - delete(tempDir); - } - - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/AndroidSupport.java b/libraries/BridJ/src/main/java/org/bridj/AndroidSupport.java deleted file mode 100644 index 4e4205fae..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/AndroidSupport.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import org.bridj.util.ClassDefiner; -import android.app.Application; -import android.content.pm.ApplicationInfo; -import android.os.Environment; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author ochafik - */ -public class AndroidSupport extends PlatformSupport { - private volatile Application app; - - AndroidSupport() {} - - - synchronized void setApp(Application application) { - if (this.app != null && application != null && this.app != application) - throw new IllegalArgumentException("Android Application has already been set to a different value : " + this.app); - - this.app = application; - } - - public static void setApplication(Application application) { - ((AndroidSupport)PlatformSupport.getInstance()).setApp(application); - } - - String adviseToSetApp() { - return app == null ? "" : "Please use AndroidSupport.setApplication(Application). "; - } - - - volatile AndroidClassDefiner classDefiner; - - synchronized File getCacheDir() throws FileNotFoundException { - File cacheDir = null; - if (app != null) - cacheDir = app.getCacheDir(); - - if (cacheDir == null || !cacheDir.isDirectory() || !cacheDir.canWrite()) - throw new FileNotFoundException("Failed to find the cache directory. " + adviseToSetApp()); - - return cacheDir; - } - @Override - public synchronized ClassDefiner getClassDefiner(ClassDefiner defaultDefiner, ClassLoader parentClassLoader) { - if (classDefiner == null) - try { - classDefiner = new AndroidClassDefiner(getCacheDir(), parentClassLoader); - } catch (IOException ex) { - throw new RuntimeException("Failed to instantiate the Android class definer : " + ex, ex); - } - return classDefiner; - } - - String getLibFileName(String libName) { - return "lib" + libName + ".so"; - } - synchronized File getNativeLibraryDir(String someBundledNativeLibraryName) throws FileNotFoundException { - //String someKnownResource = - File f = null; - if (app != null) { - try { - // ApplicationInfo.nativeLibraryDir is only available from API level 9 and later - // http://developer.android.com/reference/android/content/pm/ApplicationInfo.html#nativeLibraryDir - f = (File)ApplicationInfo.class.getField("nativeLibraryDir").get(app.getApplicationInfo()); - } catch (Throwable th) {} - } - if (f == null) { - String someKnownResource = "lib/armeabi/" + getLibFileName(someBundledNativeLibraryName); - f = new File(getApplicationDataDir(someKnownResource), "lib"); - } - - if (f != null && f.isDirectory()) - return f; - - throw new FileNotFoundException("Failed to get the native library directory " + (f != null ? "(" + f + " is not a directory). " : ". ") + adviseToSetApp()); - } - - synchronized File getApplicationDataDir(String someKnownResource) throws FileNotFoundException { - if (app != null) - return new File(app.getApplicationInfo().dataDir); - else - return new File(new File(Environment.getDataDirectory(), "data"), getPackageName(someKnownResource)); - } - - @Override - public synchronized NativeLibrary loadNativeLibrary(String name) throws IOException { - File f = new File(getNativeLibraryDir(name), getLibFileName(name)); - if (f.exists()) { - return NativeLibrary.load(f == null ? name : f.toString()); - } else { - throw new RuntimeException("File not found : " + f); - } - } - - synchronized String getPackageName(String someKnownResource) throws FileNotFoundException { - if (app != null) - return app.getPackageName(); - else { - URL resource = Platform.getResource(someKnownResource); - if (resource == null) - throw new FileNotFoundException("Resource does not exist : " + someKnownResource); - - return getAndroidPackageNameFromResourceURL(resource.toString()); - } - } - - static String getAndroidPackageNameFromResourceURL(String url) { - Pattern p = Pattern.compile("jar:file:/data/[^/]+/([^/]*?)\\.apk!.*"); - Matcher m = p.matcher(url); - String packageName = null; - if (!m.matches()) { - p = Pattern.compile("jar:file:/.*?/([^/]+)/pkg\\.apk!.*"); - m = p.matcher(url); - } - if (m.matches()) { - packageName = m.group(1); - if (packageName.matches(".*?-\\d+")) { - int i = packageName.lastIndexOf("-"); - packageName = packageName.substring(0, i); - } - } - return packageName; - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/BridJ.java b/libraries/BridJ/src/main/java/org/bridj/BridJ.java deleted file mode 100644 index e399ff733..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/BridJ.java +++ /dev/null @@ -1,1057 +0,0 @@ -package org.bridj; - -import org.bridj.ann.Forwardable; -import java.util.Set; -import java.util.HashSet; -import org.bridj.util.Utils; -import static org.bridj.util.AnnotationUtils.*; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.*; - -import org.bridj.BridJRuntime.TypeInfo; -import org.bridj.demangling.Demangler.Symbol; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.ann.Library; -import java.util.Stack; -import java.io.PrintWriter; -import java.lang.reflect.Type; -import java.net.URL; -import org.bridj.util.StringUtils; -import static org.bridj.Platform.*; -import static java.lang.System.*; -import org.bridj.util.ClassDefiner; -import org.bridj.util.ASMUtils; - -/// http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html -/** - * BridJ's central class.
- *

    - *
  • To register a class with native methods (which can be in inner classes), just add the following static block to your class : - *
    {@code
    - *      static {
    - *          BridJ.register();
    - *      }
    - * }
    - *
  • You can also register a class explicitely with {@link BridJ#register(java.lang.Class)} - *
  • To alter the name of a library, use {@link BridJ#setNativeLibraryActualName(String, String)} and {@link BridJ#addNativeLibraryAlias(String, String)} - *
  • - *
- * @author ochafik - */ -public class BridJ { - - static final Map librariesByClass = new HashMap(); - static final Map librariesFilesByName = new HashMap(); - static final Map librariesByFile = new HashMap(); - private static NativeEntities orphanEntities = new NativeEntities(); - static final Map, BridJRuntime> classRuntimes = new HashMap, BridJRuntime>(); - static final Map strongNativeObjects = new HashMap(), - weakNativeObjects = new WeakHashMap(); - - public static long sizeOf(Type type) { - Class c = Utils.getClass(type); - if (c.isPrimitive()) - return StructIO.primTypeLength(c); - else if (Pointer.class.isAssignableFrom(c)) - return Pointer.SIZE; - else if (c == CLong.class) - return CLong.SIZE; - else if (c == TimeT.class) - return TimeT.SIZE; - else if (c == SizeT.class) - return SizeT.SIZE; - else if (c == Integer.class || c == Float.class) - return 4; - else if (c == Character.class || c == Short.class) - return 2; - else if (c == Long.class || c == Double.class) - return 8; - else if (c == Boolean.class || c == Byte.class) - return 1; - else if (NativeObject.class.isAssignableFrom(c)) - return getRuntime(c).getTypeInfo(type).sizeOf(); - else if (IntValuedEnum.class.isAssignableFrom(c)) - return 4; - /*if (o instanceof NativeObject) { - NativeObject no = (NativeObject)o; - return no.typeInfo.sizeOf(no); - }*/ - throw new RuntimeException("Unable to compute size of type " + Utils.toString(type)); - } - static synchronized void registerNativeObject(NativeObject ob) { - weakNativeObjects.put(Pointer.getAddress(ob, null), ob); - } - /// Caller should display message such as "target was GC'ed. You might need to add a BridJ.protectFromGC(NativeObject), BridJ.unprotectFromGC(NativeObject) - - static synchronized NativeObject getNativeObject(long peer) { - NativeObject ob = weakNativeObjects.get(peer); - if (ob == null) { - ob = strongNativeObjects.get(peer); - } - return ob; - } - - static synchronized void unregisterNativeObject(NativeObject ob) { - long peer = Pointer.getAddress(ob, null); - weakNativeObjects.remove(peer); - strongNativeObjects.remove(peer); - } - - /** - * Keep a hard reference to a native object to avoid its garbage collection.
- * See {@link BridJ#unprotectFromGC(NativeObject)} to remove the GC protection. - */ - public static synchronized T protectFromGC(T ob) { - long peer = Pointer.getAddress(ob, null); - weakNativeObjects.remove(peer); - strongNativeObjects.put(peer, ob); - return ob; - } - - /** - * Drop the hard reference created with {@link BridJ#protectFromGC(NativeObject)}. - */ - public static synchronized T unprotectFromGC(T ob) { - long peer = Pointer.getAddress(ob, null); - if (strongNativeObjects.remove(peer) != null) { - weakNativeObjects.put(peer, ob); - } - return ob; - } - - public static void delete(NativeObject nativeObject) { - unregisterNativeObject(nativeObject); - Pointer.pointerTo(nativeObject, null).release(); - } - - /** - * Registers the native methods of the caller class and all its inner types. - *
{@code
-	 	\@Library("mylib")
-	 	public class MyLib {
-	 		static {
-	 			BridJ.register();
-			}
-			public static native void someFunc();
-		}
-		}
- */ - public static synchronized void register() { - StackTraceElement[] stackTrace = new Exception().getStackTrace(); - if (stackTrace.length < 2) { - throw new RuntimeException("No useful stack trace : cannot register with register(), please use register(Class) instead."); - } - String name = stackTrace[1].getClassName(); - try { - Class type = Class.forName(name); - register(type); - } catch (Exception ex) { - throw new RuntimeException("Failed to register class " + name, ex); - } - } - - /** - * Create a subclass of the provided original class with synchronized overrides for all native methods. - * Non-default constructors are not currently handled. - * @param - * @param original - * @throws IOException - */ - public static Class subclassWithSynchronizedNativeMethods(Class original) throws IOException { - ClassDefiner classDefiner = getRuntimeByRuntimeClass(CRuntime.class).getCallbackNativeImplementer(); - return ASMUtils.createSubclassWithSynchronizedNativeMethodsAndNoStaticFields(original, classDefiner); - } - - enum CastingType { - None, CastingNativeObject, CastingNativeObjectReturnType - } - static ThreadLocal> currentlyCastingNativeObject = new ThreadLocal>() { - - @Override - protected java.util.Stack initialValue() { - Stack s = new Stack(); - s.push(CastingType.None); - return s; - } - - ; - }; - - @Deprecated - public static boolean isCastingNativeObjectInCurrentThread() { - return currentlyCastingNativeObject.get().peek() != CastingType.None; - } - - @Deprecated - public static boolean isCastingNativeObjectReturnTypeInCurrentThread() { - return currentlyCastingNativeObject.get().peek() == CastingType.CastingNativeObjectReturnType; - } - - private static WeakHashMap knownNativeObjects = new WeakHashMap(); - public static synchronized void setJavaObjectFromNativePeer(long peer, O object) { - if (object == null) - knownNativeObjects.remove(peer); - else - knownNativeObjects.put(peer, object); - } - public static synchronized Object getJavaObjectFromNativePeer(long peer) { - return knownNativeObjects.get(peer); - } - - private static O createNativeObjectFromPointer(Pointer pointer, Type type, CastingType castingType) { - Stack s = currentlyCastingNativeObject.get(); - s.push(castingType); - try { - TypeInfo typeInfo = getTypeInfo(type); - O instance = typeInfo.cast(pointer); - if (BridJ.debug) - BridJ.info("Created native object from pointer " + pointer); - return instance; - } catch (Exception ex) { - throw new RuntimeException("Failed to cast pointer to native object of type " + Utils.getClass(type).getName(), ex); - } finally { - s.pop(); - } - } - public static void copyNativeObjectToAddress(O value, Type type, Pointer ptr) { - getTypeInfo(type).copyNativeObjectToAddress(value, (Pointer)ptr); - } - - public static O createNativeObjectFromPointer(Pointer pointer, Type type) { - return (O)createNativeObjectFromPointer(pointer, type, CastingType.CastingNativeObject); - } - public static O createNativeObjectFromReturnValuePointer(Pointer pointer, Type type) { - return (O)createNativeObjectFromPointer(pointer, type, CastingType.CastingNativeObjectReturnType); - } - private static Map, BridJRuntime> runtimes = new HashMap, BridJRuntime>(); - - public static synchronized R getRuntimeByRuntimeClass(Class runtimeClass) { - R r = (R) runtimes.get(runtimeClass); - if (r == null) { - try { - runtimes.put(runtimeClass, r = runtimeClass.newInstance()); - } catch (Exception e) { - throw new RuntimeException("Failed to instantiate runtime " + runtimeClass.getName(), e); - } - } - - return r; - } - - /** - * Get the runtime class associated with a class (using the {@link org.bridj.ann.Runtime} annotation, if any, looking up parents and defaulting to {@link org.bridj.CRuntime}). - */ - public static Class getRuntimeClass(Class type) { - org.bridj.ann.Runtime runtimeAnn = getInheritableAnnotation(org.bridj.ann.Runtime.class, type); - Class runtimeClass = null; - if (runtimeAnn != null) - runtimeClass = runtimeAnn.value(); - else - runtimeClass = CRuntime.class; - - return runtimeClass; - } - - /** - * Get the runtime associated with a class (using the {@link org.bridj.ann.Runtime} annotation, if any, looking up parents and defaulting to {@link org.bridj.CRuntime}). - */ - public static BridJRuntime getRuntime(Class type) { - synchronized (classRuntimes) { - BridJRuntime runtime = classRuntimes.get(type); - if (runtime == null) { - Class runtimeClass = getRuntimeClass(type); - runtime = getRuntimeByRuntimeClass(runtimeClass); - classRuntimes.put(type, runtime); - - if (veryVerbose) - info("Runtime for " + type.getName() + " : " + runtimeClass.getName()); - } - return runtime; - } - } - - /** - * Registers the native method of a type (and all its inner types). - *
{@code
-	 	\@Library("mylib")
-	 	public class MyLib {
-	 		static {
-	 			BridJ.register(MyLib.class);
-			}
-			public static native void someFunc();
-		}
-		}
- */ - public static BridJRuntime register(Class type) { - BridJRuntime runtime = getRuntime(type); - if (runtime == null) - for (Class child : type.getClasses()) - register(child); - else - runtime.register(type); - return runtime; - } - public static void unregister(Class type) { - BridJRuntime runtime = getRuntime(type); - if (runtime == null) - for (Class child : type.getClasses()) - register(child); - else - runtime.unregister(type); - } - static Map> typeInfos = new HashMap>(); - - static TypeInfo getTypeInfo(Type t) { - synchronized (typeInfos) { - TypeInfo info = typeInfos.get(t); - if (info == null) { - info = getRuntime(Utils.getClass(t)).getTypeInfo(t); - typeInfos.put(t, info); - } - return info; - } - } - - enum Switch { - Debug("bridj.debug", "BRIDJ_DEBUG", false, - "Debug mode (implies high verbosity)" - ), - DebugNeverFree("bridj.debug.neverFree", "BRIDJ_DEBUG_NEVER_FREE", false, - "Never free allocated pointers (deprecated)" - ), - DebugPointers("bridj.debug.pointers", "BRIDJ_DEBUG_POINTERS", false, - "Trace pointer allocations & deallocations (to debug memory issues)" - ), - VeryVerbose("bridj.veryVerbose", "BRIDJ_VERY_VERBOSE", false, - "Highly verbose mode" - ), - Verbose("bridj.verbose", "BRIDJ_VERBOSE", false, - "Verbose mode" - ), - Quiet("bridj.quiet", "BRIDJ_QUIET", false, - "Quiet mode" - ), - LogCalls("bridj.logCalls", "BRIDJ_LOG_CALLS", false, - "Log each native call performed (or call from native to Java callback)" - ), - Protected("bridj.protected", "BRIDJ_PROTECTED", false, - "Protect all native calls (including memory accesses) against native crashes." - ), - Destructors("bridj.destructors", "BRIDJ_DESTRUCTORS", true, - "Enable destructors (in languages that support them, such as C++)" - ), - Direct("bridj.direct", "BRIDJ_DIRECT", true, - "Direct mode (uses optimized assembler glue when possible to speed up calls)" - ), - StructsByValue("bridj.structsByValue", "BRIDJ_STRUCT_BY_VALUE", false, - "Enable experimental support for structs-by-value arguments and return values for C/C++ functions and methods." - ); - - public final boolean enabled, enabledByDefault; - public final String propertyName, envName, description; - /** - * Important : keep full property name and environment variable name to enable full-text search of options !!! - */ - Switch(String propertyName, String envName, boolean enabledByDefault, String description) { - if (enabledByDefault) - enabled = !("false".equals(getProperty(propertyName)) || "0".equals(getenv(envName))); - else - enabled = "true".equals(getProperty(propertyName)) || "1".equals(getenv(envName)); - - this.enabledByDefault = enabledByDefault; - this.propertyName = propertyName; - this.envName = envName; - this.description = description; - } - public String getFullDescription() { - return envName + " / " + propertyName + " (" + (enabledByDefault ? "enabled" : "disabled") + " by default) :\n\t" + description.replaceAll("\n", "\n\t"); - } - } - - static { - checkOptions(); - } - - static void checkOptions() { - Set props = new HashSet(), envs = new HashSet(); - for (Switch s : Switch.values()) { - props.add(s.propertyName); - envs.add(s.envName); - } - boolean hasUnknown = false; - for (String n : System.getenv().keySet()) { - if (!n.startsWith("BRIDJ_") || envs.contains(n)) - continue; - - if (n.endsWith("_LIBRARY")) - continue; - - error("Unknown environment variable : " + n + "=\"" + System.getenv(n) + "\""); - hasUnknown = true; - } - - for (Enumeration e = (Enumeration)System.getProperties().propertyNames(); e.hasMoreElements();) { - String n = e.nextElement(); - if (!n.startsWith("bridj.") || props.contains(n)) - continue; - - if (n.endsWith(".library")) - continue; - - error("Unknown property : " + n + "=\"" + System.getProperty(n) + "\""); - hasUnknown = true; - } - if (hasUnknown) { - StringBuilder b = new StringBuilder(); - b.append("Available options (ENVIRONMENT_VAR_NAME / javaPropertyName) :\n"); - for (Switch s : Switch.values()) { - b.append(s.getFullDescription() + "\n"); - } - error(b.toString()); - } - } - - public static final boolean debug = Switch.Debug.enabled; - public static final boolean debugNeverFree = Switch.DebugNeverFree.enabled; - public static final boolean debugPointers = Switch.DebugPointers.enabled; - public static final boolean veryVerbose = Switch.VeryVerbose.enabled; - public static final boolean verbose = debug || veryVerbose || Switch.Verbose.enabled; - public static final boolean quiet = Switch.Quiet.enabled; - - public static final boolean logCalls = Switch.LogCalls.enabled; - public static final boolean protectedMode = Switch.Protected.enabled; - public static final boolean enableDestructors = Switch.Destructors.enabled; - - static volatile int minLogLevelValue = (verbose ? Level.WARNING : Level.INFO).intValue(); - public static void setMinLogLevel(Level level) { - minLogLevelValue = level.intValue(); - } - static boolean shouldLog(Level level) { - return !quiet && (verbose || level.intValue() >= minLogLevelValue); - } - - static Logger logger; - static synchronized Logger getLogger() { - if (logger == null) - logger = Logger.getLogger(BridJ.class.getName()); - return logger; - } - public static boolean info(String message) { - return info(message, null); - } - public static boolean info(String message, Throwable ex) { - return log(Level.INFO, message, ex); - } - public static boolean debug(String message) { - if (!debug) - return true; - return info(message, null); - } - public static boolean error(String message) { - return error(message, null); - } - public static boolean error(String message, Throwable ex) { - return log(Level.INFO, message, ex); - } - public static boolean warning(String message) { - return warning(message, null); - } - public static boolean warning(String message, Throwable ex) { - return log(Level.INFO, message, ex); - } - private static boolean log(Level level, String message, Throwable ex) { - if (!shouldLog(level)) - return true; - getLogger().log(level, message, ex); - return true; - } - - static void logCall(Method m) { - info("Calling method " + m); - } - - public static synchronized NativeEntities getNativeEntities(AnnotatedElement type) throws IOException { - NativeLibrary lib = getNativeLibrary(type); - if (lib != null) { - return lib.getNativeEntities(); - } - return getOrphanEntities(); - } - - public static synchronized NativeLibrary getNativeLibrary(AnnotatedElement type) throws IOException { - NativeLibrary lib = librariesByClass.get(type); - if (lib == null) { - Library libAnn = getLibrary(type); - if (libAnn != null) { - for (String dependency : libAnn.dependencies()) { - if (verbose) - info("Trying to load dependency '" + dependency + "' of '" + libAnn.value() + "'"); - NativeLibrary depLib = getNativeLibrary(dependency); - if (depLib == null) { - throw new RuntimeException("Failed to load dependency '" + dependency + "' of library '" + libAnn.value() + "'"); - } - } - lib = getNativeLibrary(libAnn.value()); - if (lib != null) { - librariesByClass.put(type, lib); - } - } - } - return lib; - } - - /** - * Reclaims all the memory allocated by BridJ in the JVM and on the native side. - * This is automatically called at shutdown time. - */ - public synchronized static void releaseAll() { - strongNativeObjects.clear(); - weakNativeObjects.clear(); - gc(); - - for (NativeLibrary lib : librariesByFile.values()) { - lib.release(); - } - librariesByFile.clear(); - librariesByClass.clear(); - getOrphanEntities().release(); - gc(); - } - //public synchronized static void release(Class); - - public synchronized static void releaseLibrary(String name) { - File file = librariesFilesByName.remove(name); - if (file != null) { - releaseLibrary(file); - } - } - - public synchronized static void releaseLibrary(File library) { - NativeLibrary lib = librariesByFile.remove(library); - if (lib != null) { - lib.release(); - } - } - static Map libHandles = new HashMap(); - static volatile List paths; - - static List additionalPaths = new ArrayList(); - public static synchronized void addLibraryPath(String path) { - additionalPaths.add(path); - paths = null; // invalidate cached paths - } - private static void addPathsFromEnv(List out, String name) { - String env = getenv(name); - if (BridJ.verbose) - BridJ.info("Environment var " + name + " = " + env); - addPaths(out, env); - } - private static void addPathsFromProperty(List out, String name) { - String env = getProperty(name); - if (BridJ.verbose) - BridJ.info("Property " + name + " = " + env); - addPaths(out, env); - } - private static void addPaths(List out, String env) { - if (env == null) - return; - - String[] paths = env.split(File.pathSeparator); - if (paths.length == 0) - return; - if (paths.length == 1) { - out.add(paths[0]); - return; - } - out.addAll(Arrays.asList(paths)); - } - - static synchronized List getNativeLibraryPaths() { - if (paths == null) { - paths = new ArrayList(); - paths.addAll(additionalPaths); - paths.add(null); - paths.add("."); - - addPathsFromEnv(paths, "LD_LIBRARY_PATH"); - addPathsFromEnv(paths, "DYLD_LIBRARY_PATH"); - addPathsFromEnv(paths, "PATH"); - addPathsFromProperty(paths, "java.library.path"); - addPathsFromProperty(paths, "gnu.classpath.boot.library.path"); - - File javaHome = new File(getProperty("java.home")); - paths.add(new File(javaHome, "bin").toString()); - if (isMacOSX()) { - paths.add(new File(javaHome, "../Libraries").toString()); - } - - - if (isUnix()) { - String bits = is64Bits() ? "64" : "32"; - if (isLinux()) { - // First try Ubuntu's multi-arch paths (cf. https://wiki.ubuntu.com/MultiarchSpec) - String abi = isArm() ? "gnueabi" : "gnu"; - String multiArch = getMachine() + "-linux-" + abi; - paths.add("/lib/" + multiArch); - paths.add("/usr/lib/" + multiArch); - - // Add /usr/lib32 and /lib32 - paths.add("/usr/lib" + bits); - paths.add("/lib" + bits); - } else if (isSolaris()) { - // Add /usr/lib/32 and /lib/32 - paths.add("/usr/lib/" + bits); - paths.add("/lib/" + bits); - } - - paths.add("/usr/lib"); - paths.add("/lib"); - paths.add("/usr/local/lib"); - } - } - return paths; - } - - static Map libraryActualNames = new HashMap(); - /** - * Define the actual name of a library.
- * Works only before the library is loaded.
- * For instance, library "OpenGL" is actually named "OpenGL32" on Windows : BridJ.setNativeLibraryActualName("OpenGL", "OpenGL32"); - * @param name - * @param actualName - */ - public static synchronized void setNativeLibraryActualName(String name, String actualName) { - libraryActualNames.put(name, actualName); - } - - - static Map> libraryAliases = new HashMap>(); - /** - * Add a possible alias for a library.
- * Aliases are prioritary over the library (or its actual name, see {@link BridJ#setNativeLibraryActualName(String, String)}), in the order they are defined.
- * Works only before the library is loaded.
- * @param name - * @param alias - */ - public static synchronized void addNativeLibraryAlias(String name, String alias) { - List list = libraryAliases.get(name); - if (list == null) - libraryAliases.put(name, list = new ArrayList()); - if (!list.contains(alias)) - list.add(alias); - } - - static String[] getPossibleFileNames(String name) { - if (isWindows()) { - return new String[] { - name + ".dll", - name + ".drv" - }; - } else { - String jniName = "lib" + name + ".jnilib"; - if (isMacOSX()) { - return new String[] { - "lib" + name + ".dylib", - jniName - }; - } else { - return new String[] { - "lib" + name + ".so", - name + ".so", - jniName - }; - } - } - } - - private static final Pattern numPat = Pattern.compile("\\b(\\d+)\\b"); - - /** - * Given "1.2.3", will yield (1 + 2 / 1000 + 3 / 1000000) - */ - static double parseVersion(String s) { - Matcher m = numPat.matcher(s); - double res = 0.0, f = 1; - while (m.find()) { - res += Integer.parseInt(m.group(1)) * f; - f /= 1000; - } - return res; - } - static File findFileWithGreaterVersion(File dir, String[] files, String baseFileName) { - Pattern versionPattern = Pattern.compile(Pattern.quote(baseFileName) + "((:?\\.\\d+)+)"); - double maxVersion = 0; - String maxVersionFile = null; - for (String fileName : files) { - Matcher m = versionPattern.matcher(fileName); - if (m.matches()) { - double version = parseVersion(m.group(1)); - if (maxVersionFile == null || version > maxVersion) { - maxVersionFile = fileName; - maxVersion = version; - } - } - } - if (maxVersionFile == null) - return null; - - return new File(dir, maxVersionFile); - } - - static Map nativeLibraryFiles = new HashMap(); - /** - * Given a library name (e.g. "test"), finds the shared library file in the system-specific path ("/usr/bin/libtest.so", "./libtest.dylib", "c:\\windows\\system\\test.dll"...) - */ - public static File getNativeLibraryFile(String libraryName) { - if (libraryName == null) - return null; - - try { - synchronized (nativeLibraryFiles) { - File nativeLibraryFile = nativeLibraryFiles.get(libraryName); - if (nativeLibraryFile == null) { - nativeLibraryFiles.put(libraryName, nativeLibraryFile = findNativeLibraryFile(libraryName)); - } - return nativeLibraryFile; - } - } catch (Throwable th) { - warning("Library not found : " + libraryName); - return null; - } - } - /** - * Associate a library name (e.g. "test"), to its shared library file. - */ - public static void setNativeLibraryFile(String libraryName, File nativeLibraryFile) { - if (libraryName == null) - return; - - synchronized (nativeLibraryFiles) { - nativeLibraryFiles.put(libraryName, nativeLibraryFile); - } - } - static File findNativeLibraryFile(String libraryName) { - //out.println("Getting file of '" + name + "'"); - String actualName = libraryActualNames.get(libraryName); - List aliases = libraryAliases.get(libraryName); - List possibleNames = new ArrayList(); - if (aliases != null) - possibleNames.addAll(aliases); - possibleNames.add(actualName == null ? libraryName : actualName); - - if (Platform.isWindows()) { - if (libraryName.equals("c")) - possibleNames.add("msvcrt"); - else if (libraryName.equals("m")) - possibleNames.add("msvcrt"); - } - - //out.println("Possible names = " + possibleNames); - List paths = getNativeLibraryPaths(); - if (debug) - info("Looking for library '" + libraryName + "' " + (actualName != null ? "('" + actualName + "') " : "") + "in paths " + paths, null); - - for (String name : possibleNames) { - String env = getenv("BRIDJ_" + name.toUpperCase() + "_LIBRARY"); - if (env == null) - env = getProperty("bridj." + name + ".library"); - if (env != null) { - File f = new File(env); - if (f.exists()) { - try { - return f.getCanonicalFile(); - } catch (IOException ex) { - error(null, ex); - } - } - } - for (String path : paths) { - File pathFile = path == null ? null : new File(path); - File f = new File(name); - if (!f.isFile() && pathFile != null) { - String[] possibleFileNames = getPossibleFileNames(name); - for (String possibleFileName : possibleFileNames) { - f = new File(pathFile, possibleFileName); - if (f.isFile()) - break; - } - - if (!f.isFile() && isLinux()) { - String[] files = pathFile.list(); - if (files != null) - for (String possibleFileName : possibleFileNames) { - File ff = findFileWithGreaterVersion(pathFile, files, possibleFileName); - if (ff != null && (f = ff).isFile()) { - if (verbose) - info("File '" + possibleFileName + "' was not found, used versioned file '" + f + "' instead."); - break; - } - } - } - } - - if (!f.isFile()) - continue; - - try { - return f.getCanonicalFile(); - } catch (IOException ex) { - error(null, ex); - } - } - if (isMacOSX()) { - for (String s : new String[]{ - "/System/Library/Frameworks", - "/System/Library/Frameworks/ApplicationServices.framework/Frameworks", - new File(getProperty("user.home"), "Library/Frameworks").toString() - }) { - try { - File f = new File(new File(s, name + ".framework"), name); - if (f.isFile()) - return f.getCanonicalFile(); - } catch (IOException ex) { - ex.printStackTrace(); - return null; - } - } - } - try { - File f; - if (isAndroid()) - f = new File("lib" + name + ".so"); - else - f = extractEmbeddedLibraryResource(name); - - if (f == null || !f.isFile()) - throw new FileNotFoundException(StringUtils.implode(possibleNames, ", ")); - - return f; - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - return null; - } - static Boolean directModeEnabled; - - /** - * Query direct mode.
- * In direct mode, BridJ will attempt to optimize calls with assembler code, so that the overhead of each call is about the same as with plain JNI.
- * Set -Dbridj.direct=false in the command line (or setProperty("bridj.direct", "false")) or environment var BRIDJ_DIRECT=0 to disable - */ - public static boolean isDirectModeEnabled() { - if (directModeEnabled == null) { - directModeEnabled = - Switch.Direct.enabled && - !logCalls && - !protectedMode - ; - if (veryVerbose) - info("directModeEnabled = " + directModeEnabled); - } - return directModeEnabled; - } - - /** - * Set direct mode.
- * In direct mode, BridJ will attempt to optimize calls with assembler code, so that the overhead of each call is about the same as with plain JNI.
- * Set -Dbridj.direct=false in the command line (or setProperty("bridj.direct", "false")) or environment var BRIDJ_DIRECT=0 to disable - */ - static void setDirectModeEnabled(boolean v) { - directModeEnabled = v; - } - - /** - * Loads the library with the name provided in argument (see {@link #getNativeLibraryFile(String)}) - */ - public static synchronized NativeLibrary getNativeLibrary(String name) throws IOException { - if (name == null) { - return null; - } - - NativeLibrary l = libHandles.get(name); - if (l != null) { - return l; - } - - File f = getNativeLibraryFile(name); - //if (f == null) { - // throw new FileNotFoundException("Couldn't find library file for library '" + name + "'"); - //} - - return getNativeLibrary(name, f); - } - - /** - * Loads the shared library file under the provided name. Any subsequent call to {@link #getNativeLibrary(String)} will return this library. - */ - public static NativeLibrary getNativeLibrary(String name, File f) throws IOException { - NativeLibrary ll = NativeLibrary.load(f == null ? name : f.toString());; - if (ll == null) { - ll = PlatformSupport.getInstance().loadNativeLibrary(name); - if (ll == null) { - if ("c".equals(name)) { - ll = new NativeLibrary(null, 0, 0); - } - } - } - - //if (ll == null && f != null) - // ll = NativeLibrary.load(f.getName()); - if (ll == null) { - if (f != null && f.exists()) - throw new RuntimeException("Library '" + name + "' was not loaded successfully from file '" + f + "'"); - else - throw new FileNotFoundException("Library '" + name + "' was not found in path '" + getNativeLibraryPaths() + "'" + (f != null && f.exists() ? " (failed to load " + f + ")" : "")); - } - if (verbose) - info("Loaded library '" + name + "' from '" + f + "'", null); - - libHandles.put(name, ll); - return ll; - } - - /** - * Gets the name of the library declared for an annotated element. Recurses up to parents of the element (class, enclosing classes) to find any {@link org.bridj.ann.Library} annotation. - */ - public static String getNativeLibraryName(AnnotatedElement m) { - Library lib = getLibrary(m); - return lib == null ? null : lib.value(); - } - - /** - * Gets the {@link org.bridj.ann.Library} annotation for an annotated element. - * Recurses up to parents of the element (class, enclosing classes) if needed - */ - static Library getLibrary(AnnotatedElement m) { - return getInheritableAnnotation(Library.class, m); - } - - public static Symbol getSymbolByAddress(long peer) { - for (NativeLibrary lib : libHandles.values()) { - Symbol symbol = lib.getSymbol(peer); - if (symbol != null) { - return symbol; - } - } - return null; - } - - public static void setOrphanEntities(NativeEntities orphanEntities) { - BridJ.orphanEntities = orphanEntities; - } - - public static NativeEntities getOrphanEntities() { - return orphanEntities; - } - - static void initialize(NativeObject instance) { - TypeInfo typeInfo = getTypeInfo(instance.getClass()); - instance.typeInfo = typeInfo; - typeInfo.initialize(instance); - } - - static void initialize(NativeObject instance, Pointer peer) { - TypeInfo typeInfo = getTypeInfo(instance.getClass()); - instance.typeInfo = typeInfo; - typeInfo.initialize(instance, peer); - } - - static void initialize(NativeObject instance, int constructorId, Object[] args) { - // TODO handle template arguments here (or above), with class => ((class, args) => Type) caching - TypeInfo typeInfo = getTypeInfo(instance.getClass()); - instance.typeInfo = typeInfo; - typeInfo.initialize(instance, constructorId, args); - } - - static T clone(T instance) throws CloneNotSupportedException { - return ((TypeInfo)instance.typeInfo).clone(instance); - } - - /** - * Some native object need manual synchronization between Java fields and native memory.
- * An example is JNA-style structures. - */ - public static T readFromNative(T instance) { - ((TypeInfo)instance.typeInfo).readFromNative(instance); - return instance; - } - /** - * Some native object need manual synchronization between Java fields and native memory.
- * An example is JNA-style structures. - */ - public static T writeToNative(T instance) { - ((TypeInfo)instance.typeInfo).writeToNative(instance); - return instance; - } - /** - * Creates a string that describes the provided native object, printing generally-relevant internal data (for instance for structures, this will typically display the fields values).
- * This is primarily useful for debugging purposes. - */ - public static String describe(NativeObject instance) { - return ((TypeInfo)instance.typeInfo).describe(instance); - } - /** - * Creates a string that describes the provided native object type, printing generally-relevant internal data (for instance for structures, this will typically display name of the fields, their offsets and lengths...).
- * This is primarily useful for debugging purposes. - */ - public static String describe(Type nativeObjectType) { - TypeInfo typeInfo = getTypeInfo(nativeObjectType); - return typeInfo == null ? Utils.toString(nativeObjectType) : typeInfo.describe(); - } - - public static void main(String[] args) { - List libraries = new ArrayList(); - try { - File outputDir = new File("."); - for (int iArg = 0, nArgs = args.length; iArg < nArgs; iArg++) { - String arg = args[iArg]; - if (arg.equals("-d")) { - outputDir = new File(args[++iArg]); - continue; - } - try { - NativeLibrary lib = getNativeLibrary(arg); - libraries.add(lib); - - PrintWriter sout = new PrintWriter(new File(outputDir, new File(arg).getName() + ".symbols.txt")); - for (Symbol sym : lib.getSymbols()) { - sout.print(sym.getSymbol()); - sout.print(" // "); - try { - MemberRef mr = sym.getParsedRef(); - sout.print(" // " + mr); - } catch (Throwable th) { - sout.print("?"); - } - sout.println(); - } - sout.close(); - } catch (Throwable th) { - th.printStackTrace(); - } - } - PrintWriter out = new PrintWriter(new File(outputDir, "out.h")); - HeadersReconstructor.reconstructHeaders(libraries, out); - out.close(); - } catch (Exception ex) { - ex.printStackTrace(); - exit(1); - } - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/BridJRuntime.java b/libraries/BridJ/src/main/java/org/bridj/BridJRuntime.java deleted file mode 100644 index 022174f1d..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/BridJRuntime.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bridj; - -import java.lang.reflect.Type; - -/** - * Interface that each specific pluggable native runtime must implement.
- * A runtime is attached to a class via the {@link org.bridj.ann.Runtime} annotation, so any runtime can be added in thirdparty libraries.
- * A runtime typically defines NativeObject subclasses and deals with their instances lifecycle through the type information metadata {@link TypeInfo} class.
- * @author ochafik - */ -public interface BridJRuntime { - - /** - * Type information metadata + lifecycle management methods.
- * This class is not meant to be used by end users, it's used by runtimes. - */ - public interface TypeInfo { - T cast(Pointer peer); - void initialize(T instance); - void initialize(T instance, Pointer peer); - void initialize(T instance, int constructorId, Object[] args); - void destroy(T instance); - T createReturnInstance(); - T clone(T instance) throws CloneNotSupportedException; - BridJRuntime getRuntime(); - Type getType(); - - boolean equal(T instance, T other); - int compare(T instance, T other); - long sizeOf(); - void writeToNative(T instance); - String describe(T instance); - String describe(); - void readFromNative(T instance); - void copyNativeObjectToAddress(T instance, Pointer ptr); - } - Type getType(NativeObject instance); - - void register(Type type); - void unregister(Type type); - TypeInfo getTypeInfo(final Type type); - - boolean isAvailable(); - Class getActualInstanceClass(Pointer pInstance, Type officialType); - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/CLong.java b/libraries/BridJ/src/main/java/org/bridj/CLong.java deleted file mode 100644 index 296ed3864..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/CLong.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -/** - * Wraps a value which size is the same as the 'long' C type (32 bits on a 32 bits platform, 64 bits on a 64 bits platform with GCC and still 32 bits with MSVC++ on 64 bits platforms) - * @author Olivier - */ -public final class CLong extends AbstractIntegral { - - public static final int SIZE = Platform.CLONG_SIZE; - - private static final long serialVersionUID = 1542942327767932396L; - public CLong(long value) { - super(value); - } - - public static CLong valueOf(long value) { - return new CLong(value); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/CRuntime.java b/libraries/BridJ/src/main/java/org/bridj/CRuntime.java deleted file mode 100644 index 60880474c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/CRuntime.java +++ /dev/null @@ -1,560 +0,0 @@ -package org.bridj; - -import org.bridj.util.Utils; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.List; -import java.util.ArrayList; - -import org.bridj.demangling.Demangler.Symbol; -import org.bridj.NativeEntities.Builder; -import org.bridj.ann.Convention; -import org.bridj.ann.JNIBound; -import org.bridj.util.ConcurrentCache; -import static org.bridj.BridJ.*; -import static org.bridj.util.AnnotationUtils.*; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicReference; -import org.bridj.ann.Optional; - -/** - * C runtime (used by default when no {@link org.bridj.ann.Runtime} annotation is found).
- * Deals with registration and lifecycle of structs, functions, callbacks.
- * A shared C runtime instance can be retrieved with {@link CRuntime#getInstance() }. - * @author ochafik - */ -public class CRuntime extends AbstractBridJRuntime { - - final static Set registeredTypes = new HashSet(); - final AtomicReference _callbackNativeImplementer = new AtomicReference(); - - /** - * @deprecated use {@link CRuntime#getInstance() } instead - */ - @Deprecated - public CRuntime() { - - } - - public CallbackNativeImplementer getCallbackNativeImplementer() { - CallbackNativeImplementer impl = _callbackNativeImplementer.get(); - if (impl == null) { - CallbackNativeImplementer newImpl = new CallbackNativeImplementer(BridJ.getOrphanEntities(), this); - if (_callbackNativeImplementer.compareAndSet(null, newImpl)) - impl = newImpl; - else - impl = _callbackNativeImplementer.get(); - } - return impl; - } - - - public boolean isAvailable() { - return true; - } - - public static CRuntime getInstance() { - return BridJ.getRuntimeByRuntimeClass(CRuntime.class); - } - - - //@Override - public Class getActualInstanceClass(Pointer pInstance, Type officialType) { - return Utils.getClass(officialType); - } - - public class CTypeInfo implements TypeInfo { - public CTypeInfo(Type type) { - this.type = type; - this.typeClass = Utils.getClass(type); - this.structIO = StructIO.getInstance(typeClass, typeClass); - if (structIO != null) - structIO.build(); - this.pointerIO = (PointerIO)PointerIO.getInstance(structIO); - //this.castClass = getTypeForCast(typeClass); - register(typeClass); - } - protected final Type type; - protected final Class typeClass; - protected final StructIO structIO; - protected final PointerIO pointerIO; - protected volatile Class castClass; - - //@Override - public long sizeOf() { - return structIO.getStructSize(); - } - //@Override - public boolean equal(T instance, T other) { - if (structIO != null) { - if (((StructObject)instance).io != structIO) - throw new IllegalArgumentException("This is not this instance's StructIO"); - - if (((StructObject)other).io != structIO) - return false; - - return structIO.equal((StructObject)instance, (StructObject)other); - } else { - return instance.peer.equals(other.peer); - } - } - //@Override - public int compare(T instance, T other) { - if (structIO != null) { - if (((StructObject)instance).io != structIO) - throw new IllegalArgumentException("This is not this instance's StructIO"); - - if (((StructObject)other).io != structIO) - return 1; - - return structIO.compare((StructObject)instance, (StructObject)other); - } else { - return instance.peer.compareTo(other.peer); - } - } - - - //@Override - public BridJRuntime getRuntime() { - return CRuntime.this; - } - //@Override - public Type getType() { - return type; - } - - protected Class getCastClass() { - if (castClass == null) - castClass = (Class)getTypeForCast(typeClass); - return castClass; - } - protected T newCastInstance() throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class cc = getCastClass(); - try { - return (T)cc.newInstance(); - } catch (IllegalAccessException ex) { - Constructor constructor = (Constructor) cc.getConstructor(); - constructor.setAccessible(true); - return constructor.newInstance(); - } - } - - //@Override - public T cast(Pointer peer) { - try { - T instance = newCastInstance(); - // TODO template parameters here !!! - initialize(instance, peer); - return instance; - } catch (Exception ex) { - throw new RuntimeException("Failed to cast pointer " + peer + " to instance of type " + Utils.toString(type), ex); - } - } - //@Override - public T createReturnInstance() { - try { - T instance = newCastInstance(); - initialize(instance); - return instance; - } catch (Exception ex) { - throw new RuntimeException("Failed to create return instance for type " + Utils.toString(type), ex); - } - } - //@Override - public void writeToNative(T instance) { - if (instance instanceof StructObject) - structIO.writeFieldsToNative((StructObject)instance); - } - //@Override - public void readFromNative(T instance) { - if (instance instanceof StructObject) - structIO.readFieldsFromNative((StructObject)instance); - } - public void copyNativeObjectToAddress(T instance, Pointer ptr) { - if (instance instanceof StructObject) { - // TODO override in C++ to call operator= - ((StructObject)instance).peer.copyBytesTo(ptr, structIO.getStructSize()); - } - } - //@Override - public String describe(T instance) { - if (instance instanceof StructObject) - return structIO.describe((StructObject)instance); - else - return instance.toString(); - } - //@Override - public String describe() { - if (structIO != null) - return structIO.describe(); - else - return Utils.toString(typeClass); - } - - //@Override - public void initialize(T instance) { - if (!BridJ.isCastingNativeObjectInCurrentThread()) { - if (instance instanceof CallbackInterface) { - if (!(instance instanceof DynamicFunction)) - setNativeObjectPeer(instance, registerCallbackInstance((CallbackInterface)instance)); - } else - initialize(instance, -1); - - if (instance instanceof StructObject) - structIO.readFieldsFromNative((StructObject)instance); - } else if (instance instanceof StructObject) { - ((StructObject)instance).io = structIO; - } - } - //@Override - public void initialize(T instance, Pointer peer) { - instance.peer = peer; - if (instance instanceof StructObject) { - ((StructObject)instance).io = structIO; - structIO.readFieldsFromNative((StructObject)instance); - } - } - - //@Override - public void initialize(T instance, int constructorId, Object... args) { - StructObject s = (StructObject)instance; - if (constructorId < 0) { - s.io = structIO; - if (instance.peer == null) - instance.peer = Pointer.allocate(pointerIO); - } else - throw new UnsupportedOperationException("TODO implement structs constructors !"); - } - - //@Override - public T clone(T instance) throws CloneNotSupportedException { - if (instance == null) - return null; - - try { - T clone = (T)typeClass.newInstance(); - Pointer p = Pointer.allocate(pointerIO); - Pointer.pointerTo(instance).copyTo(p); - initialize(clone, p); - return clone; - } catch (Exception ex) { - throw new RuntimeException("Failed to clone instance of type " + getType()); - } - } - - //@Override - public void destroy(T instance) { - if (instance instanceof CallbackInterface) - return; - } - } - /// Needs not be fast : TypeInfo will be cached in BridJ anyway ! - //@Override - public TypeInfo getTypeInfo(final Type type) { - return new CTypeInfo(type); - } - //@Override - public void register(Type type) { - register(type, null, null); - } - public static class MethodCallInfoBuilder { - public MethodCallInfo apply(Method method) throws FileNotFoundException { - return new MethodCallInfo(method); - } - } - @Override - public void unregister(Type type) { - Class typeClass = Utils.getClass(type); - registeredTypes.remove(typeClass); - } - synchronized void register(Type type, NativeLibrary forcedLibrary, MethodCallInfoBuilder methodCallInfoBuilder) { - Class typeClass = Utils.getClass(type); - if (!BridJ.getRuntimeClass(typeClass).isInstance(this)) { - BridJ.register(typeClass); - return; - } - synchronized (registeredTypes) { - if (!registeredTypes.add(typeClass)) - return; - } - - if (methodCallInfoBuilder == null) - methodCallInfoBuilder = new MethodCallInfoBuilder(); - - assert info("Registering type " + Utils.toString(type)); - - int typeModifiers = typeClass.getModifiers(); - - NativeLibrary typeLibrary = null; - try { - typeLibrary = forcedLibrary == null ? getNativeLibrary(typeClass) : forcedLibrary; - } catch (Throwable th) {} - - ConcurrentCache builders = new ConcurrentCache(NativeEntities.Builder.class); - try { - Set handledMethods = new HashSet(); - /*if (StructObject.class.isAssignableFrom(typeClass)) { - StructIO io = StructIO.getInstance(typeClass, type, this); // TODO handle differently with templates... - io.build(); - StructIO.FieldIO[] fios = io == null ? null : io.getFields(); - if (fios != null) - for (StructIO.FieldIO fio : fios) { - NativeEntities.Builder builder = builders.get(BridJ.getOrphanEntities()); - - try { - { - MethodCallInfo getter = new MethodCallInfo(fio.getter); - getter.setIndex(fio.index); - builder.addGetter(getter); - handledMethods.add(fio.getter); - } - if (fio.setter != null) { - MethodCallInfo setter = new MethodCallInfo(fio.setter); - setter.setIndex(fio.index); - builder.addSetter(setter); - handledMethods.add(fio.setter); - } - } catch (Exception ex) { - System.err.println("Failed to register field " + fio.name + " in struct " + type); - ex.printStackTrace(); - } - } - }*/ - - if (CallbackInterface.class.isAssignableFrom(typeClass)) { - if (rootCallbackClasses.contains(type)) - return; - - if (Modifier.isAbstract(typeModifiers)) - getCallbackNativeImplementer().getCallbackImplType((Class) type, forcedLibrary); - } - - -// for (; type != null && type != Object.class; type = type.getSuperclass()) { - List nativeMethods = new ArrayList(); - for (Method method : typeClass.getDeclaredMethods()) { - int modifiers = method.getModifiers(); - if (Modifier.isNative(modifiers)) { - if (!isAnnotationPresent(JNIBound.class, method)) - nativeMethods.add(method); - } - } - - if (!nativeMethods.isEmpty()) - try { - for (Method method : nativeMethods) { - if (!handledMethods.add(method)) - continue; - - try { - NativeLibrary methodLibrary = forcedLibrary == null ? BridJ.getNativeLibrary(method) : forcedLibrary; - NativeEntities nativeEntities = methodLibrary == null ? BridJ.getOrphanEntities() : methodLibrary.getNativeEntities(); - NativeEntities.Builder builder = builders.get(nativeEntities); - - registerNativeMethod(typeClass, typeLibrary, method, methodLibrary, builder, methodCallInfoBuilder); - } catch (Exception ex) { - assert error("Method " + method.toGenericString() + " cannot be mapped : " + ex, ex); - } - } - } catch (Exception ex) { - throw new RuntimeException("Failed to register class " + Utils.toString(type), ex); - } -// } - } finally { - for (Map.Entry e : builders.entrySet()) { - e.getKey().addDefinitions(typeClass, e.getValue()); - } - registerFamily(type, forcedLibrary, methodCallInfoBuilder); - } - } - protected void registerFamily(Type type, NativeLibrary forcedLibrary, MethodCallInfoBuilder methodCallInfoBuilder) { - Class typeClass = Utils.getClass(type); - - for (Class child : typeClass.getClasses()) - register(child, forcedLibrary, methodCallInfoBuilder); - - typeClass = typeClass.getSuperclass(); - if (typeClass != null && typeClass != Object.class) - register(typeClass, forcedLibrary, methodCallInfoBuilder); - } - - protected NativeLibrary getNativeLibrary(Class type) throws IOException { - return BridJ.getNativeLibrary(type); - } - protected boolean isSymbolOptional(Method method) { - return getInheritableAnnotation(Optional.class, method) != null; - } - protected void registerNativeMethod( - Class type, - NativeLibrary typeLibrary, - Method method, - NativeLibrary methodLibrary, - Builder builder, - MethodCallInfoBuilder methodCallInfoBuilder - ) throws FileNotFoundException - { - MethodCallInfo mci; - try { - mci = methodCallInfoBuilder.apply(method); - if (mci == null) - return; - //System.out.println("method.dcCallingConvention = " + mci.dcCallingConvention + " (for method " + type.getName() + ", method " + method + ", type = " + type.getName() + ", enclosingClass = " + method.getDeclaringClass().getName() + ")"); - } catch (Throwable th) { - error("Unable to register " + method + " : " + th); - th.printStackTrace(); - return; - } - if (CallbackInterface.class.isAssignableFrom(type)) { - if (debug) - info("Registering java -> native callback : " + method); - builder.addJavaToNativeCallback(mci); - } else { - Symbol symbol = methodLibrary == null ? null : methodLibrary.getSymbol(method); - if (symbol == null) - { -// for (Demangler.Symbol symbol : methodLibrary.getSymbols()) { -// if (symbol.matches(method)) { -// address = symbol.getAddress(); -// break; -// } -// } -// if (address == null) { - if (!isSymbolOptional(method)) - error("Failed to get address of method " + method); - return; -// } - } - mci.setForwardedPointer(symbol.getAddress()); - if (!mci.hasCallingConvention()) { - Convention.Style cc = symbol.getInferredCallingConvention(); - if (cc != null) - mci.setCallingConvention(cc); - } - builder.addFunction(mci); - if (debug) - info("Registering " + method + " as C function " + symbol.getName()); - } - } - - public Pointer allocate(Class type, int constructorId, Object... args) { - if (CallbackInterface.class.isAssignableFrom(type)) { - if (constructorId != -1 || args.length != 0) - throw new RuntimeException("Callback should have a constructorId == -1 and no constructor args !"); - return null;//newCallbackInstance(type); - } - throw new RuntimeException("Cannot allocate instance of type " + type.getName() + " (unhandled NativeObject subclass)"); - } - - static final int defaultObjectSize = Platform.is64Bits() ? 8 : 4; - public static final String PROPERTY_bridj_c_defaultObjectSize = "bridj.c.defaultObjectSize"; - - public int getDefaultStructSize() { - String s = System.getProperty(PROPERTY_bridj_c_defaultObjectSize); - if (s != null) - try { - return Integer.parseInt(s); - } catch (Throwable th) { - error("Invalid value for property " + PROPERTY_bridj_c_defaultObjectSize + " : '" + s + "'"); - } - return defaultObjectSize; - } - public long sizeOf(Type structType, StructIO io) { - if (io == null) - io = StructIO.getInstance(Utils.getClass(structType), structType); - long size; - if (io == null || (size = io.getStructSize()) <= 0) - return getDefaultStructSize(); - return size; - } - - protected Set rootCallbackClasses = new HashSet(Arrays.asList(Callback.class, DynamicFunction.class)); - - protected Method getUniqueAbstractCallbackMethod(Class type) { - Class parent = null; - while ((parent = type.getSuperclass()) != null && !rootCallbackClasses.contains(parent)) { - type = parent; - } - - Method method = null; - for (Method dm : type.getDeclaredMethods()) { - int modifiers = dm.getModifiers(); - if (!Modifier.isAbstract(modifiers)) - continue; - - if (method == null) - method = dm; - else - throw new RuntimeException("Callback " + type.getName() + " has more than one abstract method (" + dm + " and " + method + ")"); - //break; - } - if (method == null) - throw new RuntimeException("Type doesn't have any abstract method : " + type.getName() + " (parent = " + parent.getName() + ")"); - return method; - } - - public Class getTypeForCast(Type type) { - Class typeClass = Utils.getClass(type); - if (CallbackInterface.class.isAssignableFrom(typeClass)) - return getCallbackNativeImplementer().getCallbackImplType((Class) typeClass, null); - else - return (Class)typeClass; - } - - /** - * Get a shared factory of native function wrappers that have a given signatures. - * @param library library to which the allocated native thunks will be bound (can be null, in which case the native allocations will be bound to {@link BridJ#getOrphanEntities() }) - * @param callingConvention calling convention used by the functions (if null, default is typically {@link org.bridj.ann.Convention.Style#CDecl}) - * @param returnType return type of the functions - * @param parameterTypes parameter types of the functions - * Also see {@link DynamicFunction} and {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) }. - */ - public DynamicFunctionFactory getDynamicFunctionFactory(NativeLibrary library, Convention.Style callingConvention, Type returnType, Type... parameterTypes) { - return getCallbackNativeImplementer().getDynamicCallback(library, callingConvention, returnType, parameterTypes); - } - - public static Pointer createCToJavaCallback(MethodCallInfo mci, Type t) { - mci.prependCallbackCC(); - final long handle = JNI.createCToJavaCallback(mci); - long peer = JNI.getActualCToJavaCallback(handle); - - final Throwable stackTrace = BridJ.debugPointers ? - new RuntimeException().fillInStackTrace() : null; - - return (Pointer)Pointer.pointerToAddress(peer, t, new Pointer.Releaser() { - - //@Override - public void release(Pointer p) { - if (BridJ.debugPointers) - BridJ.info("Freeing callback pointer " + p + "\n(Creation trace = \n\t" + Utils.toString(p.creationTrace).replaceAll("\n", "\n\t") + "\n)", new RuntimeException().fillInStackTrace()); - - if (BridJ.debugNeverFree) - return; - - JNI.freeCToJavaCallback(handle);//p.getPeer()); - } - }); - } - protected Pointer registerCallbackInstance(T instance) { - try { - Class c = instance.getClass(); - MethodCallInfo mci = new MethodCallInfo(getUniqueAbstractCallbackMethod(c)); - mci.setDeclaringClass(c); - mci.setJavaCallback(instance); - return createCToJavaCallback(mci, c); - } catch (Exception e) { - throw new RuntimeException("Failed to register callback instance of type " + instance.getClass().getName(), e); - } - } - - protected void setNativeObjectPeer(NativeObjectInterface instance, Pointer peer) { - ((NativeObject)instance).peer = (Pointer)peer; - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/CallIO.java b/libraries/BridJ/src/main/java/org/bridj/CallIO.java deleted file mode 100644 index 90a1d91c9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/CallIO.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.bridj; - -import org.bridj.dyncall.DyncallLibrary.DCstruct; -import java.lang.reflect.Constructor; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; -import static org.bridj.util.Utils.*; - -interface CallIO { - Object newInstance(long address); - void checkArg(Object arg); - long getDCStruct(); - long getPeer(Object o); - - public static class Utils { - public static CallIO createPointerCallIOToTargetType(Type targetType) { - return new CallIO.GenericPointerHandler(targetType); - } - public static > CallIO createValuedEnumCallIO(final Class enumClass) { - return new CallIO() { - - public Object newInstance(long value) { - return FlagSet.fromValue(value, enumClass); - } - - public void checkArg(Object e) { - if (!(e instanceof FlagSet)) - enumClass.cast(e); - } - public long getDCStruct() { - return 0; - } - - public long getPeer(Object o) { - return 0; - } - - }; - } - //static final Map instances = new HashMap(); - public static /*synchronized*/ CallIO createPointerCallIO(Type type) { - //CallIO io = instances.get(type); - //if (io == null) - // instances.put(type, io = ) - return createPointerCallIO(org.bridj.util.Utils.getClass(type), type); - } - public static CallIO createPointerCallIO(Class cl, Type type) { - if (cl == Pointer.class) - return createPointerCallIOToTargetType(getUniqueParameterizedTypeParameter(type)); - - assert TypedPointer.class.isAssignableFrom(cl); - return new CallIO.TypedPointerIO(((Class)cl)); - } - } - - public static class TypedPointerIO implements CallIO { - Class type; - Constructor constructor; - public TypedPointerIO(Class type) { - this.type = type; - try { - this.constructor = type.getConstructor(long.class); - } catch (Exception ex) { - throw new RuntimeException("Failed to create " + CallIO.class.getName() + " for type " + type.getName(), ex); - } - } - //@Override - public Pointer newInstance(long address) { - try { - return address == 0 ? null : (Pointer) constructor.newInstance(address); - } catch (Exception ex) { - throw new RuntimeException("Failed to instantiate pointer of type " + type.getName(), ex); - } - } - //@Override - public void checkArg(Object ptr) { - type.cast(ptr); - } - public long getDCStruct() { - return 0; - } - - public long getPeer(Object o) { - return Pointer.getPeer((Pointer)o); - } - } - - public static class NativeObjectHandler implements CallIO { - final Class nativeClass; - final Type nativeType; - final Pointer pStruct; - public NativeObjectHandler(Class type, Type t, Pointer pStruct) { - this.nativeClass = type; - this.nativeType = t; - this.pStruct = pStruct; - } - //@Override - public NativeObject newInstance(long address) { - return Pointer.pointerToAddress(address).getNativeObject(nativeClass); - } - //@Override - public void checkArg(Object ptr) { - if (ptr == null) - throw new IllegalArgumentException("Native object of type " + nativeClass.getName() + " passed by value cannot be given a null value !"); - } - public long getDCStruct() { - return Pointer.getPeer(pStruct); - } - public long getPeer(Object o) { - return Pointer.getAddress((NativeObject)o, nativeClass); - } - } - - public static class GenericPointerHandler implements CallIO { - Type targetType; - PointerIO pointerIO; - public GenericPointerHandler(Type targetType) { - this.targetType = targetType; - this.pointerIO = PointerIO.getInstance(targetType); - } - //@Override - public Pointer newInstance(long address) { - return Pointer.pointerToAddress(address, pointerIO); - } - //@Override - public void checkArg(Object ptr) { - //Pointer pointer = (Pointer)ptr; - //if (pointer.getIO() == null) - // pointer.setIO(pointerIO); - // TODO check existing pointerio ! - } - public long getDCStruct() { - return 0; - } - - public long getPeer(Object o) { - return Pointer.getPeer((Pointer)o); - } - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/Callback.java b/libraries/BridJ/src/main/java/org/bridj/Callback.java deleted file mode 100644 index f790a4ee1..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/Callback.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import org.bridj.Pointer; -import org.bridj.ann.Runtime; - -/** - * Native C callback (beware : don't let your callbacks be GC'd before they're used).
- * To protect a callback against the GC, you can keep a reference to your callback or use {@link BridJ#protectFromGC(org.bridj.NativeObject) } / {@link BridJ#unprotectFromGC(org.bridj.NativeObject) }.
- * A callback is a Java object with only one abstract method exposed as a C function pointer to the native world.
- * Here's an example of callback definition (use JNAerator to generate them automatically) : - *
{@code
- *  // typedef int (*MyCallback)(int a, int b);
- *  public static abstract class MyCallback extends Callback {
-		public abstract int doSomething(int a, int b);
-	}
- * }
- * @author Olivier Chafik - */ -@Runtime(CRuntime.class) -public abstract class Callback> extends NativeObject implements CallbackInterface { - public Pointer toPointer() { - return (Pointer)Pointer.pointerTo(this); - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/CallbackInterface.java b/libraries/BridJ/src/main/java/org/bridj/CallbackInterface.java deleted file mode 100644 index 4dff6557b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/CallbackInterface.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -/** - * For internal use in BridJ only : marks a callback - * @author ochafik - */ -public interface CallbackInterface extends NativeObjectInterface { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/CallbackNativeImplementer.java b/libraries/BridJ/src/main/java/org/bridj/CallbackNativeImplementer.java deleted file mode 100644 index 3d4f7a671..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/CallbackNativeImplementer.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.bridj; - -import org.bridj.util.ClassDefiner; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; -import java.io.FileNotFoundException; - -//import org.objectweb.asm.*; -import static org.objectweb.asm.Opcodes.*; - -import static org.bridj.util.JNIUtils.*; -import org.bridj.*; -import org.bridj.CRuntime.MethodCallInfoBuilder; -import org.bridj.NativeEntities.Builder; -import org.bridj.ann.Convention; -import org.bridj.util.ASMUtils; -import org.bridj.util.Pair; -import org.bridj.util.Utils; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.signature.SignatureWriter; - -//import org.objectweb.asm.attrs.*; -class CallbackNativeImplementer extends ClassLoader implements ClassDefiner { - - Map, Class> implClasses = new HashMap, Class>(); - String implNameSuffix = "_NativeImpl"; - final NativeEntities nativeEntities; - final CRuntime runtime; - volatile ClassDefiner classDefiner; - public CallbackNativeImplementer(NativeEntities nativeEntities, CRuntime runtime) { - super(Platform.getClassLoader()); - this.nativeEntities = nativeEntities; - this.runtime = runtime; - } - - public synchronized ClassDefiner getClassDefiner() { - if (classDefiner == null) { - classDefiner = PlatformSupport.getInstance().getClassDefiner(this, this); - } - return classDefiner; - } - - - /** - * The class created here is to be used to cast a pointer to a callback - * @param callbackType - */ - public synchronized Class getCallbackImplType(Class callbackType, NativeLibrary forcedLibrary) { - Class callbackImplType = implClasses.get(callbackType); - if (callbackImplType == null) { - try { - String callbackTypeName = callbackType.getName().replace('.', '/'); - String callbackTypeImplName = callbackTypeName.replace('$', '_') + implNameSuffix; - String sourceFile = callbackType.getSimpleName() + implNameSuffix + ".java"; - - Method callbackMethod = runtime.getUniqueAbstractCallbackMethod(callbackType); - - Class[] parameterTypes = callbackMethod.getParameterTypes(); - MethodCallInfo mci = new MethodCallInfo(callbackMethod); - String methodName = callbackMethod.getName(); - String methodSignature = mci.getJavaSignature();//mci.getASMSignature(); - - byte[] byteArray = emitBytes(sourceFile, callbackTypeName, callbackTypeImplName, methodName, methodSignature); - callbackImplType = getClassDefiner().defineClass(callbackTypeImplName.replace('/', '.'), byteArray); - implClasses.put(callbackType, callbackImplType); - runtime.register(callbackImplType, forcedLibrary, null); - } catch (Exception ex) { - throw new RuntimeException("Failed to create implementation class for callback type " + callbackType.getName() + " : " + ex, ex); - } - } - return (Class)callbackImplType; - } - protected Map>>, DynamicFunctionFactory> dynamicCallbacks = new HashMap>>, DynamicFunctionFactory>(); - - private static volatile long nextDynamicCallbackId = 0; - private static synchronized long getNextDynamicCallbackId() { - return nextDynamicCallbackId++; - } - - public synchronized DynamicFunctionFactory getDynamicCallback(NativeLibrary library, final Convention.Style callingConvention, Type returnType, Type... paramTypes) { - List list = new ArrayList(paramTypes.length + 1); - list.add(returnType); - list.addAll(Arrays.asList(paramTypes)); - Pair> pl = new Pair>(callingConvention, list); - Pair>> key = new Pair>>(library, pl); - DynamicFunctionFactory cb = dynamicCallbacks.get(key); - if (cb == null) { - try { - StringBuilder javaSig = new StringBuilder("("), desc = new StringBuilder(); - for (Type paramType : paramTypes) { - javaSig.append(getNativeSignature(Utils.getClass(paramType))); - desc.append(ASMUtils.typeDesc(paramType)); - } - javaSig.append(")").append(getNativeSignature(Utils.getClass(returnType))); - desc.append("To").append(ASMUtils.typeDesc(returnType)).append("_").append(getNextDynamicCallbackId()); - - String callbackTypeImplName = "org/bridj/dyncallbacks/" + desc; - String methodName = "apply"; - - byte[] byteArray = emitBytes("", DynamicFunction.class.getName().replace(".", "/"), callbackTypeImplName, methodName, javaSig.toString()); - Class callbackImplType = (Class)getClassDefiner().defineClass(callbackTypeImplName.replace('/', '.'), byteArray); - - Class[] paramClasses = new Class[paramTypes.length]; - for (int i = 0, n = paramTypes.length; i < n; i++) - paramClasses[i] = Utils.getClass(paramTypes[i]); - - MethodCallInfoBuilder methodCallInfoBuilder = new MethodCallInfoBuilder() { - public MethodCallInfo apply(Method method) throws FileNotFoundException { - MethodCallInfo mci = super.apply(method); - mci.setCallingConvention(callingConvention); - return mci; - } - }; - cb = new DynamicFunctionFactory(callbackImplType, callbackImplType.getMethod(methodName, paramClasses), methodCallInfoBuilder); - dynamicCallbacks.put(key, cb); - - runtime.register(callbackImplType, null, methodCallInfoBuilder); - - } catch (Throwable th) { - th.printStackTrace(); - throw new RuntimeException("Failed to create callback for " + list + " : " + th, th); - } - } - return cb; - } - private byte[] emitBytes(String sourceFile, String callbackTypeName, - String callbackTypeImplName, String methodName, - String methodSignature) { - ClassWriter cw = new ClassWriter(0); - cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, - callbackTypeImplName, null, - callbackTypeName, null); - - cw.visitSource(sourceFile, null); - -// { -// AnnotationVisitor av = cw.visitAnnotation(classSig(org.bridj.ann.Runtime.class), true); -// av.visit("value", Type.getType(classSig(CRuntime.class))); -// av.visitEnd(); -// } - { - MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(5, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, callbackTypeName, - "", "()V"); - mv.visitInsn(RETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", - "L" + callbackTypeImplName + ";", null, l0, l1, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - } - { - MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_NATIVE, methodName, methodSignature, null, null); - mv.visitEnd(); - } - cw.visitEnd(); - - return cw.toByteArray(); - } - - public Class defineClass(String className, byte[] data) throws ClassFormatError { - return defineClass(className, data, 0, data.length); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ComplexDouble.java b/libraries/BridJ/src/main/java/org/bridj/ComplexDouble.java deleted file mode 100644 index d80433303..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ComplexDouble.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bridj; -import org.bridj.ann.*; - -public class ComplexDouble extends StructObject { - @Field(0) - public double real() { - return this.io.getDoubleField(this, 0); - } - @Field(0) - public ComplexDouble real(double real) { - this.io.setDoubleField(this, 0, real); - return this; - } - @Field(1) - public double imag() { - return this.io.getDoubleField(this, 0); - } - @Field(1) - public ComplexDouble imag(double imag) { - this.io.setDoubleField(this, 0, imag); - return this; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/DefaultNativeList.java b/libraries/BridJ/src/main/java/org/bridj/DefaultNativeList.java deleted file mode 100644 index 50ff4955e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/DefaultNativeList.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import java.util.AbstractList; -import java.util.RandomAccess; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import static org.bridj.Pointer.*; - -/** - * TODO : smart rewrite by chunks for removeAll and retainAll ! - * @author ochafik - * @param - */ -class DefaultNativeList extends AbstractList implements NativeList, RandomAccess { - /* - * For optimization purposes, please look at AbstractList.java and AbstractCollection.java : - * http://www.koders.com/java/fidCFCB47A1819AB345234CC04B6A1EA7554C2C17C0.aspx?s=iso - * http://www.koders.com/java/fidA34BB0789922998CD34313EE49D61B06851A4397.aspx?s=iso - * - * We've reimplemented more methods than needed on purpose, for performance reasons (mainly using a native-optimized indexOf, that uses memmem and avoids deserializing too many elements) - */ - - final ListType type; - final PointerIO io; - volatile Pointer pointer; - volatile long size; - - public Pointer getPointer() { - return pointer; - } - - /** - * Create a native list that uses the provided storage and implementation strategy - * @param pointer - * @param type Implementation type - */ - DefaultNativeList(Pointer pointer, ListType type) { - if (pointer == null || type == null) - throw new IllegalArgumentException("Cannot build a " + getClass().getSimpleName() + " with " + pointer + " and " + type); - - this.io = pointer.getIO("Cannot create a list out of untyped pointer " + pointer); - this.type = type; - this.size = pointer.getValidElements(); - this.pointer = pointer; - } - - protected void checkModifiable() { - if (type == ListType.Unmodifiable) - throw new UnsupportedOperationException("This list is unmodifiable"); - } - - protected int safelyCastLongToInt(long i, String content) { - if (i > Integer.MAX_VALUE) - throw new RuntimeException(content + " is bigger than Java int's maximum value : " + i); - - return (int)i; - } - - @Override - public int size() { - return safelyCastLongToInt(size, "Size of the native list"); - } - - @Override - public void clear() { - checkModifiable(); - size = 0; - } - - @Override - public T get(int i) { - if (i >= size || i < 0) - throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size +")"); - - return pointer.get(i); - } - - @Override - public T set(int i, T e) { - checkModifiable(); - if (i >= size || i < 0) - throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size +")"); - - T old = pointer.get(i); - pointer.set(i, e); - return old; - } - - void add(long i, T e) { - checkModifiable(); - if (i > size || i < 0) - throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size +")"); - requireSize(size + 1); - if (i < size) { - pointer.moveBytesAtOffsetTo(i, pointer, i + 1, size - i); - } - pointer.set(i, e); - size++; - } - @Override - public void add(int i, T e) { - add((long)i, e); - } - - protected void requireSize(long newSize) { - if (newSize > pointer.getValidElements()) { - switch (type) { - case Dynamic: - long nextSize = newSize < 5 ? newSize + 1 : (long)(newSize * 1.6); - Pointer newPointer = allocateArray(io, nextSize); - pointer.copyTo(newPointer); - pointer = newPointer; - break; - case FixedCapacity: - throw new UnsupportedOperationException("This list has a fixed capacity, cannot grow its storage"); - case Unmodifiable: - // should not happen ! - checkModifiable(); - } - } - } - - T remove(long i) { - checkModifiable(); - if (i >= size || i < 0) - throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size +")"); - T old = pointer.get(i); - long targetSize = io.getTargetSize(); - pointer.moveBytesAtOffsetTo((i + 1) * targetSize, pointer, i * targetSize, targetSize); - size--; - return old; - } - - @Override - public T remove(int i) { - return remove((long)i); - } - - @Override - public boolean remove(Object o) { - checkModifiable(); - long i = indexOf(o, true, 0); - if (i < 0) - return false; - - remove(i); - return true; - } - - long indexOf(Object o, boolean last, int offset) { - Pointer pointer = this.pointer; - assert offset >= 0 && (last || offset > 0); - if (offset > 0) - pointer = pointer.next(offset); - - Pointer needle = allocate(io); - needle.set((T)o); - Pointer occurrence = last ? pointer.findLast(needle) : pointer.find(needle); - if (occurrence == null) - return -1; - - return occurrence.getPeer() - pointer.getPeer(); - } - - @Override - public int indexOf(Object o) { - return safelyCastLongToInt(indexOf(o, false, 0), "Index of the object"); - } - - @Override - public int lastIndexOf(Object o) { - return safelyCastLongToInt(indexOf(o, true, 0), "Last index of the object"); - } - - @Override - public boolean contains(Object o) { - return indexOf(o) >= 0; - } - - @Override - public boolean addAll(int i, Collection clctn) { - if (i >= 0 && i < size) - requireSize(size + clctn.size()); - return super.addAll(i, clctn); - } - - @Override - public Object[] toArray() { - return pointer.validElements(size).toArray(); - } - - @Override - public T[] toArray(T[] ts) { - return pointer.validElements(size).toArray(ts); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/DynamicCallback.java b/libraries/BridJ/src/main/java/org/bridj/DynamicCallback.java deleted file mode 100644 index 267f57407..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/DynamicCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bridj; - -public interface DynamicCallback { - R apply(Object... args); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/DynamicFunction.java b/libraries/BridJ/src/main/java/org/bridj/DynamicFunction.java deleted file mode 100644 index 6f77b21f9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/DynamicFunction.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -import static org.bridj.Pointer.*; - -/** - * Generic C function which invocation involves a bit of Java reflection.
- * To create a dynamic function, use {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } or {@link CRuntime#getDynamicFunctionFactory(org.bridj.NativeLibrary, org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) }. - * @author ochafik - * @param R Return type of the function (can be {@link java.lang.Void}) - */ -public abstract class DynamicFunction extends Callback { - /// Don't GC the factory, which holds the native callback handle - DynamicFunctionFactory factory; - Method method; - - protected DynamicFunction() {} - - public R apply(Object... args) { - try { - return (R) method.invoke(this, args); - } catch (Throwable th) { - th.printStackTrace(); - throw new RuntimeException("Failed to invoke callback" + " : " + th, th); - } - } - - @Override - public String toString() { - return method.toString(); - } - - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/DynamicFunctionFactory.java b/libraries/BridJ/src/main/java/org/bridj/DynamicFunctionFactory.java deleted file mode 100644 index 7dd57ad04..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/DynamicFunctionFactory.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bridj; - -import org.bridj.CRuntime.MethodCallInfoBuilder; -import org.bridj.ann.Convention; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -import static org.bridj.Pointer.*; - -/** - * Factory that is able to create dynamic functions bindings with a given signature - */ -public class DynamicFunctionFactory { - - final Constructor constructor; - final Method method; - final long callbackHandle; - - DynamicFunctionFactory(Class callbackClass, Method method, /*Convention.Style style,*/ MethodCallInfoBuilder methodCallInfoBuilder) { - try { - this.constructor = callbackClass.getConstructor(); - this.method = method; - - MethodCallInfo mci = methodCallInfoBuilder.apply(method); - callbackHandle = JNI.bindJavaToCCallbacks(mci); - } catch (Throwable th) { - th.printStackTrace(); - throw new RuntimeException("Failed to instantiate callback" + " : " + th, th); - } - } - - @Override - protected void finalize() throws Throwable { - if (BridJ.debugNeverFree) - return; - - JNI.freeJavaToCCallbacks(callbackHandle, 1); - } - - - public DynamicFunction newInstance(Pointer functionPointer) { - if (functionPointer == null) - return null; - - try { - DynamicFunction dcb = constructor.newInstance(); - dcb.peer = (Pointer) functionPointer; - dcb.method = method; - dcb.factory = this; - - return dcb; - } catch (Throwable th) { - th.printStackTrace(); - throw new RuntimeException("Failed to instantiate callback" + " : " + th, th); - } - } - - @Override - public String toString() { - return getClass().getSimpleName() + "(" + method + ")"; - } - - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/DyncallStructs.java b/libraries/BridJ/src/main/java/org/bridj/DyncallStructs.java deleted file mode 100644 index be17e6735..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/DyncallStructs.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bridj; - - -import org.bridj.StructIO.FieldDecl; -import java.lang.reflect.Type; -import java.util.List; -import org.bridj.StructIO.AggregatedFieldDesc; -import org.bridj.util.Utils; -import static org.bridj.dyncall.DyncallLibrary.*; - -class DyncallStructs { - Pointer struct; - - static int toDCAlignment(long structIOAlignment) { - return structIOAlignment <= 0 ? DEFAULT_ALIGNMENT : (int)structIOAlignment; - } - public static Pointer buildDCstruct(StructIO io) { - if (!BridJ.Switch.StructsByValue.enabled) - return null; - - List aggregatedFields = io.getAggregatedFields(); - Pointer struct = dcNewStruct(aggregatedFields.size(), toDCAlignment(io.getStructAlignment())).withReleaser(new Pointer.Releaser() { - public void release(Pointer p) { - dcFreeStruct(p.as(DCstruct.class)); - } - }); - fillDCstruct(io.structType, struct, aggregatedFields); - dcCloseStruct(struct); - - long expectedSize = io.getStructSize(); - long size = dcStructSize(struct); - - if (expectedSize != size) { - BridJ.error("Struct size computed for " + Utils.toString(io.structType) + " by BridJ (" + expectedSize + " bytes) and dyncall (" + size + " bytes) differ !"); - return null; - } - return struct; - } - protected static void fillDCstruct(Type structType, Pointer struct, List aggregatedFields) { - for (AggregatedFieldDesc aggregatedField : aggregatedFields) { - FieldDecl field = aggregatedField.fields.get(0); - Type fieldType = field.desc.nativeTypeOrPointerTargetType; - if (fieldType == null) - fieldType = field.desc.valueType; - Class fieldClass = Utils.getClass(fieldType); - - int alignment = toDCAlignment(aggregatedField.alignment); - long arrayLength = field.desc.arrayLength; - - if (StructObject.class.isAssignableFrom(fieldClass)) { - StructIO subIO = StructIO.getInstance(fieldClass, fieldType); - List subAggregatedFields = subIO.getAggregatedFields(); - - dcSubStruct(struct, subAggregatedFields.size(), alignment, arrayLength); - try { - fillDCstruct(subIO.structType, struct, subAggregatedFields); - } finally { - dcCloseStruct(struct); - } - } else { - int dctype; - if (fieldClass == int.class) - dctype = DC_SIGCHAR_INT; - else if (fieldClass == long.class || fieldClass == Long.class) { - // TODO handle weird cases - dctype = DC_SIGCHAR_LONGLONG; - } else if (fieldClass == short.class || fieldClass == char.class || fieldClass == Short.class || fieldClass == Character.class) - dctype = DC_SIGCHAR_SHORT; - else if (fieldClass == byte.class || fieldClass == boolean.class || fieldClass == Byte.class || fieldClass == Boolean.class) - dctype = DC_SIGCHAR_CHAR; // handle @IntBool annotation ? - else if (fieldClass == float.class || fieldClass == Float.class) - dctype = DC_SIGCHAR_FLOAT; - else if (fieldClass == double.class || fieldClass == Double.class) - dctype = DC_SIGCHAR_DOUBLE; - else if (Pointer.class.isAssignableFrom(fieldClass)) - dctype = DC_SIGCHAR_POINTER; - else - throw new IllegalArgumentException("Unable to create dyncall struct field for type " + Utils.toString(fieldType) + " in struct " + Utils.toString(structType)); - - dcStructField(struct, dctype, alignment, arrayLength); - } - } - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/EllipsisHelper.java b/libraries/BridJ/src/main/java/org/bridj/EllipsisHelper.java deleted file mode 100644 index a2188d42a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/EllipsisHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bridj; - -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -import org.bridj.NativeConstants.ValueType; - -class EllipsisHelper { - static ThreadLocal holders = new ThreadLocal() { - protected IntBuffer[] initialValue() { - return new IntBuffer[1]; - } - }; - public static IntBuffer unrollEllipsis(Object[] args) { - IntBuffer[] holder = holders.get(); - int n = args.length; - IntBuffer buf = holder[0]; - if (buf == null || buf.capacity() < n) { - buf = ByteBuffer.allocateDirect(n * 4).asIntBuffer(); - } - for (int i = 0; i < n; i++) { - Object arg = args[i]; - ValueType type; - if (arg == null || arg instanceof Pointer) - type = ValueType.ePointerValue; - else if (arg instanceof Integer) - type = ValueType.eIntValue; - else if (arg instanceof Long) - type = ValueType.eLongValue; - else if (arg instanceof Short) - type = ValueType.eShortValue; - else if (arg instanceof Double) - type = ValueType.eDoubleValue; - else if (arg instanceof Float) - type = ValueType.eFloatValue; - else if (arg instanceof Byte) - type = ValueType.eByteValue; - else if (arg instanceof Boolean) - type = ValueType.eBooleanValue; - else if (arg instanceof Character) - type = ValueType.eWCharValue; - else if (arg instanceof SizeT) { - type = ValueType.eSizeTValue; - args[i] = arg = ((SizeT)arg).longValue(); - } else if (arg instanceof CLong) { - type = ValueType.eCLongValue; - args[i] = arg = ((CLong)arg).longValue(); - } else if (arg instanceof NativeObject) { - type = ValueType.eNativeObjectValue; - } else - throw new IllegalArgumentException("Argument type not handled in variable argument calls : " + arg + " (" + arg.getClass().getName() + ")"); - - buf.put(i, type.ordinal()); - } - return buf; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/FlagSet.java b/libraries/BridJ/src/main/java/org/bridj/FlagSet.java deleted file mode 100644 index 634606667..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/FlagSet.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.WeakHashMap; - -/** - * Set of int-valued enum values that is itself int-valued (bitwise OR of all the values).
- * This helps use Java enums (that implement {@link ValuedEnum}) as combinable C flags (see {@link FlagSet#fromValues(Enum[]) fromValues(E...) }). - * @author ochafik - */ -public class FlagSet> implements ValuedEnum { - private final long value; - private final Class enumClass; - private E[] enumClassValues; - - protected FlagSet(long value, Class enumClass, E[] enumClassValues) { - this.enumClass = enumClass; - this.value = value; - this.enumClassValues = enumClassValues; - } - - private static Map, Object[]> enumsCache = new WeakHashMap, Object[]>(); - - @SuppressWarnings("unchecked") - private static synchronized > EE[] getValues(Class enumClass) { - EE[] values = (EE[])enumsCache.get(enumClass); - if (values == null) { - try { - Method valuesMethod = enumClass.getMethod("values"); - Class valuesType = valuesMethod.getReturnType(); - if (!valuesType.isArray() || !ValuedEnum.class.isAssignableFrom(valuesType.getComponentType())) - throw new RuntimeException(); - enumsCache.put(enumClass, values = (EE[])valuesMethod.invoke(null)); - } catch (Exception ex) { - throw new IllegalArgumentException("Class " + enumClass + " does not have a public static " + ValuedEnum.class.getName() + "[] values() method.", ex); - } - } - return (EE[])values; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof ValuedEnum)) - return false; - return value() == ((ValuedEnum)o).value(); - } - - @Override - public int hashCode() { - return ((Long)value()).hashCode(); - } - - //@Override - public Iterator iterator() { - return getMatchingEnums().iterator(); - } - public E toEnum() { - E nullMatch = null; - E match = null; - for (E e : getMatchingEnums()) { - if (((ValuedEnum)e).value() == 0) - nullMatch = e; - else if (match == null) - match = e; - else - throw new NoSuchElementException("More than one enum value corresponding to " + this + " : " + e + " and " + match + "..."); - } - if (match != null) - return match; - - if (value() == 0) - return nullMatch; - - throw new NoSuchElementException("No enum value corresponding to " + this); - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - b.append(enumClass.getSimpleName()).append("(").append(value()).append(" = "); - try { - boolean first = true; - for (E e : this.getMatchingEnums()) { - if (first) - first = false; - else - b.append(" | "); - b.append(e); - } - } catch (Throwable th) { - b.append("?"); - } - b.append(")"); - return b.toString(); - } - - public static > FlagSet fromValue(long value, Class enumClass) { - return new FlagSet(value, enumClass, null); - } - public static class IntFlagSet> extends FlagSet implements IntValuedEnum { - protected IntFlagSet(long value, Class enumClass, E[] enumClassValues) { - super(value, enumClass, enumClassValues); - } - } - public static > IntFlagSet fromValue(int value, Class enumClass) { - return new IntFlagSet(value, enumClass, null); - } - public static > FlagSet fromValue(ValuedEnum value) { - if (value instanceof Enum) - return FlagSet.fromValue(value.value(), (EE)value); - else - return (FlagSet)value; - } - public static > FlagSet fromValue(long value, EE... enumValue) { - return new FlagSet(value, null, enumValue); - } - public static > IntFlagSet fromValue(int value, EE... enumValue) { - return new IntFlagSet(value, null, enumValue); - } - /** - * Isolate bits that are set in the value.
- * For instance, {@code getBits(0xf)} yields {@literal 0x1, 0x2, 0x4, 0x8} - * @param value - * @return split bits, which give the value back if OR-ed all together. - */ - public static List getBits(final long value) { - List list = new ArrayList(); - for (int i = 0; i < 64; i++) { - long bit = 1L << i; - if ((value & bit) != 0) - list.add(bit); - } - return list; - } - - /** - * Get the integral value of this FlagSet. - * @return value of the flag set - */ - //@Override - public long value() { - return value; - } - - public Class getEnumClass() { - return enumClass; - } - - protected E[] getEnumClassValues() { - return enumClassValues == null ? enumClassValues = getValues(enumClass) : enumClassValues; - } - - /** - * Tests if the flagset value is equal to the OR combination of all the given values combined with bitwise OR operations.
- * The following C code : - *
{@code
-     * E v = ...; // E is an enum type
-     * if (v == (E_V1 | E_V2)) { ... }
-     * }
- * Can be translated to the following Java + BridJ code : - *
{@code
-     * FlagSet v = ...;
-     * if (v.is(E_V1, E_V2)) { ... }
-     * }
- */ - public boolean is(E... valuesToBeCombinedWithOR) { - return value() == orValue(valuesToBeCombinedWithOR); - } - - /** - * Tests if the flagset value is contains the OR combination of all the given values combined with bitwise OR operations.
- * The following C code : - *
{@code
-     * E v = ...; // E is an enum type
-     * if (v & (E_V1 | E_V2)) { ... }
-     * }
- * Can be translated to the following Java + BridJ code : - *
{@code
-     * FlagSet v = ...;
-     * if (v.has(E_V1, E_V2)) { ... }
-     * }
- */ - public boolean has(E... valuesToBeCombinedWithOR) { - return (value() & orValue(valuesToBeCombinedWithOR)) != 0; - } - - public FlagSet or(E... valuesToBeCombinedWithOR) { - return new FlagSet(value() | orValue(valuesToBeCombinedWithOR), enumClass, null); - } - - static > long orValue(E... valuesToBeCombinedWithOR) { - long value = 0; - for (E v : valuesToBeCombinedWithOR) - value |= ((ValuedEnum)v).value(); - return value; - } - public FlagSet without(E... valuesToBeCombinedWithOR) { - return new FlagSet(value() & ~orValue(valuesToBeCombinedWithOR), enumClass, null); - } - public FlagSet and(E... valuesToBeCombinedWithOR) { - return new FlagSet(value() & orValue(valuesToBeCombinedWithOR), enumClass, null); - } - - protected List getMatchingEnums() { - List ret = new ArrayList(); - if (enumClass != null) { - for (E e : getEnumClassValues()) { - long eMask = ((ValuedEnum)e).value(); - if ((value & eMask) == eMask) - ret.add((E)e); - } - } - - return ret; - } - - public static > FlagSet fromValues(E... enumValues) { - long value = 0; - Class cl = null; - for (E enumValue : enumValues) { - if (enumValue == null) - continue; - if (cl == null) - cl = enumValue.getClass(); - value |= ((ValuedEnum)enumValue).value(); - } - return new FlagSet(value, cl, enumValues); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/GenericCallback.java b/libraries/BridJ/src/main/java/org/bridj/GenericCallback.java deleted file mode 100644 index d6ea8269a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/GenericCallback.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -import static org.bridj.Pointer.*; - -/** - * Generic Java callback to be called from C. - * @author ochafik - */ -public interface GenericCallback { - public abstract Object apply(Object... args); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/HeadersReconstructor.java b/libraries/BridJ/src/main/java/org/bridj/HeadersReconstructor.java deleted file mode 100644 index bb2790e3f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/HeadersReconstructor.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bridj; -import java.util.*; -import java.io.*; -import static org.bridj.demangling.Demangler.*; - -/** - * Unfinished experiment to (partially) reconstruct a header out of parsed shared libraries symbols.
- * Beware: GCC does not add return types to mangled C++ signatures, so this will be left as '?' in the resulting sources. - * @author ochafik - */ -public class HeadersReconstructor { - - public static void reconstructHeaders(Iterable libraries, PrintWriter out) { - List orphanMembers = new ArrayList(); - Map> membersByClass = new HashMap>(); - for (NativeLibrary library : libraries) { - for (Symbol symbol : library.getSymbols()) { - MemberRef mr = symbol.getParsedRef(); - if (mr == null) - continue; - - TypeRef et = mr.getEnclosingType(); - if (et == null) - orphanMembers.add(mr); - else { - List mrs = membersByClass.get(et); - if (mrs == null) - membersByClass.put(et, mrs = new ArrayList()); - mrs.add(mr); - } - } - } - for (TypeRef tr : membersByClass.keySet()) - out.println("class " + tr + ";"); - - for (MemberRef mr : orphanMembers) - out.println(mr + ";"); - - for (Map.Entry> e : membersByClass.entrySet()) { - TypeRef tr = e.getKey(); - List mrs = e.getValue(); - out.println("class " + tr + " \n{"); - for (MemberRef mr : mrs) { - out.println("\t" + mr + ";"); - } - out.println("}"); - } - - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/IntValuedEnum.java b/libraries/BridJ/src/main/java/org/bridj/IntValuedEnum.java deleted file mode 100644 index 1fa31848c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/IntValuedEnum.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - - -/** - * Interface for Java enumerations that have an int value associated.
- * Beware: while this is the default, in C++ not all enums are ints (any integral types may be used for enums). - * @param type of the enum - */ -public interface IntValuedEnum> extends ValuedEnum { -} diff --git a/libraries/BridJ/src/main/java/org/bridj/LastError.java b/libraries/BridJ/src/main/java/org/bridj/LastError.java deleted file mode 100644 index cab7951a3..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/LastError.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bridj; - -import java.io.FileNotFoundException; -import org.bridj.ann.*; - -//import static org.bridj.LastError.Windows.*; -//import static org.bridj.LastError.Unix.*; -import static org.bridj.Pointer.*; - -/** - * Native error that correspond to the errno or GetLastError() mechanism.
- * Some C functions declare errors by marking an error code in errno or through SetLastError(int).
- * If you want their corresponding bindings to throw an exception whenever such an error was marked, simply make them throw this exception explicitly.
- * On Windows, BridJ will first check GetLastError(), then if no error was found it will check errno (on the other platforms only errno is available).
- * For instance, look at the following binding of the C-library strtoul function : - *
- * @Library("c")
- * {@code
- * public static native long strtoul(Pointer str, Pointer> endptr, int base) throws LastError;
- * }
- * @author Olivier Chafik - */ -public class LastError extends NativeError { - final int code; - final String description; - - LastError(int code, String description) { - super((description == null ? "?" : description.trim()) + " (error code = " + code + ")");//toString(code)); - this.code = code; - this.description = description; - if (BridJ.verbose) - BridJ.info("Last error detected : " + getMessage()); - } - - /** - * Native error code (as returned by errno or GetLastError()). - */ - public int getCode() { - return code; - } - - /** - * Native error description (as returned by strerror or FormatMessage). - */ - public String getDescription() { - return description; - } - - static void throwNewInstance(int code, String description) { - if (code == 0) - return; - - throw new LastError(code, description); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/MethodCallInfo.java b/libraries/BridJ/src/main/java/org/bridj/MethodCallInfo.java deleted file mode 100644 index 83551a312..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/MethodCallInfo.java +++ /dev/null @@ -1,615 +0,0 @@ -package org.bridj; -import java.lang.annotation.Annotation; -import static org.bridj.NativeConstants.*; -import static org.bridj.dyncall.DyncallLibrary.*; -import org.bridj.ann.Constructor; -//import org.bridj.cpp.CPPObject; - -import java.lang.reflect.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; -import org.bridj.ann.Convention; -import org.bridj.ann.DisableDirect; -import org.bridj.ann.Ptr; -import org.bridj.ann.Virtual; -import org.bridj.util.Utils; -import static org.bridj.util.AnnotationUtils.*; -/** - * Internal class that encapsulate all the knowledge about a native method call : signatures (ASM, dyncall and Java), calling convention, context... - * @author Olivier - */ -public class MethodCallInfo { - - /*public static class GenericMethodInfo { - Type returnType, paramsTypes[]; - } - GenericMethodInfo genericInfo = new GenericMethodInfo();*/ - List callIOs; - private Class declaringClass; - long nativeClass; - int returnValueType, paramsValueTypes[]; - Method method;//, definition; - String methodName, symbolName; - private long forwardedPointer; - String dcSignature; - String javaSignature; - String asmSignature; - Object javaCallback; - boolean isGenericCallback; - boolean isObjCBlock; - int virtualIndex = -1; - int virtualTableOffset = 0; - private int dcCallingConvention = DC_CALL_C_DEFAULT; - - boolean isVarArgs; - boolean isStatic; - boolean isCPlusPlus; - boolean direct; - boolean startsWithThis; - boolean bNeedsThisPointer; - boolean bThrowLastError; - - public MethodCallInfo(Method method) { - this(method, method); - } - static boolean derivesFrom(Class c, String className) { - while (c != null) { - if (c.getName().equals(className)) - return true; - c = c.getSuperclass(); - } - return false; - } - public MethodCallInfo(Type genericReturnType, Type[] parameterTypes, boolean prependJNIPointers) { - this(genericReturnType, new Annotation[0], parameterTypes, new Annotation[parameterTypes.length][], prependJNIPointers); - } - public MethodCallInfo(Type genericReturnType, Annotation[] returnAnnotations, Type[] parameterTypes, Annotation[][] paramsAnnotations, boolean prependJNIPointers) { - init(null, Utils.getClass(genericReturnType), genericReturnType, returnAnnotations, Utils.getClasses(parameterTypes), parameterTypes, paramsAnnotations, prependJNIPointers, false, true); - } - public MethodCallInfo(Method method, Method definition) { - this.setMethod(method); - //this.setDefinition(definition); - this.setDeclaringClass(method.getDeclaringClass()); - symbolName = methodName; - - int modifiers = method.getModifiers(); - isStatic = Modifier.isStatic(modifiers); - isVarArgs = method.isVarArgs(); - boolean isNative = Modifier.isNative(modifiers); - boolean isVirtual = isAnnotationPresent(Virtual.class, definition); - boolean isDirectModeAllowed = - getInheritableAnnotation(DisableDirect.class, definition) == null && - BridJ.isDirectModeEnabled(); - - isCPlusPlus = !isStatic && derivesFrom(method.getDeclaringClass(), "org.bridj.cpp.CPPObject"); - isObjCBlock = !isStatic && derivesFrom(method.getDeclaringClass(), "org.bridj.objc.ObjCBlock"); - - init( - method, - method.getReturnType(), method.getGenericReturnType(), method.getAnnotations(), - method.getParameterTypes(), method.getGenericParameterTypes(), method.getParameterAnnotations(), - isNative, - isVirtual, - isDirectModeAllowed - ); - - Convention cc = getInheritableAnnotation(Convention.class, definition); - if (cc != null) { - setCallingConvention(cc.value()); - } - List> exceptionTypes = Arrays.asList(definition.getExceptionTypes()); - if (!exceptionTypes.isEmpty()) { - this.direct = false; // there is no crash / exception protection for direct raw calls - if (exceptionTypes.contains(LastError.class)) - this.bThrowLastError = true; - } - - } - protected void init(AnnotatedElement annotatedElement, Class returnType, Type genericReturnType, Annotation[] returnAnnotations, Class[] parameterTypes, Type[] genericParameterTypes, Annotation[][] paramsAnnotations, boolean prependJNIPointers, boolean isVirtual, boolean isDirectModeAllowed) { - assert returnType != null; - assert genericReturnType != null; - assert parameterTypes != null; - assert genericParameterTypes != null; - assert returnAnnotations != null; - assert parameterTypes.length == genericParameterTypes.length; - assert paramsAnnotations.length == genericParameterTypes.length; - - int nParams = genericParameterTypes.length; - paramsValueTypes = new int[nParams]; - - direct = isDirectModeAllowed; // TODO on native side : test number of parameters (on 64 bits win : must be <= 4) - - StringBuilder - javaSig = new StringBuilder(64), - asmSig = new StringBuilder(64), - dcSig = new StringBuilder(16); - javaSig.append('('); - asmSig.append('('); - if (prependJNIPointers)//!isCPlusPlus) - dcSig.append(DC_SIGCHAR_POINTER).append(DC_SIGCHAR_POINTER); // JNIEnv*, jobject: always present in native-bound functions - - if (BridJ.debug) - BridJ.info("Analyzing " + (declaringClass == null ? "anonymous method" : declaringClass.getName() + "." + methodName)); - - if (isObjCBlock) - appendToSignature(0, ValueType.ePointerValue, Pointer.class, Pointer.class, null, dcSig, null); - - for (int iParam = 0; iParam < nParams; iParam++) { -// Options paramOptions = paramsOptions[iParam] = new Options(); - Type genericParameterType = genericParameterTypes[iParam]; - Class parameterType = parameterTypes[iParam]; - - ValueType paramValueType = getValueType(iParam, nParams, parameterType, genericParameterType, null, paramsAnnotations[iParam]); - if (BridJ.veryVerbose) - BridJ.info("\tparam " + paramValueType); - paramsValueTypes[iParam] = paramValueType.ordinal(); - - appendToSignature(iParam, paramValueType, parameterType, genericParameterType, javaSig, dcSig, asmSig); - } - javaSig.append(')'); - asmSig.append(')'); - dcSig.append(')'); - - ValueType retType = getValueType(-1, nParams, returnType, genericReturnType, annotatedElement, returnAnnotations); - if (BridJ.veryVerbose) - BridJ.info("\treturns " + retType); - appendToSignature(-1, retType, returnType, genericReturnType, javaSig, dcSig, asmSig); - returnValueType = retType.ordinal(); - - javaSignature = javaSig.toString(); - asmSignature = asmSig.toString(); - dcSignature = dcSig.toString(); - - isCPlusPlus = isCPlusPlus || isVirtual; - - if (isCPlusPlus && !isStatic) { - if (!startsWithThis) - direct = false; - bNeedsThisPointer = true; - if (Platform.isWindows()) { - if (!Platform.is64Bits()) - setDcCallingConvention(DC_CALL_C_X86_WIN32_THIS_MS); - } else { - //if (!Platform.is64Bits()) - // setDcCallingConvention(DC_CALL_C_X86_WIN32_THIS_GNU); - } - } - - if (nParams > Platform.getMaxDirectMappingArgCount()) - this.direct = false; - - if (BridJ.veryVerbose) { - BridJ.info("\t-> direct " + direct); - BridJ.info("\t-> javaSignature " + javaSignature); - BridJ.info("\t-> callIOs " + callIOs); - BridJ.info("\t-> asmSignature " + asmSignature); - BridJ.info("\t-> dcSignature " + dcSignature); - } - - if (BridJ.veryVerbose) - BridJ.info((direct ? "[mappable as direct] " : "[not mappable as direct] ") + method); - } - - boolean hasCC; - public boolean hasCallingConvention() { - return hasCC; - } - public void setCallingConvention(Convention.Style style) { - if (style == null) - return; - - if (!Platform.isWindows() || Platform.is64Bits()) - return; - - switch (style) { - case FastCall: - this.direct = false; - setDcCallingConvention(Platform.isWindows() ? DC_CALL_C_X86_WIN32_FAST_MS : DC_CALL_C_DEFAULT); // TODO allow GCC-compiled C++ libs on windows - break; - case Pascal: - case StdCall: - this.direct = false; - setDcCallingConvention(DC_CALL_C_X86_WIN32_STD); - break; - case ThisCall: - this.direct = false; - setDcCallingConvention(Platform.isWindows() ? DC_CALL_C_X86_WIN32_THIS_MS : DC_CALL_C_DEFAULT); - } - if (BridJ.veryVerbose) - BridJ.info("Setting CC " + style + " (-> " + dcCallingConvention + ") for " + methodName); - - } - void addCallIO(CallIO handler) { - if (callIOs == null) - callIOs = new ArrayList(); - callIOs.add(handler); - } - public CallIO[] getCallIOs() { - if (callIOs == null) - return new CallIO[0]; - return callIOs.toArray(new CallIO[callIOs.size()]); - } - - public void prependCallbackCC() { - char cc = getDcCallbackConvention(getDcCallingConvention()); - if (cc == 0) - return; - - dcSignature = String.valueOf(DC_SIGCHAR_CC_PREFIX) + String.valueOf(cc) + dcSignature; - } - public String getDcSignature() { - return dcSignature; - } - public String getJavaSignature() { - return javaSignature; - } - public String getASMSignature() { - return asmSignature; - } - boolean getBoolAnnotation(Class ac, AnnotatedElement element, Annotation... directAnnotations) { - Annotation ann = getAnnotation(ac, element, directAnnotations); - return ann != null; - } - public ValueType getValueType(int iParam, int nParams, Class c, Type t, AnnotatedElement element, Annotation... directAnnotations) { - boolean isPtr = isAnnotationPresent(Ptr.class, element, directAnnotations); - boolean isCLong = isAnnotationPresent(org.bridj.ann.CLong.class, element, directAnnotations); - Constructor cons = getAnnotation(Constructor.class, element, directAnnotations); - - if (isPtr || cons != null || isCLong) { - if (!(c == Long.class || c == Long.TYPE)) - throw new RuntimeException("Annotation should only be used on a long parameter, not on a " + c.getName()); - - if (isPtr) { - if (!Platform.is64Bits()) - direct = false; - } else if (isCLong) { - if (Platform.CLONG_SIZE != 8) - direct = false; - } else if (cons != null) { - isCPlusPlus = true; - startsWithThis = true; - if (iParam != 0) - throw new RuntimeException("Annotation " + Constructor.class.getName() + " cannot have more than one (long) argument"); - } - return ValueType.eSizeTValue; - } - if (c == null || c.equals(Void.TYPE)) - return ValueType.eVoidValue; - if (c == Integer.class || c == Integer.TYPE) - return ValueType.eIntValue; - if (c == Long.class || c == Long.TYPE) { - return !isPtr || Platform.is64Bits() ? ValueType.eLongValue : ValueType.eIntValue; - } - if (c == Short.class || c == Short.TYPE) - return ValueType.eShortValue; - if (c == Byte.class || c == Byte.TYPE) - return ValueType.eByteValue; - if (c == Boolean.class || c == Boolean.TYPE) - return ValueType.eBooleanValue; - if (c == Float.class || c == Float.TYPE) { - usesFloats(); - return ValueType.eFloatValue; - } - if (c == char.class || c == Character.TYPE) { - if (Platform.WCHAR_T_SIZE != 2) - direct = false; - return ValueType.eWCharValue; - } - if (c == Double.class || c == Double.TYPE) { - usesFloats(); - return ValueType.eDoubleValue; - } - if (c == CLong.class) { - direct = false; - return ValueType.eCLongObjectValue; - } - if (c == SizeT.class) { - direct = false; - return ValueType.eSizeTObjectValue; - } - if (c == TimeT.class) { - direct = false; - return ValueType.eTimeTObjectValue; - } - if (Pointer.class.isAssignableFrom(c)) { - direct = false; - CallIO cio = CallIO.Utils.createPointerCallIO(c, t); - if (BridJ.veryVerbose) - BridJ.info("CallIO : " + cio); - addCallIO(cio); - return ValueType.ePointerValue; - } - if (c.isArray() && iParam == nParams - 1) { - direct = false; - return ValueType.eEllipsis; - } - if (ValuedEnum.class.isAssignableFrom(c)) { - direct = false; - CallIO cio = CallIO.Utils.createValuedEnumCallIO((Class)Utils.getClass(Utils.getUniqueParameterizedTypeParameter(t))); - if (BridJ.veryVerbose) - BridJ.info("CallIO : " + cio); - addCallIO(cio); - - return ValueType.eIntFlagSet; - } - if (NativeObject.class.isAssignableFrom(c)) { - Pointer pStruct = null; - if (StructObject.class.isAssignableFrom(c)) { - StructIO io = StructIO.getInstance(c, t); - try { - pStruct = DyncallStructs.buildDCstruct(io); - } catch (Throwable th) { - BridJ.error("Unable to create low-level struct metadata for " + Utils.toString(t) + " : won't be able to use it as a by-value function argument.", th); - } - } - addCallIO(new CallIO.NativeObjectHandler((Class)c, t, pStruct)); - direct = false; - return ValueType.eNativeObjectValue; - } - - throw new NoSuchElementException("No " + ValueType.class.getSimpleName() + " for class " + c.getName()); - } - void usesFloats() { - /* - if (direct && Platform.isMacOSX()) { - direct = false; - assert BridJ.warning("[unstable direct] FIXME Disable direct call due to float/double usage in " + method); - } - */ - } - - public void appendToSignature(int iParam, ValueType type, Class parameterType, Type genericParameterType, StringBuilder javaSig, StringBuilder dcSig, StringBuilder asmSig) { - char dcChar; - String javaChar, asmChar = null; - switch (type) { - case eVoidValue: - dcChar = DC_SIGCHAR_VOID; - javaChar = "V"; - break; - case eIntValue: - dcChar = DC_SIGCHAR_INT; - javaChar = "I"; - break; - case eLongValue: - dcChar = DC_SIGCHAR_LONGLONG; - javaChar = "J"; - break; - case eSizeTValue: - javaChar = "J"; - if (Platform.SIZE_T_SIZE == 8) { - dcChar = DC_SIGCHAR_LONGLONG; - } else { - dcChar = DC_SIGCHAR_INT; - direct = false; - } - break; - case eShortValue: - dcChar = DC_SIGCHAR_SHORT; - javaChar = "S"; - break; - case eDoubleValue: - dcChar = DC_SIGCHAR_DOUBLE; - javaChar = "D"; - break; - case eFloatValue: - dcChar = DC_SIGCHAR_FLOAT; - javaChar = "F"; - break; - case eByteValue: - dcChar = DC_SIGCHAR_CHAR; - javaChar = "B"; - break; - case eBooleanValue: - dcChar = DC_SIGCHAR_BOOL; - javaChar = "Z"; - break; - case eWCharValue: - switch (Platform.WCHAR_T_SIZE) { - case 1: - dcChar = DC_SIGCHAR_CHAR; - direct = false; - break; - case 2: - dcChar = DC_SIGCHAR_SHORT; - break; - case 4: - dcChar = DC_SIGCHAR_INT; - direct = false; - break; - default: - throw new RuntimeException("Unhandled sizeof(wchar_t) in GetJavaTypeSignature: " + Platform.WCHAR_T_SIZE); - } - javaChar = "C"; - break; - case eIntFlagSet: - dcChar = DC_SIGCHAR_INT; - javaChar = "L" + parameterType.getName().replace('.', '/') + ";";//"Lorg/bridj/ValuedEnum;"; - direct = false; - break; - case eCLongObjectValue: - dcChar = DC_SIGCHAR_POINTER; - javaChar = "Lorg/bridj/CLong;"; - direct = false; - break; - case eSizeTObjectValue: - dcChar = DC_SIGCHAR_POINTER; - javaChar = "Lorg/bridj/SizeT;"; - direct = false; - break; - case eTimeTObjectValue: - dcChar = DC_SIGCHAR_POINTER; - javaChar = "Lorg/bridj/TimeT;"; - direct = false; - break; - case ePointerValue: - dcChar = DC_SIGCHAR_POINTER; - javaChar = "L" + parameterType.getName().replace('.', '/') + ";"; -// javaChar = "Lorg/bridj/Pointer;"; - direct = false; - break; - case eNativeObjectValue: - dcChar = DC_SIGCHAR_STRUCT; // TODO : unroll struct signature ? - javaChar = "L" + parameterType.getName().replace('.', '/') + ";"; - direct = false; -// if (parameterType.equals(declaringClass)) { -// // special case of self-returning pointers -// dcChar = DC_SIGCHAR_POINTER; - break; - case eEllipsis: - javaChar = "[Ljava/lang/Object;"; - dcChar = '?'; - break; - default: - direct = false; - throw new RuntimeException("Unhandled " + ValueType.class.getSimpleName() + ": " + type); - } - if (genericParameterType instanceof ParameterizedType && iParam < 0) - { - ParameterizedType pt = (ParameterizedType)genericParameterType; - // TODO handle all cases !!! - Type[] ts = pt.getActualTypeArguments(); - if (ts != null && ts.length == 1) { - Type t = ts[0]; - if (t instanceof ParameterizedType) - t = ((ParameterizedType)t).getRawType(); - if (t instanceof Class) { - Class c = (Class)t; - if (javaChar.endsWith(";")) { - asmChar = javaChar.substring(0, javaChar.length() - 1) + "<*L" + c.getName().replace('.', '/') + ";>"; - //asmChar += ";"; - } - } - } - } - if (javaSig != null) - javaSig.append(javaChar); - if (asmChar == null) - asmChar = javaChar; - if (asmSig != null) - asmSig.append(asmChar); - if (dcSig != null) - dcSig.append(dcChar); - } -/* - public void setDefinition(Method definition) { - this.definition = definition; - } - - public Method getDefinition() { - return definition; - } -*/ - - - public void setMethod(Method method) { - this.method = method; - if (method != null) - this.methodName = method.getName(); - if (declaringClass == null) - setDeclaringClass(method.getDeclaringClass()); - - } - - public void setJavaSignature(String javaSignature) { - this.javaSignature = javaSignature; - } - - - - public Method getMethod() { - return method; - } - - - public void setDeclaringClass(Class declaringClass) { - this.declaringClass = declaringClass; - } - - - public Class getDeclaringClass() { - return declaringClass; - } - - - public void setForwardedPointer(long forwardedPointer) { - this.forwardedPointer = forwardedPointer; - } - - - public long getForwardedPointer() { - return forwardedPointer; - } - - - /** - * Used for C++ virtual indexes and for struct fields ids - * @param virtualIndex - */ - public void setVirtualIndex(int virtualIndex) { - //new RuntimeException("Setting virtualIndex of " + getMethod().getName() + " = " + virtualIndex).printStackTrace(); - this.virtualIndex = virtualIndex; - - if (BridJ.veryVerbose) { - BridJ.info("\t-> virtualIndex " + virtualIndex); - } - } - - - public int getVirtualIndex() { - return virtualIndex; - } - - public String getSymbolName() { - return symbolName; - } - public void setSymbolName(String symbolName) { - this.symbolName = symbolName; - } - - static char getDcCallbackConvention(int dcCallingConvention) { - switch (dcCallingConvention) { - case DC_CALL_C_X86_WIN32_STD : - return DC_SIGCHAR_CC_STDCALL; - case DC_CALL_C_X86_WIN32_FAST_MS : - return DC_SIGCHAR_CC_FASTCALL_MS; - case DC_CALL_C_X86_WIN32_FAST_GNU : - return DC_SIGCHAR_CC_FASTCALL_GNU; - case DC_CALL_C_X86_WIN32_THIS_MS : - return DC_SIGCHAR_CC_THISCALL_MS; - default: - return 0; - } - } - - public void setDcCallingConvention(int dcCallingConvention) { - hasCC = true; - this.dcCallingConvention = dcCallingConvention; - } - - - public int getDcCallingConvention() { - return dcCallingConvention; - } - - public Object getJavaCallback() { - return javaCallback; - } - - public void setJavaCallback(Object javaCallback) { - this.javaCallback = javaCallback; - } - - public void setGenericCallback(boolean genericCallback) { - this.isGenericCallback = genericCallback; - } - - public boolean isGenericCallback() { - return isGenericCallback; - } - - public void setNativeClass(long nativeClass) { - this.nativeClass = nativeClass; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeConstants.java b/libraries/BridJ/src/main/java/org/bridj/NativeConstants.java deleted file mode 100644 index e4721f0ab..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeConstants.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -/** - * Internal constants used in BridJ's native library. - * @author Olivier - */ -class NativeConstants { - /** - * BridJ constants - */ - enum ValueType { - eVoidValue, - eWCharValue, - eCLongValue, - eCLongObjectValue, - eSizeTValue, - eSizeTObjectValue, - eIntValue, - eShortValue, - eByteValue, - eBooleanValue, - eLongValue, - eDoubleValue, - eFloatValue, - ePointerValue, - eEllipsis, - eIntFlagSet, - eNativeObjectValue, - eTimeTObjectValue - } - - /** - * BridJ constants - */ - enum CallbackType { - eJavaCallbackToNativeFunction, - eNativeToJavaCallback, - eJavaToNativeFunction, - eJavaToVirtualMethod - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeEntities.java b/libraries/BridJ/src/main/java/org/bridj/NativeEntities.java deleted file mode 100644 index 0e8e070e0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeEntities.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bridj; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Collection of handles to natively-bound classes and methods (which native resources can be released all at once). - * @author ochafik - */ -public class NativeEntities { - static class CBInfo { - long handle; - int size; - public CBInfo(long handle, int size) { - this.handle = handle; - this.size = size; - } - - } - Map, CBInfo> - functions = new HashMap, CBInfo>(), - virtualMethods = new HashMap, CBInfo>(), - //getters = new HashMap, CBInfo>(), - //setters = new HashMap, CBInfo>(), - javaToNativeCallbacks = new HashMap, CBInfo>(), - //cppMethods = new HashMap, CBInfo>(), - objcMethodInfos = new HashMap, CBInfo>(); - - /** - * Helper class to build a NativeEntities instance easily. - */ - public static class Builder { - List - functionInfos = new ArrayList(), - virtualMethods = new ArrayList(), - javaToNativeCallbacks = new ArrayList(), - //getters = new ArrayList(), - cppMethodInfos = new ArrayList(), - objcMethodInfos = new ArrayList(); - //List getterInfos = new ArrayList(); - - public void addFunction(MethodCallInfo info) { - functionInfos.add(info); - } - public void addVirtualMethod(MethodCallInfo info) { - virtualMethods.add(info); - } - /*public void addGetter(MethodCallInfo info) { - getters.add(info); - } - public void addSetter(MethodCallInfo info) { - getters.add(info); - }*/ - public void addJavaToNativeCallback(MethodCallInfo info) { - javaToNativeCallbacks.add(info); - } - public void addMethodFunction(MethodCallInfo info) { - cppMethodInfos.add(info); - }//*/ - public void addObjCMethod(MethodCallInfo info) { - objcMethodInfos.add(info); - } - } - - /** - * Free everything (native callbacks, bindings, etc...).
- * Called automatically by {@link NativeEntities#finalize()} upon garbage collection. - */ - public void release() { - if (BridJ.debugNeverFree) - return; - - for (CBInfo callbacks : functions.values()) - JNI.freeCFunctionBindings(callbacks.handle, callbacks.size); - - /* - for (CBInfo callbacks : cppMethods.values()) - JNI.freeCPPMethodBindings(callbacks.handle, callbacks.size); - //*/ - for (CBInfo callbacks : javaToNativeCallbacks.values()) - JNI.freeJavaToCCallbacks(callbacks.handle, callbacks.size); - - for (CBInfo callbacks : virtualMethods.values()) - JNI.freeVirtualMethodBindings(callbacks.handle, callbacks.size); - - //for (CBInfo callbacks : getters.values()) - // JNI.freeGetters(callbacks.handle, callbacks.size); - - for (CBInfo callbacks : objcMethodInfos.values()) - JNI.freeObjCMethodBindings(callbacks.handle, callbacks.size); - } - @Override - public void finalize() { - release(); - } - public void addDefinitions(Class type, Builder builder) { - int n; - try { - - n = builder.functionInfos.size(); - if (n != 0) - functions.put(type, new CBInfo(JNI.bindJavaMethodsToCFunctions(builder.functionInfos.toArray(new MethodCallInfo[n])), n)); - - n = builder.virtualMethods.size(); - if (n != 0) - virtualMethods.put(type, new CBInfo(JNI.bindJavaMethodsToVirtualMethods(builder.virtualMethods.toArray(new MethodCallInfo[n])), n)); - - n = builder.javaToNativeCallbacks.size(); - if (n != 0) - javaToNativeCallbacks.put(type, new CBInfo(JNI.bindJavaToCCallbacks(builder.javaToNativeCallbacks.toArray(new MethodCallInfo[n])), n)); - - /* - n = builder.cppMethodInfos.size(); - if (n != 0) - cppMethods.put(type, new CBInfo(JNI.bindJavaMethodsToCPPMethods(builder.cppMethodInfos.toArray(new MethodCallInfo[n])), n)); - //*/ - n = builder.objcMethodInfos.size(); - if (n != 0) - objcMethodInfos.put(type, new CBInfo(JNI.bindJavaMethodsToObjCMethods(builder.objcMethodInfos.toArray(new MethodCallInfo[n])), n)); - - /*n = builder.getters.size(); - if (n != 0) - getters.put(type, new CBInfo(JNI.bindGetters(builder.getters.toArray(new MethodCallInfo[n])), n)); - */ - } catch (Throwable th) { - assert BridJ.error("Failed to add native definitions for class " + type.getName(), th); - } - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeError.java b/libraries/BridJ/src/main/java/org/bridj/NativeError.java deleted file mode 100644 index ea1c3a68f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeError.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj; - -import static org.bridj.SignalConstants.*; -import static java.lang.Long.toHexString; -/** - * Native error encapsulated as a Java error. - * @author ochafik - */ -public abstract class NativeError extends Error { - protected NativeError(String message) { - super(message); - } - static String toHex(long address) { - return "0x" + Long.toHexString(address); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeLibrary.java b/libraries/BridJ/src/main/java/org/bridj/NativeLibrary.java deleted file mode 100644 index 126984d12..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeLibrary.java +++ /dev/null @@ -1,367 +0,0 @@ -/** - * - */ -package org.bridj; - -import java.io.*; -import java.util.regex.*; -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Constructor; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Arrays; - -import org.bridj.demangling.Demangler.DemanglingException; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.demangling.Demangler.Symbol; -import org.bridj.ann.Virtual; -import org.bridj.demangling.GCC4Demangler; -import org.bridj.demangling.VC9Demangler; -import java.lang.reflect.Type; -import static org.bridj.Pointer.*; -import static org.bridj.util.AnnotationUtils.*; - -import java.util.Collection; -import org.bridj.Platform.DeleteFiles; -import org.bridj.demangling.Demangler; -import org.bridj.util.ProcessUtils; -import org.bridj.util.StringUtils; - -/** - * Representation of a native shared library, with symbols retrieval / matching facilities.
- * This class is not meant to be used by end users, it's used by pluggable runtimes instead. - * @author ochafik - */ -public class NativeLibrary { - volatile long handle, symbols; - String path; - final File canonicalFile; - //Map, long[]> callbacks = new HashMap, long[]>(); - NativeEntities nativeEntities = new NativeEntities(); - - Map addrToName; - Map nameToSym; -// Map nameToAddr; - - - protected NativeLibrary(String path, long handle, long symbols) throws IOException { - this.path = path; - this.handle = handle; - this.symbols = symbols; - this.canonicalFile = path == null ? null : new File(path).getCanonicalFile(); - - Platform.addNativeLibrary(this); - } - - long getSymbolsHandle() { - return symbols; - } - NativeEntities getNativeEntities() { - return nativeEntities; - } - static String followGNULDScript(String path) { - try { - Reader r = new FileReader(path); - try { - char c; - while ((c = (char)r.read()) == ' ' || c == '\t' || c == '\n') {} - if (c == '/' && r.read() == '*') { - BufferedReader br = new BufferedReader(r); - r = br; - String line; - StringBuilder b = new StringBuilder("/*"); - while ((line = br.readLine()) != null) - b.append(line).append('\n'); - String src = b.toString(); - Pattern ldGroupPattern = Pattern.compile("GROUP\\s*\\(\\s*([^\\s)]+)[^)]*\\)"); - Matcher m = ldGroupPattern.matcher(src); - if (m.find()) { - String actualPath = m.group(1); - if (BridJ.verbose) - BridJ.info("Parsed LD script '" + path + "', found absolute reference to '" + actualPath + "'"); - return actualPath; - } else { - BridJ.error("Failed to parse LD script '" + path + "' !"); - } - } - } finally { - r.close(); - } - } catch (Throwable th) { - BridJ.error("Unexpected error: " + th, th); - } - return path; - } - public static NativeLibrary load(String path) throws IOException { - long handle = 0; - File file = new File(path); - boolean exists = file.exists(); - if (file.isAbsolute() && !exists) - return null; - - if (Platform.isUnix() && exists) - path = followGNULDScript(path); - - handle = JNI.loadLibrary(path); - if (handle == 0) - return null; - long symbols = JNI.loadLibrarySymbols(path); - return new NativeLibrary(path, handle, symbols); - } - - /*public boolean methodMatchesSymbol(Class declaringClass, Method method, String symbol) { - return symbol.contains(method.getName()) && symbol.contains(declaringClass.getSimpleName()); - }*/ - - long getHandle() { - if (path != null && handle == 0) - throw new RuntimeException("Library was released and cannot be used anymore"); - return handle; - } - @Override - protected void finalize() throws Throwable { - release(); - } - public synchronized void release() { - if (handle == 0) - return; - - if (BridJ.verbose) - BridJ.info("Releasing library '" + path + "'"); - - nativeEntities.release(); - - JNI.freeLibrarySymbols(symbols); - JNI.freeLibrary(handle); - handle = 0; - - if (canonicalFile != null && Platform.temporaryExtractedLibraryCanonicalFiles.remove(canonicalFile)) { - if (canonicalFile.delete()) { - if (BridJ.verbose) - BridJ.info("Deleted temporary library file '" + canonicalFile + "'"); - } else - BridJ.error("Failed to delete temporary library file '" + canonicalFile + "'"); - } - - } - public Pointer getSymbolPointer(String name) { - return pointerToAddress(getSymbolAddress(name)); - } - public long getSymbolAddress(String name) { - if (nameToSym != null) { - Symbol addr = nameToSym.get(name); -// long addr = nameToAddr.get(name); -// if (addr != 0) - if (addr != null) - return addr.getAddress(); - } - long address = JNI.findSymbolInLibrary(getHandle(), name); - if (address == 0) - address = JNI.findSymbolInLibrary(getHandle(), "_" + name); - return address; - } - - public synchronized Symbol getSymbol(AnnotatedElement member) throws FileNotFoundException { - org.bridj.ann.Symbol mg = getAnnotation(org.bridj.ann.Symbol.class, member); - String name = null; - if (member instanceof Member) - name = ((Member)member).getName(); - - List names = new ArrayList(); - if (mg != null) - names.addAll(Arrays.asList(mg.value())); - if (name != null) - names.add(name); - - for (String n : names) - { - Symbol handle = getSymbol(n); - if (handle == null) - handle = getSymbol("_" + n); - if (handle == null) - handle = getSymbol(n + (Platform.useUnicodeVersionOfWindowsAPIs ? "W" : "A")); - if (handle != null) - return handle; - } - - if (member instanceof Method) { - Method method = (Method)member; - for (Demangler.Symbol symbol : getSymbols()) { - if (symbol.matches(method)) - return symbol; - } - } - return null; - } - - public boolean isMSVC() { - return Platform.isWindows(); - } - /** Filter for symbols */ - public interface SymbolAccepter { - boolean accept(Symbol symbol); - } - public Symbol getFirstMatchingSymbol(SymbolAccepter accepter) { - for (Symbol symbol : getSymbols()) - if (accepter.accept(symbol)) - return symbol; - return null; - } - public Collection getSymbols() { - try { - scanSymbols(); - } catch (Exception ex) { - assert BridJ.error("Failed to scan symbols of library '" + path + "'", ex); - } - return nameToSym == null ? Collections.EMPTY_LIST : Collections.unmodifiableCollection(nameToSym.values()); - } - public String getSymbolName(long address) { - if (addrToName == null && getSymbolsHandle() != 0)//Platform.isUnix()) - return JNI.findSymbolName(getHandle(), getSymbolsHandle(), address); - - Demangler.Symbol symbol = getSymbol(address); - return symbol == null ? null : symbol.getSymbol(); - } - - public Symbol getSymbol(long address) { - try { - scanSymbols(); - Symbol symbol = addrToName.get(address); - return symbol; - } catch (Exception ex) { - throw new RuntimeException("Failed to get name of address " + address, ex); - } - } - public Symbol getSymbol(String name) { - try { - Symbol symbol; - long addr; - - if (nameToSym == null) {// symbols not scanned yet, try without them ! - addr = JNI.findSymbolInLibrary(getHandle(), name); - if (addr != 0) { - symbol = new Symbol(name, this); - symbol.setAddress(addr); - return symbol; - } - } - scanSymbols(); - if (nameToSym == null) - return null; - - symbol = nameToSym.get(name); - if (addrToName == null) { - if (symbol == null) { - addr = JNI.findSymbolInLibrary(getHandle(), name); - if (addr != 0) { - symbol = new Symbol(name, this); - symbol.setAddress(addr); - nameToSym.put(name, symbol); - } - } - } - return symbol; - } catch (Exception ex) { - ex.printStackTrace(); - return null; -// throw new RuntimeException("Failed to get symbol " + name, ex); - } - } - void scanSymbols() throws Exception { - if (addrToName != null) - return; - - nameToSym = new HashMap(); -// nameToAddr = new HashMap(); - - String[] symbs = null; - if (false) // TODO turn to false !!! - try { - if (Platform.isMacOSX()) { - Process process = java.lang.Runtime.getRuntime().exec(new String[] {"nm", "-gj", path}); - BufferedReader rin = new BufferedReader(new InputStreamReader(process.getInputStream())); - String line; - List symbsList = new ArrayList(); - while ((line = rin.readLine()) != null) { - symbsList.add(line); - } - symbs = symbsList.toArray(new String[symbsList.size()]); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - if (symbs == null) { - //System.out.println("Calling getLibrarySymbols"); - symbs = JNI.getLibrarySymbols(getHandle(), getSymbolsHandle()); - //System.out.println("Got " + symbs + " (" + (symbs == null ? "null" : symbs.length + "") + ")"); - } - - if (symbs == null) - return; - - addrToName = new HashMap(); - - boolean is32 = !Platform.is64Bits(); - for (String name : symbs) { - if (name == null) - continue; - - long addr = JNI.findSymbolInLibrary(getHandle(), name); - if (addr == 0 && name.startsWith("_")) { - String n2 = name.substring(1); - addr = JNI.findSymbolInLibrary(getHandle(), n2); - if (addr == 0) { - n2 = "_" + name; - addr = JNI.findSymbolInLibrary(getHandle(), n2); - } - if (addr != 0) - name = n2; - - } - if (addr == 0) { - if (BridJ.verbose) - BridJ.warning("Symbol '" + name + "' not found."); - continue; - } - //if (is32) - // addr = addr & 0xffffffffL; - //System.out.println("Symbol " + Long.toHexString(addr) + " = '" + name + "'"); - - Symbol sym = new Demangler.Symbol(name, this); - sym.setAddress(addr); - addrToName.put(addr, sym); - nameToSym.put(name, sym); - //nameToAddr.put(name, addr); - //System.out.println("'" + name + "' = \t" + TestCPP.hex(addr) + "\n\t" + sym.getParsedRef()); - } - if (BridJ.debug) { - BridJ.info("Found " + nameToSym.size() + " symbols in '" + path + "' :"); - - for (Symbol sym : nameToSym.values()) - BridJ.info("DEBUG(BridJ): library=\"" + path + "\", symbol=\"" + sym.getSymbol() + "\", address=" + Long.toHexString(sym.getAddress()) + ", demangled=\"" + sym.getParsedRef() + "\""); - - //for (Symbol sym : nameToSym.values()) - // System.out.println("Symbol '" + sym + "' = " + sym.getParsedRef()); - } - } - - public MemberRef parseSymbol(String symbol) throws DemanglingException { - if ("__cxa_pure_virtual".equals(symbol)) - return null; - - Demangler demangler; - if (Platform.isWindows()) - demangler = new VC9Demangler(this, symbol); - else - demangler = new GCC4Demangler(this, symbol); - return demangler.parseSymbol(); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeList.java b/libraries/BridJ/src/main/java/org/bridj/NativeList.java deleted file mode 100644 index 007450acf..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeList.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import java.util.RandomAccess; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import org.bridj.cpp.std.vector; -import static org.bridj.Pointer.*; - -/** - * Interface for lists that use a native storage.
- * The only method added to this interface {@link NativeList#getPointer()} returns a pointer to this list, which is does not necessarily point to the first element of the -list (it depends on the list's implementation : for instance {@link vector}.getPointer() will return a pointer to the vector structure's pointer, while a list created out of a pointer through {@link Pointer#asList() } will return their storage pointer) - * @author ochafik - */ -public interface NativeList extends List { - /** - * Returns a pointer to this list, which is does not necessarily point to the first element of the -list.
- * The semantics of the returned pointer depends on the list's implementation : - * for instance {@link vector}.getPointer() will return a pointer to the vector structure's pointer, - * while a list created out of a pointer through {@link Pointer#asList() } will return their storage pointer) - */ - public Pointer getPointer(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeObject.java b/libraries/BridJ/src/main/java/org/bridj/NativeObject.java deleted file mode 100644 index 1308ff573..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeObject.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import java.util.Stack; - -/** - * Base class for native objects. - * @author Olivier - */ -public abstract class NativeObject implements NativeObjectInterface { - - protected Pointer peer; - protected BridJRuntime.TypeInfo typeInfo; - - protected NativeObject(Pointer peer) { - BridJ.initialize(this, peer); - } - - protected NativeObject() { - BridJ.initialize(this); - } - - protected NativeObject(int constructorId, Object... args) { - BridJ.initialize(this, constructorId, args); - } - /* - @Override - protected void finalize() throws Throwable { - BridJ.deallocate(this); - }*/ - - public NativeObject clone() throws CloneNotSupportedException { - return BridJ.clone(this); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof NativeObject)) - return false; - - return typeInfo.equal(this, (NativeObject)o); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/NativeObjectInterface.java b/libraries/BridJ/src/main/java/org/bridj/NativeObjectInterface.java deleted file mode 100644 index 6e4f285c4..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/NativeObjectInterface.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bridj; - -/** - * Marker interface that's useful to know that implementations extend NativeObject (when only dealing with interfaces) - * @author ochafik - */ -public interface NativeObjectInterface { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/Platform.java b/libraries/BridJ/src/main/java/org/bridj/Platform.java deleted file mode 100644 index 0dbc84800..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/Platform.java +++ /dev/null @@ -1,678 +0,0 @@ -package org.bridj; - -import org.bridj.util.ProcessUtils; -import java.util.Set; -import java.util.HashSet; -import java.util.regex.Pattern; -import java.io.*; -import java.net.URL; - -import java.util.List; -import java.util.Collections; -import java.util.Collection; -import java.util.ArrayList; -import java.net.MalformedURLException; -import java.net.URLClassLoader; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import org.bridj.util.StringUtils; - -/** - * Information about the execution platform (OS, architecture, native sizes...) and platform-specific actions. - *
    - *
  • To know if the JVM platform is 32 bits or 64 bits, use {@link Platform#is64Bits()} - *
  • To know if the OS is an Unix-like system, use {@link Platform#isUnix()} - *
  • To open files and URLs in a platform-specific way, use {@link Platform#open(File)}, {@link Platform#open(URL)}, {@link Platform#show(File)} - *
- * @author ochafik - */ -public class Platform { - static final String osName = System.getProperty("os.name", ""); - - private static boolean inited; - static final String BridJLibraryName = "bridj"; - - public static final int - POINTER_SIZE, - WCHAR_T_SIZE, - SIZE_T_SIZE, - TIME_T_SIZE, - CLONG_SIZE; - - /*interface FunInt { - int apply(); - } - static int tryInt(FunInt f, int defaultValue) { - try { - return f.apply(); - } catch (Throwable th) { - return defaultValue; - } - }*/ - static final ClassLoader systemClassLoader; - public static ClassLoader getClassLoader() { - return getClassLoader(BridJ.class); - } - public static ClassLoader getClassLoader(Class cl) { - ClassLoader loader = cl == null ? null : cl.getClassLoader(); - if (loader == null) - loader = Thread.currentThread().getContextClassLoader(); - return loader == null ? systemClassLoader : loader; - } - public static InputStream getResourceAsStream(String path) { - URL url = getResource(path); - try { - return url != null ? url.openStream() : null; - } catch (IOException ex) { - if (BridJ.verbose) - BridJ.warning("Failed to get resource '" + path + "'", ex); - return null; - } - } - public static URL getResource(String path) { - if (!path.startsWith("/")) - path = "/" + path; - - URL in = BridJ.class.getResource(path); - if (in != null) - return in; - - ClassLoader[] cls = { - BridJ.class.getClassLoader(), - Thread.currentThread().getContextClassLoader(), - systemClassLoader - }; - for (ClassLoader cl : cls) { - if (cl != null && (in = cl.getResource(path)) != null) - return in; - } - return null; - } - - /* - public static class utsname { - public final String sysname, nodename, release, version, machine; - public utsname(String sysname, String nodename, String release, String version, String machine) { - this.sysname = sysname; - this.nodename = nodename; - this.release = release; - this.version = version; - this.machine = machine; - } - public String toString() { - StringBuilder b = new StringBuilder("{\n"); - b.append("\tsysname: \"").append(sysname).append("\",\n"); - b.append("\tnodename: \"").append(nodename).append("\",\n"); - b.append("\trelease: \"").append(release).append("\",\n"); - b.append("\tversion: \"").append(version).append("\",\n"); - b.append("\tmachine: \"").append(machine).append("\"\n"); - return b.append("}").toString(); - } - } - public static native utsname uname(); - */ - static final List embeddedLibraryResourceRoots = new ArrayList(); - - /** - * BridJ is able to automatically extract native binaries bundled in the application's JARs, using a customizable root path and a predefined architecture-dependent subpath. This method adds an alternative root path to the search list.
- * For instance, if you want to load library "mylib" and call addEmbeddedLibraryResourceRoot("my/company/lib/"), BridJ will look for library in the following locations : - *
    - *
  • "my/company/lib/darwin_universal/libmylib.dylib" on MacOS X (or darwin_x86, darwin_x64, darwin_ppc if the binary is not universal)
  • - *
  • "my/company/lib/win32/mylib.dll" on Windows (use win64 on 64 bits architectures)
  • - *
  • "my/company/lib/linux_x86/libmylib.so" on Linux (use linux_x64 on 64 bits architectures)
  • - *
  • "my/company/lib/sunos_x86/libmylib.so" on Solaris (use sunos_x64 / sunos_sparc on other architectures)
  • - *
  • "lib/armeabi/libmylib.so" on Android (for Android-specific reasons, only the "lib" sub-path can effectively contain loadable binaries)
  • - *
- * For other platforms or for an updated list of supported platforms, please have a look at BridJ's JAR contents (under "org/bridj/lib") and/or to its source tree, browsable online. - */ - public static synchronized void addEmbeddedLibraryResourceRoot(String root) { - embeddedLibraryResourceRoots.add(0, root); - } - - static Set temporaryExtractedLibraryCanonicalFiles = Collections.synchronizedSet(new LinkedHashSet()); - static void addTemporaryExtractedLibraryFileToDeleteOnExit(File file) throws IOException { - File canonicalFile = file.getCanonicalFile(); - - // Give a chance to NativeLibrary.release() to delete the file : - temporaryExtractedLibraryCanonicalFiles.add(canonicalFile); - - // Ask Java to delete the file upon exit if it still exists - canonicalFile.deleteOnExit(); - } - - - private static final String arch; - private static boolean is64Bits; - private static File extractedLibrariesTempDir; - - static { - arch = System.getProperty("os.arch"); - { - String dataModel = System.getProperty("sun.arch.data.model", System.getProperty("com.ibm.vm.bitmode")); - if ("32".equals(dataModel)) - is64Bits = false; - else if ("64".equals(dataModel)) - is64Bits = true; - else { - is64Bits = - arch.contains("64") || - arch.equalsIgnoreCase("sparcv9"); - } - } - systemClassLoader = createClassLoader(); - - addEmbeddedLibraryResourceRoot("lib/"); - if (!isAndroid()) { - addEmbeddedLibraryResourceRoot("org/bridj/lib/"); - if (!Version.VERSION_SPECIFIC_SUB_PACKAGE.equals("")) - addEmbeddedLibraryResourceRoot("org/bridj/" + Version.VERSION_SPECIFIC_SUB_PACKAGE + "/lib/"); - } - - try { - extractedLibrariesTempDir = createTempDir("BridJExtractedLibraries"); - initLibrary(); - } catch (Throwable th) { - th.printStackTrace(); - } - POINTER_SIZE = sizeOf_ptrdiff_t(); - WCHAR_T_SIZE = sizeOf_wchar_t(); - SIZE_T_SIZE = sizeOf_size_t(); - TIME_T_SIZE = sizeOf_time_t(); - CLONG_SIZE = sizeOf_long(); - - is64Bits = POINTER_SIZE == 8; - - Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { - shutdown(); - }}); - } - private static List nativeLibraries = new ArrayList(); - static void addNativeLibrary(NativeLibrary library) { - synchronized (nativeLibraries) { - nativeLibraries.add(library); - } - } - private static void shutdown() { - //releaseNativeLibraries(); - deleteTemporaryExtractedLibraryFiles(); - } - private static void releaseNativeLibraries() { - synchronized (nativeLibraries) { - // Release libraries in reverse order : - for (int iLibrary = nativeLibraries.size(); iLibrary-- != 0;) { - NativeLibrary lib = nativeLibraries.get(iLibrary); - try { - lib.release(); - } catch (Throwable th) { - BridJ.error("Failed to release library '" + lib.path + "' : " + th, th); - } - } - } - } - private static void deleteTemporaryExtractedLibraryFiles() { - synchronized (temporaryExtractedLibraryCanonicalFiles) { - temporaryExtractedLibraryCanonicalFiles.add(extractedLibrariesTempDir); - - // Release libraries in reverse order : - List filesToDeleteAfterExit = new ArrayList(); - for (File tempFile : Platform.temporaryExtractedLibraryCanonicalFiles) { - if (tempFile.delete()) { - if (BridJ.verbose) - BridJ.info("Deleted temporary library file '" + tempFile + "'"); - } else - filesToDeleteAfterExit.add(tempFile); - } - if (!filesToDeleteAfterExit.isEmpty()) { - if (BridJ.verbose) - BridJ.info("Attempting to delete " + filesToDeleteAfterExit.size() + " files after JVM exit : " + StringUtils.implode(filesToDeleteAfterExit, ", ")); - - try { - ProcessUtils.startJavaProcess(DeleteFiles.class, filesToDeleteAfterExit); - } catch (Throwable ex) { - BridJ.error("Failed to launch process to delete files after JVM exit : " + ex, ex); - } - } - } - } - public static class DeleteFiles { - static boolean delete(List files) { - for (Iterator it = files.iterator(); it.hasNext();) { - File file = it.next(); - if (file.delete()) - it.remove(); - } - return files.isEmpty(); - } - final static long - TRY_DELETE_EVERY_MILLIS = 50, - FAIL_AFTER_MILLIS = 10000; - public static void main(String[] args) { - try { - List files = new LinkedList(); - for (String arg : args) - files.add(new File(arg)); - - long start = System.currentTimeMillis(); - while (!delete(files)) { - long elapsed = System.currentTimeMillis() - start; - if (elapsed > FAIL_AFTER_MILLIS) { - System.err.println("Failed to delete the following files : " + StringUtils.implode(files)); - System.exit(1); - } - - Thread.sleep(TRY_DELETE_EVERY_MILLIS); - } - } catch (Throwable th) { - th.printStackTrace(); - } finally { - System.exit(0); - } - } - } - static ClassLoader createClassLoader() - { - List urls = new ArrayList(); - for (String propName : new String[] { "java.class.path", "sun.boot.class.path" }) { - String prop = System.getProperty(propName); - if (prop == null) - continue; - - for (String path : prop.split(File.pathSeparator)) { - path = path.trim(); - if (path.length() == 0) - continue; - - URL url; - try { - url = new URL(path); - } catch (MalformedURLException ex) { - try { - url = new File(path).toURI().toURL(); - } catch (MalformedURLException ex2) { - url = null; - } - } - if (url != null) - urls.add(url); - } - } - //System.out.println("URLs for synthetic class loader :"); - //for (URL url : urls) - // System.out.println("\t" + url); - return new URLClassLoader(urls.toArray(new URL[urls.size()])); - } - static String getenvOrProperty(String envName, String javaName, String defaultValue) { - String value = System.getenv(envName); - if (value == null) - value = System.getProperty(javaName); - if (value == null) - value = defaultValue; - return value; - } - - public static synchronized void initLibrary() { - if (inited) { - return; - } - inited = true; - - try { - boolean loaded = false; - - String forceLibFile = getenvOrProperty("BRIDJ_LIBRARY", "bridj.library", null); - - String lib = null; - - if (forceLibFile != null) { - try { - System.load(lib = forceLibFile); - loaded = true; - } catch (Throwable ex) { - BridJ.error("Failed to load forced library " + forceLibFile, ex); - } - } - - if (!loaded) { - if (!Platform.isAndroid()) { - try { - File libFile = extractEmbeddedLibraryResource(BridJLibraryName); - if (libFile == null) { - throw new FileNotFoundException("Failed to extract embedded library '" + BridJLibraryName + "' (could be a classloader issue, or missing binary in resource path " + StringUtils.implode(embeddedLibraryResourceRoots, ", ") + ")"); - } - - if (BridJ.veryVerbose) - BridJ.info("Loading library " + libFile); - System.load(lib = libFile.toString()); - BridJ.setNativeLibraryFile(BridJLibraryName, libFile); - loaded = true; - } catch (IOException ex) { - BridJ.error("Failed to load '" + BridJLibraryName + "'", ex); - } - } - if (!loaded) { - System.loadLibrary("bridj"); - } - } - if (BridJ.veryVerbose) - BridJ.info("Loaded library " + lib); - - init(); - - //if (BridJ.protectedMode) - // BridJ.info("Protected mode enabled"); - if (BridJ.logCalls) { - BridJ.info("Calls logs enabled"); - } - - } catch (Throwable ex) { - throw new RuntimeException("Failed to initialize " + BridJ.class.getSimpleName(), ex); - } - } - private static native void init(); - - public static boolean isLinux() { - return isUnix() && osName.toLowerCase().contains("linux"); - } - public static boolean isMacOSX() { - return isUnix() && (osName.startsWith("Mac") || osName.startsWith("Darwin")); - } - public static boolean isSolaris() { - return isUnix() && (osName.startsWith("SunOS") || osName.startsWith("Solaris")); - } - public static boolean isBSD() { - return isUnix() && (osName.contains("BSD") || isMacOSX()); - } - public static boolean isUnix() { - return File.separatorChar == '/'; - } - public static boolean isWindows() { - return File.separatorChar == '\\'; - } - - public static boolean isWindows7() { - return osName.equals("Windows 7"); - } - - /** - * Whether to use Unicode versions of Windows APIs rather than ANSI versions (for functions that haven't been bound yet : has no effect on functions that have already been bound).
- * Some Windows APIs such as SendMessage have two versions : - *
    - *
  • one that uses single-byte character strings (SendMessageA, with 'A' for ANSI strings)
  • - *
  • one that uses unicode character strings (SendMessageW, with 'W' for Wide strings).
  • - *
- *
- * In a C/C++ program, this behaviour is controlled by the UNICODE macro definition.
- * By default, BridJ will use the Unicode versions. Set this field to false, set the bridj.useUnicodeVersionOfWindowsAPIs property to "false" or the BRIDJ_USE_UNICODE_VERSION_OF_WINDOWS_APIS environment variable to "0" to use the ANSI string version instead. - */ - public static boolean useUnicodeVersionOfWindowsAPIs = !( - "false".equals(System.getProperty("bridj.useUnicodeVersionOfWindowsAPIs")) || - "0".equals(System.getenv("BRIDJ_USE_UNICODE_VERSION_OF_WINDOWS_APIS")) - ); - - private static String getArch() { - return arch; - } - /** - * Machine (as returned by `uname -m`, except for i686 which is actually i386), adjusted to the JVM platform (32 or 64 bits) - */ - public static String getMachine() { - String arch = getArch(); - if (arch.equals("amd64") || arch.equals("x86_64")) { - if (is64Bits()) - return "x86_64"; - else - return "i386"; // we are running a 32 bits JVM on a 64 bits platform - } - return arch; - } - - public static boolean isAndroid() { - return "dalvik".equalsIgnoreCase(System.getProperty("java.vm.name")) && isLinux(); - } - public static boolean isArm() { - String arch = getArch(); - return "arm".equals(arch); - } - public static boolean isSparc() { - String arch = getArch(); - return - "sparc".equals(arch) || - "sparcv9".equals(arch); - } - public static boolean is64Bits() { - return is64Bits; - } - public static boolean isAmd64Arch() { - String arch = getArch(); - return arch.equals("x86_64"); - } - - static synchronized Collection getEmbeddedLibraryResource(String name) { - Collection ret = new ArrayList(); - - for (String root : embeddedLibraryResourceRoots) { - if (root == null) - continue; - - if (isWindows()) - ret.add(root + (is64Bits() ? "win64/" : "win32/") + name + ".dll"); - else if (isMacOSX()) { - String suff = "/lib" + name + ".dylib"; - if (isArm()) - ret.add(root + "iphoneos_arm32_arm" + suff); - else { - String pref = root + "darwin_"; - String univ = pref + "universal" + suff; - if (isAmd64Arch()) { - ret.add(univ); - ret.add(pref + "x64" + suff); - } else - ret.add(univ); - } - } - else { - String path = null; - if (isAndroid()) { - assert root.equals("lib/"); - path = root + "armeabi/"; // Android SDK + NDK-style .so embedding = lib/armeabi/libTest.so - } - else if (isLinux()) - path = root + (isArm() ? "linux_arm32_arm/" : is64Bits() ? "linux_x64/" : "linux_x86/"); - else if (isSolaris()) { - if (isSparc()) { - path = root + (is64Bits() ? "sunos_sparc64/" : "sunos_sparc/"); - } else { - path = root + (is64Bits() ? "sunos_x64/" : "sunos_x86/"); - } - } - if (path != null) { - ret.add(path + "lib" + name + ".so"); - ret.add(path + name + ".so"); - } - } - } - if (ret.isEmpty()) - throw new RuntimeException("Platform not supported ! (os.name='" + osName + "', os.arch='" + System.getProperty("os.arch") + "')"); - - if (BridJ.veryVerbose) - BridJ.info("Embedded paths for library " + name + " : " + ret); - return ret; - } - - static void tryDeleteFilesInSameDirectory(final File legitFile, final Pattern fileNamePattern, long atLeastOlderThanMillis) { - final long maxModifiedDateForDeletion = System.currentTimeMillis() - atLeastOlderThanMillis; - new Thread(new Runnable() { public void run() { - File dir = legitFile.getParentFile(); - String legitFileName = legitFile.getName(); - try { - for (String name : dir.list()) { - if (name.equals(legitFileName)) - continue; - - if (!fileNamePattern.matcher(name).matches()) - continue; - - File file = new File(dir, name); - if (file.lastModified() > maxModifiedDateForDeletion) - continue; - - if (file.delete() && BridJ.verbose) - BridJ.info("Deleted old binary file '" + file + "'"); - } - } catch (SecurityException ex) { - // no right to delete files in that directory - BridJ.warning("Failed to delete files matching '" + fileNamePattern + "' in directory '" + dir + "'", ex); - } catch (Throwable ex) { - BridJ.error("Unexpected error : " + ex, ex); - } - }}).start(); - } - static final long DELETE_OLD_BINARIES_AFTER_MILLIS = 24 * 60 * 60 * 1000; // 24 hours - - static File extractEmbeddedLibraryResource(String name) throws IOException { - String firstLibraryResource = null; - for (String libraryResource : getEmbeddedLibraryResource(name)) { - if (firstLibraryResource == null) - firstLibraryResource = libraryResource; - int i = libraryResource.lastIndexOf('.'); - int len; - byte[] b = new byte[8196]; - InputStream in = getResourceAsStream(libraryResource); - if (in == null) { - File f = new File(libraryResource); - if (!f.exists()) - f = new File(f.getName()); - if (f.exists()) - return f.getCanonicalFile(); - continue; - } - String fileName = new File(libraryResource).getName(); - File libFile = new File(extractedLibrariesTempDir, fileName); - OutputStream out = new BufferedOutputStream(new FileOutputStream(libFile)); - while ((len = in.read(b)) > 0) - out.write(b, 0, len); - out.close(); - in.close(); - - addTemporaryExtractedLibraryFileToDeleteOnExit(libFile); - addTemporaryExtractedLibraryFileToDeleteOnExit(libFile.getParentFile()); - - return libFile; - } - return null; - //throw new FileNotFoundException(firstLibraryResource); - } - - static final int maxTempFileAttempts = 20; - static File createTempDir(String prefix) throws IOException { - File dir; - for (int i = 0; i < maxTempFileAttempts; i++) { - dir = File.createTempFile(prefix, ""); - if (dir.delete() && dir.mkdirs()) { - return dir; - } - } - throw new RuntimeException("Failed to create temp dir with prefix '" + prefix + "' despite " + maxTempFileAttempts + " attempts!"); - } - - /** - * Opens an URL with the default system action. - * @param url url to open - * @throws NoSuchMethodException if opening an URL on the current platform is not supported - */ - public static final void open(URL url) throws NoSuchMethodException { - if (url.getProtocol().equals("file")) { - open(new File(url.getFile())); - } else { - if (Platform.isMacOSX()) { - execArgs("open", url.toString()); - } else if (Platform.isWindows()) { - execArgs("rundll32", "url.dll,FileProtocolHandler", url.toString()); - } else if (Platform.isUnix() && hasUnixCommand("gnome-open")) { - execArgs("gnome-open", url.toString()); - } else if (Platform.isUnix() && hasUnixCommand("konqueror")) { - execArgs("konqueror", url.toString()); - } else if (Platform.isUnix() && hasUnixCommand("mozilla")) { - execArgs("mozilla", url.toString()); - } else { - throw new NoSuchMethodException("Cannot open urls on this platform"); - } - } - } - - /** - * Opens a file with the default system action. - * @param file file to open - * @throws NoSuchMethodException if opening a file on the current platform is not supported - */ - public static final void open(File file) throws NoSuchMethodException { - if (Platform.isMacOSX()) { - execArgs("open", file.getAbsolutePath()); - } else if (Platform.isWindows()) { - if (file.isDirectory()) { - execArgs("explorer", file.getAbsolutePath()); - } else { - execArgs("start", file.getAbsolutePath()); - } - } else if (Platform.isUnix() && hasUnixCommand("gnome-open")) { - execArgs("gnome-open", file.toString()); - } else if (Platform.isUnix() && hasUnixCommand("konqueror")) { - execArgs("konqueror", file.toString()); - } else if (Platform.isSolaris() && file.isDirectory()) { - execArgs("/usr/dt/bin/dtfile", "-folder", file.getAbsolutePath()); - } else { - throw new NoSuchMethodException("Cannot open files on this platform"); - } - } - - /** - * Show a file in its parent directory, if possible selecting the file (not possible on all platforms). - * @param file file to show in the system's default file navigator - * @throws NoSuchMethodException if showing a file on the current platform is not supported - */ - public static final void show(File file) throws NoSuchMethodException, IOException { - if (Platform.isWindows()) { - exec("explorer /e,/select,\"" + file.getCanonicalPath() + "\""); - } else { - open(file.getAbsoluteFile().getParentFile()); - } - } - - static final void execArgs(String... cmd) throws NoSuchMethodException { - try { - Runtime.getRuntime().exec(cmd); - } catch (Exception ex) { - ex.printStackTrace(); - throw new NoSuchMethodException(ex.toString()); - } - } - - static final void exec(String cmd) throws NoSuchMethodException { - try { - Runtime.getRuntime().exec(cmd).waitFor(); - } catch (Exception ex) { - ex.printStackTrace(); - throw new NoSuchMethodException(ex.toString()); - } - } - - static final boolean hasUnixCommand(String name) { - try { - Process p = Runtime.getRuntime().exec(new String[]{"which", name}); - return p.waitFor() == 0; - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - static native int sizeOf_size_t(); - static native int sizeOf_time_t(); - static native int sizeOf_wchar_t(); - static native int sizeOf_ptrdiff_t(); - static native int sizeOf_long(); - - static native int getMaxDirectMappingArgCount(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/PlatformSupport.java b/libraries/BridJ/src/main/java/org/bridj/PlatformSupport.java deleted file mode 100644 index b623b3e5d..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/PlatformSupport.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import org.bridj.util.ClassDefiner; -import java.io.IOException; - -class PlatformSupport { - PlatformSupport() {} - - public ClassDefiner getClassDefiner(ClassDefiner defaultDefiner, ClassLoader parentClassLoader) { - return defaultDefiner; - } - private final static PlatformSupport instance; - static { - PlatformSupport _instance = null; - if (Platform.isAndroid()) - try { - _instance = (PlatformSupport)Class.forName("org.bridj.AndroidSupport").newInstance();; - } catch (Exception ex) { - throw new RuntimeException("Failed to instantiate the Android support class... Was the BridJ jar tampered with / trimmed too much ?", ex); - } - - if (_instance == null) - _instance = new PlatformSupport(); - - instance = _instance; - } - - public static PlatformSupport getInstance() { - return instance; - } - - - public NativeLibrary loadNativeLibrary(String name) throws IOException { - return null; - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/SignalConstants.java b/libraries/BridJ/src/main/java/org/bridj/SignalConstants.java deleted file mode 100644 index 05e125e3b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/SignalConstants.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bridj; - -/** - * POSIX signal constants for use from {@link org.bridj.NativeError.SignalError} - * @author ochafik - */ -class SignalConstants -{ - public static final int SIGABRT = 6; - public static final int SIGALRM = 14; - public static final int SIGBUS = 10; - public static final int SIGCHLD = 20; - public static final int SIGCONT = 19; - public static final int SIGEMT = 7; - public static final int SIGFPE = 8; - public static final int SIGHUP = 1; - public static final int SIGILL = 4; - public static final int SIGINFO = 29; - public static final int SIGINT = 2; - public static final int SIGIO = 23; - public static final int SIGIOT = 6; - public static final int SIGKILL = 9; - public static final int SIGPIPE = 13; - public static final int SIGPOLL = 7; - public static final int SIGPROF = 27; - public static final int SIGQUIT = 3; - public static final int SIGSEGV = 11; - public static final int SIGSTOP = 17; - public static final int SIGSYS = 12; - public static final int SIGTERM = 15; - public static final int SIGTRAP = 5; - public static final int SIGTSTP = 18; - public static final int SIGTTIN = 21; - public static final int SIGTTOU = 22; - public static final int SIGURG = 16; - public static final int SIGUSR1 = 30; - public static final int SIGUSR2 = 31; - public static final int SIGVTALRM = 26; - public static final int SIGWINCH = 28; - public static final int SIGXCPU = 24; - public static final int SIGXFSZ = 25; - public static final int BUS_ADRALN = 1; - public static final int BUS_ADRERR = 2; - public static final int BUS_OBJERR = 3; - public static final int CLD_CONTINUED = 6; - public static final int CLD_DUMPED = 3; - public static final int CLD_EXITED = 1; - public static final int CLD_KILLED = 2; - public static final int CLD_STOPPED = 5; - public static final int CLD_TRAPPED = 4; - public static final int FPE_FLTDIV = 1; - public static final int FPE_FLTINV = 5; - public static final int FPE_FLTOVF = 2; - public static final int FPE_FLTRES = 4; - public static final int FPE_FLTSUB = 6; - public static final int FPE_FLTUND = 3; - public static final int FPE_INTDIV = 7; - public static final int FPE_INTOVF = 8; - public static final int ILL_BADSTK = 8; - public static final int ILL_COPROC = 7; - public static final int ILL_ILLADR = 5; - public static final int ILL_ILLOPC = 1; - public static final int ILL_ILLOPN = 4; - public static final int ILL_ILLTRP = 2; - public static final int ILL_PRVOPC = 3; - public static final int ILL_PRVREG = 6; - public static final int POLL_ERR = 4; - public static final int POLL_HUP = 6; - public static final int POLL_IN = 1; - public static final int POLL_MSG = 3; - public static final int POLL_OUT = 2; - public static final int POLL_PRI = 5; - public static final int SEGV_ACCERR = 2; - public static final int SEGV_MAPERR = 1; - public static final int TRAP_BRKPT = 1; - public static final int TRAP_TRACE = 2; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/SignalError.java b/libraries/BridJ/src/main/java/org/bridj/SignalError.java deleted file mode 100644 index 70ede2969..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/SignalError.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.bridj; - -/** - * POSIX signal error, such as "Segmentation fault" or "Bus error".
- * Not public yet. - */ -class SignalError extends NativeError { - final int signal; - final int code; - final long address; - - SignalError(int signal, int code, long address) { - super(getFullSignalMessage(signal, code, address)); - this.signal = signal; - this.code = code; - this.address = address; - } - - /** - * POSIX signal associated with this error - */ - public int getSignal() { - return signal; - } - - /** - * POSIX signal code associated with this error - */ - public int getCode() { - return code; - } - - /** - * Memory address that caused the SIGBUS or SIGSEGV signal, or zero for other signals - */ - public long getAddress() { - return address; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SignalError)) { - return false; - } - SignalError e = (SignalError) obj; - return signal == e.signal && code == e.code; - } - - @Override - public int hashCode() { - return ((Integer) signal).hashCode() ^ ((Integer) code).hashCode() ^ ((Long) address).hashCode(); - } - - public static String getFullSignalMessage(int signal, int code, long address) { - String simple = getSignalMessage(signal, 0, address); - if (code == 0) { - return simple; - } - String sub = getSignalMessage(signal, code, address); - if (sub.equals(simple)) { - return simple; - } - return simple + " (" + sub + ")"; - } - public static void throwNew(int signal, int code, long address) { - throw new SignalError(signal, code, address); - } - /** - * http://pubs.opengroup.org/onlinepubs/7908799/xsh/signal.h.html - */ - public static String getSignalMessage(int signal, int code, long address) { - switch (signal) { - case SignalConstants.SIGSEGV: - switch (code) { - case SignalConstants.SEGV_MAPERR: - return "Address not mapped to object"; - case SignalConstants.SEGV_ACCERR: - return "Invalid permission for mapped object"; - default: - return "Segmentation fault : " + toHex(address); - } - case SignalConstants.SIGBUS: - switch (code) { - case SignalConstants.BUS_ADRALN: - return "Invalid address alignment"; - case SignalConstants.BUS_ADRERR: - return "Nonexistent physical address"; - case SignalConstants.BUS_OBJERR: - return "Object-specific HW error"; - default: - return "Bus error : " + toHex(address); - } - case SignalConstants.SIGABRT: - return "Native exception (call to abort())"; - case SignalConstants.SIGFPE: - switch (code) { - case SignalConstants.FPE_INTDIV: - return "Integer divide by zero"; - case SignalConstants.FPE_INTOVF: - return "Integer overflow"; - case SignalConstants.FPE_FLTDIV: - return "Floating point divide by zero"; - case SignalConstants.FPE_FLTOVF: - return "Floating point overflow"; - case SignalConstants.FPE_FLTUND: - return "Floating point underflow"; - case SignalConstants.FPE_FLTRES: - return "Floating point inexact result"; - case SignalConstants.FPE_FLTINV: - return "Invalid floating point operation"; - case SignalConstants.FPE_FLTSUB: - return "Subscript out of range"; - default: - return "Floating point error"; - } - case SignalConstants.SIGSYS: - return "Bad argument to system call"; - case SignalConstants.SIGTRAP: - switch (code) { - case SignalConstants.TRAP_BRKPT: - return "Process breakpoint"; - case SignalConstants.TRAP_TRACE: - return "Process trace trap"; - default: - return "Trace trap"; - } - case SignalConstants.SIGILL: - switch (code) { - case SignalConstants.ILL_ILLOPC: - return "Illegal opcode"; - case SignalConstants.ILL_ILLTRP: - return "Illegal trap"; - case SignalConstants.ILL_PRVOPC: - return "Privileged opcode"; - case SignalConstants.ILL_ILLOPN: - return "Illegal operand"; - case SignalConstants.ILL_ILLADR: - return "Illegal addressing mode"; - case SignalConstants.ILL_PRVREG: - return "Privileged register"; - case SignalConstants.ILL_COPROC: - return "Coprocessor error"; - case SignalConstants.ILL_BADSTK: - return "Internal stack error"; - default: - return "Illegal instruction"; - } - default: - return "Native error"; - } - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/SizeT.java b/libraries/BridJ/src/main/java/org/bridj/SizeT.java deleted file mode 100644 index c47644bce..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/SizeT.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -/** - * Wraps a value which size is the same as the 'size_t' C type (32 bits on a 32 bits platform, 64 bits on a 64 bits platform) - * @author Olivier - */ -public final class SizeT extends AbstractIntegral { - - public static final int SIZE = Platform.SIZE_T_SIZE; - - public static final SizeT ZERO = new SizeT(0), ONE = new SizeT(1); - - private static final long serialVersionUID = 1547942367767922396L; - - public SizeT(long value) { - super(value); - } - - public static SizeT valueOf(long value) { - if (value == 0) - return ZERO; - if (value == 1) - return ONE; - return new SizeT(value); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/StringList.java b/libraries/BridJ/src/main/java/org/bridj/StringList.java deleted file mode 100644 index 2c550cf23..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/StringList.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bridj; - -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -class StringList { - public final ByteBuffer stringsBuffer; - public final IntBuffer offsetsBuffer; - public StringList(String[] strings) { - int n = strings.length; - byte[][] bytes = new byte[n][]; - offsetsBuffer = ByteBuffer.allocateDirect(n * 4).asIntBuffer(); - int offset = 0; - for (int i = 0; i < n; i++) { - offsetsBuffer.put(i, offset); - offset += (bytes[i] = strings[i].getBytes()).length + 1; - } - stringsBuffer = ByteBuffer.allocateDirect(offset); - for (int i = 0; i < n; i++) { - byte[] str = bytes[i]; - stringsBuffer.put(str); - stringsBuffer.put((byte)0); - } - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/StructObject.java b/libraries/BridJ/src/main/java/org/bridj/StructObject.java deleted file mode 100644 index 969c09aba..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/StructObject.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bridj; - -import org.bridj.ann.Constructor; - -/** - * Base class for C structs. - * @author Olivier - */ -@org.bridj.ann.Runtime(CRuntime.class) -public abstract class StructObject extends NativeObject { - protected StructIO io; - - protected StructObject() { - super(); - } - /** - * Identified constructor with an arbirary number of arguments - * @param voidArg always null, here to disambiguate some sub-constructors - * @param constructorId identifier of the constructor, has to match a {@link Constructor} annotation or be -1. - * @param args - */ - protected StructObject(Void voidArg, int constructorId, Object... args) { - super(constructorId, args); - } - protected StructObject(Pointer peer) { - super(peer); - } - - /** - * Creates a String out of this struct using BridJ.describe(this) (see {@link BridJ#describe(NativeObject) }). - */ - @Override - public String toString() { - return BridJ.describe(this); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/TimeT.java b/libraries/BridJ/src/main/java/org/bridj/TimeT.java deleted file mode 100644 index 62ccb1229..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/TimeT.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bridj; -import org.bridj.ann.*; -import java.util.List; -import java.util.Date; - -/** - * Wraps a value which size is the same as the 'time_t' C type (defined in time.h) - * @author Olivier - */ -public final class TimeT extends AbstractIntegral { - - public static final int SIZE = Platform.TIME_T_SIZE; - static { - BridJ.register(); - } - - public TimeT(long value) { - super(value); - } - - public Date toDate() { - return new Date(value); - } - - public static TimeT valueOf(long value) { - return new TimeT(value); - } - - public static TimeT valueOf(Date value) { - return valueOf(value.getTime()); - } - - @Override - public String toString() { - return "TimeT(value = " + value + ", time = " + toDate() + ")"; - } - - @Struct(customizer = timeval_customizer.class) - public static class timeval extends StructObject { - - public long getTime() { - return seconds() * 1000 + milliseconds(); - } - - @Field(0) - public long seconds() { - return this.io.getCLongField(this, 0); - } - @Field(0) - public timeval seconds(long seconds) { - this.io.setCLongField(this, 0, seconds); - return this; - } - public final long seconds_$eq(long seconds) { - seconds(seconds); - return seconds; - } - @Field(1) - public int milliseconds() { - return this.io.getIntField(this, 1); - } - @Field(1) - public timeval milliseconds(int milliseconds) { - this.io.setIntField(this, 1, milliseconds); - return this; - } - public final int milliseconds_$eq(int milliseconds) { - milliseconds(milliseconds); - return milliseconds; - } - } - - public static class timeval_customizer extends StructIO.DefaultCustomizer { - @Override - public void beforeLayout(StructIO io, List aggregatedFields) { - StructIO.AggregatedFieldDesc secondsField = aggregatedFields.get(0); - if (Platform.isWindows() || !Platform.is64Bits()) - secondsField.byteLength = 4; - else - secondsField.byteLength = 8; - - secondsField.alignment = secondsField.byteLength; - } - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/TypedPointer.java b/libraries/BridJ/src/main/java/org/bridj/TypedPointer.java deleted file mode 100644 index b99c1a8fa..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/TypedPointer.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bridj; - -/** - * Class used by JNAerator to represent pointers to unknown structs that were typedef-ed in the following frequent pattern : - *
{@code
- *  typedef struct _A *A;
- * }
- * @author ochafik - */ -public class TypedPointer extends Pointer.OrderedPointer { - Pointer copy; - - private TypedPointer(PointerIO io, long peer) { - super(io, peer, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, 0, null); - } - public TypedPointer(long address) { - this(PointerIO.getPointerInstance(), address); - } - public TypedPointer(Pointer ptr) { - this(PointerIO.getPointerInstance(), ptr.getPeer()); - copy = ptr; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ValuedEnum.java b/libraries/BridJ/src/main/java/org/bridj/ValuedEnum.java deleted file mode 100644 index ab755b151..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ValuedEnum.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.util.Collections; -import java.util.Iterator; - -/** - * Interface for Java enumerations that have an integral value associated - * @author ochafik - * @param type of the enum - */ -public interface ValuedEnum> extends Iterable { - long value(); -// -// public static class EnumWrapper> implements ValuedEnum { -// EE enumValue; -// public EnumWrapper(EE enumValue) { -// if (enumValue == null) -// throw new IllegalArgumentException("Null enum value !"); -// this.enumValue = enumValue; -// } -// -// @Override -// public long value() { -// return enumValue.ordinal(); -// } -// -// @Override -// public Iterator iterator() { -// return Collections.singleton(enumValue).iterator(); -// } -// -// } -// -// public enum MyEnum implements ValuedEnum { -// A(1), B(2); -// -// MyEnum(long value) { this.value = value; } -// long value; -// @Override -// public long value() { -// return ordinal(); -// } -// -// @Override -// public Iterator iterator() { -// return Collections.singleton(this).iterator(); -// } -// -// public static ValuedEnum fromValue(long value) { -// return FlagSet.fromValue(value, values()); -// } -// } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/WinExceptionsConstants.java b/libraries/BridJ/src/main/java/org/bridj/WinExceptionsConstants.java deleted file mode 100644 index 762d936e8..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/WinExceptionsConstants.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -/** - * - * @author Olivier - */ -class WinExceptionsConstants { - - public static final int CONTROL_C_EXIT = -1073741510; - public static final int DBG_COMMAND_EXCEPTION = 1073807369; - public static final int DBG_CONTINUE = 65538; - public static final int DBG_CONTROL_BREAK = 1073807368; - public static final int DBG_CONTROL_C = 1073807365; - public static final int DBG_EXCEPTION_HANDLED = 65537; - public static final int DBG_EXCEPTION_NOT_HANDLED = -2147418111; - public static final int DBG_TERMINATE_PROCESS = 1073807364; - public static final int DBG_TERMINATE_THREAD = 1073807363; - public static final int EXCEPTION_ACCESS_VIOLATION = -1073741819; - public static final int EXCEPTION_ARRAY_BOUNDS_EXCEEDED = -1073741684; - public static final int EXCEPTION_BREAKPOINT = -2147483645; - public static final int EXCEPTION_DATATYPE_MISALIGNMENT = -2147483646; - public static final int EXCEPTION_FLT_DENORMAL_OPERAND = -1073741683; - public static final int EXCEPTION_FLT_DIVIDE_BY_ZERO = -1073741682; - public static final int EXCEPTION_FLT_INEXACT_RESULT = -1073741681; - public static final int EXCEPTION_FLT_INVALID_OPERATION = -1073741680; - public static final int EXCEPTION_FLT_OVERFLOW = -1073741679; - public static final int EXCEPTION_FLT_STACK_CHECK = -1073741678; - public static final int EXCEPTION_FLT_UNDERFLOW = -1073741677; - public static final int EXCEPTION_GUARD_PAGE = -2147483647; - public static final int EXCEPTION_ILLEGAL_INSTRUCTION = -1073741795; - public static final int EXCEPTION_INT_DIVIDE_BY_ZERO = -1073741676; - public static final int EXCEPTION_INT_OVERFLOW = -1073741675; - public static final int EXCEPTION_INVALID_DISPOSITION = -1073741786; - public static final int EXCEPTION_INVALID_HANDLE = -1073741816; - public static final int EXCEPTION_IN_PAGE_ERROR = -1073741818; - public static final int EXCEPTION_NONCONTINUABLE_EXCEPTION = -1073741787; - public static final int EXCEPTION_PRIV_INSTRUCTION = -1073741674; - public static final int EXCEPTION_SINGLE_STEP = -2147483644; - public static final int EXCEPTION_STACK_OVERFLOW = -1073741571; - public static final int STATUS_ABANDONED_WAIT_0 = 128; - public static final int STATUS_ACCESS_VIOLATION = -1073741819; - public static final int STATUS_ARRAY_BOUNDS_EXCEEDED = -1073741684; - public static final int STATUS_BREAKPOINT = -2147483645; - public static final int STATUS_CONTROL_C_EXIT = -1073741510; - public static final int STATUS_DATATYPE_MISALIGNMENT = -2147483646; - public static final int STATUS_FLOAT_DENORMAL_OPERAND = -1073741683; - public static final int STATUS_FLOAT_DIVIDE_BY_ZERO = -1073741682; - public static final int STATUS_FLOAT_INEXACT_RESULT = -1073741681; - public static final int STATUS_FLOAT_INVALID_OPERATION = -1073741680; - public static final int STATUS_FLOAT_MULTIPLE_FAULTS = -1073741132; - public static final int STATUS_FLOAT_MULTIPLE_TRAPS = -1073741131; - public static final int STATUS_FLOAT_OVERFLOW = -1073741679; - public static final int STATUS_FLOAT_STACK_CHECK = -1073741678; - public static final int STATUS_FLOAT_UNDERFLOW = -1073741677; - public static final int STATUS_GUARD_PAGE_VIOLATION = -2147483647; - public static final int STATUS_ILLEGAL_INSTRUCTION = -1073741795; - public static final int STATUS_INTEGER_DIVIDE_BY_ZERO = -1073741676; - public static final int STATUS_INTEGER_OVERFLOW = -1073741675; - public static final int STATUS_INVALID_DISPOSITION = -1073741786; - public static final int STATUS_INVALID_HANDLE = -1073741816; - public static final int STATUS_IN_PAGE_ERROR = -1073741818; - public static final int STATUS_NONCONTINUABLE_EXCEPTION = -1073741787; - public static final int STATUS_NO_MEMORY = -1073741801; - public static final int STATUS_PENDING = 259; - public static final int STATUS_PRIVILEGED_INSTRUCTION = -1073741674; - public static final int STATUS_REG_NAT_CONSUMPTION = -1073741111; - public static final int STATUS_SEGMENT_NOTIFICATION = 1073741829; - public static final int STATUS_SINGLE_STEP = -2147483644; - public static final int STATUS_STACK_OVERFLOW = -1073741571; - public static final int STATUS_SXS_EARLY_DEACTIVATION = -1072365553; - public static final int STATUS_SXS_INVALID_DEACTIVATION = -1072365552; - public static final int STATUS_TIMEOUT = 258; - public static final int STATUS_USER_APC = 192; - public static final int STATUS_WAIT_0 = 0; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/WindowsError.java b/libraries/BridJ/src/main/java/org/bridj/WindowsError.java deleted file mode 100644 index 1564e3656..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/WindowsError.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bridj; -import java.lang.reflect.Field; -import static org.bridj.WinExceptionsConstants.*; - -/** - * Native Windows error as caught by a __try { ... } __except (...) { ... } block. - * Not public yet. - * @author Olivier - */ -class WindowsError extends NativeError { - final int code; - final long info, address; - WindowsError(int code, long info, long address) { - super(computeMessage(code, info, address)); - this.code = code; - this.info = info; - this.address = address; - } - public static void throwNew(int code, long info, long address) { - throw new WindowsError(code, info, address); - } - static String subMessage(long info, long address) { - switch ((int)info) { - case 0: return "Attempted to read from inaccessible address " + toHex(address); - case 1: return "Attempted to write to inaccessible address " + toHex(address); - case 8: return "Attempted to execute memory " + toHex(address) + " that's not executable (DEP violation)"; - default: return "?"; - } - } - public static String computeMessage(int code, long info, long address) { - switch (code) { - case EXCEPTION_ACCESS_VIOLATION: - return "EXCEPTION_ACCESS_VIOLATION : " + subMessage(info, address); - case EXCEPTION_IN_PAGE_ERROR: - return "EXCEPTION_IN_PAGE_ERROR : " + subMessage(info, address); - default: - try { - for (Field field : WinExceptionsConstants.class.getFields()) { - if (field.getName().startsWith("EXCEPTION_") && field.getType() == int.class) { - int value = (Integer)field.get(null); - if (value == code) - return field.getName(); - } - } - } catch (Throwable th) {} - return "Windows native error (code = " + code + ", info = " + info + ", address = " + address + ") !"; - } - - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Alignment.java b/libraries/BridJ/src/main/java/org/bridj/ann/Alignment.java deleted file mode 100644 index 62c31fdf1..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Alignment.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Alignment of a C struct / struct field, in bytes.
- * If this annotation is not present, BridJ will infer the alignment using the C/C++ rules. - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) -public @interface Alignment { - int value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Array.java b/libraries/BridJ/src/main/java/org/bridj/ann/Array.java deleted file mode 100644 index e0c6a5c84..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Array.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Mono- or multi-dimensional array length (used on Pointer types). - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) -public @interface Array { - long[] value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Bits.java b/libraries/BridJ/src/main/java/org/bridj/ann/Bits.java deleted file mode 100644 index 543482923..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Bits.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Size in bits of a struct's bit field - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) -public @interface Bits { - int value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/CLong.java b/libraries/BridJ/src/main/java/org/bridj/ann/CLong.java deleted file mode 100644 index 793457048..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/CLong.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Indicate that a Java long value is represented by a C 'long' integer (which size is platform- and compiler-dependent). - * @author Olivier Chafik - */ -@Forwardable -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -public @interface CLong { -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Constructor.java b/libraries/BridJ/src/main/java/org/bridj/ann/Constructor.java deleted file mode 100644 index 75e5e6835..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Constructor.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Indicate the index of a constructor.
- * It is important that all constructors have an unique index that helps identify them, and that they call NativeObject's parent constructor with the same index. - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface Constructor { - int value() default -1; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Convention.java b/libraries/BridJ/src/main/java/org/bridj/ann/Convention.java deleted file mode 100644 index f1865b0e7..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Convention.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; - -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -/** - * Force the method call convention to some value.
- * Without this annotation, BridJ will do its best to infer the call convention from the context (C++ method, symbol decoration...) - * @author Olivier Chafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.CONSTRUCTOR}) -@Inherited -public @interface Convention { - /** - * Calling convention enums - */ - public enum Style { - /** - * __stdcall convention (specific to Windows x86, won't have any effect on other platforms) - */ - StdCall, - /** - * __fastcall convention - */ - FastCall, - /** - * __cdecl convention (default for regular C functions) - */ - CDecl, - Pascal, - /** - * __clrcall convention (not supported, specific to Windows .NET mixed-mode assemblies) - */ - CLRCall, - /** - * __thiscall convention (default for regular C++ methods) - */ - ThisCall - } - Style value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/DisableDirect.java b/libraries/BridJ/src/main/java/org/bridj/ann/DisableDirect.java deleted file mode 100644 index b17f7269c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/DisableDirect.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Forbid direct assembly wiring of a native method.
- * On select platforms and when some conditions are met, BridJ connects the native code to Java using optimized assembly glues, which might not be as stable as using dyncall (BridJ's ffi library).
- * In case of unexplained crash / bug, one should first try to set the BRIDJ_DIRECT=0 environment variable or set the bridj.direct=false Java property.
- * If this solves the issue, a bug should be filed and this annotation can be used as a workaround to selectively disable raw calls for some methods. - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface DisableDirect { } diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Field.java b/libraries/BridJ/src/main/java/org/bridj/ann/Field.java deleted file mode 100644 index 79ff09f0b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Field.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Indicate the index of a structure field (in Java, the order of methods and fields is unspecified so you need to order them explicitely).
- * For C++ structs, the index is absolute : it must take into account the fields in parent classes (unlike {@link Virtual}, which virtual table offset is relative to the declared class). - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) -public @interface Field { - /** - * Index of the field in a struct (first field has index 0).
- * Fields of parent structures must be taken into account (if parent struct has 2 fields, first field of sub-struct has index 2).
- * If more than one field are given the same index, this will produce an union at that index. - */ - int value(); - - /** - * Absolute index of the field from the start of the struct - */ - //int offset() default Integer.MIN_VALUE; - - /** - * Declare that this field shares its space with another (the two or more fields are in an union).
- * The unionWith index must be the index of the first field of the union. - */ - int unionWith() default -1; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Forwardable.java b/libraries/BridJ/src/main/java/org/bridj/ann/Forwardable.java deleted file mode 100644 index f5de9ba4d..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Forwardable.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * For annotations that can be forwarded to other annotations. - * E.g. @Ptr can be forwarded to @MyPtr if the MyPtr annotation class is annotated with @Ptr - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.ANNOTATION_TYPE}) -public @interface Forwardable { - -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/JNIBound.java b/libraries/BridJ/src/main/java/org/bridj/ann/JNIBound.java deleted file mode 100644 index b016b39ff..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/JNIBound.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Tells BridJ not to bind native methods marked with this annotation (assumes there's a legit plain-JNI binding for them) - * @author Olivier Chafik - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface JNIBound { -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Library.java b/libraries/BridJ/src/main/java/org/bridj/ann/Library.java deleted file mode 100644 index 0416ceedf..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Library.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specify the name of the native library that should be bound to the class or method this annotation is put on.
- * This name can then be changed at runtime to match the platform-specific name of the library with @see org.bridj.BridJ#setNativeLibraryActualName(String, String).
- * Alternative aliases can also be added at runtime with @see org.bridj.BridJ#addNativeLibraryAlias(String, String). - * @author Olivier Chafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Inherited -@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface Library { - /** - * Name of this library. - */ - String value(); - /** - * Names of libraries that need to be loaded before this library is loaded - */ - String[] dependencies() default {}; - String versionPattern() default ""; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Name.java b/libraries/BridJ/src/main/java/org/bridj/ann/Name.java deleted file mode 100644 index d1a918627..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Name.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specify the real non-obfuscated name of a field / method (useful when the name is a Java keyword but not a C one, e.g. to bind a C function named 'transient') - * @author Olivier Chafik - */ -@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Name { - String value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Optional.java b/libraries/BridJ/src/main/java/org/bridj/ann/Optional.java deleted file mode 100644 index b0ab6cbc9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Optional.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Applies to native methods that might not be present to avoid polluting error logs (useful for "optional" methods in many libraries). - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface Optional {} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Ptr.java b/libraries/BridJ/src/main/java/org/bridj/ann/Ptr.java deleted file mode 100644 index 5b500fbaa..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Ptr.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Indicate that a Java long value is represented by a natively-sized integer ('size_t' and pointer types). - * @author Olivier Chafik - */ -@Forwardable -@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Ptr { -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Runtime.java b/libraries/BridJ/src/main/java/org/bridj/ann/Runtime.java deleted file mode 100644 index 530cd9335..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Runtime.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.bridj.BridJRuntime; - -/** -* Specify the runtime that should be used to bind native methods (default is {@link org.bridj.CRuntime} if no annotation is provided). -
-Also see @see org.bridj.Bridj.register(). - * @author Olivier - */ -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -public @interface Runtime { - Class // - value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Struct.java b/libraries/BridJ/src/main/java/org/bridj/ann/Struct.java deleted file mode 100644 index 3cd33f8d9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Struct.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bridj.ann; - -import org.bridj.StructIO; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Struct details such as explicit fields packing and padding. - */ -@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -public @interface Struct { - int pack() default -1; - //int padding() default -1; - int fieldCount() default -1; - int size() default -1; - Class customizer() default StructIO.Customizer.class; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Symbol.java b/libraries/BridJ/src/main/java/org/bridj/ann/Symbol.java deleted file mode 100644 index 6250361f6..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Symbol.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specify the raw native shared symbol for a function / method, including the mangling (C++, __stdcall...).
- * If you just need to change the name but don't know the exact mangled symbol, use {@link Name} instead. - * @author Olivier Chafik - */ -@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Symbol { - String[] value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Template.java b/libraries/BridJ/src/main/java/org/bridj/ann/Template.java deleted file mode 100644 index 755b3389b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Template.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * C++ template parameters metadata - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface Template { - Class[] value(); - String[] paramNames() default {}; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Union.java b/libraries/BridJ/src/main/java/org/bridj/ann/Union.java deleted file mode 100644 index 0833aa3c3..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Union.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marks a struct as an union (same as putting unionWith = 0 in every {@link Field} annotation). - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR}) -public @interface Union { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/Virtual.java b/libraries/BridJ/src/main/java/org/bridj/ann/Virtual.java deleted file mode 100644 index f024850cd..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/Virtual.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Mark a C++ method as virtual and specify its position in the virtual table.
- * The virtual table offset is optional but strongly recommended (will fail in many cases without it).
- * This position is relative to the struct's declared class, not to the parent structures/classes (unlike {@link Field}, which index is absolute). - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Virtual { - /** - * Optional relative virtual table offset for the C++ method (starts at 0 for each C++ class, even if it has ancestors with virtual methods) - */ - int value() default -1; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/ann/package-info.java b/libraries/BridJ/src/main/java/org/bridj/ann/package-info.java deleted file mode 100644 index 6634071c3..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/ann/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ annotations classes (used to decorate bindings ; you do not need to browse this if you are using JNAerator). -*/ -package org.bridj.ann; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPObject.java b/libraries/BridJ/src/main/java/org/bridj/cpp/CPPObject.java deleted file mode 100644 index e7c388619..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPObject.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp; - -import java.util.Stack; - -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Runtime; -import org.bridj.cpp.mfc.MFCRuntime; -import org.bridj.BridJ; - -import java.util.Map; - -/** - * Base class for C++ structs and classes. - * @author Olivier - */ -@Runtime(CPPRuntime.class) -public abstract class CPPObject extends StructObject { - Map, Object[]> templateParameters; - - protected CPPObject() {} - protected CPPObject(Pointer peer) { - super(peer); - } - protected CPPObject(Void voidArg, int constructorId, Object... args) { - super(voidArg, constructorId, args); - } - /* - @Override - protected void finalize() throws Throwable { - BridJ.deallocate(this); - }*/ -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cpp/CPPRuntime.java deleted file mode 100644 index e9d09eca0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPRuntime.java +++ /dev/null @@ -1,863 +0,0 @@ - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.cpp; - -import org.bridj.SizeT; -import java.util.Set; -import org.bridj.ann.Template; -import org.bridj.DynamicFunction; -import org.bridj.demangling.Demangler.IdentLike; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.util.Pair; -import java.lang.reflect.Constructor; -import org.bridj.DynamicFunctionFactory; -import org.bridj.ann.Convention; -import org.bridj.Callback; -import org.bridj.Platform; -import java.io.FileNotFoundException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.GenericDeclaration; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.TypeVariable; -import java.util.HashMap; -import java.util.Map; - -import org.bridj.BridJ; -import static org.bridj.BridJ.*; -import org.bridj.JNI; -import org.bridj.MethodCallInfo; -import org.bridj.NativeLibrary; -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.PointerIO; - -import static org.bridj.dyncall.DyncallLibrary.*; - -import org.bridj.demangling.Demangler.Symbol; -import org.bridj.NativeEntities.Builder; -import org.bridj.ann.Virtual; -import org.bridj.CRuntime; -import org.bridj.NativeLibrary.SymbolAccepter; -import org.bridj.util.Utils; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Arrays; -import java.util.HashSet; -import java.util.TreeMap; -import org.bridj.ann.Convention.Style; -import org.bridj.demangling.Demangler.SpecialName; -import static org.bridj.Pointer.*; -import org.bridj.demangling.Demangler; - -/** - * C++ runtime (derives from the C runtime).
- * Deals with registration and lifecycle of C++ classes and methods (virtual or not). - * @author ochafik - */ -public class CPPRuntime extends CRuntime { - - public static final int DEFAULT_CONSTRUCTOR = -1, SKIP_CONSTRUCTOR = -2; - - public static CPPRuntime getInstance() { - return BridJ.getRuntimeByRuntimeClass(CPPRuntime.class); - } - public Object[] getTemplateParameters(CPPObject object, Class typeClass) { - synchronized(object) { - Object[] params = null; - if (object.templateParameters != null) { - params = object.templateParameters.get(typeClass); - } - return params;// == null ? new Object[0] : params; - } - } - public void setTemplateParameters(CPPObject object, Class typeClass, Object[] params) { - synchronized(object) { - if (object.templateParameters == null) - object.templateParameters = new HashMap, Object[]>(); - object.templateParameters.put(typeClass, params); - } - } - protected interface ClassTypeVariableExtractor { - Type extract(CPPObject instance); - } - protected interface MethodTypeVariableExtractor { - Type extract(CPPObject instance, Object[] methodTemplateParameters); - } - - protected static int getAnnotatedTemplateTypeVariableIndexInArguments(TypeVariable var) { - GenericDeclaration d = var.getGenericDeclaration(); - AnnotatedElement e = (AnnotatedElement)d; - - Template t = e.getAnnotation(Template.class); - if (t == null) - throw new RuntimeException(e + " is not a C++ class template (misses the @" + Template.class.getName() + " annotation)"); - - int iTypeVar = Arrays.asList(d.getTypeParameters()).indexOf(var); - int nTypes = 0, iParam = -1; - Class[] values = t.value(); - for (int i = 0, n = values.length; i < n; i++) { - Class c = values[i]; - if (c == Class.class || c == Type.class) - nTypes++; - - if (nTypes == iTypeVar) { - iParam = i; - break; - } - } - if (iParam < 0) - throw new RuntimeException("Couldn't find the type variable " + var + " (offset " + iTypeVar + ") in the @" + Template.class.getName() + " annotation : " + Arrays.asList(values)); - - return iParam; - } - protected ClassTypeVariableExtractor createClassTypeVariableExtractor(TypeVariable> var) { - final Class typeClass = var.getGenericDeclaration(); - final int iTypeInParams = getAnnotatedTemplateTypeVariableIndexInArguments(var); - return new ClassTypeVariableExtractor() { - public Type extract(CPPObject instance) { - typeClass.cast(instance); - Object[] params = getTemplateParameters(instance, typeClass); - if (params == null) - throw new RuntimeException("No type parameters found in this instance : " + instance); - - return (Type)params[iTypeInParams]; - } - }; - } - protected MethodTypeVariableExtractor createMethodTypeVariableExtractor(TypeVariable var) { - GenericDeclaration d = var.getGenericDeclaration(); - if (d instanceof Class) { - final Class typeClass = (Class)d; - final ClassTypeVariableExtractor ce = createClassTypeVariableExtractor((TypeVariable)var); - return new MethodTypeVariableExtractor() { - public Type extract(CPPObject instance, Object[] methodTemplateParameters) { - return ce.extract(instance); - } - }; - } else { - Method method = (Method)d; - final Class typeClass = method.getDeclaringClass(); - - final int iTypeInParams = getAnnotatedTemplateTypeVariableIndexInArguments(var); - return new MethodTypeVariableExtractor() { - public Type extract(CPPObject instance, Object[] methodTemplateParameters) { - typeClass.cast(instance); - return (Type)methodTemplateParameters[iTypeInParams]; - } - }; - } - } - - @Override - public Class getActualInstanceClass(Pointer pInstance, Type officialType) { - //String className = null; - // For C++ classes in general, take type info at offset -1 of vtable (if first field matches the address of a known static or dynamic virtual table) and use it to create the correct instance. -// Pointer vptr = pInstance.getPointer(0); -// Symbol symbol = BridJ.getSymbolByAddress(vptr.getPeer()); -// if (symbol != null && symbol.isVirtualTable()) { -// if (symbol.enclosingType.matches(officialType)) -// return officialType; -// -// try { -// Class type = BridJ.getCPPRuntime().getCPPClass(symbol.enclosingType); -// if (officialType == null || officialType.isAssignableFrom(type)) -// return type; -// } catch (ClassNotFoundException ex) {} -// return officialType; -// -// /*long tinf = JNI.get_pointer(ptr - Pointer.SIZE); -// symbol = BridJ.getSymbolByAddress(tinf); -// if (symbol != null && symbol.isTypeInfo()) { -// -// }*/ -// } - // For Objective-C classes, use "const char* className = class_getName([yourObject class]);" and match to registered classes or more - // Bundle auto-generated type mappings files : bridj::CPPTest=org.bridj.test.cpp.CPPTest - // - return Utils.getClass(officialType); - } - Map, Integer> virtualMethodsCounts = new HashMap, Integer>(); - - public int getVirtualMethodsCount(Class type) { - Integer count = virtualMethodsCounts.get(type); - if (count == null) { - List mets = new ArrayList(); - listVirtualMethods(type, mets); - - // TODO unify this ! - virtualMethodsCounts.put(type, count = mets.size()); - } - return count; - } - - protected static class VirtMeth { - Method implementation, definition; - } - protected void listVirtualMethods(Class type, List out) { - if (!CPPObject.class.isAssignableFrom(type)) { - return; - } - - Class sup = type.getSuperclass(); - if (sup != CPPObject.class) { - listVirtualMethods(sup, out); - } - - int nParentMethods = out.size(); - - Map newVirtuals = new TreeMap(); - - methods: - for (Method method : type.getDeclaredMethods()) { - String methodName = method.getName(); - Type[] methodParameterTypes = method.getGenericParameterTypes(); - for (int iParentMethod = 0; iParentMethod < nParentMethods; iParentMethod++) { - VirtMeth pvm = out.get(iParentMethod); - Method parentMethod = pvm.definition; - if (parentMethod.getDeclaringClass() == type) - continue; // was just added in the same listVirtualMethods call ! - - //if (parentMethod.getAnnotation(Virtual.class) == null) - // continue; // not a virtual method, too bad - - if (parentMethod.getName().equals(methodName) && isOverridenSignature(parentMethod.getGenericParameterTypes(), methodParameterTypes, 0)) { - VirtMeth vm = new VirtMeth(); - vm.definition = pvm.definition; - vm.implementation = method; - out.set(iParentMethod, vm); - continue methods; - } - } - - Virtual virtual = method.getAnnotation(Virtual.class); - if (virtual != null) { - VirtMeth vm = new VirtMeth(); - vm.definition = vm.implementation = method; - newVirtuals.put(virtual.value(), vm); - } - } - out.addAll(newVirtuals.values()); - } - - @Override - protected void registerNativeMethod(Class type, NativeLibrary typeLibrary, Method method, NativeLibrary methodLibrary, Builder builder, MethodCallInfoBuilder methodCallInfoBuilder) throws FileNotFoundException { - - int modifiers = method.getModifiers(); - boolean isCPPClass = CPPObject.class.isAssignableFrom(method.getDeclaringClass()); - -// Annotation[][] anns = method.getParameterAnnotations(); - if (!isCPPClass) { - super.registerNativeMethod(type, typeLibrary, method, methodLibrary, builder, methodCallInfoBuilder); - return; - } - - MethodCallInfo mci = methodCallInfoBuilder.apply(method); - - Virtual va = method.getAnnotation(Virtual.class); - if (va == null) { - Symbol symbol = methodLibrary.getSymbol(method); - mci.setForwardedPointer(symbol == null ? 0 : symbol.getAddress()); - if (mci.getForwardedPointer() == 0) { - assert error("Method " + method.toGenericString() + " is not virtual but its address could not be resolved in the library."); - return; - } - if (Modifier.isStatic(modifiers)) { - builder.addFunction(mci); - if (debug) - info("Registering " + method + " as function or static C++ method " + symbol.getName()); - } else { - builder.addFunction(mci); - if (debug) - info("Registering " + method + " as C++ method " + symbol.getName()); - } - } else { - if (Modifier.isStatic(modifiers)) { - warning("Method " + method.toGenericString() + " is native and maps to a function, but is not static."); - } - - int theoreticalVirtualIndex = va.value(); - int theoreticalAbsoluteVirtualIndex = theoreticalVirtualIndex < 0 ? - 1 : getAbsoluteVirtualIndex(method, theoreticalVirtualIndex, type); - - int absoluteVirtualIndex; - - Pointer> pVirtualTable = isCPPClass && typeLibrary != null ? (Pointer)pointerToAddress(getVirtualTable(type, typeLibrary), Pointer.class) : null; - if (pVirtualTable == null) { - if (theoreticalAbsoluteVirtualIndex < 0) { - error("Method " + method.toGenericString() + " is virtual but the virtual table of class " + type.getName() + " was not found and the virtual method index is not provided in its @Virtual annotation."); - return; - } - absoluteVirtualIndex = theoreticalAbsoluteVirtualIndex; - } else { - int guessedAbsoluteVirtualIndex = getPositionInVirtualTable(pVirtualTable, method, typeLibrary); - if (guessedAbsoluteVirtualIndex < 0) { - if (theoreticalAbsoluteVirtualIndex < 0) { - error("Method " + method.toGenericString() + " is virtual but its position could not be found in the virtual table."); - return; - } else { - absoluteVirtualIndex = theoreticalAbsoluteVirtualIndex; - } - } else { - if (theoreticalAbsoluteVirtualIndex >= 0 && guessedAbsoluteVirtualIndex != theoreticalAbsoluteVirtualIndex) { - warning("Method " + method.toGenericString() + " has @Virtual annotation indicating virtual index " + theoreticalAbsoluteVirtualIndex + ", but analysis of the actual virtual table rather indicates it has index " + guessedAbsoluteVirtualIndex + " (using the guess)"); - } - absoluteVirtualIndex = guessedAbsoluteVirtualIndex; - } - } - mci.setVirtualIndex(absoluteVirtualIndex); - if (debug) - info("Registering " + method.toGenericString() + " as virtual C++ method with absolute virtual table index = " + absoluteVirtualIndex); - builder.addVirtualMethod(mci); - } - } - int getAbsoluteVirtualIndex(Method method, int virtualIndex, Class type) { - Class superclass = type.getSuperclass(); - int virtualOffset = getVirtualMethodsCount(superclass); - boolean isNewVirtual = true; - if (superclass != null) { - try { - // TODO handle polymorphism in overloads : - superclass.getMethod(method.getName(), method.getParameterTypes()); - isNewVirtual = false; - } catch (NoSuchMethodException ex) {} - } - int absoluteVirtualIndex = isNewVirtual ? virtualOffset + virtualIndex : virtualIndex; - return absoluteVirtualIndex; - } - public static class MemoryOperators { - protected DynamicFunction> newFct; - protected DynamicFunction> newArrayFct; - protected DynamicFunction deleteFct; - protected DynamicFunction deleteArrayFct; - - protected MemoryOperators() {} - public MemoryOperators(NativeLibrary library) { - for (Symbol sym : library.getSymbols()) { - try { - MemberRef parsedRef = sym.getParsedRef(); - IdentLike n = parsedRef.getMemberName(); - - if (SpecialName.New.equals(n)) - newFct = pointerToAddress(sym.getAddress()).asDynamicFunction(null, Pointer.class, SizeT.class); - else if (SpecialName.NewArray.equals(n)) - newFct = pointerToAddress(sym.getAddress()).asDynamicFunction(null, Pointer.class, SizeT.class); - else if (SpecialName.Delete.equals(n)) - newFct = pointerToAddress(sym.getAddress()).asDynamicFunction(null, Void.class, Pointer.class); - else if (SpecialName.DeleteArray.equals(n)) - newFct = pointerToAddress(sym.getAddress()).asDynamicFunction(null, Void.class, Pointer.class); - - } catch (Exception ex) {} - } - } - - public Pointer cppNew(long size) { - return newFct.apply(new SizeT(size)); - } - public Pointer cppNewArray(long size) { - return newArrayFct.apply(new SizeT(size)); - } - public void cppDelete(Pointer ptr) { - deleteFct.apply(ptr); - } - public void cppDeleteArray(Pointer ptr) { - deleteArrayFct.apply(ptr); - } - } - volatile MemoryOperators memoryOperators; - - public synchronized MemoryOperators getMemoryOperators() { - if (memoryOperators == null) { - try { - NativeLibrary libStdCpp = BridJ.getNativeLibrary("stdc++"); - memoryOperators = new MemoryOperators(libStdCpp); - } catch (Exception ex) { - BridJ.error(null, ex); - } - } - return memoryOperators; - } - - int getPositionInVirtualTable(Method method, NativeLibrary library) { - Class type = method.getDeclaringClass(); - Pointer> pVirtualTable = (Pointer)pointerToAddress(getVirtualTable(type, library), Pointer.class); - return getPositionInVirtualTable(pVirtualTable, method, library); - } - String getCPPClassName(Class declaringClass) { - return declaringClass.getSimpleName(); - } - - public int getPositionInVirtualTable(Pointer> pVirtualTable, Method method, NativeLibrary library) { - //Pointer typeInfo = pVirtualTable.get(1); - int methodsOffset = 0;//library.isMSVC() ? 0 : -2;///2; - String className = getCPPClassName(method.getDeclaringClass()); - for (int iVirtual = 0;; iVirtual++) { - Pointer pMethod = pVirtualTable.get(methodsOffset + iVirtual); - String virtualMethodName = pMethod == null ? null : library.getSymbolName(pMethod.getPeer()); - //System.out.println("#\n# At index " + methodsOffset + " + " + iVirtual + " of vptr for class " + className + ", found symbol " + Long.toHexString(pMethod.getPeer()) + " = '" + virtualMethodName + "'\n#"); - if (virtualMethodName == null) { - if (debug) - info("\tVtable(" + className + ")[" + iVirtual + "] = null"); - return -1; - } - try { - MemberRef mr = library.parseSymbol(virtualMethodName); - if (debug) - info("\tVtable(" + className + ")[" + iVirtual + "] = " + virtualMethodName + " = " + mr); - if (mr != null && mr.matchesSignature(method)) - return iVirtual; - else if (library.isMSVC() && !mr.matchesEnclosingType(method)) - break; // no NULL terminator in MSVC++ vtables, so we have to guess when we've reached the end - } catch (Demangler.DemanglingException ex) { - BridJ.warning("Failed to demangle '" + virtualMethodName + "' during inspection of virtual table for '" + method.toGenericString() + "' : " + ex); - } - - } - return -1; - } - static int getDefaultDyncallCppConvention() { - int convention = DC_CALL_C_DEFAULT; - if (!Platform.is64Bits() && Platform.isWindows()) { - convention = DC_CALL_C_X86_WIN32_THIS_MS; - } - return convention; - } - - private String ptrToString(Pointer ptr, NativeLibrary library) { - return ptr == null ? "null" : Long.toHexString(ptr.getPeer()) + " (" + library.getSymbolName(ptr.getPeer()) + ")"; - } - - @Convention(Style.ThisCall) - public abstract static class CPPDestructor extends Callback { - public abstract void destroy(long peer); - } - - Set typesThatDontNeedASyntheticVirtualTable = new HashSet(); - Map syntheticVirtualTables = new HashMap(); - - protected boolean installRegularVTablePtr(Type type, NativeLibrary library, Pointer peer) { - long vtablePtr = getVirtualTable(type, library); - if (vtablePtr != 0) { - if (BridJ.debug) - BridJ.info("Installing regular vtable pointer " + Pointer.pointerToAddress(vtablePtr) + " to instance at " + peer + " (type = " + Utils.toString(type) + ")"); - peer.setSizeT(vtablePtr); - return true; - } - return false; - } - protected boolean installSyntheticVTablePtr(Type type, NativeLibrary library, Pointer peer) { - synchronized (syntheticVirtualTables) { - VTable vtable = syntheticVirtualTables.get(type); - if (vtable == null) { - if (!typesThatDontNeedASyntheticVirtualTable.contains(type)) { - List methods = new ArrayList(); - listVirtualMethods(Utils.getClass(type), methods); - boolean needsASyntheticVirtualTable = false; - for (VirtMeth method : methods) - if (!Modifier.isNative(method.implementation.getModifiers())) { - needsASyntheticVirtualTable = true; - break; - } - if (needsASyntheticVirtualTable) { - Type parentType = Utils.getParent(type); - Pointer parentVTablePtr = null; - if (CPPObject.class.isAssignableFrom(Utils.getClass(parentType))) { - parentVTablePtr = peer.getPointer(Pointer.class); - if (BridJ.debug) { - BridJ.info("Found parent virtual table pointer = " + ptrToString(parentVTablePtr, library)); - /*Pointer expectedParentVTablePtr = pointerToAddress(getVirtualTable(parentType, library), Pointer.class); - if (expectedParentVTablePtr != null && !Utils.eq(parentVTablePtr, expectedParentVTablePtr)) - BridJ.warning("Weird parent virtual table pointer : expected " + ptrToString(expectedParentVTablePtr, library) + ", got " + ptrToString(parentVTablePtr, library)); - */ - - } - //parentVTablePtr = pointerToAddress(getVirtualTable(parentType, library), Pointer.class); - } - syntheticVirtualTables.put(type, vtable = synthetizeVirtualTable(type, parentVTablePtr, methods, library)); - } else { - typesThatDontNeedASyntheticVirtualTable.add(type); - } - } - } - if (vtable != null) { - if (BridJ.debug) - BridJ.info("Installing synthetic vtable pointer " + vtable.ptr + " to instance at " + peer + " (type = " + Utils.toString(type) + ", " + vtable.callbacks.size() + " callbacks)"); - peer.setPointer(vtable.ptr); - return vtable.ptr != null; - } else - return false; - } - } - static class VTable { - Pointer> ptr; - Map> callbacks = new HashMap>(); - } - protected VTable synthetizeVirtualTable(Type type, Pointer parentVTablePtr, List methods, NativeLibrary library) { - int nMethods = methods.size(); - //Pointer parentVTablePtr = pointerToAddress(getVirtualTable(Utils.getParent(type), library), Pointer.class); - VTable vtable = new VTable(); - vtable.ptr = allocatePointers(nMethods + 2).next(2); // leave two null pointers at index -2 and -1, to say there's no runtime type information available. - - Class c = Utils.getClass(type); - for (int iMethod = 0; iMethod < nMethods; iMethod++) { - VirtMeth vm = methods.get(iMethod); - Pointer pMethod; - if (Modifier.isNative(vm.implementation.getModifiers())) { - pMethod = parentVTablePtr == null ? null : parentVTablePtr.get(iMethod); - } else { - try { - MethodCallInfo mci = new MethodCallInfo(vm.implementation, vm.definition); - mci.setDeclaringClass(vm.implementation.getDeclaringClass()); - pMethod = createCToJavaCallback(mci, c); - vtable.callbacks.put(vm.implementation, pMethod); - } catch (Throwable th) { - BridJ.error("Failed to register overridden method " + vm.implementation + " for type " + type + " (original method = " + vm.definition + ")", th); - pMethod = null; - } - } - vtable.ptr.set(iMethod, (Pointer)pMethod); - } - return vtable; - } - static int getTemplateParametersCount(Class typeClass) { - Template t = typeClass.getAnnotation(Template.class); - // TODO do something with these args ! - int templateParametersCount = t == null ? 0 : t.value().length; - return templateParametersCount; - } - Map, DynamicFunction> constructors = new HashMap, DynamicFunction>(); - DynamicFunction getConstructor(final Class typeClass, final Type type, NativeLibrary lib, int constructorId) { - Pair key = new Pair(type, constructorId); - DynamicFunction constructor = constructors.get(key); - if (constructor == null) { - try { - final Constructor constr; - try { - constr = findConstructor(typeClass, constructorId, true); - - if (debug) - BridJ.info("Found constructor for " + Utils.toString(type) + " : " + constr); - } catch (NoSuchMethodException ex) { - if (debug) - BridJ.info("No constructor for " + Utils.toString(type)); - return null; - } - Symbol symbol = lib == null ? null : lib.getFirstMatchingSymbol(new SymbolAccepter() { public boolean accept(Symbol symbol) { - return symbol.matchesConstructor(constr.getDeclaringClass() == Utils.getClass(type) ? type : constr.getDeclaringClass() /* TODO */, constr); - }}); - if (symbol == null) { - if (debug) - BridJ.info("No matching constructor for " + Utils.toString(type) + " (" + constr + ")"); - return null; - } - - if (debug) - info("Registering constructor " + constr + " as " + symbol.getName()); - - // TODO do something with these args ! - int templateParametersCount = getTemplateParametersCount(typeClass); - - Class[] consParamTypes = constr.getParameterTypes(); - Class[] consThisParamTypes = new Class[consParamTypes.length + 1 - templateParametersCount]; - consThisParamTypes[0] = Pointer.class; - System.arraycopy(consParamTypes, templateParametersCount, consThisParamTypes, 1, consParamTypes.length - templateParametersCount); - - DynamicFunctionFactory constructorFactory = getDynamicFunctionFactory(lib, Style.ThisCall, void.class, consThisParamTypes); - - constructor = constructorFactory.newInstance(pointerToAddress(symbol.getAddress())); - constructors.put(key, constructor); - } catch (Throwable th) { - th.printStackTrace(); - throw new RuntimeException("Unable to create constructor " + constructorId + " for " + type + " : " + th, th); - } - } - return constructor; - } - Map destructors = new HashMap(); - CPPDestructor getDestructor(final Class typeClass, Type type, NativeLibrary lib) { - CPPDestructor destructor = destructors.get(type); - if (destructor == null) { - Symbol symbol = lib.getFirstMatchingSymbol(new SymbolAccepter() { public boolean accept(Symbol symbol) { - return symbol.matchesDestructor(typeClass); - }}); - if (BridJ.debug && symbol != null) - info("Registering destructor of " + Utils.toString(type) + " as " + symbol.getName()); - - if (symbol != null) - destructors.put(type, destructor = pointerToAddress(symbol.getAddress(), CPPDestructor.class).get()); - } - return destructor; - } - Pointer.Releaser newCPPReleaser(final Type type) { - try { - final Class typeClass = Utils.getClass(type); - NativeLibrary lib = BridJ.getNativeLibrary(typeClass); - return newCPPReleaser(type, typeClass, lib); - } catch (Throwable th) { - throw new RuntimeException("Failed to create a C++ destructor for type " + Utils.toString(type) + " : " + th, th); - } - } - Pointer.Releaser newCPPReleaser(final Type type, final Class typeClass, NativeLibrary lib) throws FileNotFoundException { - Pointer.Releaser releaser = null; - //final Class typeClass = Utils.getClass(type); - //NativeLibrary lib = BridJ.getNativeLibrary(typeClass); - if (lib != null && BridJ.enableDestructors) { - final CPPDestructor destructor = getDestructor(typeClass, type, lib); - if (destructor != null) - releaser = new Pointer.Releaser() { //@Override - public void release(Pointer p) { - if (BridJ.debug) - BridJ.info("Destructing instance of C++ type " + Utils.toString(type) + " (address = " + p + ", destructor = " + pointerTo(destructor) + ")"); - - //System.out.println("Destructing instance of C++ type " + type + "..."); - long peer = p.getPeer(); - destructor.destroy(peer); - BridJ.setJavaObjectFromNativePeer(peer, null); - }}; - } - return releaser; - } - protected Pointer newCPPInstance(T instance, final Type type, int constructorId, Object... args) { - Pointer peer = null; - try { - final Class typeClass = Utils.getClass(type); - NativeLibrary lib = BridJ.getNativeLibrary(typeClass); - - if (BridJ.debug) - info("Creating C++ instance of type " + type + " with args " + Arrays.asList(args)); - Pointer.Releaser releaser = newCPPReleaser(type, typeClass, lib); - - long size = sizeOf(type, null); - peer = (Pointer) Pointer.allocateBytes(PointerIO.getInstance(type), size, releaser).as(type); - - DynamicFunction constructor = constructorId == SKIP_CONSTRUCTOR ? null : getConstructor(typeClass, type, lib, constructorId); - - if (lib != null && CPPObject.class.isAssignableFrom(typeClass)) { - installRegularVTablePtr(type, lib, peer); - } else { - // TODO ObjCObject : call alloc on class type !! - } - - // Setting the C++ template parameters in the instance : - int templateParametersCount = getTemplateParametersCount(typeClass); - if (templateParametersCount > 0) { - Object[] templateArgs = new Object[templateParametersCount]; - System.arraycopy(args, 0, templateArgs, 0, templateParametersCount); - setTemplateParameters(instance, typeClass, templateArgs); - } - - // Calling the constructor with the non-template parameters : - if (constructor != null) { - Object[] consThisArgs = new Object[args.length - templateParametersCount + 1]; - consThisArgs[0] = peer; - System.arraycopy(args, templateParametersCount, consThisArgs, 1, args.length - templateParametersCount); - - constructor.apply(consThisArgs); - } - - // Install synthetic virtual table and associate the Java instance to the corresponding native pointer : - if (CPPObject.class.isAssignableFrom(typeClass)) { - if (installSyntheticVTablePtr(type, lib, peer)) - BridJ.setJavaObjectFromNativePeer(peer.getPeer(), instance); - } else { - // TODO ObjCObject : call alloc on class type !! - } - return peer; - } catch (Exception ex) { - ex.printStackTrace(); - if (peer != null) { - peer.release(); - } - throw new RuntimeException("Failed to allocate new instance of type " + type, ex); - } - } - - - /* - Map>> vtablePtrs = new HashMap>>(); - @SuppressWarnings("unchecked") - public - //Pointer> - long getVirtualTable(Type type, NativeLibrary library) { - Pointer> p = vtablePtrs.get(type); - if (p == null) { - Class typeClass = Utils.getClass(type); - // TODO ask for real template name - String className = typeClass.getSimpleName(); - String vtableSymbol; - if (Platform.isWindows()) - vtableSymbol = "??_7" + className + "@@6B@"; - else - vtableSymbol = "_ZTV" + className.length() + className; - - long addr = library.getSymbolAddress(vtableSymbol); - //long addr = JNI.findSymbolInLibrary(getHandle(), vtableSymbolName); -// System.out.println(TestCPP.hex(addr)); -// TestCPP.print(type.getName() + " vtable", addr, 5, 2); - - p = (Pointer)Pointer.pointerToAddress(addr, Pointer.class); - vtablePtrs.put(type, p); - } - return p.getPeer(); - }*/ - - Map vtables = new HashMap(); - long getVirtualTable(Type type, NativeLibrary library) { - Long vtable = vtables.get(type); - if (vtable == null) { - final Class typeClass = Utils.getClass(type); - if (false) { - String className = typeClass.getSimpleName(); - String vtableSymbol; - if (Platform.isWindows()) - vtableSymbol = "??_7" + className + "@@6B@"; - else - vtableSymbol = "_ZTV" + className.length() + className; - - vtables.put(type, vtable = library.getSymbolAddress(vtableSymbol)); - } else { - Symbol symbol = library.getFirstMatchingSymbol(new SymbolAccepter() { public boolean accept(Symbol symbol) { - return symbol.matchesVirtualTable(typeClass); - }}); - if (symbol != null) { - if (BridJ.debug) - info("Registering vtable of " + Utils.toString(type) + " as " + symbol.getName()); -// Pointer pp = pointerToAddress(symbol.getAddress(), Pointer.class); -// -// for (int i = 0; i < 6; i++) { -// Pointer p = pp.get(i); -//// if (p == null) -//// break; -// String n = p == null ? null : library.getSymbolName(p.getPeer()); -// info("\tVtable entry " + i + " = " + p + " (" + n + ")"); -//// if (n == null) -//// break; -// } - } - else if (getVirtualMethodsCount(typeClass) > 0) - error("Failed to find a vtable for type " + Utils.toString(type)); - - if (symbol != null) { - long address = symbol.getAddress(); - vtable = library.isMSVC() ? address : address + 2 * Pointer.SIZE; - } else { - vtable = 0L; - } - vtables.put(type, vtable);//*/ - } - } - return vtable; - } - - public class CPPTypeInfo extends CTypeInfo { - public CPPTypeInfo(Type type) { - super(type); - } - Map>, ClassTypeVariableExtractor> classTypeVariableExtractors; - Map, MethodTypeVariableExtractor> methodTypeVariableExtractors; - - public Type resolveClassType(CPPObject instance, TypeVariable var) { - return getClassTypeVariableExtractor((TypeVariable)var).extract(instance); - } - public Type resolveMethodType(CPPObject instance, Object[] methodTemplateParameters, TypeVariable var) { - return getMethodTypeVariableExtractor(var).extract(instance, methodTemplateParameters); - } - protected synchronized ClassTypeVariableExtractor getClassTypeVariableExtractor(TypeVariable> var) { - if (classTypeVariableExtractors == null) - classTypeVariableExtractors = new HashMap>, ClassTypeVariableExtractor>(); - ClassTypeVariableExtractor e = classTypeVariableExtractors.get(var); - if (e == null) - classTypeVariableExtractors.put(var, e = createClassTypeVariableExtractor(var)); - return e; - } - protected synchronized MethodTypeVariableExtractor getMethodTypeVariableExtractor(TypeVariable var) { - if (methodTypeVariableExtractors == null) - methodTypeVariableExtractors = new HashMap, MethodTypeVariableExtractor>(); - MethodTypeVariableExtractor e = methodTypeVariableExtractors.get(var); - if (e == null) - methodTypeVariableExtractors.put(var, e = createMethodTypeVariableExtractor(var)); - return e; - } - - @Override - public long sizeOf() { - // TODO handle template size here ? (depends on template args) - return super.sizeOf(); - } - - @Override - public T createReturnInstance() { - try { - Object[] templateParameters = getTemplateParameters(type); - T instance = (T) getCastClass().newInstance(); - initialize(instance, SKIP_CONSTRUCTOR, templateParameters); - //setTemplateParameters(instance, typeClass, getTemplateParameters(type)); - return instance; - } catch (Throwable th) { - throw new RuntimeException("Failed to create a return instance for type " + Utils.toString(type) + " : " + th, th); - } - } - - @Override - public T cast(Pointer peer) { - if (BridJ.isCastingNativeObjectReturnTypeInCurrentThread()) { - peer = peer.withReleaser(newCPPReleaser(type)); - } - T instance = super.cast(peer); - Object[] templateParameters = getTemplateParameters(type); - setTemplateParameters(instance, (Class)typeClass, templateParameters); - return instance; - } - - @SuppressWarnings("unchecked") - @Override - public void initialize(T instance, int constructorId, Object... args) { - if (instance instanceof CPPObject) { - //instance.peer = allocate(instance.getClass(), constructorId, args); - int[] position = new int[] { 0 }; - - Type cppType = CPPType.parseCPPType(CPPType.cons((Class)typeClass, args), position); - //int actualArgsOffset = position[0] - 1, nActualArgs = args.length - actualArgsOffset; - //System.out.println("actualArgsOffset = " + actualArgsOffset); - //Object[] actualArgs = new Object[nActualArgs]; - //System.arraycopy(args, actualArgsOffset, actualArgs, 0, nActualArgs); - - setNativeObjectPeer(instance, newCPPInstance((CPPObject)instance, cppType, constructorId, args)); - super.initialize(instance, DEFAULT_CONSTRUCTOR); - } else { - super.initialize(instance, constructorId, args); - } - } - - @Override - public T clone(T instance) throws CloneNotSupportedException { - if (instance instanceof CPPObject) { - // TODO use copy constructor !!! - } - return super.clone(instance); - } - - @Override - public void destroy(T instance) { - //TODO call destructor here ? (and call here from finalizer manually created by autogenerated classes - } - - private Object[] getTemplateParameters(Type type) { - if (!(type instanceof CPPType)) - return null; - return ((CPPType)type).getTemplateParameters(); - } - } - /// Needs not be fast : TypeInfo will be cached in BridJ anyway ! - @Override - public TypeInfo getTypeInfo(final Type type) { - return new CPPTypeInfo(type); - } - - public CPPTypeInfo getCPPTypeInfo(final Type type) { - return (CPPTypeInfo)getTypeInfo(type); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPType.java b/libraries/BridJ/src/main/java/org/bridj/cpp/CPPType.java deleted file mode 100644 index 53a973d51..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/CPPType.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp; - -import java.util.Stack; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import java.lang.reflect.Type; -import java.lang.reflect.ParameterizedType; - -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Runtime; -import org.bridj.ann.Template; -import org.bridj.cpp.mfc.MFCRuntime; -import org.bridj.BridJ; - - -/** - * Representation of a C++ type (including template parameters, which can be types or constants). - * @author Olivier - */ -public class CPPType implements ParameterizedType { - private final Type[] actualTypeArguments; - private final Type ownerType; - private final Type rawType; - private final Object[] templateParameters; - - public CPPType(Type ownerType, Type rawType, Object... templateParameters) { - this.ownerType = ownerType; - this.actualTypeArguments = getTypes(templateParameters); - this.rawType = rawType; - this.templateParameters = templateParameters; - } - public CPPType(Type rawType, Object... templateParameters) { - this(null, rawType, templateParameters); - } - - private static Type[] getTypes(Object[] objects) { - List ret = new ArrayList(objects.length); - for (int i = 0, n = objects.length; i < n; i++) { - Object o = objects[i]; - if (o instanceof Type) - ret.add((Type)o); - } - return ret.toArray(new Type[ret.size()]); - } - - static Object[] cons(Class firstClass, Object... flattenedClassesAndParams) { - Object[] a = new Object[flattenedClassesAndParams.length + 1]; - a[0] = firstClass; - System.arraycopy(flattenedClassesAndParams, 0, a, 1, flattenedClassesAndParams.length); - return a; - } - public static Type getCPPType(Object... flattenedClassesAndParams) { - int[] position = new int[] { 0 }; - Type t = parseCPPType(flattenedClassesAndParams, position); - if (position[0] < flattenedClassesAndParams.length) - parseError("Unexpected trailing parameters", flattenedClassesAndParams, position); - - return t; - } - static void parseError(String message, Object[] flattenedClassesAndParams, int[] position) { - throw new IllegalArgumentException("Error while parsing C++ type in " + Arrays.asList(flattenedClassesAndParams) + " at offset " + position[0] + " : " + message); - } - static void notEOF(String message, Object[] flattenedClassesAndParams, int[] position) { - if (position[0] >= flattenedClassesAndParams.length) - throw new IllegalArgumentException("EOF while parsing C++ type in " + Arrays.asList(flattenedClassesAndParams) + " at offset " + position[0] + " : " + message); - } - - static Type parseCPPType(Object[] flattenedClassesAndParams, int[] position) { - notEOF("expecting class", flattenedClassesAndParams, position); - Object oc = flattenedClassesAndParams[position[0]]; - if (!(oc instanceof Class)) - parseError("expected class", flattenedClassesAndParams, position); - Class c = (Class)oc; - position[0]++; - Template t = c.getAnnotation(Template.class); - - Class[] paramTypes = t == null ? null : t.value(); - int nParams = paramTypes == null ? 0 : paramTypes.length; - Object[] params = new Object[nParams]; - for (int iParam = 0; iParam < nParams; iParam++) { - notEOF("expecting param " + iParam + " for template " + c.getName(), flattenedClassesAndParams, position); - Object param = flattenedClassesAndParams[position[0]]; - Type paramType = paramTypes[iParam]; - if (paramType.equals(Class.class) && param.getClass().equals(Class.class)) - param = parseCPPType(flattenedClassesAndParams, position); - else { - if (!((Class)paramType).isInstance(param)) - parseError("bad type for template param " + iParam + " : expected a " + paramType + ", got " + param, flattenedClassesAndParams, position); - position[0]++; - } - params[iParam] = param; - } - return nParams == 0 ? c : new CPPType(c, params); - } - - //@Override - public Type[] getActualTypeArguments() { - return actualTypeArguments.clone(); - } - - //@Override - public java.lang.reflect.Type getOwnerType() { - return ownerType; - } - - //@Override - public java.lang.reflect.Type getRawType() { - return rawType; - } - - public Object[] getTemplateParameters() { - return templateParameters.clone(); - } - - @Override - public int hashCode() { - int h = getRawType().hashCode(); - if (getOwnerType() != null) - h ^= getOwnerType().hashCode(); - for (int i = 0, n = templateParameters.length; i < n; i++) - h ^= templateParameters[i].hashCode(); - return h; - } - - static boolean eq(Object a, Object b) { - if ((a == null) != (b == null)) - return false; - if (a != null && !a.equals(b)) - return false; - return true; - } - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof CPPType)) - return false; - - CPPType t = (CPPType)o; - if (!eq(getRawType(), t.getRawType())) - return false; - if (!eq(getOwnerType(), t.getOwnerType())) - return false; - - Object[] tp = t.templateParameters; - if (templateParameters.length != tp.length) - return false; - - for (int i = 0, n = templateParameters.length; i < n; i++) - if (!eq(templateParameters[i], tp[i])) - return false; - - return true; - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - if (getOwnerType() != null) - b.append(getOwnerType()).append('.'); - - b.append(getRawType()); - int n = templateParameters.length; - if (n != 0) { - b.append('<'); - for (int i = 0; i < n; i++) { - if (i > 0) - b.append(", "); - b.append(templateParameters[i]); - } - b.append('>'); - } - return b.toString(); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/CLSID.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/CLSID.java deleted file mode 100644 index 4f1b43dc7..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/CLSID.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bridj.cpp.com; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Inherited -@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface CLSID { - String value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMCallableWrapper.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMCallableWrapper.java deleted file mode 100644 index 130b240bb..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMCallableWrapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bridj.cpp.com; - -import org.bridj.Pointer; - -/** - * Implementing the IDispatch Interface : http://msdn.microsoft.com/en-us/library/ms221037.aspx - * Simulating COM Interfaces : http://msdn.microsoft.com/en-us/library/111chfb8.aspx - */ -public class COMCallableWrapper extends IDispatch { - Object instance; - public COMCallableWrapper(Object instance) { - this.instance = instance; - } -// public class IDispatchImpl extends IDispatch { - @Override - public int GetIDsOfNames(Pointer riid, - Pointer> rgszNames, int cNames, - int lcid, Pointer rgDispId) { - - // TODO - return COMRuntime.E_NOTIMPL; - } - @Override - public int Invoke(int dispIdMember, Pointer riid, int lcid, - short wFlags, Pointer pDispParams, - Pointer pVarResult, Pointer pExcepInfo, - Pointer puArgErr) { - - // TODO - return COMRuntime.E_NOTIMPL; - } - @Override - public int GetTypeInfo(int iTInfo, int lcid, - Pointer> ppTInfo) { - // TODO - return COMRuntime.E_NOTIMPL; - } - @Override - public int GetTypeInfoCount(Pointer pctinfo) { - // TODO - return COMRuntime.E_NOTIMPL; - } -// } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMRuntime.java deleted file mode 100644 index 8d2ab2da5..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/COMRuntime.java +++ /dev/null @@ -1,467 +0,0 @@ -package org.bridj.cpp.com; - -import java.lang.reflect.Type; -import java.lang.reflect.Method; - -import org.bridj.ValuedEnum; -import org.bridj.FlagSet; -import org.bridj.BridJ; -import org.bridj.Pointer; -import org.bridj.CRuntime; -import org.bridj.Platform; -import org.bridj.Pointer.StringType; -import org.bridj.ann.Convention; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; -import org.bridj.ann.Runtime; -import org.bridj.cpp.CPPRuntime; -import static org.bridj.cpp.com.VARENUM.*; -import org.bridj.cpp.com.VARIANT.__VARIANT_NAME_1_union; -import org.bridj.cpp.com.VARIANT.__VARIANT_NAME_1_union.__tagVARIANT; -import org.bridj.cpp.com.VARIANT.__VARIANT_NAME_1_union.__tagVARIANT.__VARIANT_NAME_3_union; -import org.bridj.util.Utils; -import static org.bridj.Pointer.*; -import static org.bridj.cpp.com.OLEAutomationLibrary.*; - -/* - * Adding Icons, Previews and Shortcut Menus : - * http://msdn.microsoft.com/en-us/library/bb266530(VS.85).aspx - * - * TODO CoCreateInstanceEx - * TODO CoRegisterClassObject - * TODO CoRevokeClassObject - * TODO CoCreateGuid - * - * IDL syntax : - * http://caml.inria.fr/pub/old_caml_site/camlidl/htmlman/main002.html - * - * Registering a Running EXE Server : - * http://msdn.microsoft.com/en-us/library/ms680076(VS.85).aspx - */ -/** - * Microsoft COM runtime, along with useful constants and methods.
- * All COM classes must extends {@link org.bridj.cpp.com.IUnknown} and hence inherit from it the correct {@link org.bridj.ann.Runtime} annotation that references {@link org.bridj.cpp.com.COMRuntime}. - */ -@Library("Ole32") -@Runtime(CRuntime.class) -@Convention(Convention.Style.StdCall) -public class COMRuntime extends CPPRuntime { - static { - if (Platform.isWindows()) - BridJ.register(); - } - public static final int - CLSCTX_INPROC_SERVER = 0x1, - CLSCTX_INPROC_HANDLER = 0x2, - CLSCTX_LOCAL_SERVER = 0x4, - CLSCTX_INPROC_SERVER16 = 0x8, - CLSCTX_REMOTE_SERVER = 0x10, - CLSCTX_INPROC_HANDLER16 = 0x20, - CLSCTX_RESERVED1 = 0x40, - CLSCTX_RESERVED2 = 0x80, - CLSCTX_RESERVED3 = 0x100, - CLSCTX_RESERVED4 = 0x200, - CLSCTX_NO_CODE_DOWNLOAD = 0x400, - CLSCTX_RESERVED5 = 0x800, - CLSCTX_NO_CUSTOM_MARSHAL = 0x1000, - CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000, - CLSCTX_NO_FAILURE_LOG = 0x4000, - CLSCTX_DISABLE_AAA = 0x8000, - CLSCTX_ENABLE_AAA = 0x10000, - CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000, - CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000, - CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000, - CLSCTX_ENABLE_CLOAKING = 0x100000, - CLSCTX_PS_DLL = 0x80000000; - - public static final int - CLSCTX_INPROC = CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER, - CLSCTX_ALL =(CLSCTX_INPROC_SERVER| - CLSCTX_INPROC_HANDLER| - CLSCTX_LOCAL_SERVER| - CLSCTX_REMOTE_SERVER), - CLSCTX_SERVER = (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER); - - public static final int S_OK = 0, - S_FALSE = 1, - REGDB_E_CLASSNOTREG = 0x80040154, - CLASS_E_NOAGGREGATION = 0x80040110, - CO_E_NOTINITIALIZED = 0x800401F0; - - public static final int E_UNEXPECTED = 0x8000FFFF; - public static final int E_NOTIMPL = 0x80004001; - public static final int E_OUTOFMEMORY = 0x8007000E; - public static final int E_INVALIDARG = 0x80070057; - public static final int E_NOINTERFACE = 0x80004002; - public static final int E_POINTER = 0x80004003; - public static final int E_HANDLE = 0x80070006; - public static final int E_ABORT = 0x80004004; - public static final int E_FAIL = 0x80004005; - public static final int E_ACCESSDENIED = 0x80070005; - - - public static final int DISP_E_BADVARTYPE = -2147352568; - public static final int DISP_E_NOTACOLLECTION = -2147352559; - public static final int DISP_E_MEMBERNOTFOUND = -2147352573; - public static final int DISP_E_ARRAYISLOCKED = -2147352563; - public static final int DISP_E_EXCEPTION = -2147352567; - public static final int DISP_E_TYPEMISMATCH = -2147352571; - public static final int DISP_E_BADINDEX = -2147352565; - public static final int DISP_E_BADCALLEE = -2147352560; - public static final int DISP_E_OVERFLOW = -2147352566; - public static final int DISP_E_UNKNOWNINTERFACE = -2147352575; - public static final int DISP_E_DIVBYZERO = -2147352558; - public static final int DISP_E_UNKNOWNLCID = -2147352564; - public static final int DISP_E_PARAMNOTOPTIONAL = -2147352561; - public static final int DISP_E_PARAMNOTFOUND = -2147352572; - public static final int DISP_E_BADPARAMCOUNT = -2147352562; - public static final int DISP_E_BUFFERTOOSMALL = -2147352557; - public static final int DISP_E_UNKNOWNNAME = -2147352570; - public static final int DISP_E_NONAMEDARGS = -2147352569; - - public static interface COINIT { - public final int - COINIT_APARTMENTTHREADED = 0x2, // Apartment model - COINIT_MULTITHREADED = 0x0, // OLE calls objects on any thread. - COINIT_DISABLE_OLE1DDE = 0x4, // Don't use DDE for Ole1 support. - COINIT_SPEED_OVER_MEMORY = 0x8; - } - - @Deprecated - public static native int CoCreateInstance( - Pointer rclsid, - Pointer pUnkOuter, - int dwClsContext, - Pointer riid, - Pointer> ppv - ); - - static native int CoInitializeEx(@Ptr long pvReserved, int dwCoInit); - static native int CoInitialize(@Ptr long pvReserved); - static native void CoUninitialize(); - - static void error(int err) { - switch (err) { - case E_INVALIDARG: - case E_OUTOFMEMORY: - case E_UNEXPECTED: - throw new RuntimeException("Error " + Integer.toHexString(err)); - case S_OK: - return; - case CO_E_NOTINITIALIZED: - throw new RuntimeException("CoInitialized wasn't called !!"); - case E_NOINTERFACE: - throw new RuntimeException("Interface does not inherit from class"); - case E_POINTER: - throw new RuntimeException("Allocated pointer pointer is null !!"); - default: - throw new RuntimeException("Unexpected COM error code : " + err); - } - } - /** - * Get the IID declared for a class using the {@link IID} annotation. - * @throws RuntimeException if the class isn't annotated with IID - */ - public static Pointer getIID(Class type) { - IID id = type.getAnnotation(IID.class); - if (id == null) - throw new RuntimeException("No " + IID.class.getName() + " annotation set on type " + type.getName() + " !"); - - return (Pointer)parseGUID(id.value()); - } - - /** - * Get the CLSID declared for a class using the {@link CLSID} annotation. - * @throws RuntimeException if the class isn't annotated with CLSID - */ - public static Pointer getCLSID(Class type) { - CLSID id = type.getAnnotation(CLSID.class); - if (id == null) - throw new RuntimeException("No " + CLSID.class.getName() + " annotation set on type " + type.getName() + " !"); - - return (Pointer)parseGUID(id.value()); - } - static ThreadLocal comInitializer = new ThreadLocal() { - @Override - protected Object initialValue() { - error(CoInitializeEx(0, COINIT.COINIT_MULTITHREADED)); - return new Object() { - @Override - protected void finalize() throws Throwable { - CoUninitialize(); - } - }; - } - }; - - @Override - protected boolean isSymbolOptional(Method method) { - return true; - } - - /** - * Initialize COM the current thread (uninitialization is done automatically upon thread death).
- * Calls CoInitialize with COINIT_MULTITHREADED max once per thread.
- * This is called automatically in {@link COMRuntime#newInstance(Class)}, so you'll typically never need to call this method by hand. - */ - public static void initialize() { - comInitializer.get(); - } - public static I newInstance(Class type) throws ClassNotFoundException { - return newInstance(type, type); - } - public static I newInstance(Class instanceClass, Class instanceInterface) throws ClassNotFoundException { - initialize(); - - Pointer> p = Pointer.allocatePointer(); - Pointer clsid = getCLSID(instanceClass), uuid = getIID(instanceInterface); - try { - int ret = CoCreateInstance(clsid, null, CLSCTX_ALL, uuid, p); - if (ret == REGDB_E_CLASSNOTREG) - throw new ClassNotFoundException("COM class is not registered : " + instanceClass.getSimpleName() + " (clsid = " + clsid.getCString() + ")"); - error(ret); - - Pointer inst = p.getPointer(); - if (inst == null) - throw new RuntimeException("Serious low-level issue : CoCreateInstance executed fine but we only retrieved a null pointer !"); - - I instance = inst.getNativeObject(instanceInterface); - return instance; - } finally { - Pointer.release(p, clsid, uuid); - } - } - - private static final String model = "00000000-0000-0000-0000-000000000000"; - - // Need to parse as (int, short, short, char[8]) - public static Pointer parseGUID(String descriptor) { - Pointer out = Pointer.allocateBytes(16 + 4); - descriptor = descriptor.replaceAll("-", ""); - if (descriptor.length() != 32) - throw new RuntimeException("Expected something like :\n" + model + "\nBut got instead :\n" +descriptor); - - out.setIntAtOffset(0, (int)Long.parseLong(descriptor.substring(0, 8), 16)); - out.setShortAtOffset(4, (short)Long.parseLong(descriptor.substring(8, 12), 16)); - out.setShortAtOffset(6, (short)Long.parseLong(descriptor.substring(12, 16), 16)); - for (int i = 0; i < 8; i++) - out.setByteAtOffset(8 + i, (byte)Long.parseLong(descriptor.substring(16 + i * 2, 16 + i * 2 + 2), 16)); - - return out; - } - - static ValuedEnum getType(VARIANT v) { - __VARIANT_NAME_1_union v1 = v.__VARIANT_NAME_1(); - __tagVARIANT v2 = v1.__VARIANT_NAME_2(); - short vt = v2.vt(); - return FlagSet.fromValue(vt, VARENUM.class); - } - static VARIANT setType(VARIANT v, ValuedEnum vt) { - __VARIANT_NAME_1_union v1 = v.__VARIANT_NAME_1(); - __tagVARIANT v2 = v1.__VARIANT_NAME_2(); - v2.vt((short)vt.value()); - return v; - } - static VARIANT.__VARIANT_NAME_1_union.__tagVARIANT.__VARIANT_NAME_3_union getValues(VARIANT v) { - __VARIANT_NAME_1_union v1 = v.__VARIANT_NAME_1(); - __tagVARIANT v2 = v1.__VARIANT_NAME_2(); - __VARIANT_NAME_3_union v3 = v2.__VARIANT_NAME_3(); - return v3; - } - - /** - * Convert the VARIANT value to an equivalent Java value. - * @throws UnsupportedOperationException if the VARIANT type is not handled yet - * @throws RuntimeException if the VARIANT is invalid - */ - public static Object getValue(VARIANT v) { - - FlagSet vt = FlagSet.fromValue(getType(v)); - __VARIANT_NAME_3_union values = getValues(v); - if (vt.has(VT_BYREF)) { - switch (vt.without(VT_BYREF).toEnum()) { - case VT_DISPATCH: - return values.ppdispVal(); - case VT_UNKNOWN: - return values.ppunkVal(); - case VT_VARIANT: - return values.pvarVal(); - case VT_I1 : - case VT_UI1 : - return values.pbVal(); - /* UINT16 */ - case VT_I2 : - case VT_UI2 : - return values.piVal(); - /* UINT32 */ - case VT_I4 : - case VT_UI4 : - return values.plVal(); - case VT_R4: - return values.pfltVal(); - case VT_R8: - return values.pdblVal(); - /* UINT64 */ - case VT_I8 : - case VT_UI8 : - return values.pllVal(); - /* BOOL */ - case VT_BOOL : - return values.pbVal().as(Boolean.class); - - case VT_BSTR: - return values.pbstrVal(); - case VT_LPSTR: - return values.byref().getCString(); - case VT_LPWSTR: - return values.byref().getWideCString(); - case VT_PTR: - default: - return values.byref(); - } - } - switch (vt.toEnum()) { - /* UINT8 */ - case VT_I1 : - case VT_UI1 : - return values.bVal(); - /* UINT16 */ - case VT_I2 : - case VT_UI2 : - return values.uiVal(); - /* UINT32 */ - case VT_I4 : - case VT_UI4 : - return values.ulVal(); - /* UINT64 */ - case VT_I8 : - case VT_UI8 : - return values.ullVal(); - /* BOOL */ - case VT_BOOL : - return values.bVal() != 0; - case VT_R4: - return values.fltVal(); - case VT_R8: - return values.dblVal(); - case VT_BSTR: - return values.bstrVal().getString(StringType.BSTR); - case VT_EMPTY: - return null; - default: - throw new UnsupportedOperationException("Conversion not implemented yet from VARIANT type " + vt + " to Java !"); - } - } - - static void change(VARIANT v, ValuedEnum vt) { - Pointer pv = pointerTo(v); - int res = VariantChangeType(pv, pv, (short)0, (short)vt.value()); - assert res == S_OK; - } - public static VARIANT setValue(VARIANT v, Object value) { - //ValuedEnum vt; - __VARIANT_NAME_3_union values = getValues(v); - if (value == null) { - change(v, VT_EMPTY); - //values.byref(null); - } else if (value instanceof Integer) { - change(v, VT_I4); - values.lVal((Integer)value); - } else if (value instanceof Long) { - change(v, VT_I8); - values.llval((Long)value); - } else if (value instanceof Short) { - change(v, VT_I2); - values.iVal((Short)value); - } else if (value instanceof Byte) { - change(v, VT_I1); - values.bVal((Byte)value); - } else if (value instanceof Float) { - change(v, VT_R4); - values.fltVal((Float)value); - } else if (value instanceof Double) { - change(v, VT_I8); - values.dblVal((Double)value); - } else if (value instanceof Character) { - change(v, VT_I2); - values.iVal((short)((Character)value).charValue()); - } else if (value instanceof String) { - change(v, VT_BSTR); - /*String str = (String)value; - int len = str.length(); - int capacity = SysStringLen(values.bstrVal()); - /Pointer chars = - if (len > capacity) - SysReAllocStringLen values.bstrVal() - SysReAllocString(values.bstrVal().getReference(), - */ - values.bstrVal().setString((String)value, StringType.BSTR); - } else if (value instanceof Pointer) { - Pointer ptr = (Pointer)value; - Type targetType = ptr.getTargetType(); - Class targetClass = Utils.getClass(targetType); - if (targetClass == null) - change(v, VT_PTR); - else { - VARENUM ve; - if (targetClass == Integer.class || targetClass == int.class) - ve = VT_I4; - else if(targetClass == Long.class || targetClass == long.class) - ve = VT_I8; - else if(targetClass == Short.class || targetClass == short.class) - ve = VT_I2; - else if(targetClass == Byte.class || targetClass == byte.class) - ve = VT_I1; - else if(targetClass == Character.class || targetClass == char.class) - ve = VT_LPWSTR; // TODO - else if(targetClass == Boolean.class || targetClass == boolean.class) - ve = VT_BOOL; - else if(targetClass == Float.class || targetClass == float.class) - ve = VT_R4; - else if(targetClass == Double.class || targetClass == double.class) - ve = VT_R8; - else if(Pointer.class.isAssignableFrom(targetClass)) - ve = VT_PTR; - else - ve = null; // TODO - - change(v, FlagSet.fromValues(VT_BYREF, ve)); - } - } else - throw new UnsupportedOperationException("Unable to convert an object of type " + value.getClass().getName() + " to a COM VARIANT object !"); - - //setType(v, vt); - return v; - } - - public static String toString(VARIANT v) { - StringBuilder b = new StringBuilder("Variant(value = "); - try { - b.append(getValue(v)); - } catch (Throwable th) { - b.append("?"); - } - b.append(", type = ").append(getType(v)).append(")"); - - return b.toString(); - } - public static VARIANT clone(VARIANT v) { - VARIANT c = new VARIANT(); - int res = VariantCopy(pointerTo(v), pointerTo(c)); - switch (res) { - case S_OK: - break; - case DISP_E_ARRAYISLOCKED: - throw new RuntimeException("The variant contains an array that is locked."); - case DISP_E_BADVARTYPE: - throw new RuntimeException("The source and destination have an invalid variant type (usually uninitialized)."); - case E_OUTOFMEMORY: - throw new RuntimeException("Memory could not be allocated for the copy."); - case E_INVALIDARG: - throw new RuntimeException("One of the arguments is invalid."); - default: - throw new RuntimeException("Grave error : unexpected error code for VariantCopy : " + res); - } - return c; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/CY.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/CY.java deleted file mode 100644 index fe8a7b944..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/CY.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class CY extends StructObject { - @Field(0) - public long int64() { - return this.io.getLongField(this, 0); - } - @Field(0) - public CY int64(long int64) { - this.io.setLongField(this, 0, int64); - return this; - } - public final long int64_$eq(long int64) { - int64(int64); - return int64; - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/DECIMAL.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/DECIMAL.java deleted file mode 100644 index bd583406c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/DECIMAL.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class DECIMAL extends StructObject { - /// C type : USHORT - @Field(0) - public short wReserved() { - return this.io.getShortField(this, 0); - } - /// C type : USHORT - @Field(0) - public DECIMAL wReserved(short wReserved) { - this.io.setShortField(this, 0, wReserved); - return this; - } - /// C type : USHORT - public final short wReserved_$eq(short wReserved) { - wReserved(wReserved); - return wReserved; - } - @Field(1) - public byte scale() { - return this.io.getByteField(this, 1); - } - @Field(1) - public DECIMAL scale(byte scale) { - this.io.setByteField(this, 1, scale); - return this; - } - public final byte scale_$eq(byte scale) { - scale(scale); - return scale; - } - @Field(2) - public byte sign() { - return this.io.getByteField(this, 2); - } - @Field(2) - public DECIMAL sign(byte sign) { - this.io.setByteField(this, 2, sign); - return this; - } - public final byte sign_$eq(byte sign) { - sign(sign); - return sign; - } - /// C type : ULONG - @Field(3) - public int Hi32() { - return this.io.getIntField(this, 3); - } - /// C type : ULONG - @Field(3) - public DECIMAL Hi32(int Hi32) { - this.io.setIntField(this, 3, Hi32); - return this; - } - /// C type : ULONG - public final int Hi32_$eq(int Hi32) { - Hi32(Hi32); - return Hi32; - } - @Field(4) - public long Lo64() { - return this.io.getLongField(this, 4); - } - @Field(4) - public DECIMAL Lo64(long Lo64) { - this.io.setLongField(this, 4, Lo64); - return this; - } - public final long Lo64_$eq(long Lo64) { - Lo64(Lo64); - return Lo64; - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/GUID.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/GUID.java deleted file mode 100644 index fbe3ed983..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/GUID.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Array; -import org.bridj.ann.CLong; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class GUID extends StructObject { - @Field(0) - public int Data1() { - return this.io.getIntField(this, 0); - } - @Field(0) - public GUID Data1(int Data1) { - this.io.setIntField(this, 0, Data1); - return this; - } - public final int Data1_$eq(int Data1) { - Data1(Data1); - return Data1; - } - @Field(1) - public short Data2() { - return this.io.getShortField(this, 1); - } - @Field(1) - public GUID Data2(short Data2) { - this.io.setShortField(this, 1, Data2); - return this; - } - public final short Data2_$eq(short Data2) { - Data2(Data2); - return Data2; - } - @Field(2) - public short Data3() { - return this.io.getShortField(this, 2); - } - @Field(2) - public GUID Data3(short Data3) { - this.io.setShortField(this, 2, Data3); - return this; - } - public final short Data3_$eq(short Data3) { - Data3(Data3); - return Data3; - } - /// C type : unsigned char[8] - @Array({8}) - @Field(3) - public Pointer Data4() { - return this.io.getPointerField(this, 3); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IClassFactory.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/IClassFactory.java deleted file mode 100644 index 128d8c78e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IClassFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bridj.cpp.com; - -import org.bridj.Pointer; - -import org.bridj.ann.Convention; -import org.bridj.ann.Virtual; -import org.bridj.ann.Convention.Style; - -import org.bridj.*; -import org.bridj.ann.*; -import org.bridj.ann.Runtime; -import static org.bridj.cpp.com.COMRuntime.*; - -@IID("00000001-0000-0000-C000-000000000046") -public class IClassFactory extends IUnknown -{ - @Virtual(0) // TODO handle in runtime not as zero but as count of parents' virtual methods + 0 - @Deprecated - public native int CreateInstance( - Pointer pUnkOuter, - Pointer riid, - Pointer> ppvObject - ); - - public I CreateInstance(Class type) { - Pointer> p = Pointer.allocatePointer(IUnknown.class); - int ret = CreateInstance(null, getIID(type), p); - if (ret != S_OK) - return null; - - return p.get().getNativeObject(type); - } - - @Virtual(1) - public native int LockServer(boolean fLock); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IDispatch.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/IDispatch.java deleted file mode 100644 index 3fd3b9070..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IDispatch.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com; - -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.ValuedEnum; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Virtual; -import java.util.Collections; -import java.util.Iterator; - -/** - * - * @author Olivier - */ -@IID("00020400-0000-0000-C000-000000000046") -public class IDispatch extends IUnknown { - public static class DISPPARAMS extends StructObject { - @Field(0) - public native Pointer rgvarg(); - @Field(1) - public native Pointer rgdispidNamedArgs(); - @Field(2) - public native int cArgs(); - @Field(3) - public native int cNamedArgs(); - } - - - public static class EXCEPINFO extends StructObject { - @Field(0) - public native short wCode(); - @Field(1) - public native short wReserved(); - @Field(2) - public native Pointer bstrSource(); - @Field(3) - public native Pointer bstrDescription(); - @Field(4) - public native Pointer bstrHelpFile(); - @Field(5) - public native int dwHelpContext(); - @Field(6) - public native Pointer pvReserved(); - @Field(7) - public native Pointer pfnDeferredFillIn();//HRESULT (__stdcall *pfnDeferredFillIn)(struct tagEXCEPINFO *); - @Field(8) - public native int scode(); - } - @Virtual(0) - public native int GetTypeInfoCount(Pointer pctinfo); - - @Virtual(1) - public native int GetTypeInfo(int iTInfo, int lcid, Pointer> ppTInfo); - - @Virtual(2) - public native int GetIDsOfNames( - Pointer riid,//REFIID riid, - Pointer> rgszNames, - int cNames, - int lcid, //LCID lcid, - Pointer rgDispId); //DISPID *rgDispId); - - @Virtual(3) - public native int Invoke( - int dispIdMember, - Pointer riid, - int lcid, - short wFlags, - Pointer pDispParams, - Pointer pVarResult, - Pointer pExcepInfo, - Pointer puArgErr - ); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IID.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/IID.java deleted file mode 100644 index 1d64e0e3c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IID.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bridj.cpp.com; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Inherited -@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface IID { - String value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IRecordInfo.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/IRecordInfo.java deleted file mode 100644 index a4ab02ec8..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IRecordInfo.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.Pointer; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.ann.Virtual; -/** - * native declaration : line 176
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@IID("0000002F-0000-0000-C000-000000000046") -public class IRecordInfo extends IUnknown { -// public IRecordInfo() { -// super(); -// } -// public IRecordInfo(Pointer pointer) { -// super(pointer); -// } - @Virtual(0) - public native int RecordInit(Pointer pvNew); - @Virtual(1) - public native int RecordClear(Pointer pvExisting); - @Virtual(2) - public native int RecordCopy(Pointer pvExisting, Pointer pvNew); - @Virtual(3) - public native int GetGuid(Pointer pguid); - @Virtual(4) - public native int GetName(Pointer > pbstrName); - @Virtual(5) - public native int GetSize(Pointer pcbSize); - @Virtual(6) - public native int GetTypeInfo(Pointer > ppTypeInfo); - @Virtual(7) - public native int GetField(Pointer pvData, Pointer szFieldName, Pointer pvarField); - @Virtual(8) - public native int GetFieldNoCopy(Pointer pvData, Pointer szFieldName, Pointer pvarField, Pointer > ppvDataCArray); - @Virtual(9) - public native int PutField(int wFlags, Pointer pvData, Pointer szFieldName, Pointer pvarField); - @Virtual(10) - public native int PutFieldNoCopy(int wFlags, Pointer pvData, Pointer szFieldName, Pointer pvarField); - @Virtual(11) - public native int GetFieldNames(Pointer pcNames, Pointer > rgBstrNames); - @Virtual(12) - public native boolean IsMatchingType(Pointer pRecordInfo); - @Virtual(13) - public native Pointer RecordCreate(); - @Virtual(14) - public native int RecordCreateCopy(Pointer pvSource, Pointer > ppvDest); - @Virtual(15) - public native int RecordDestroy(Pointer pvRecord); -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/ITypeInfo.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/ITypeInfo.java deleted file mode 100644 index 7b8d6c74a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/ITypeInfo.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com; - -/** - * - * @author Olivier - */ -@IID("00020401-0000-0000-C000-000000000046") -public class ITypeInfo extends IUnknown { - // TODO -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IUnknown.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/IUnknown.java deleted file mode 100644 index d9ecf9f39..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/IUnknown.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bridj.cpp.com; - -import org.bridj.*; -import org.bridj.ann.*; -import org.bridj.ann.Runtime; -import org.bridj.cpp.CPPObject; -import org.bridj.cpp.mfc.MFCRuntime; - -import static org.bridj.cpp.com.COMRuntime.*; - -@Convention(Convention.Style.StdCall) -@IID("00000000-0000-0000-C000-000000000046") -@Runtime(COMRuntime.class) -public class IUnknown extends CPPObject { - protected boolean autoRelease; - - public static IUnknown wrap(Object object) { - if (object instanceof IUnknown) - return (IUnknown)object; - - return new COMCallableWrapper(object); - } - @Override - protected void finalize() throws Throwable { - if (autoRelease) - Release(); - super.finalize(); - } - - - @Virtual(0) - @Deprecated - public native int QueryInterface( - Pointer riid, - Pointer> ppvObject - ); - - public I QueryInterface(Class type) { - Pointer> p = Pointer.allocatePointer(IUnknown.class); - int ret = QueryInterface(getIID(type), p); - if (ret != S_OK) - return null; - - return p.get().getNativeObject(type); - } - - @Virtual(1) - public native int AddRef(); - - @Virtual(2) - public native int Release(); - -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/OLEAutomationLibrary.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/OLEAutomationLibrary.java deleted file mode 100644 index d81db18c2..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/OLEAutomationLibrary.java +++ /dev/null @@ -1,1211 +0,0 @@ -package org.bridj.cpp.com; -import java.util.Collections; -import java.util.Iterator; -import org.bridj.BridJ; -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.TypedPointer; -import org.bridj.ValuedEnum; -import org.bridj.ann.CLong; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.cpp.CPPObject; -import org.bridj.cpp.CPPRuntime; -/** - * Wrapper for library oleaut32
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("oleaut32") -@Runtime(CPPRuntime.class) -public class OLEAutomationLibrary { - static { - BridJ.register(); - } - - - /// native declaration : line 33 - public static class ITypeLib extends CPPObject { -// public ITypeLib() { -// super(); -// } -// public ITypeLib(Pointer pointer) { -// super(pointer); -// } - }; - /// native declaration : line 34 - public static class ICreateTypeLib extends CPPObject { -// public ICreateTypeLib() { -// super(); -// } -// public ICreateTypeLib(Pointer pointer) { -// super(pointer); -// } - }; - /// native declaration : line 35 - public static class ICreateTypeLib2 extends CPPObject { -// public ICreateTypeLib2() { -// super(); -// } -// public ICreateTypeLib2(Pointer pointer) { -// super(pointer); -// } - }; - /// native declaration : line 36 - public static class ICreateErrorInfo extends CPPObject { -// public ICreateErrorInfo() { -// super(); -// } -// public ICreateErrorInfo(Pointer pointer) { -// super(pointer); -// } - }; - /// native declaration : line 37 - public static class IErrorInfo extends CPPObject { -// public IErrorInfo() { -// super(); -// } -// public IErrorInfo(Pointer pointer) { -// super(pointer); -// } - }; - - public enum SYSKIND implements IntValuedEnum { - SYS_WIN16(0), - SYS_WIN32(1), - SYS_MAC(2); - SYSKIND(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - }; - public enum CALLCONV implements IntValuedEnum { - CC_FASTCALL(0), - CC_CDECL(1), - CC_MSCPASCAL(2), - CC_PASCAL(CC_MSCPASCAL.value()), - CC_MACPASCAL(CC_MSCPASCAL.value() + 1), - CC_STDCALL(CC_MSCPASCAL.value() + 2), - CC_FPFASTCALL(CC_MSCPASCAL.value() + 3), - CC_SYSCALL(CC_MSCPASCAL.value() + 4), - CC_MPWCDECL(CC_MSCPASCAL.value() + 5), - CC_MPWPASCAL(CC_MSCPASCAL.value() + 6), - CC_MAX(CC_MSCPASCAL.value() + 7); - CALLCONV(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - }; - public enum REGKIND implements IntValuedEnum { - REGKIND_DEFAULT(0), - REGKIND_REGISTER(1), - REGKIND_NONE(2); - REGKIND(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - }; - public static final int NUMPRS_TRAILING_WHITE = 2; - public static final int VAR_TIMEVALUEONLY = 1; - public static final int VARIANT_USE_NLS = 128; - public static final int VTDATEGRE_MIN = -657434; - public static final int ACTIVEOBJECT_WEAK = 1; - public static final int NUMPRS_EXPONENT = 2048; - public static final int NUMPRS_USE_ALL = 4096; - public static final int NUMPRS_THOUSANDS = 512; - public static final int STDOLE_MINORVERNUM = 0; - public static final int VARIANT_LOCALBOOL = 16; - public static final int VARIANT_NOVALUEPROP = 1; - public static final int NUMPRS_PARENS = 128; - public static final int VARCMP_GT = 2; - public static final int VARCMP_LT = 0; - public static final int NUMPRS_STD = 8191; - public static final int VAR_CALENDAR_GREGORIAN = 256; - public static final int NUMPRS_LEADING_PLUS = 4; - public static final int LOAD_TLB_AS_64BIT = 64; - public static final int LOCALE_USE_NLS = 268435456; - public static final int VTDATEGRE_MAX = 2958465; - public static final int NUMPRS_DECIMAL = 256; - public static final int STDOLE_MAJORVERNUM = 1; - public static final int NUMPRS_INEXACT = 131072; - public static final int VARIANT_CALENDAR_THAI = 32; - public static final int VARCMP_EQ = 1; - public static final int ACTIVEOBJECT_STRONG = 0; - public static final int NUMPRS_TRAILING_PLUS = 8; - public static final int STDOLE2_MINORVERNUM = 0; - public static final int VARIANT_NOUSEROVERRIDE = 4; - public static final int NUMPRS_CURRENCY = 1024; - public static final int VAR_CALENDAR_THAI = 128; - public static final int STDOLE2_LCID = 0; - public static final int VAR_FOURDIGITYEARS = 64; - public static final int DISPATCH_PROPERTYPUT = 4; - public static final int VARIANT_CALENDAR_GREGORIAN = 64; - public static final int NUMPRS_HEX_OCT = 64; - public static final int NUMPRS_LEADING_WHITE = 1; - public static final int DISPATCH_PROPERTYPUTREF = 8; - public static final int ID_DEFAULTINST = -2; - public static final int VAR_LOCALBOOL = 16; - public static final int STDOLE_LCID = 0; - public static final int NUMPRS_TRAILING_MINUS = 32; - public static final int NUMPRS_LEADING_MINUS = 16; - public static final int VARIANT_ALPHABOOL = 2; - public static final int VAR_VALIDDATE = 4; - public static final int VARIANT_CALENDAR_HIJRI = 8; - public static final int VAR_DATEVALUEONLY = 2; - public static final int STDOLE2_MAJORVERNUM = 2; - public static final int LOAD_TLB_AS_32BIT = 32; - public static final int NUMPRS_NEG = 65536; - public static final int VAR_CALENDAR_HIJRI = 8; - public static final int DISPATCH_METHOD = 1; - public static final int VARCMP_NULL = 3; - public static final int DISPATCH_PROPERTYGET = 2; - public static final int VAR_FORMAT_NOSUBSTITUTE = 32; - public static final int MASK_TO_RESET_TLB_BITS = ~(LOAD_TLB_AS_32BIT | LOAD_TLB_AS_64BIT); - - - public static class DATE extends StructObject { - public DATE() { - super(); - } -// public DATE(Pointer pointer) { -// super(pointer); -// } - }; - public static class DISPPARAMS extends StructObject { - public DISPPARAMS() { - super(); - } -// public DISPPARAMS(Pointer pointer) { -// super(pointer); -// } - }; - /// native declaration : line 22 - public static class EXCEPINFO extends StructObject { - public EXCEPINFO() { - super(); - } -// public EXCEPINFO(Pointer pointer) { -// super(pointer); -// } - }; - - - public static class CUSTDATAITEM extends StructObject { - public CUSTDATAITEM() { - super(); - } -// public CUSTDATAITEM(Pointer pointer) { -// super(pointer); -// } - /// C type : GUID - @Field(0) - public GUID guid() { - return this.io.getNativeObjectField(this, 0); - } - /// C type : VARIANTARG - @Field(1) - public VARIANT varValue() { - return this.io.getNativeObjectField(this, 1); - } - }; - public static class CUSTDATA extends StructObject { - public CUSTDATA() { - super(); - } -// public CUSTDATA(Pointer pointer) { -// super(pointer); -// } - @Field(0) - public int cCustData() { - return this.io.getIntField(this, 0); - } - @Field(0) - public CUSTDATA cCustData(int cCustData) { - this.io.setIntField(this, 0, cCustData); - return this; - } - public final int cCustData_$eq(int cCustData) { - cCustData(cCustData); - return cCustData; - } - /// C type : LPCUSTDATAITEM - @Field(1) - public Pointer prgCustData() { - return this.io.getPointerField(this, 1); - } - /// C type : LPCUSTDATAITEM - @Field(1) - public CUSTDATA prgCustData(Pointer prgCustData) { - this.io.setPointerField(this, 1, prgCustData); - return this; - } - /// C type : LPCUSTDATAITEM - public final Pointer prgCustData_$eq(Pointer prgCustData) { - prgCustData(prgCustData); - return prgCustData; - } - } - public static class SYSTEMTIME extends StructObject { - public SYSTEMTIME() { - super(); - } -// public SYSTEMTIME(Pointer pointer) { -// super(pointer); -// } - @Field(0) - public short wYear() { - return this.io.getShortField(this, 0); - } - @Field(0) - public SYSTEMTIME wYear(short wYear) { - this.io.setShortField(this, 0, wYear); - return this; - } - public final short wYear_$eq(short wYear) { - wYear(wYear); - return wYear; - } - @Field(1) - public short wMonth() { - return this.io.getShortField(this, 1); - } - @Field(1) - public SYSTEMTIME wMonth(short wMonth) { - this.io.setShortField(this, 1, wMonth); - return this; - } - public final short wMonth_$eq(short wMonth) { - wMonth(wMonth); - return wMonth; - } - @Field(2) - public short wDayOfWeek() { - return this.io.getShortField(this, 2); - } - @Field(2) - public SYSTEMTIME wDayOfWeek(short wDayOfWeek) { - this.io.setShortField(this, 2, wDayOfWeek); - return this; - } - public final short wDayOfWeek_$eq(short wDayOfWeek) { - wDayOfWeek(wDayOfWeek); - return wDayOfWeek; - } - @Field(3) - public short wDay() { - return this.io.getShortField(this, 3); - } - @Field(3) - public SYSTEMTIME wDay(short wDay) { - this.io.setShortField(this, 3, wDay); - return this; - } - public final short wDay_$eq(short wDay) { - wDay(wDay); - return wDay; - } - @Field(4) - public short wHour() { - return this.io.getShortField(this, 4); - } - @Field(4) - public SYSTEMTIME wHour(short wHour) { - this.io.setShortField(this, 4, wHour); - return this; - } - public final short wHour_$eq(short wHour) { - wHour(wHour); - return wHour; - } - @Field(5) - public short wMinute() { - return this.io.getShortField(this, 5); - } - @Field(5) - public SYSTEMTIME wMinute(short wMinute) { - this.io.setShortField(this, 5, wMinute); - return this; - } - public final short wMinute_$eq(short wMinute) { - wMinute(wMinute); - return wMinute; - } - @Field(6) - public short wSecond() { - return this.io.getShortField(this, 6); - } - @Field(6) - public SYSTEMTIME wSecond(short wSecond) { - this.io.setShortField(this, 6, wSecond); - return this; - } - public final short wSecond_$eq(short wSecond) { - wSecond(wSecond); - return wSecond; - } - @Field(7) - public short wMilliseconds() { - return this.io.getShortField(this, 7); - } - @Field(7) - public SYSTEMTIME wMilliseconds(short wMilliseconds) { - this.io.setShortField(this, 7, wMilliseconds); - return this; - } - public final short wMilliseconds_$eq(short wMilliseconds) { - wMilliseconds(wMilliseconds); - return wMilliseconds; - } - }; - public static class UDATE extends StructObject { - public UDATE() { - super(); - } -// public UDATE(Pointer pointer) { -// super(pointer); -// } - /// C type : SYSTEMTIME - @Field(0) - public SYSTEMTIME st() { - return this.io.getNativeObjectField(this, 0); - } - /// C type : USHORT - @Field(1) - public short wDayOfYear() { - return this.io.getShortField(this, 1); - } - /// C type : USHORT - @Field(1) - public UDATE wDayOfYear(short wDayOfYear) { - this.io.setShortField(this, 1, wDayOfYear); - return this; - } - /// C type : USHORT - public final short wDayOfYear_$eq(short wDayOfYear) { - wDayOfYear(wDayOfYear); - return wDayOfYear; - } - }; - public static class NUMPARSE extends StructObject { - public NUMPARSE() { - super(); - } -// public NUMPARSE(Pointer pointer) { -// super(pointer); -// } - /** - * Number of parsed digits
- * C type : INT - */ - @Field(0) - public int cDig() { - return this.io.getIntField(this, 0); - } - /** - * Number of parsed digits
- * C type : INT - */ - @Field(0) - public NUMPARSE cDig(int cDig) { - this.io.setIntField(this, 0, cDig); - return this; - } - /// C type : INT - public final int cDig_$eq(int cDig) { - cDig(cDig); - return cDig; - } - /** - * Acceptable state of the input string (NUMPRS_ flags)
- * C type : ULONG - */ - @Field(1) - public int dwInFlags() { - return this.io.getIntField(this, 1); - } - /** - * Acceptable state of the input string (NUMPRS_ flags)
- * C type : ULONG - */ - @Field(1) - public NUMPARSE dwInFlags(int dwInFlags) { - this.io.setIntField(this, 1, dwInFlags); - return this; - } - /// C type : ULONG - public final int dwInFlags_$eq(int dwInFlags) { - dwInFlags(dwInFlags); - return dwInFlags; - } - /** - * Parsed state of the output string (NUMPRS_ flags)
- * C type : ULONG - */ - @Field(2) - public int dwOutFlags() { - return this.io.getIntField(this, 2); - } - /** - * Parsed state of the output string (NUMPRS_ flags)
- * C type : ULONG - */ - @Field(2) - public NUMPARSE dwOutFlags(int dwOutFlags) { - this.io.setIntField(this, 2, dwOutFlags); - return this; - } - /// C type : ULONG - public final int dwOutFlags_$eq(int dwOutFlags) { - dwOutFlags(dwOutFlags); - return dwOutFlags; - } - /** - * Number of characters parsed from input string
- * C type : INT - */ - @Field(3) - public int cchUsed() { - return this.io.getIntField(this, 3); - } - /** - * Number of characters parsed from input string
- * C type : INT - */ - @Field(3) - public NUMPARSE cchUsed(int cchUsed) { - this.io.setIntField(this, 3, cchUsed); - return this; - } - /// C type : INT - public final int cchUsed_$eq(int cchUsed) { - cchUsed(cchUsed); - return cchUsed; - } - /** - * Base of the number (but apparently unused)
- * C type : INT - */ - @Field(4) - public int nBaseShift() { - return this.io.getIntField(this, 4); - } - /** - * Base of the number (but apparently unused)
- * C type : INT - */ - @Field(4) - public NUMPARSE nBaseShift(int nBaseShift) { - this.io.setIntField(this, 4, nBaseShift); - return this; - } - /// C type : INT - public final int nBaseShift_$eq(int nBaseShift) { - nBaseShift(nBaseShift); - return nBaseShift; - } - /** - * Scale of the number in powers of 10
- * C type : INT - */ - @Field(5) - public int nPwr10() { - return this.io.getIntField(this, 5); - } - /** - * Scale of the number in powers of 10
- * C type : INT - */ - @Field(5) - public NUMPARSE nPwr10(int nPwr10) { - this.io.setIntField(this, 5, nPwr10); - return this; - } - /// C type : INT - public final int nPwr10_$eq(int nPwr10) { - nPwr10(nPwr10); - return nPwr10; - } - }; - public static class PARAMDATA extends StructObject { - public PARAMDATA() { - super(); - } -// public PARAMDATA(Pointer pointer) { -// super(pointer); -// } - /** - * Name of Parameter
- * C type : OLECHAR* - */ - @Field(0) - public Pointer szName() { - return this.io.getPointerField(this, 0); - } - /** - * Name of Parameter
- * C type : OLECHAR* - */ - @Field(0) - public PARAMDATA szName(Pointer szName) { - this.io.setPointerField(this, 0, szName); - return this; - } - /// C type : OLECHAR* - public final Pointer szName_$eq(Pointer szName) { - szName(szName); - return szName; - } - /** - * Type of Parameter
- * C type : VARTYPE - */ - @Field(1) - public short vt() { - return this.io.getShortField(this, 1); - } - /** - * Type of Parameter
- * C type : VARTYPE - */ - @Field(1) - public PARAMDATA vt(short vt) { - this.io.setShortField(this, 1, vt); - return this; - } - /// C type : VARTYPE - public final short vt_$eq(short vt) { - vt(vt); - return vt; - } - }; - public static class METHODDATA extends StructObject { - public METHODDATA() { - super(); - } -// public METHODDATA(Pointer pointer) { -// super(pointer); -// } - /** - * Name of method
- * C type : OLECHAR* - */ - @Field(0) - public Pointer szName() { - return this.io.getPointerField(this, 0); - } - /** - * Name of method
- * C type : OLECHAR* - */ - @Field(0) - public METHODDATA szName(Pointer szName) { - this.io.setPointerField(this, 0, szName); - return this; - } - /// C type : OLECHAR* - public final Pointer szName_$eq(Pointer szName) { - szName(szName); - return szName; - } - /** - * Parameters of the method
- * C type : PARAMDATA* - */ - @Field(1) - public Pointer ppdata() { - return this.io.getPointerField(this, 1); - } - /** - * Parameters of the method
- * C type : PARAMDATA* - */ - @Field(1) - public METHODDATA ppdata(Pointer ppdata) { - this.io.setPointerField(this, 1, ppdata); - return this; - } - /// C type : PARAMDATA* - public final Pointer ppdata_$eq(Pointer ppdata) { - ppdata(ppdata); - return ppdata; - } - /** - * Id of the method
- * C type : DISPID - */ - @CLong - @Field(2) - public long dispid() { - return this.io.getCLongField(this, 2); - } - /** - * Id of the method
- * C type : DISPID - */ - @CLong - @Field(2) - public METHODDATA dispid(long dispid) { - this.io.setCLongField(this, 2, dispid); - return this; - } - /// C type : DISPID - public final long dispid_$eq(long dispid) { - dispid(dispid); - return dispid; - } - /** - * Vtable index of the method
- * C type : UINT - */ - @Field(3) - public int iMeth() { - return this.io.getIntField(this, 3); - } - /** - * Vtable index of the method
- * C type : UINT - */ - @Field(3) - public METHODDATA iMeth(int iMeth) { - this.io.setIntField(this, 3, iMeth); - return this; - } - /// C type : UINT - public final int iMeth_$eq(int iMeth) { - iMeth(iMeth); - return iMeth; - } - /** - * Calling convention of the method
- * C type : CALLCONV - */ - @Field(4) - public ValuedEnum cc() { - return this.io.getEnumField(this, 4); - } - /** - * Calling convention of the method
- * C type : CALLCONV - */ - @Field(4) - public METHODDATA cc(ValuedEnum cc) { - this.io.setEnumField(this, 4, cc); - return this; - } - /// C type : CALLCONV - public final ValuedEnum cc_$eq(ValuedEnum cc) { - cc(cc); - return cc; - } - /** - * Number of parameters in the method
- * C type : UINT - */ - @Field(5) - public int cArgs() { - return this.io.getIntField(this, 5); - } - /** - * Number of parameters in the method
- * C type : UINT - */ - @Field(5) - public METHODDATA cArgs(int cArgs) { - this.io.setIntField(this, 5, cArgs); - return this; - } - /// C type : UINT - public final int cArgs_$eq(int cArgs) { - cArgs(cArgs); - return cArgs; - } - /// Type of the method (DISPATCH_ flags) - @Field(6) - public short wFlags() { - return this.io.getShortField(this, 6); - } - /// Type of the method (DISPATCH_ flags) - @Field(6) - public METHODDATA wFlags(short wFlags) { - this.io.setShortField(this, 6, wFlags); - return this; - } - public final short wFlags_$eq(short wFlags) { - wFlags(wFlags); - return wFlags; - } - /** - * Type of the return value
- * C type : VARTYPE - */ - @Field(7) - public short vtReturn() { - return this.io.getShortField(this, 7); - } - /** - * Type of the return value
- * C type : VARTYPE - */ - @Field(7) - public METHODDATA vtReturn(short vtReturn) { - this.io.setShortField(this, 7, vtReturn); - return this; - } - /// C type : VARTYPE - public final short vtReturn_$eq(short vtReturn) { - vtReturn(vtReturn); - return vtReturn; - } - }; - public static class INTERFACEDATA extends StructObject { - public INTERFACEDATA() { - super(); - } -// public INTERFACEDATA(Pointer pointer) { -// super(pointer); -// } - /** - * Methods of the object
- * C type : METHODDATA* - */ - @Field(0) - public Pointer pmethdata() { - return this.io.getPointerField(this, 0); - } - /** - * Methods of the object
- * C type : METHODDATA* - */ - @Field(0) - public INTERFACEDATA pmethdata(Pointer pmethdata) { - this.io.setPointerField(this, 0, pmethdata); - return this; - } - /// C type : METHODDATA* - public final Pointer pmethdata_$eq(Pointer pmethdata) { - pmethdata(pmethdata); - return pmethdata; - } - /** - * Number of methods in the object
- * C type : UINT - */ - @Field(1) - public int cMembers() { - return this.io.getIntField(this, 1); - } - /** - * Number of methods in the object
- * C type : UINT - */ - @Field(1) - public INTERFACEDATA cMembers(int cMembers) { - this.io.setIntField(this, 1, cMembers); - return this; - } - /// C type : UINT - public final int cMembers_$eq(int cMembers) { - cMembers(cMembers); - return cMembers; - } - }; - public static native int OaBuildVersion(); - public static native Pointer SysAllocString(Pointer OLECHARPtr1); - public static native Pointer SysAllocStringByteLen(int UINT1); - public static native Pointer SysAllocStringLen(Pointer OLECHARPtr1, int UINT1); - public static native void SysFreeString(Pointer BSTR1); - public static native int SysReAllocString(Pointer > LPBSTR1, Pointer OLECHARPtr1); - public static native int SysReAllocStringLen(Pointer > BSTRPtr1, Pointer OLECHARPtr1, int UINT1); - public static native int SysStringByteLen(Pointer BSTR1); - public static native int SysStringLen(Pointer BSTR1); - public static native int SetErrorInfo(int ULONG1, Pointer IErrorInfoPtr1); - public static native int GetErrorInfo(int ULONG1, Pointer > IErrorInfoPtrPtr1); - public static native int CreateErrorInfo(Pointer > ICreateErrorInfoPtrPtr1); - public static native Pointer SafeArrayCreate(short VARTYPE1, int UINT1, Pointer SAFEARRAYBOUNDPtr1); - public static native Pointer SafeArrayCreateEx(short VARTYPE1, int UINT1, Pointer SAFEARRAYBOUNDPtr1); - public static native Pointer SafeArrayCreateVector(short VARTYPE1, @CLong long LONG1, int ULONG1); - public static native Pointer SafeArrayCreateVectorEx(short VARTYPE1, @CLong long LONG1, int ULONG1); - public static native int SafeArrayAllocDescriptor(int UINT1, Pointer > SAFEARRAYPtrPtr1); - public static native int SafeArrayAllocDescriptorEx(short VARTYPE1, int UINT1, Pointer > SAFEARRAYPtrPtr1); - public static native int SafeArrayAllocData(Pointer SAFEARRAYPtr1); - public static native int SafeArrayDestroyDescriptor(Pointer SAFEARRAYPtr1); - public static native int SafeArrayPutElement(Pointer SAFEARRAYPtr1, Pointer LONGPtr1, Pointer voidPtr1); - public static native int SafeArrayGetElement(Pointer SAFEARRAYPtr1, Pointer LONGPtr1, Pointer voidPtr1); - public static native int SafeArrayLock(Pointer SAFEARRAYPtr1); - public static native int SafeArrayUnlock(Pointer SAFEARRAYPtr1); - public static native int SafeArrayGetUBound(Pointer SAFEARRAYPtr1, int UINT1, Pointer LONGPtr1); - public static native int SafeArrayGetLBound(Pointer SAFEARRAYPtr1, int UINT1, Pointer LONGPtr1); - public static native int SafeArrayGetDim(Pointer SAFEARRAYPtr1); - public static native int SafeArrayGetElemsize(Pointer SAFEARRAYPtr1); - public static native int SafeArrayGetVartype(Pointer SAFEARRAYPtr1, Pointer VARTYPEPtr1); - public static native int SafeArrayAccessData(Pointer SAFEARRAYPtr1, Pointer > voidPtrPtr1); - public static native int SafeArrayUnaccessData(Pointer SAFEARRAYPtr1); - public static native int SafeArrayPtrOfIndex(Pointer SAFEARRAYPtr1, Pointer LONGPtr1, Pointer > voidPtrPtr1); - public static native int SafeArrayCopyData(Pointer SAFEARRAYPtr1, Pointer SAFEARRAYPtr2); - public static native int SafeArrayDestroyData(Pointer SAFEARRAYPtr1); - public static native int SafeArrayDestroy(Pointer SAFEARRAYPtr1); - public static native int SafeArrayCopy(Pointer SAFEARRAYPtr1, Pointer > SAFEARRAYPtrPtr1); - public static native int SafeArrayRedim(Pointer SAFEARRAYPtr1, Pointer SAFEARRAYBOUNDPtr1); - public static native int SafeArraySetRecordInfo(Pointer SAFEARRAYPtr1, Pointer IRecordInfoPtr1); - public static native int SafeArrayGetRecordInfo(Pointer SAFEARRAYPtr1, Pointer > IRecordInfoPtrPtr1); - public static native int SafeArraySetIID(Pointer SAFEARRAYPtr1, Pointer REFGUID1); - public static native int SafeArrayGetIID(Pointer SAFEARRAYPtr1, Pointer GUIDPtr1); - public static native int VectorFromBstr(Pointer BSTR1, Pointer > SAFEARRAYPtrPtr1); - public static native int BstrFromVector(Pointer SAFEARRAYPtr1, Pointer > BSTRPtr1); - public static native int RegisterActiveObject(Pointer LPUNKNOWN1, int DWORD1); - public static native int RevokeActiveObject(int DWORD1); - public static native int GetActiveObject(Pointer > LPUNKNOWNPtr1); - public static native int GetRecordInfoFromTypeInfo(Pointer ITypeInfoPtr1, Pointer > IRecordInfoPtrPtr1); - public static native int GetRecordInfoFromGuids(Pointer REFGUID1, int ULONG1, int ULONG2, int LCID1, Pointer REFGUID2, Pointer > IRecordInfoPtrPtr1); - public static native void VariantInit(Pointer VARIANTPtr1); - public static native int VariantClear(Pointer VARIANTPtr1); - public static native int VariantCopy(Pointer VARIANTPtr1, Pointer VARIANTPtr2); - public static native int VariantCopyInd(Pointer VARIANTPtr1, Pointer VARIANTPtr2); - public static native int VariantChangeType(Pointer VARIANTPtr1, Pointer VARIANTPtr2, short USHORT1, short VARTYPE1); - public static native int VariantChangeTypeEx(Pointer VARIANTPtr1, Pointer VARIANTPtr2, int LCID1, short USHORT1, short VARTYPE1); - public static native int VarUI1FromI2(short SHORT1, Pointer BYTEPtr1); - public static native int VarUI1FromI4(@CLong long LONG1, Pointer BYTEPtr1); - public static native int VarUI1FromI8(long LONG641, Pointer BYTEPtr1); - public static native int VarUI1FromR4(float FLOAT1, Pointer BYTEPtr1); - public static native int VarUI1FromR8(double DOUBLE1, Pointer BYTEPtr1); - public static native int VarUI1FromDate(DATE DATE1, Pointer BYTEPtr1); - public static native int VarUI1FromBool(short VARIANT_BOOL1, Pointer BYTEPtr1); - public static native int VarUI1FromI1(byte char1, Pointer BYTEPtr1); - public static native int VarUI1FromUI2(short USHORT1, Pointer BYTEPtr1); - public static native int VarUI1FromUI4(int ULONG1, Pointer BYTEPtr1); - public static native int VarUI1FromUI8(long ULONG641, Pointer BYTEPtr1); - public static native int VarUI1FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer BYTEPtr1); - public static native int VarUI1FromCy(CY CY1, Pointer BYTEPtr1); - public static native int VarUI1FromDec(Pointer DECIMALPtr1, Pointer BYTEPtr1); - public static native int VarUI1FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer BYTEPtr1); - public static native int VarI2FromUI1(byte BYTE1, Pointer SHORTPtr1); - public static native int VarI2FromI4(@CLong long LONG1, Pointer SHORTPtr1); - public static native int VarI2FromI8(long LONG641, Pointer SHORTPtr1); - public static native int VarI2FromR4(float FLOAT1, Pointer SHORTPtr1); - public static native int VarI2FromR8(double DOUBLE1, Pointer SHORTPtr1); - public static native int VarI2FromDate(DATE DATE1, Pointer SHORTPtr1); - public static native int VarI2FromBool(short VARIANT_BOOL1, Pointer SHORTPtr1); - public static native int VarI2FromI1(byte char1, Pointer SHORTPtr1); - public static native int VarI2FromUI2(short USHORT1, Pointer SHORTPtr1); - public static native int VarI2FromUI4(int ULONG1, Pointer SHORTPtr1); - public static native int VarI2FromUI8(long ULONG641, Pointer SHORTPtr1); - public static native int VarI2FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer SHORTPtr1); - public static native int VarI2FromCy(CY CY1, Pointer SHORTPtr1); - public static native int VarI2FromDec(Pointer DECIMALPtr1, Pointer SHORTPtr1); - public static native int VarI2FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer SHORTPtr1); - public static native int VarI4FromUI1(byte BYTE1, Pointer LONGPtr1); - public static native int VarI4FromI2(short SHORT1, Pointer LONGPtr1); - public static native int VarI4FromI8(long LONG641, Pointer LONGPtr1); - public static native int VarI4FromR4(float FLOAT1, Pointer LONGPtr1); - public static native int VarI4FromR8(double DOUBLE1, Pointer LONGPtr1); - public static native int VarI4FromDate(DATE DATE1, Pointer LONGPtr1); - public static native int VarI4FromBool(short VARIANT_BOOL1, Pointer LONGPtr1); - public static native int VarI4FromI1(byte char1, Pointer LONGPtr1); - public static native int VarI4FromUI2(short USHORT1, Pointer LONGPtr1); - public static native int VarI4FromUI4(int ULONG1, Pointer LONGPtr1); - public static native int VarI4FromUI8(long ULONG641, Pointer LONGPtr1); - public static native int VarI4FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer LONGPtr1); - public static native int VarI4FromCy(CY CY1, Pointer LONGPtr1); - public static native int VarI4FromDec(Pointer DECIMALPtr1, Pointer LONGPtr1); - public static native int VarI4FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer LONGPtr1); - public static native int VarI8FromUI1(byte BYTE1, Pointer LONG64Ptr1); - public static native int VarI8FromI2(short SHORT1, Pointer LONG64Ptr1); - public static native int VarI8FromI4(@CLong long LONG1, Pointer LONG64Ptr1); - public static native int VarI8FromR4(float FLOAT1, Pointer LONG64Ptr1); - public static native int VarI8FromR8(double DOUBLE1, Pointer LONG64Ptr1); - public static native int VarI8FromDate(DATE DATE1, Pointer LONG64Ptr1); - public static native int VarI8FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer LONG64Ptr1); - public static native int VarI8FromBool(short VARIANT_BOOL1, Pointer LONG64Ptr1); - public static native int VarI8FromI1(byte char1, Pointer LONG64Ptr1); - public static native int VarI8FromUI2(short USHORT1, Pointer LONG64Ptr1); - public static native int VarI8FromUI4(int ULONG1, Pointer LONG64Ptr1); - public static native int VarI8FromUI8(long ULONG641, Pointer LONG64Ptr1); - public static native int VarI8FromDec(Pointer pdecIn, Pointer LONG64Ptr1); - public static native int VarI8FromInt(int intIn, Pointer LONG64Ptr1); - public static native int VarI8FromCy(CY CY1, Pointer LONG64Ptr1); - public static native int VarI8FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer LONG64Ptr1); - public static native int VarR4FromUI1(byte BYTE1, Pointer FLOATPtr1); - public static native int VarR4FromI2(short SHORT1, Pointer FLOATPtr1); - public static native int VarR4FromI4(@CLong long LONG1, Pointer FLOATPtr1); - public static native int VarR4FromI8(long LONG641, Pointer FLOATPtr1); - public static native int VarR4FromR8(double DOUBLE1, Pointer FLOATPtr1); - public static native int VarR4FromDate(DATE DATE1, Pointer FLOATPtr1); - public static native int VarR4FromBool(short VARIANT_BOOL1, Pointer FLOATPtr1); - public static native int VarR4FromI1(byte char1, Pointer FLOATPtr1); - public static native int VarR4FromUI2(short USHORT1, Pointer FLOATPtr1); - public static native int VarR4FromUI4(int ULONG1, Pointer FLOATPtr1); - public static native int VarR4FromUI8(long ULONG641, Pointer FLOATPtr1); - public static native int VarR4FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer FLOATPtr1); - public static native int VarR4FromCy(CY CY1, Pointer FLOATPtr1); - public static native int VarR4FromDec(Pointer DECIMALPtr1, Pointer FLOATPtr1); - public static native int VarR4FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer FLOATPtr1); - public static native int VarR8FromUI1(byte BYTE1, Pointer doublePtr1); - public static native int VarR8FromI2(short SHORT1, Pointer doublePtr1); - public static native int VarR8FromI4(@CLong long LONG1, Pointer doublePtr1); - public static native int VarR8FromI8(long LONG641, Pointer doublePtr1); - public static native int VarR8FromR4(float FLOAT1, Pointer doublePtr1); - public static native int VarR8FromDate(DATE DATE1, Pointer doublePtr1); - public static native int VarR8FromBool(short VARIANT_BOOL1, Pointer doublePtr1); - public static native int VarR8FromI1(byte char1, Pointer doublePtr1); - public static native int VarR8FromUI2(short USHORT1, Pointer doublePtr1); - public static native int VarR8FromUI4(int ULONG1, Pointer doublePtr1); - public static native int VarR8FromUI8(long ULONG641, Pointer doublePtr1); - public static native int VarR8FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer doublePtr1); - public static native int VarR8FromCy(CY CY1, Pointer doublePtr1); - public static native int VarR8FromDec(Pointer DECIMALPtr1, Pointer doublePtr1); - public static native int VarR8FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer doublePtr1); - public static native int VarDateFromUI1(byte BYTE1, Pointer DATEPtr1); - public static native int VarDateFromI2(short SHORT1, Pointer DATEPtr1); - public static native int VarDateFromI4(@CLong long LONG1, Pointer DATEPtr1); - public static native int VarDateFromI8(long LONG641, Pointer DATEPtr1); - public static native int VarDateFromR4(float FLOAT1, Pointer DATEPtr1); - public static native int VarDateFromR8(double DOUBLE1, Pointer DATEPtr1); - public static native int VarDateFromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer DATEPtr1); - public static native int VarDateFromI1(byte char1, Pointer DATEPtr1); - public static native int VarDateFromUI2(short USHORT1, Pointer DATEPtr1); - public static native int VarDateFromUI4(int ULONG1, Pointer DATEPtr1); - public static native int VarDateFromUI8(long ULONG641, Pointer DATEPtr1); - public static native int VarDateFromBool(short VARIANT_BOOL1, Pointer DATEPtr1); - public static native int VarDateFromCy(CY CY1, Pointer DATEPtr1); - public static native int VarDateFromDec(Pointer DECIMALPtr1, Pointer DATEPtr1); - public static native int VarDateFromDisp(Pointer IDispatchPtr1, int LCID1, Pointer DATEPtr1); - public static native int VarCyFromUI1(byte BYTE1, Pointer CYPtr1); - public static native int VarCyFromI2(short sIn, Pointer CYPtr1); - public static native int VarCyFromI4(@CLong long LONG1, Pointer CYPtr1); - public static native int VarCyFromI8(long LONG641, Pointer CYPtr1); - public static native int VarCyFromR4(float FLOAT1, Pointer CYPtr1); - public static native int VarCyFromR8(double DOUBLE1, Pointer CYPtr1); - public static native int VarCyFromDate(DATE DATE1, Pointer CYPtr1); - public static native int VarCyFromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer CYPtr1); - public static native int VarCyFromBool(short VARIANT_BOOL1, Pointer CYPtr1); - public static native int VarCyFromI1(byte char1, Pointer CYPtr1); - public static native int VarCyFromUI2(short USHORT1, Pointer CYPtr1); - public static native int VarCyFromUI4(int ULONG1, Pointer CYPtr1); - public static native int VarCyFromUI8(long ULONG641, Pointer CYPtr1); - public static native int VarCyFromDec(Pointer DECIMALPtr1, Pointer CYPtr1); - public static native int VarCyFromDisp(Pointer IDispatchPtr1, int LCID1, Pointer CYPtr1); - public static native int VarBstrFromUI1(byte BYTE1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromI2(short SHORT1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromI4(@CLong long LONG1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromI8(long LONG641, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromR4(float FLOAT1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromR8(double DOUBLE1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromDate(DATE DATE1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromBool(short VARIANT_BOOL1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromI1(byte char1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromUI2(short USHORT1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromUI8(long ULONG641, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromUI4(int ULONG1, int LCID1, int ULONG2, Pointer > BSTRPtr1); - public static native int VarBstrFromCy(CY CY1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromDec(Pointer DECIMALPtr1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBstrFromDisp(Pointer IDispatchPtr1, int LCID1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarBoolFromUI1(byte BYTE1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromI2(short SHORT1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromI4(@CLong long LONG1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromI8(long LONG641, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromR4(float FLOAT1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromR8(double DOUBLE1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromDate(DATE DATE1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromI1(byte char1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromUI2(short USHORT1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromUI4(int ULONG1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromUI8(long ULONG641, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromCy(CY CY1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromDec(Pointer DECIMALPtr1, Pointer VARIANT_BOOLPtr1); - public static native int VarBoolFromDisp(Pointer IDispatchPtr1, int LCID1, Pointer VARIANT_BOOLPtr1); - public static native int VarI1FromUI1(byte BYTE1, Pointer charPtr1); - public static native int VarI1FromI2(short SHORT1, Pointer charPtr1); - public static native int VarI1FromI4(@CLong long LONG1, Pointer charPtr1); - public static native int VarI1FromI8(long LONG641, Pointer charPtr1); - public static native int VarI1FromR4(float FLOAT1, Pointer charPtr1); - public static native int VarI1FromR8(double DOUBLE1, Pointer charPtr1); - public static native int VarI1FromDate(DATE DATE1, Pointer charPtr1); - public static native int VarI1FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer charPtr1); - public static native int VarI1FromBool(short VARIANT_BOOL1, Pointer charPtr1); - public static native int VarI1FromUI2(short USHORT1, Pointer charPtr1); - public static native int VarI1FromUI4(int ULONG1, Pointer charPtr1); - public static native int VarI1FromUI8(long ULONG641, Pointer charPtr1); - public static native int VarI1FromCy(CY CY1, Pointer charPtr1); - public static native int VarI1FromDec(Pointer DECIMALPtr1, Pointer charPtr1); - public static native int VarI1FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer charPtr1); - public static native int VarUI2FromUI1(byte BYTE1, Pointer USHORTPtr1); - public static native int VarUI2FromI2(short SHORT1, Pointer USHORTPtr1); - public static native int VarUI2FromI4(@CLong long LONG1, Pointer USHORTPtr1); - public static native int VarUI2FromI8(long LONG641, Pointer USHORTPtr1); - public static native int VarUI2FromR4(float FLOAT1, Pointer USHORTPtr1); - public static native int VarUI2FromR8(double DOUBLE1, Pointer USHORTPtr1); - public static native int VarUI2FromDate(DATE DATE1, Pointer USHORTPtr1); - public static native int VarUI2FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer USHORTPtr1); - public static native int VarUI2FromBool(short VARIANT_BOOL1, Pointer USHORTPtr1); - public static native int VarUI2FromI1(byte char1, Pointer USHORTPtr1); - public static native int VarUI2FromUI4(int ULONG1, Pointer USHORTPtr1); - public static native int VarUI2FromUI8(long ULONG641, Pointer USHORTPtr1); - public static native int VarUI2FromCy(CY CY1, Pointer USHORTPtr1); - public static native int VarUI2FromDec(Pointer DECIMALPtr1, Pointer USHORTPtr1); - public static native int VarUI2FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer USHORTPtr1); - public static native int VarUI4FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer ULONGPtr1); - public static native int VarUI4FromUI1(byte BYTE1, Pointer ULONGPtr1); - public static native int VarUI4FromI2(short SHORT1, Pointer ULONGPtr1); - public static native int VarUI4FromI4(@CLong long LONG1, Pointer ULONGPtr1); - public static native int VarUI4FromI8(long LONG641, Pointer ULONGPtr1); - public static native int VarUI4FromR4(float FLOAT1, Pointer ULONGPtr1); - public static native int VarUI4FromR8(double DOUBLE1, Pointer ULONGPtr1); - public static native int VarUI4FromDate(DATE DATE1, Pointer ULONGPtr1); - public static native int VarUI4FromBool(short VARIANT_BOOL1, Pointer ULONGPtr1); - public static native int VarUI4FromI1(byte char1, Pointer ULONGPtr1); - public static native int VarUI4FromUI2(short USHORT1, Pointer ULONGPtr1); - public static native int VarUI4FromUI8(long ULONG641, Pointer ULONGPtr1); - public static native int VarUI4FromCy(CY CY1, Pointer ULONGPtr1); - public static native int VarUI4FromDec(Pointer DECIMALPtr1, Pointer ULONGPtr1); - public static native int VarUI4FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer ULONGPtr1); - public static native int VarUI8FromUI1(byte BYTE1, Pointer ULONG64Ptr1); - public static native int VarUI8FromI2(short SHORT1, Pointer ULONG64Ptr1); - public static native int VarUI8FromI4(@CLong long LONG1, Pointer ULONG64Ptr1); - public static native int VarUI8FromI8(long LONG641, Pointer ULONG64Ptr1); - public static native int VarUI8FromR4(float FLOAT1, Pointer ULONG64Ptr1); - public static native int VarUI8FromR8(double DOUBLE1, Pointer ULONG64Ptr1); - public static native int VarUI8FromDate(DATE DATE1, Pointer ULONG64Ptr1); - public static native int VarUI8FromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer ULONG64Ptr1); - public static native int VarUI8FromBool(short VARIANT_BOOL1, Pointer ULONG64Ptr1); - public static native int VarUI8FromI1(byte char1, Pointer ULONG64Ptr1); - public static native int VarUI8FromUI2(short USHORT1, Pointer ULONG64Ptr1); - public static native int VarUI8FromUI4(int ULONG1, Pointer ULONG64Ptr1); - public static native int VarUI8FromDec(Pointer DECIMALPtr1, Pointer ULONG64Ptr1); - public static native int VarUI8FromInt(int INT1, Pointer ULONG64Ptr1); - public static native int VarUI8FromCy(CY CY1, Pointer ULONG64Ptr1); - public static native int VarUI8FromDisp(Pointer IDispatchPtr1, int LCID1, Pointer ULONG64Ptr1); - public static native int VarDecFromUI1(byte BYTE1, Pointer DECIMALPtr1); - public static native int VarDecFromI2(short SHORT1, Pointer DECIMALPtr1); - public static native int VarDecFromI4(@CLong long LONG1, Pointer DECIMALPtr1); - public static native int VarDecFromI8(long LONG641, Pointer DECIMALPtr1); - public static native int VarDecFromR4(float FLOAT1, Pointer DECIMALPtr1); - public static native int VarDecFromR8(double DOUBLE1, Pointer DECIMALPtr1); - public static native int VarDecFromDate(DATE DATE1, Pointer DECIMALPtr1); - public static native int VarDecFromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer DECIMALPtr1); - public static native int VarDecFromBool(short VARIANT_BOOL1, Pointer DECIMALPtr1); - public static native int VarDecFromI1(byte char1, Pointer DECIMALPtr1); - public static native int VarDecFromUI2(short USHORT1, Pointer DECIMALPtr1); - public static native int VarDecFromUI4(int ULONG1, Pointer DECIMALPtr1); - public static native int VarDecFromUI8(long ULONG641, Pointer DECIMALPtr1); - public static native int VarDecFromCy(CY CY1, Pointer DECIMALPtr1); - public static native int VarDecFromDisp(Pointer IDispatchPtr1, int LCID1, Pointer DECIMALPtr1); - public static native int VarR4CmpR8(float float1, double double1); - public static native int VarR8Pow(double double1, double double2, Pointer doublePtr1); - public static native int VarR8Round(double double1, int int1, Pointer doublePtr1); - public static native int VarDecAbs(Pointer DECIMALPtr1, Pointer DECIMALPtr2); - public static native int VarDecAdd(Pointer DECIMALPtr1, Pointer DECIMALPtr2, Pointer DECIMALPtr3); - public static native int VarDecCmp(Pointer DECIMALPtr1, Pointer DECIMALPtr2); - public static native int VarDecCmpR8(Pointer DECIMALPtr1, double DOUBLE1); - public static native int VarDecDiv(Pointer DECIMALPtr1, Pointer DECIMALPtr2, Pointer DECIMALPtr3); - public static native int VarDecFix(Pointer DECIMALPtr1, Pointer DECIMALPtr2); - public static native int VarDecInt(Pointer DECIMALPtr1, Pointer DECIMALPtr2); - public static native int VarDecMul(Pointer DECIMALPtr1, Pointer DECIMALPtr2, Pointer DECIMALPtr3); - public static native int VarDecNeg(Pointer DECIMALPtr1, Pointer DECIMALPtr2); - public static native int VarDecRound(Pointer DECIMALPtr1, int int1, Pointer DECIMALPtr2); - public static native int VarDecSub(Pointer DECIMALPtr1, Pointer DECIMALPtr2, Pointer DECIMALPtr3); - public static native int VarCyAbs(CY CY1, Pointer CYPtr1); - public static native int VarCyAdd(CY CY1, CY CY2, Pointer CYPtr1); - public static native int VarCyCmp(CY CY1, CY CY2); - public static native int VarCyCmpR8(CY CY1, double DOUBLE1); - public static native int VarCyFix(CY CY1, Pointer CYPtr1); - public static native int VarCyInt(CY CY1, Pointer CYPtr1); - public static native int VarCyMul(CY CY1, CY CY2, Pointer CYPtr1); - public static native int VarCyMulI4(CY CY1, @CLong long LONG1, Pointer CYPtr1); - public static native int VarCyMulI8(CY CY1, long LONG641, Pointer CYPtr1); - public static native int VarCyNeg(CY CY1, Pointer CYPtr1); - public static native int VarCyRound(CY CY1, int INT1, Pointer CYPtr1); - public static native int VarCySub(CY CY1, CY CY2, Pointer CYPtr1); - public static native int VarAdd(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarAnd(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarCat(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarDiv(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarEqv(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarIdiv(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarImp(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarMod(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarMul(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarOr(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarPow(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarSub(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarXor(Pointer LPVARIANT1, Pointer LPVARIANT2, Pointer LPVARIANT3); - public static native int VarAbs(Pointer LPVARIANT1, Pointer LPVARIANT2); - public static native int VarFix(Pointer LPVARIANT1, Pointer LPVARIANT2); - public static native int VarInt(Pointer LPVARIANT1, Pointer LPVARIANT2); - public static native int VarNeg(Pointer LPVARIANT1, Pointer LPVARIANT2); - public static native int VarNot(Pointer LPVARIANT1, Pointer LPVARIANT2); - public static native int VarRound(Pointer LPVARIANT1, int int1, Pointer LPVARIANT2); - public static native int VarCmp(Pointer LPVARIANT1, Pointer LPVARIANT2, int LCID1, int ULONG1); - public static native int VarBstrCmp(Pointer BSTR1, Pointer BSTR2, int LCID1, int ULONG1); - public static native int VarBstrCat(Pointer BSTR1, Pointer BSTR2, Pointer > BSTRPtr1); - public static native int VarParseNumFromStr(Pointer OLECHARPtr1, int LCID1, int ULONG1, Pointer NUMPARSEPtr1, Pointer BYTEPtr1); - public static native int VarNumFromParseNum(Pointer NUMPARSEPtr1, Pointer BYTEPtr1, int ULONG1, Pointer VARIANTPtr1); - public static native int DosDateTimeToVariantTime(short USHORT1, short USHORT2, Pointer doublePtr1); - public static native int VariantTimeToDosDateTime(double double1, Pointer USHORTPtr1, Pointer USHORTPtr2); - public static native int VariantTimeToSystemTime(double DOUBLE1, Pointer LPSYSTEMTIME1); - public static native int SystemTimeToVariantTime(Pointer LPSYSTEMTIME1, Pointer doublePtr1); - public static native int VarDateFromUdate(Pointer UDATEPtr1, int ULONG1, Pointer DATEPtr1); - public static native int VarDateFromUdateEx(Pointer UDATEPtr1, int LCID1, int ULONG1, Pointer DATEPtr1); - public static native int VarUdateFromDate(DATE DATE1, int ULONG1, Pointer UDATEPtr1); - public static native int VarWeekdayName(int int1, int int2, int int3, int ULONG1, Pointer > BSTRPtr1); - public static native int VarMonthName(int int1, int int2, int ULONG1, Pointer > BSTRPtr1); - public static native int GetAltMonthNames(int LCID1, Pointer > > LPOLESTRPtrPtr1); - public static native int VarFormat(Pointer LPVARIANT1, Pointer LPOLESTR1, int int1, int int2, int ULONG1, Pointer > BSTRPtr1); - public static native int VarFormatCurrency(Pointer LPVARIANT1, int int1, int int2, int int3, int int4, int ULONG1, Pointer > BSTRPtr1); - public static native int VarFormatDateTime(Pointer LPVARIANT1, int int1, int ULONG1, Pointer > BSTRPtr1); - public static native int VarFormatNumber(Pointer LPVARIANT1, int int1, int int2, int int3, int int4, int ULONG1, Pointer > BSTRPtr1); - public static native int VarFormatPercent(Pointer LPVARIANT1, int int1, int int2, int int3, int int4, int ULONG1, Pointer > BSTRPtr1); - public static native int VarFormatFromTokens(Pointer LPVARIANT1, Pointer LPOLESTR1, int ULONG1, Pointer > BSTRPtr1, int LCID1); - public static native int VarTokenizeFormatString(Pointer LPOLESTR1, int int1, int int2, int int3, int LCID1, Pointer intPtr1); - public static native int DispGetParam(Pointer DISPPARAMSPtr1, int UINT1, short VARTYPE1, Pointer VARIANTPtr1, Pointer UINTPtr1); - public static native int DispGetIDsOfNames(Pointer ITypeInfoPtr1, Pointer > OLECHARPtrPtr1, int UINT1, Pointer DISPIDPtr1); - public static native int DispInvoke(Pointer voidPtr1, Pointer ITypeInfoPtr1, @CLong long DISPID1, short WORD1, Pointer DISPPARAMSPtr1, Pointer VARIANTPtr1, Pointer EXCEPINFOPtr1, Pointer UINTPtr1); - public static native int CreateDispTypeInfo(Pointer INTERFACEDATAPtr1, int LCID1, Pointer > ITypeInfoPtrPtr1); - public static native int CreateStdDispatch(Pointer IUnknownPtr1, Pointer voidPtr1, Pointer ITypeInfoPtr1, Pointer > IUnknownPtrPtr1); - public static native int DispCallFunc(Pointer voidPtr1, ValuedEnum CALLCONV1, short VARTYPE1, int UINT1, Pointer VARTYPEPtr1, Pointer > VARIANTARGPtrPtr1, Pointer VARIANTPtr1); - public static native int LHashValOfNameSysA(ValuedEnum SYSKIND1, int LCID1); - public static native int LHashValOfNameSys(ValuedEnum SYSKIND1, int LCID1); - public static native int CreateTypeLib(ValuedEnum SYSKIND1, Pointer OLECHARPtr1, Pointer > ICreateTypeLibPtrPtr1); - public static native int CreateTypeLib2(ValuedEnum SYSKIND1, Pointer > ICreateTypeLib2PtrPtr1); - public static native int LoadRegTypeLib(Pointer REFGUID1, short WORD1, short WORD2, int LCID1, Pointer > ITypeLibPtrPtr1); - public static native int LoadTypeLib(Pointer OLECHARPtr1, Pointer > ITypeLibPtrPtr1); - public static native int LoadTypeLibEx(ValuedEnum REGKIND1, Pointer > ITypeLibPtrPtr1); - public static native int QueryPathOfRegTypeLib(Pointer REFGUID1, short WORD1, short WORD2, int LCID1, Pointer > LPBSTR1); - public static native int RegisterTypeLib(Pointer ITypeLibPtr1, Pointer OLECHARPtr1, Pointer OLECHARPtr2); - public static native int UnRegisterTypeLib(Pointer REFGUID1, short WORD1, short WORD2, int LCID1, ValuedEnum SYSKIND1); - public static native int RegisterTypeLibForUser(Pointer ITypeLibPtr1, Pointer OLECHARPtr1, Pointer OLECHARPtr2); - public static native int UnRegisterTypeLibForUser(Pointer REFGUID1, short WORD1, short WORD2, int LCID1, ValuedEnum SYSKIND1); - public static native void ClearCustData(Pointer LPCUSTDATA1); -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/RECT.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/RECT.java deleted file mode 100644 index db7574450..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/RECT.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.CLong; -import org.bridj.ann.Runtime; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class RECT extends StructObject { - @CLong - @Field(0) - public long left() { - return this.io.getCLongField(this, 0); - } - @CLong - @Field(0) - public RECT left(long left) { - this.io.setCLongField(this, 0, left); - return this; - } - public final long left_$eq(long left) { - left(left); - return left; - } - @CLong - @Field(1) - public long top() { - return this.io.getCLongField(this, 1); - } - @CLong - @Field(1) - public RECT top(long top) { - this.io.setCLongField(this, 1, top); - return this; - } - public final long top_$eq(long top) { - top(top); - return top; - } - @CLong - @Field(2) - public long right() { - return this.io.getCLongField(this, 2); - } - @CLong - @Field(2) - public RECT right(long right) { - this.io.setCLongField(this, 2, right); - return this; - } - public final long right_$eq(long right) { - right(right); - return right; - } - @CLong - @Field(3) - public long bottom() { - return this.io.getCLongField(this, 3); - } - @CLong - @Field(3) - public RECT bottom(long bottom) { - this.io.setCLongField(this, 3, bottom); - return this; - } - public final long bottom_$eq(long bottom) { - bottom(bottom); - return bottom; - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAY.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAY.java deleted file mode 100644 index 9c8e4b16f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAY.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Array; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class SAFEARRAY extends StructObject { - /// C type : USHORT - @Field(0) - public short cDims() { - return this.io.getShortField(this, 0); - } - /// C type : USHORT - @Field(0) - public SAFEARRAY cDims(short cDims) { - this.io.setShortField(this, 0, cDims); - return this; - } - /// C type : USHORT - public final short cDims_$eq(short cDims) { - cDims(cDims); - return cDims; - } - /// C type : USHORT - @Field(1) - public short fFeatures() { - return this.io.getShortField(this, 1); - } - /// C type : USHORT - @Field(1) - public SAFEARRAY fFeatures(short fFeatures) { - this.io.setShortField(this, 1, fFeatures); - return this; - } - /// C type : USHORT - public final short fFeatures_$eq(short fFeatures) { - fFeatures(fFeatures); - return fFeatures; - } - /// C type : ULONG - @Field(2) - public int cbElements() { - return this.io.getIntField(this, 2); - } - /// C type : ULONG - @Field(2) - public SAFEARRAY cbElements(int cbElements) { - this.io.setIntField(this, 2, cbElements); - return this; - } - /// C type : ULONG - public final int cbElements_$eq(int cbElements) { - cbElements(cbElements); - return cbElements; - } - /// C type : ULONG - @Field(3) - public int cLocks() { - return this.io.getIntField(this, 3); - } - /// C type : ULONG - @Field(3) - public SAFEARRAY cLocks(int cLocks) { - this.io.setIntField(this, 3, cLocks); - return this; - } - /// C type : ULONG - public final int cLocks_$eq(int cLocks) { - cLocks(cLocks); - return cLocks; - } - /// C type : PVOID - @Field(4) - public Pointer pvData() { - return this.io.getPointerField(this, 4); - } - /// C type : PVOID - @Field(4) - public SAFEARRAY pvData(Pointer pvData) { - this.io.setPointerField(this, 4, pvData); - return this; - } - /// C type : PVOID - public final Pointer pvData_$eq(Pointer pvData) { - pvData(pvData); - return pvData; - } - /// C type : SAFEARRAYBOUND[1] - @Array({1}) - @Field(5) - public Pointer rgsabound() { - return this.io.getPointerField(this, 5); - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAYBOUND.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAYBOUND.java deleted file mode 100644 index d881c21a6..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/SAFEARRAYBOUND.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.CLong; -import org.bridj.ann.Field; -import org.bridj.ann.Runtime; -import org.bridj.ann.Library; -/** - * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Runtime(CRuntime.class) -public class SAFEARRAYBOUND extends StructObject { - /// C type : ULONG - @Field(0) - public int cElements() { - return this.io.getIntField(this, 0); - } - /// C type : ULONG - @Field(0) - public SAFEARRAYBOUND cElements(int cElements) { - this.io.setIntField(this, 0, cElements); - return this; - } - /// C type : ULONG - public final int cElements_$eq(int cElements) { - cElements(cElements); - return cElements; - } - @CLong - @Field(1) - public long lLbound() { - return this.io.getCLongField(this, 1); - } - @CLong - @Field(1) - public SAFEARRAYBOUND lLbound(long lLbound) { - this.io.setCLongField(this, 1, lLbound); - return this; - } - public final long lLbound_$eq(long lLbound) { - lLbound(lLbound); - return lLbound; - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARENUM.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARENUM.java deleted file mode 100644 index a9f9b7bbd..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARENUM.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.bridj.cpp.com; -import java.util.Collections; -import java.util.Iterator; -import org.bridj.BridJ; -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.ValuedEnum; - -public enum VARENUM implements IntValuedEnum { - VT_EMPTY(0), - VT_NULL(1), - VT_I2(2), - VT_I4(3), - VT_R4(4), - VT_R8(5), - VT_CY(6), - VT_DATE(7), - VT_BSTR(8), - VT_DISPATCH(9), - VT_ERROR(10), - VT_BOOL(11), - VT_VARIANT(12), - VT_UNKNOWN(13), - VT_DECIMAL(14), - VT_I1(16), - VT_UI1(17), - VT_UI2(18), - VT_UI4(19), - VT_I8(20), - VT_UI8(21), - VT_INT(22), - VT_UINT(23), - VT_VOID(24), - VT_HRESULT(25), - VT_PTR(26), - VT_SAFEARRAY(27), - VT_CARRAY(28), - VT_USERDEFINED(29), - VT_LPSTR(30), - VT_LPWSTR(31), - VT_FILETIME(64), - VT_BLOB(65), - VT_STREAM(66), - VT_STORAGE(67), - VT_STREAMED_OBJECT(68), - VT_STORED_OBJECT(69), - VT_BLOB_OBJECT(70), - VT_CF(71), - VT_CLSID(72), - VT_VECTOR(0x1000), - VT_ARRAY(0x2000), - VT_BYREF(0x4000), - VT_RESERVED(0x8000), - VT_ILLEGAL(0xFFFF), - VT_ILLEGALMASKED(0xFFF), - VT_TYPEMASK(0xFFF); - VARENUM(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } -}; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARIANT.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARIANT.java deleted file mode 100644 index 3845246f4..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/VARIANT.java +++ /dev/null @@ -1,1128 +0,0 @@ -package org.bridj.cpp.com; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ValuedEnum; -import org.bridj.ann.CLong; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Union; -import org.bridj.ann.Runtime; - -/** - * Represents an object that can be interpreted as more than one type. - */ -@Runtime(CRuntime.class) -public class VARIANT extends StructObject { - public VARIANT(Object value) { - super(); - COMRuntime.setValue(this, value); - } - public VARIANT() { - super(); - } - public VARIANT clone() { - return COMRuntime.clone(this); - } - /// C type : __VARIANT_NAME_1_union - @Field(0) - public VARIANT.__VARIANT_NAME_1_union __VARIANT_NAME_1() { - return this.io.getNativeObjectField(this, 0); - } - /// native declaration : line 107 - @Union - public static class __VARIANT_NAME_1_union extends StructObject { - public __VARIANT_NAME_1_union() { - super(); - } -// public __VARIANT_NAME_1_union(Pointer pointer) { -// super(pointer); -// } - /// C type : __tagVARIANT - @Field(0) - public VARIANT.__VARIANT_NAME_1_union.__tagVARIANT __VARIANT_NAME_2() { - return this.io.getNativeObjectField(this, 0); - } - /// C type : DECIMAL - @Field(1) - public DECIMAL decVal() { - return this.io.getNativeObjectField(this, 1); - } - /// native declaration : line 109 - public static class __tagVARIANT extends StructObject { - public __tagVARIANT() { - super(); - } -// public __tagVARIANT(Pointer pointer) { -// super(pointer); -// } - /// C type : VARTYPE - @Field(0) - public short vt() { - return this.io.getShortField(this, 0); - } - /// C type : VARTYPE - @Field(0) - public __tagVARIANT vt(short vt) { - this.io.setShortField(this, 0, vt); - return this; - } - /// C type : VARTYPE - public final short vt_$eq(short vt) { - vt(vt); - return vt; - } - @Field(1) - public short wReserved1() { - return this.io.getShortField(this, 1); - } - @Field(1) - public __tagVARIANT wReserved1(short wReserved1) { - this.io.setShortField(this, 1, wReserved1); - return this; - } - public final short wReserved1_$eq(short wReserved1) { - wReserved1(wReserved1); - return wReserved1; - } - @Field(2) - public short wReserved2() { - return this.io.getShortField(this, 2); - } - @Field(2) - public __tagVARIANT wReserved2(short wReserved2) { - this.io.setShortField(this, 2, wReserved2); - return this; - } - public final short wReserved2_$eq(short wReserved2) { - wReserved2(wReserved2); - return wReserved2; - } - @Field(3) - public short wReserved3() { - return this.io.getShortField(this, 3); - } - @Field(3) - public __tagVARIANT wReserved3(short wReserved3) { - this.io.setShortField(this, 3, wReserved3); - return this; - } - public final short wReserved3_$eq(short wReserved3) { - wReserved3(wReserved3); - return wReserved3; - } - /// C type : __VARIANT_NAME_3_union - @Field(4) - public VARIANT.__VARIANT_NAME_1_union.__tagVARIANT.__VARIANT_NAME_3_union __VARIANT_NAME_3() { - return this.io.getNativeObjectField(this, 4); - } - /// native declaration : line 115 - @Union - public static class __VARIANT_NAME_3_union extends StructObject { - public __VARIANT_NAME_3_union() { - super(); - } -// public __VARIANT_NAME_3_union(Pointer pointer) { -// super(pointer); -// } - /// VT_I8 - @Field(0) - public long llval() { - return this.io.getLongField(this, 0); - } - /// VT_I8 - @Field(0) - public __VARIANT_NAME_3_union llval(long llval) { - this.io.setLongField(this, 0, llval); - return this; - } - public final long llval_$eq(long llval) { - llval(llval); - return llval; - } - /// VT_I4 - @CLong - @Field(1) - public long lVal() { - return this.io.getCLongField(this, 1); - } - /// VT_I4 - @CLong - @Field(1) - public __VARIANT_NAME_3_union lVal(long lVal) { - this.io.setCLongField(this, 1, lVal); - return this; - } - public final long lVal_$eq(long lVal) { - lVal(lVal); - return lVal; - } - /// VT_UI1 - @Field(2) - public byte bVal() { - return this.io.getByteField(this, 2); - } - /// VT_UI1 - @Field(2) - public __VARIANT_NAME_3_union bVal(byte bVal) { - this.io.setByteField(this, 2, bVal); - return this; - } - public final byte bVal_$eq(byte bVal) { - bVal(bVal); - return bVal; - } - /** - * VT_I2
- * C type : SHORT - */ - @Field(3) - public short iVal() { - return this.io.getShortField(this, 3); - } - /** - * VT_I2
- * C type : SHORT - */ - @Field(3) - public __VARIANT_NAME_3_union iVal(short iVal) { - this.io.setShortField(this, 3, iVal); - return this; - } - /// C type : SHORT - public final short iVal_$eq(short iVal) { - iVal(iVal); - return iVal; - } - /** - * VT_R4
- * C type : FLOAT - */ - @Field(4) - public float fltVal() { - return this.io.getFloatField(this, 4); - } - /** - * VT_R4
- * C type : FLOAT - */ - @Field(4) - public __VARIANT_NAME_3_union fltVal(float fltVal) { - this.io.setFloatField(this, 4, fltVal); - return this; - } - /// C type : FLOAT - public final float fltVal_$eq(float fltVal) { - fltVal(fltVal); - return fltVal; - } - /** - * VT_R8
- * C type : DOUBLE - */ - @Field(5) - public double dblVal() { - return this.io.getDoubleField(this, 5); - } - /** - * VT_R8
- * C type : DOUBLE - */ - @Field(5) - public __VARIANT_NAME_3_union dblVal(double dblVal) { - this.io.setDoubleField(this, 5, dblVal); - return this; - } - /// C type : DOUBLE - public final double dblVal_$eq(double dblVal) { - dblVal(dblVal); - return dblVal; - } - /** - * VT_BOOL
- * C type : VARIANT_BOOL - */ - @Field(6) - public int boolVal() { - return this.io.getIntField(this, 6); - } - /** - * VT_BOOL
- * C type : VARIANT_BOOL - */ - @Field(6) - public __VARIANT_NAME_3_union boolVal(int boolVal) { - this.io.setIntField(this, 6, boolVal); - return this; - } - /// C type : VARIANT_BOOL - public final int boolVal_$eq(int boolVal) { - boolVal(boolVal); - return boolVal; - } - /// C type : _VARIANT_BOOL - @Field(7) - public int bool() { - return this.io.getIntField(this, 7); - } - /// C type : _VARIANT_BOOL - @Field(7) - public __VARIANT_NAME_3_union bool(int bool) { - this.io.setIntField(this, 7, bool); - return this; - } - /// C type : _VARIANT_BOOL - public final int bool_$eq(int bool) { - bool(bool); - return bool; - } - /** - * VT_ERROR
- * C type : SCODE - */ - @Field(8) - public int scode() { - return this.io.getIntField(this, 8); - } - /** - * VT_ERROR
- * C type : SCODE - */ - @Field(8) - public __VARIANT_NAME_3_union scode(int scode) { - this.io.setIntField(this, 8, scode); - return this; - } - /// C type : SCODE - public final int scode_$eq(int scode) { - scode(scode); - return scode; - } - /** - * VT_CY
- * C type : CY - */ - @Field(9) - public CY cyVal() { - return this.io.getNativeObjectField(this, 9); - } - /** - * VT_DATE
- * C type : DATE - */ - @Field(10) - public double date() { - return this.io.getDoubleField(this, 10); - } - /** - * VT_DATE
- * C type : DATE - */ - @Field(10) - public __VARIANT_NAME_3_union date(double date) { - this.io.setDoubleField(this, 10, date); - return this; - } - /// C type : DATE - public final double date_$eq(double date) { - date(date); - return date; - } - /** - * VT_BSTR
- * C type : BSTR - */ - @Field(11) - public Pointer bstrVal() { - return this.io.getPointerField(this, 11); - } - /** - * VT_BSTR
- * C type : BSTR - */ - @Field(11) - public __VARIANT_NAME_3_union bstrVal(Pointer bstrVal) { - this.io.setPointerField(this, 11, bstrVal); - return this; - } - /// C type : BSTR - public final Pointer bstrVal_$eq(Pointer bstrVal) { - bstrVal(bstrVal); - return bstrVal; - } - /** - * VT_UNKNOWN
- * C type : IUnknown* - */ - @Field(12) - public Pointer punkVal() { - return this.io.getPointerField(this, 12); - } - /** - * VT_UNKNOWN
- * C type : IUnknown* - */ - @Field(12) - public __VARIANT_NAME_3_union punkVal(Pointer punkVal) { - this.io.setPointerField(this, 12, punkVal); - return this; - } - /// C type : IUnknown* - public final Pointer punkVal_$eq(Pointer punkVal) { - punkVal(punkVal); - return punkVal; - } - /** - * VT_DISPATCH
- * C type : IDispatch* - */ - @Field(13) - public Pointer pdispVal() { - return this.io.getPointerField(this, 13); - } - /** - * VT_DISPATCH
- * C type : IDispatch* - */ - @Field(13) - public __VARIANT_NAME_3_union pdispVal(Pointer pdispVal) { - this.io.setPointerField(this, 13, pdispVal); - return this; - } - /// C type : IDispatch* - public final Pointer pdispVal_$eq(Pointer pdispVal) { - pdispVal(pdispVal); - return pdispVal; - } - /** - * VT_ARRAY|*
- * C type : SAFEARRAY* - */ - @Field(14) - public Pointer parray() { - return this.io.getPointerField(this, 14); - } - /** - * VT_ARRAY|*
- * C type : SAFEARRAY* - */ - @Field(14) - public __VARIANT_NAME_3_union parray(Pointer parray) { - this.io.setPointerField(this, 14, parray); - return this; - } - /// C type : SAFEARRAY* - public final Pointer parray_$eq(Pointer parray) { - parray(parray); - return parray; - } - /** - * VT_BYREF|VT_UI1
- * C type : BYTE* - */ - @Field(15) - public Pointer pbVal() { - return this.io.getPointerField(this, 15); - } - /** - * VT_BYREF|VT_UI1
- * C type : BYTE* - */ - @Field(15) - public __VARIANT_NAME_3_union pbVal(Pointer pbVal) { - this.io.setPointerField(this, 15, pbVal); - return this; - } - /// C type : BYTE* - public final Pointer pbVal_$eq(Pointer pbVal) { - pbVal(pbVal); - return pbVal; - } - /** - * VT_BYREF|VT_I2
- * C type : SHORT* - */ - @Field(16) - public Pointer piVal() { - return this.io.getPointerField(this, 16); - } - /** - * VT_BYREF|VT_I2
- * C type : SHORT* - */ - @Field(16) - public __VARIANT_NAME_3_union piVal(Pointer piVal) { - this.io.setPointerField(this, 16, piVal); - return this; - } - /// C type : SHORT* - public final Pointer piVal_$eq(Pointer piVal) { - piVal(piVal); - return piVal; - } - /** - * VT_BYREF|VT_I4
- * C type : LONG* - */ - @Field(17) - public Pointer plVal() { - return this.io.getPointerField(this, 17); - } - /** - * VT_BYREF|VT_I4
- * C type : LONG* - */ - @Field(17) - public __VARIANT_NAME_3_union plVal(Pointer plVal) { - this.io.setPointerField(this, 17, plVal); - return this; - } - /// C type : LONG* - public final Pointer plVal_$eq(Pointer plVal) { - plVal(plVal); - return plVal; - } - /** - * VT_BYREF|VT_I8
- * C type : LONGLONG* - */ - @Field(18) - public Pointer pllVal() { - return this.io.getPointerField(this, 18); - } - /** - * VT_BYREF|VT_I8
- * C type : LONGLONG* - */ - @Field(18) - public __VARIANT_NAME_3_union pllVal(Pointer pllVal) { - this.io.setPointerField(this, 18, pllVal); - return this; - } - /// C type : LONGLONG* - public final Pointer pllVal_$eq(Pointer pllVal) { - pllVal(pllVal); - return pllVal; - } - /** - * VT_BYREF|VT_R4
- * C type : FLOAT* - */ - @Field(19) - public Pointer pfltVal() { - return this.io.getPointerField(this, 19); - } - /** - * VT_BYREF|VT_R4
- * C type : FLOAT* - */ - @Field(19) - public __VARIANT_NAME_3_union pfltVal(Pointer pfltVal) { - this.io.setPointerField(this, 19, pfltVal); - return this; - } - /// C type : FLOAT* - public final Pointer pfltVal_$eq(Pointer pfltVal) { - pfltVal(pfltVal); - return pfltVal; - } - /** - * VT_BYREF|VT_R8
- * C type : DOUBLE* - */ - @Field(20) - public Pointer pdblVal() { - return this.io.getPointerField(this, 20); - } - /** - * VT_BYREF|VT_R8
- * C type : DOUBLE* - */ - @Field(20) - public __VARIANT_NAME_3_union pdblVal(Pointer pdblVal) { - this.io.setPointerField(this, 20, pdblVal); - return this; - } - /// C type : DOUBLE* - public final Pointer pdblVal_$eq(Pointer pdblVal) { - pdblVal(pdblVal); - return pdblVal; - } - /** - * VT_BYREF|VT_BOOL
- * C type : VARIANT_BOOL* - */ - @Field(21) - public Pointer pboolVal() { - return this.io.getPointerField(this, 21); - } - /** - * VT_BYREF|VT_BOOL
- * C type : VARIANT_BOOL* - */ - @Field(21) - public __VARIANT_NAME_3_union pboolVal(Pointer pboolVal) { - this.io.setPointerField(this, 21, pboolVal); - return this; - } - /// C type : VARIANT_BOOL* - public final Pointer pboolVal_$eq(Pointer pboolVal) { - pboolVal(pboolVal); - return pboolVal; - } - /// C type : _VARIANT_BOOL* - @Field(22) - public Pointer pbool() { - return this.io.getPointerField(this, 22); - } - /// C type : _VARIANT_BOOL* - @Field(22) - public __VARIANT_NAME_3_union pbool(Pointer pbool) { - this.io.setPointerField(this, 22, pbool); - return this; - } - /// C type : _VARIANT_BOOL* - public final Pointer pbool_$eq(Pointer pbool) { - pbool(pbool); - return pbool; - } - /** - * VT_BYREF|VT_ERROR
- * C type : SCODE* - */ - @Field(23) - public Pointer pscode() { - return this.io.getPointerField(this, 23); - } - /** - * VT_BYREF|VT_ERROR
- * C type : SCODE* - */ - @Field(23) - public __VARIANT_NAME_3_union pscode(Pointer pscode) { - this.io.setPointerField(this, 23, pscode); - return this; - } - /// C type : SCODE* - public final Pointer pscode_$eq(Pointer pscode) { - pscode(pscode); - return pscode; - } - /** - * VT_BYREF|VT_CY
- * C type : CY* - */ - @Field(24) - public Pointer pcyVal() { - return this.io.getPointerField(this, 24); - } - /** - * VT_BYREF|VT_CY
- * C type : CY* - */ - @Field(24) - public __VARIANT_NAME_3_union pcyVal(Pointer pcyVal) { - this.io.setPointerField(this, 24, pcyVal); - return this; - } - /// C type : CY* - public final Pointer pcyVal_$eq(Pointer pcyVal) { - pcyVal(pcyVal); - return pcyVal; - } - /** - * VT_BYREF|VT_DATE
- * C type : DATE* - */ - @Field(25) - public Pointer pdate() { - return this.io.getPointerField(this, 25); - } - /** - * VT_BYREF|VT_DATE
- * C type : DATE* - */ - @Field(25) - public __VARIANT_NAME_3_union pdate(Pointer pdate) { - this.io.setPointerField(this, 25, pdate); - return this; - } - /// C type : DATE* - public final Pointer pdate_$eq(Pointer pdate) { - pdate(pdate); - return pdate; - } - /** - * VT_BYREF|VT_BSTR
- * C type : BSTR* - */ - @Field(26) - public Pointer > pbstrVal() { - return this.io.getPointerField(this, 26); - } - /** - * VT_BYREF|VT_BSTR
- * C type : BSTR* - */ - @Field(26) - public __VARIANT_NAME_3_union pbstrVal(Pointer > pbstrVal) { - this.io.setPointerField(this, 26, pbstrVal); - return this; - } - /// C type : BSTR* - public final Pointer > pbstrVal_$eq(Pointer > pbstrVal) { - pbstrVal(pbstrVal); - return pbstrVal; - } - /** - * VT_BYREF|VT_UNKNOWN
- * C type : IUnknown** - */ - @Field(27) - public Pointer > ppunkVal() { - return this.io.getPointerField(this, 27); - } - /** - * VT_BYREF|VT_UNKNOWN
- * C type : IUnknown** - */ - @Field(27) - public __VARIANT_NAME_3_union ppunkVal(Pointer > ppunkVal) { - this.io.setPointerField(this, 27, ppunkVal); - return this; - } - /// C type : IUnknown** - public final Pointer > ppunkVal_$eq(Pointer > ppunkVal) { - ppunkVal(ppunkVal); - return ppunkVal; - } - /** - * VT_BYREF|VT_DISPATCH
- * C type : IDispatch** - */ - @Field(28) - public Pointer > ppdispVal() { - return this.io.getPointerField(this, 28); - } - /** - * VT_BYREF|VT_DISPATCH
- * C type : IDispatch** - */ - @Field(28) - public __VARIANT_NAME_3_union ppdispVal(Pointer > ppdispVal) { - this.io.setPointerField(this, 28, ppdispVal); - return this; - } - /// C type : IDispatch** - public final Pointer > ppdispVal_$eq(Pointer > ppdispVal) { - ppdispVal(ppdispVal); - return ppdispVal; - } - /** - * VT_BYREF|VT_ARRAY
- * C type : SAFEARRAY** - */ - @Field(29) - public Pointer > pparray() { - return this.io.getPointerField(this, 29); - } - /** - * VT_BYREF|VT_ARRAY
- * C type : SAFEARRAY** - */ - @Field(29) - public __VARIANT_NAME_3_union pparray(Pointer > pparray) { - this.io.setPointerField(this, 29, pparray); - return this; - } - /// C type : SAFEARRAY** - public final Pointer > pparray_$eq(Pointer > pparray) { - pparray(pparray); - return pparray; - } - /** - * VT_BYREF|VT_VARIANT
- * C type : VARIANT* - */ - @Field(30) - public Pointer pvarVal() { - return this.io.getPointerField(this, 30); - } - /** - * VT_BYREF|VT_VARIANT
- * C type : VARIANT* - */ - @Field(30) - public __VARIANT_NAME_3_union pvarVal(Pointer pvarVal) { - this.io.setPointerField(this, 30, pvarVal); - return this; - } - /// C type : VARIANT* - public final Pointer pvarVal_$eq(Pointer pvarVal) { - pvarVal(pvarVal); - return pvarVal; - } - /** - * Generic ByRef
- * C type : PVOID* - */ - @Field(31) - public Pointer > byref() { - return this.io.getPointerField(this, 31); - } - /** - * Generic ByRef
- * C type : PVOID* - */ - @Field(31) - public __VARIANT_NAME_3_union byref(Pointer > byref) { - this.io.setPointerField(this, 31, byref); - return this; - } - /// C type : PVOID* - public final Pointer > byref_$eq(Pointer > byref) { - byref(byref); - return byref; - } - /** - * VT_I1
- * C type : CHAR - */ - @Field(32) - public byte cVal() { - return this.io.getByteField(this, 32); - } - /** - * VT_I1
- * C type : CHAR - */ - @Field(32) - public __VARIANT_NAME_3_union cVal(byte cVal) { - this.io.setByteField(this, 32, cVal); - return this; - } - /// C type : CHAR - public final byte cVal_$eq(byte cVal) { - cVal(cVal); - return cVal; - } - /** - * VT_UI2
- * C type : USHORT - */ - @Field(33) - public short uiVal() { - return this.io.getShortField(this, 33); - } - /** - * VT_UI2
- * C type : USHORT - */ - @Field(33) - public __VARIANT_NAME_3_union uiVal(short uiVal) { - this.io.setShortField(this, 33, uiVal); - return this; - } - /// C type : USHORT - public final short uiVal_$eq(short uiVal) { - uiVal(uiVal); - return uiVal; - } - /** - * VT_UI4
- * C type : ULONG - */ - @Field(34) - public int ulVal() { - return this.io.getIntField(this, 34); - } - /** - * VT_UI4
- * C type : ULONG - */ - @Field(34) - public __VARIANT_NAME_3_union ulVal(int ulVal) { - this.io.setIntField(this, 34, ulVal); - return this; - } - /// C type : ULONG - public final int ulVal_$eq(int ulVal) { - ulVal(ulVal); - return ulVal; - } - /// VT_UI8 - @Field(35) - public long ullVal() { - return this.io.getLongField(this, 35); - } - /// VT_UI8 - @Field(35) - public __VARIANT_NAME_3_union ullVal(long ullVal) { - this.io.setLongField(this, 35, ullVal); - return this; - } - public final long ullVal_$eq(long ullVal) { - ullVal(ullVal); - return ullVal; - } - /** - * VT_INT
- * C type : INT - */ - @Field(36) - public int intVal() { - return this.io.getIntField(this, 36); - } - /** - * VT_INT
- * C type : INT - */ - @Field(36) - public __VARIANT_NAME_3_union intVal(int intVal) { - this.io.setIntField(this, 36, intVal); - return this; - } - /// C type : INT - public final int intVal_$eq(int intVal) { - intVal(intVal); - return intVal; - } - /** - * VT_UINT
- * C type : UINT - */ - @Field(37) - public int uintVal() { - return this.io.getIntField(this, 37); - } - /** - * VT_UINT
- * C type : UINT - */ - @Field(37) - public __VARIANT_NAME_3_union uintVal(int uintVal) { - this.io.setIntField(this, 37, uintVal); - return this; - } - /// C type : UINT - public final int uintVal_$eq(int uintVal) { - uintVal(uintVal); - return uintVal; - } - /** - * VT_BYREF|VT_DECIMAL
- * C type : DECIMAL* - */ - @Field(38) - public Pointer pdecVal() { - return this.io.getPointerField(this, 38); - } - /** - * VT_BYREF|VT_DECIMAL
- * C type : DECIMAL* - */ - @Field(38) - public __VARIANT_NAME_3_union pdecVal(Pointer pdecVal) { - this.io.setPointerField(this, 38, pdecVal); - return this; - } - /// C type : DECIMAL* - public final Pointer pdecVal_$eq(Pointer pdecVal) { - pdecVal(pdecVal); - return pdecVal; - } - /** - * VT_BYREF|VT_I1
- * C type : CHAR* - */ - @Field(39) - public Pointer pcVal() { - return this.io.getPointerField(this, 39); - } - /** - * VT_BYREF|VT_I1
- * C type : CHAR* - */ - @Field(39) - public __VARIANT_NAME_3_union pcVal(Pointer pcVal) { - this.io.setPointerField(this, 39, pcVal); - return this; - } - /// C type : CHAR* - public final Pointer pcVal_$eq(Pointer pcVal) { - pcVal(pcVal); - return pcVal; - } - /** - * VT_BYREF|VT_UI2
- * C type : USHORT* - */ - @Field(40) - public Pointer puiVal() { - return this.io.getPointerField(this, 40); - } - /** - * VT_BYREF|VT_UI2
- * C type : USHORT* - */ - @Field(40) - public __VARIANT_NAME_3_union puiVal(Pointer puiVal) { - this.io.setPointerField(this, 40, puiVal); - return this; - } - /// C type : USHORT* - public final Pointer puiVal_$eq(Pointer puiVal) { - puiVal(puiVal); - return puiVal; - } - /** - * VT_BYREF|VT_UI4
- * C type : ULONG* - */ - @Field(41) - public Pointer pulVal() { - return this.io.getPointerField(this, 41); - } - /** - * VT_BYREF|VT_UI4
- * C type : ULONG* - */ - @Field(41) - public __VARIANT_NAME_3_union pulVal(Pointer pulVal) { - this.io.setPointerField(this, 41, pulVal); - return this; - } - /// C type : ULONG* - public final Pointer pulVal_$eq(Pointer pulVal) { - pulVal(pulVal); - return pulVal; - } - /** - * VT_BYREF|VT_UI8
- * C type : ULONGLONG* - */ - @Field(42) - public Pointer pullVal() { - return this.io.getPointerField(this, 42); - } - /** - * VT_BYREF|VT_UI8
- * C type : ULONGLONG* - */ - @Field(42) - public __VARIANT_NAME_3_union pullVal(Pointer pullVal) { - this.io.setPointerField(this, 42, pullVal); - return this; - } - /// C type : ULONGLONG* - public final Pointer pullVal_$eq(Pointer pullVal) { - pullVal(pullVal); - return pullVal; - } - /** - * VT_BYREF|VT_INT
- * C type : INT* - */ - @Field(43) - public Pointer pintVal() { - return this.io.getPointerField(this, 43); - } - /** - * VT_BYREF|VT_INT
- * C type : INT* - */ - @Field(43) - public __VARIANT_NAME_3_union pintVal(Pointer pintVal) { - this.io.setPointerField(this, 43, pintVal); - return this; - } - /// C type : INT* - public final Pointer pintVal_$eq(Pointer pintVal) { - pintVal(pintVal); - return pintVal; - } - /** - * VT_BYREF|VT_UINT
- * C type : UINT* - */ - @Field(44) - public Pointer puintVal() { - return this.io.getPointerField(this, 44); - } - /** - * VT_BYREF|VT_UINT
- * C type : UINT* - */ - @Field(44) - public __VARIANT_NAME_3_union puintVal(Pointer puintVal) { - this.io.setPointerField(this, 44, puintVal); - return this; - } - /// C type : UINT* - public final Pointer puintVal_$eq(Pointer puintVal) { - puintVal(puintVal); - return puintVal; - } - /// C type : __tagBRECORD - @Field(45) - public VARIANT.__VARIANT_NAME_1_union.__tagVARIANT.__VARIANT_NAME_3_union.__tagBRECORD __VARIANT_NAME_4() { - return this.io.getNativeObjectField(this, 45); - } - /// native declaration : line 162 - public static class __tagBRECORD extends StructObject { - public __tagBRECORD() { - super(); - } -// public __tagBRECORD(Pointer pointer) { -// super(pointer); -// } - /// C type : PVOID - @Field(0) - public Pointer pvRecord() { - return this.io.getPointerField(this, 0); - } - /// C type : PVOID - @Field(0) - public __tagBRECORD pvRecord(Pointer pvRecord) { - this.io.setPointerField(this, 0, pvRecord); - return this; - } - /// C type : PVOID - public final Pointer pvRecord_$eq(Pointer pvRecord) { - pvRecord(pvRecord); - return pvRecord; - } - /// C type : IRecordInfo* - @Field(1) - public Pointer pRecInfo() { - return this.io.getPointerField(this, 1); - } - /// C type : IRecordInfo* - @Field(1) - public __tagBRECORD pRecInfo(Pointer pRecInfo) { - this.io.setPointerField(this, 1, pRecInfo); - return this; - } - /// C type : IRecordInfo* - public final Pointer pRecInfo_$eq(Pointer pRecInfo) { - pRecInfo(pRecInfo); - return pRecInfo; - } - }; - }; - }; - }; - public Object getValue() { - return COMRuntime.getValue(this); - } - public VARIANT setValue(Object value) { - return COMRuntime.setValue(this, value); - } - - @Override - public String toString() { - return COMRuntime.toString(this); - } - - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/package-info.java deleted file mode 100644 index f3d86878b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ COM support (Windows-only, working but under-tested). -*/ -package org.bridj.cpp.com; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellFolder.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellFolder.java deleted file mode 100644 index 191e642a5..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellFolder.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com.shell; - -import org.bridj.cpp.com.CLSID; -import org.bridj.cpp.com.IID; -import org.bridj.cpp.com.IUnknown; - -/** - * - * @author Olivier - */ -@IID("000214E6-0000-0000-C000-000000000046") -@CLSID("000214E6-0000-0000-C000-000000000046") -public class IShellFolder extends IUnknown { - -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellWindows.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellWindows.java deleted file mode 100644 index 4d3c5ada9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/IShellWindows.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com.shell; - -import org.bridj.cpp.com.CLSID; -import org.bridj.cpp.com.IDispatch; -import org.bridj.cpp.com.IID; - -/** - * IShellWindows provides access to the collection of open Shell windows (see @see http://msdn.microsoft.com/en-us/library/cc836570(VS.85).aspx) - * @author Olivier - */ -@IID("85CB6900-4D95-11CF-960C-0080C7F4EE85") -@CLSID("9BA05972-F6A8-11CF-A442-00A0C90A8F39") -public class IShellWindows extends IDispatch { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList.java deleted file mode 100644 index 21ed902ca..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com.shell; - -import org.bridj.Pointer; -import org.bridj.ann.Virtual; -import org.bridj.cpp.com.IID; -import org.bridj.cpp.com.IUnknown; - -/** - * - * @author Olivier - */ -@IID("56FDF342-FD6D-11D0-958A-006097C9A090") -public class ITaskbarList extends IUnknown { - - @Virtual(0) public native void HrInit(); - @Virtual(1) public native void AddTab(Pointer hWnd); - @Virtual(2) public native void DeleteTab(Pointer hWnd); - @Virtual(3) public native void ActivateTab(Pointer hWnd); - @Virtual(4) public native void SetActiveAlt(Pointer hWnd); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList2.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList2.java deleted file mode 100644 index e1b0cd0a9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList2.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com.shell; - -import org.bridj.Pointer; -import org.bridj.ann.Virtual; - -/** - * - * @author Olivier - */ -public class ITaskbarList2 extends ITaskbarList { - @Virtual(0) public native int MarkFullscreenWindow(Pointer hWnd, boolean fFullscreen); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList3.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList3.java deleted file mode 100644 index 0c79d940e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/ITaskbarList3.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.com.shell; -import java.util.Collections; -import java.util.Iterator; -import org.bridj.ValuedEnum; -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Array; -import org.bridj.ann.Field; -import org.bridj.ann.Virtual; -import org.bridj.cpp.com.CLSID; -import org.bridj.cpp.com.IID; - -@IID("EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF") -@CLSID("56FDF344-FD6D-11d0-958A-006097C9A090") -public class ITaskbarList3 extends ITaskbarList2 { - public enum THUMBBUTTONMASK implements IntValuedEnum { - THB_BITMAP(0x00000001), - THB_ICON(0x00000002), - THB_TOOLTIP(0x00000004), - THB_FLAGS(0x00000008); - THUMBBUTTONMASK(int value) { - this.value = value; - } - public final int value; - //@Override - public long value() { - return value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - /// http://msdn.microsoft.com/en-us/library/dd562321(VS.85).aspx - public enum THUMBBUTTONFLAGS implements IntValuedEnum { - THBF_ENABLED(0x00000000), - THBF_DISABLED(0x00000001), - THBF_DISMISSONCLICK(0x00000002), - THBF_NOBACKGROUND(0x00000004), - THBF_HIDDEN(0x00000008), - THBF_NONINTERACTIVE(0x00000010); - THUMBBUTTONFLAGS(int value) { - this.value = value; - } - final int value; - //@Override - public long value() { - return value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - public static class THUMBBUTTON extends StructObject { - @Field(0) - public native ValuedEnum dwMask(); - public native void dwMask(ValuedEnum dwMask); - @Field(1) - public native int iId(); - public native void iId(int iId); - @Field(2) - public native int iBitmap(); - public native void iBitmap(int iBitmap); - @Field(3) - public native Pointer hIcon(); - public native void hIcon(Pointer hIcon); - @Field(4) @Array(260) - public native Pointer szTip(); - public native void szTip(Pointer szTip); - @Field(5) - public native ValuedEnum dwFlags(); - public native void dwFlags(ValuedEnum dwFlags); - } - @Virtual(0) public native int SetProgressValue(Pointer hWnd, long Completed, long Total); - - public enum TbpFlag implements IntValuedEnum { - TBPF_NOPROGRESS(0), - TBPF_INDETERMINATE(1), - TBPF_NORMAL(2), - TBPF_ERROR(4), - TBPF_PAUSED(8); - - TbpFlag(int value) { - this.value = value; - } - public final int value; - //@Override/ - public long value() { - return value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - - - //@Virtual(1) public native int SetProgressState(Pointer hWnd, ValuedEnum Flags); - @Virtual(1) public native int SetProgressState(Pointer hWnd, ValuedEnum Flags); - - @Virtual(2) public native void RegisterTab(Pointer hWndTab, Pointer hWndMDI); - @Virtual(3) public native void UnregisterTab(Pointer hWndTab); - @Virtual(4) public native void SetTabOrder(Pointer hWndTab, Pointer hwndInsertBefore); - @Virtual(5) public native void SetTabActive(Pointer hWndTab, Pointer hWndMDI, int dwReserved); - @Virtual(6) public native void ThumbBarAddButtons(Pointer hWnd, int cButtons, Pointer pButtons); - @Virtual(7) public native void ThumbBarUpdateButtons(Pointer hWnd, int cButtons, Pointer pButtons); - @Virtual(8) public native void ThumbBarSetImageList(Pointer hWnd, Pointer himl); - @Virtual(9) public native void SetOverlayIcon(Pointer hWnd, Pointer hIcon, Pointer pszDescription); - @Virtual(10) public native void SetThumbnailTooltip(Pointer hWnd, Pointer pszTip); - - public class RECT { - - } - @Virtual(11) public native void SetThumbnailClip(Pointer hWnd, Pointer prcClip); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/package-info.java deleted file mode 100644 index 538328509..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/com/shell/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** -BridJ mappings for some common Windows COM Shell interfaces. -

-See {@link org.bridj.demos.TaskbarListDemo} for an example of use. -*/ -package org.bridj.cpp.com.shell; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/AFXSignature.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/AFXSignature.java deleted file mode 100644 index b773df11b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/AFXSignature.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; - -public enum AFXSignature { - AfxSig_vwww(Void.TYPE, int.class, int.class, int.class), // void (UINT, UINT, UINT) - AfxSig_vwp(Void.TYPE, Pointer.class, CPoint.class); // void (CWnd*, CPoint) - - AFXSignature(Class returnType, Class... paramTypes) { - this.returnType = returnType; - this.paramTypes = paramTypes; - } - final Class returnType; - final Class[] paramTypes; - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CArchive.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CArchive.java deleted file mode 100644 index fb4b8e8ea..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CArchive.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bridj.cpp.mfc; - -public class CArchive extends CObject { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CCmdUI.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CCmdUI.java deleted file mode 100644 index feddc7b22..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CCmdUI.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.ann.Virtual; - - -public class CCmdUI extends MFCObject { - - @Virtual - public native void Enable(boolean bOn); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CObject.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CObject.java deleted file mode 100644 index 30e654133..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CObject.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; - -import org.bridj.ann.Convention; -import org.bridj.ann.Virtual; -import org.bridj.ann.Convention.Style; - -@Convention(Style.StdCall) -public class CObject extends MFCObject { - - public CObject() {} - public CObject(Pointer pInstance, MFCRuntime mfcRuntime) { - super(pInstance); - } - - @Virtual - public native Pointer GetRuntimeClass(); - - /** - * @see http://msdn.microsoft.com/en-us/library/b7tsah76(VS.80).aspx - * @param pClass - */ - @Virtual - public native boolean IsKindOf(Pointer pClass); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CPoint.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CPoint.java deleted file mode 100644 index 6b66b89b5..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CPoint.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.StructObject; -import org.bridj.ann.Field; - -/** - * - * @author Olivier - */ -public class CPoint extends StructObject { - @Field(0) - public native int x(); - @Field(0) - public native void x(int x); - @Field(0) - public native int y(); - @Field(0) - public native void y(int y); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CRuntimeClass.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CRuntimeClass.java deleted file mode 100644 index b006397d0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CRuntimeClass.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; -import org.bridj.ann.Field; -import org.bridj.func.Fun0; - -public class CRuntimeClass extends MFCObject { - // Attributes - @Field(0) - public native Pointer m_lpszClassName(); - public native void m_lpszClassName(Pointer m_lpszClassName); - @Field(1) - public native int m_nObjectSize(); - public native void m_nObjectSize(int m_nObjectSize); - @Field(2) - public native int m_wSchema(); // schema number of the loaded class - public native void m_wSchema(int m_wSchema); // schema number of the loaded class - - @Field(3) - public native Pointer>> m_pfnCreateObject(); // NULL => abstract class - public native void m_pfnCreateObject(Pointer>> m_pfnCreateObject); // NULL => abstract class - - /*#ifdef _AFXDLL - CRuntimeClass* (PASCAL* m_pfnGetBaseClass)(); - #else - CRuntimeClass* m_pBaseClass; - #endif - */ - @Field(4) - public native Pointer m_pBaseClass(); - public native void m_pBaseClass(Pointer m_pBaseClass); - -// Operations - public native Pointer CreateObject(); - public native boolean IsDerivedFrom(Pointer pBaseClass); - - // dynamic name lookup and creation - public native static Pointer FromName(Pointer /*LPCSTR*/ lpszClassName); - public native static Pointer FromName$2(Pointer lpszClassName); - public native static Pointer CreateObject(Pointer lpszClassName); - public native static Pointer CreateObject$2(Pointer lpszClassName); - - // Implementation - public native void Store(Pointer ar); - public native static Pointer Load(Pointer ar, Pointer pwSchemaNum); - - // CRuntimeClass objects linked together in simple list - @Field(5) - public native Pointer m_pNextClass(); // linked list of registered classes - public native void m_pNextClass(Pointer m_pNextClass); // linked list of registered classes - @Field(6) - public native Pointer /*AFX_CLASSINIT*/ m_pClassInit(); - public native void m_pClassInit(Pointer m_pClassInit); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CString.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CString.java deleted file mode 100644 index 46f872057..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CString.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -/** - * - * @author Olivier - */ -public class CString extends CStringT { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CStringT.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CStringT.java deleted file mode 100644 index d1c3ea331..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CStringT.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.cpp.CPPObject; - -/** - * - * @author Olivier - */ -public class CStringT extends CPPObject { - Class BaseType; - Class StringTraits; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CWnd.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CWnd.java deleted file mode 100644 index 1be584c38..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/CWnd.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; -import org.bridj.ann.Virtual; - -/** - * - * @author Olivier - */ -public class CWnd extends MFCObject { - @Virtual - public native int SendMessage(int message, int wParam, int lParam); - - @Virtual - public native void SetWindowText(Pointer lpszString); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCObject.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCObject.java deleted file mode 100644 index 2886e6494..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCObject.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.cpp.CPPObject; - -@Library(value="mfc90u.dll", versionPattern = "mfc(?:(\\d)(\\d))?u") -@Runtime(MFCRuntime.class) -public class MFCObject extends CPPObject { - protected MFCObject() {} - protected MFCObject(Pointer peer) { - super(peer); - } - protected MFCObject(Void voidArg, int constructorId, Object... args) { - super(voidArg, constructorId, args); - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCRuntime.java deleted file mode 100644 index bebcffef5..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MFCRuntime.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.BridJ; -import org.bridj.Callback; -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.util.Utils; -import org.bridj.cpp.CPPRuntime; - -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * - * @author Olivier - */ -public class MFCRuntime extends CPPRuntime { - Method mfcGetMessageMap; - String mfcGetMessageMapMangling; - Callback mfcGetMessageMapCallback; - - Set> hasMessageMap = new HashSet>(); - - @Override - public Class getActualInstanceClass(Pointer pInstance, Type officialType) { - Class officialTypeClass = Utils.getClass(officialType); - // For MFC classes, use GetRuntimeClass() - if (CObject.class.isAssignableFrom(officialTypeClass)) { - Pointer pClass = new CObject((Pointer)pInstance, this).GetRuntimeClass(); - if (pClass != null) { - CRuntimeClass rtc = pClass.get(); - try { - Class type = (Class)getMFCClass(rtc.m_lpszClassName()); - if (officialTypeClass == null || officialTypeClass.isAssignableFrom(type)) - return type; - } catch (ClassNotFoundException ex) {} - return officialTypeClass; - } - } - - // TODO Auto-generated method stub - return super.getActualInstanceClass(pInstance, officialType); - } - - private Class getMFCClass(Pointer mLpszClassName) throws ClassNotFoundException { - throw new ClassNotFoundException(mLpszClassName.getCString()); - } - - public void getExtraFieldsOfNewClass(Class type, Map out) { - //super.getExtraFieldsOfNewClass(type, out); - if (!hasMessageMap.contains(type)) - return; - - out.put("messageMap", Pointer.class); - } - - public void getOverriddenVirtualMethods(Map> out) { - //super.getVirtualMethodBindings(out); - out.put("mfcGetMessageMap", Pointer.pointerTo(mfcGetMessageMapCallback)); - } - - @Override - public void register(Type type) { - super.register(type); - Class typeClass = Utils.getClass(type); - - MessageMapBuilder map = new MessageMapBuilder(); - for (Method method : typeClass.getMethods()) { - - OnCommand onCommand = method.getAnnotation(OnCommand.class); - if (onCommand != null) - map.add(method, onCommand); - - OnCommandEx onCommandEx = method.getAnnotation(OnCommandEx.class); - if (onCommandEx != null) - map.add(method, onCommandEx); - - OnUpdateCommand onUpdateCommand = method.getAnnotation(OnUpdateCommand.class); - if (onUpdateCommand != null) - map.add(method, onUpdateCommand); - - OnRegisteredMessage onRegisteredMessage = method.getAnnotation(OnRegisteredMessage.class); - if (onRegisteredMessage != null) - map.add(method, onRegisteredMessage); - - OnMessage onMessage = method.getAnnotation(OnMessage.class); - if (onMessage != null) - map.add(method, onMessage); - } - if (!map.isEmpty()) - map.register(this, typeClass); - - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MessageMapBuilder.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MessageMapBuilder.java deleted file mode 100644 index 80f51f107..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/MessageMapBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import java.lang.reflect.Method; - -/** - * - * @author Olivier - */ -public class MessageMapBuilder { - - void add(Method method, OnCommand onCommand) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - void add(Method method, OnCommandEx onCommandEx) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - void add(Method method, OnUpdateCommand onUpdateCommand) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - void add(Method method, OnRegisteredMessage onRegisteredMessage) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - void add(Method method, OnMessage onMessage) { - throw new UnsupportedOperationException("Not yet implemented"); - } - - boolean isEmpty() { - throw new UnsupportedOperationException("Not yet implemented"); - } - - void register(MFCRuntime rt, Class type) { - throw new UnsupportedOperationException("Not yet implemented"); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommand.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommand.java deleted file mode 100644 index 8ad2b942c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommand.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -public @interface OnCommand { - /// Command id - int value(); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommandEx.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommandEx.java deleted file mode 100644 index fd6f559e2..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnCommandEx.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -/** - * - * @author Olivier - */ -public @interface OnCommandEx { - int[] value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnMessage.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnMessage.java deleted file mode 100644 index 46a4a99ae..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnMessage.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; -import static org.bridj.cpp.mfc.AFXSignature.*; -/** - * http://msdn.microsoft.com/en-us/library/0812b0wa(VS.80).aspx - * C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE\afxwin.h - */ -public @interface OnMessage { - - /// C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE\afxmsg_.h - public enum Type { - WM_KEYDOWN("OnKeyDown", AfxSig_vwww), - WM_LBUTTONDOWN("OnLButtonDown", AfxSig_vwp); - - Type(String defaultName, AFXSignature afxSig) { - this.afxSig = afxSig; - this.defaultName = defaultName; - } - final String defaultName; - final AFXSignature afxSig; - } - Type value(); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnRegisteredMessage.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnRegisteredMessage.java deleted file mode 100644 index 2f90c9a3a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnRegisteredMessage.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -/// See MFC API RegisterWindowMessage -public @interface OnRegisteredMessage { - /// Message name - String value(); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnUpdateCommand.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnUpdateCommand.java deleted file mode 100644 index 8852db785..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/OnUpdateCommand.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -public @interface OnUpdateCommand { - /// Command id - int value(); -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/StandardAfxCommands.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/StandardAfxCommands.java deleted file mode 100644 index a1d874beb..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/StandardAfxCommands.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -/// c:\program files\microsoft visual studio 8\vc\atlmfc\include\afxres.h -public interface StandardAfxCommands { - public static final int - ID_FILE_NEW = 0xE100, - ID_FILE_OPEN = 0xE101, - ID_FILE_CLOSE = 0xE102, - ID_FILE_SAVE = 0xE103, - ID_FILE_SAVE_AS = 0xE104, - ID_FILE_PAGE_SETUP = 0xE105, - ID_FILE_PRINT_SETUP = 0xE106, - ID_FILE_PRINT = 0xE107, - ID_FILE_PRINT_DIRECT = 0xE108, - ID_FILE_PRINT_PREVIEW = 0xE109, - ID_FILE_UPDATE = 0xE10A, - ID_FILE_SAVE_COPY_AS = 0xE10B, - ID_FILE_SEND_MAIL = 0xE10C, - ID_FILE_NEW_FRAME = 0xE10D, - ID_FILE_MRU_FIRST = 0xE110, - ID_FILE_MRU_FILE1 = 0xE110, // range - 16 max - ID_FILE_MRU_FILE2 = 0xE111, - ID_FILE_MRU_FILE3 = 0xE112, - ID_FILE_MRU_FILE4 = 0xE113, - ID_FILE_MRU_FILE5 = 0xE114, - ID_FILE_MRU_FILE6 = 0xE115, - ID_FILE_MRU_FILE7 = 0xE116, - ID_FILE_MRU_FILE8 = 0xE117, - ID_FILE_MRU_FILE9 = 0xE118, - ID_FILE_MRU_FILE10 = 0xE119, - ID_FILE_MRU_FILE11 = 0xE11A, - ID_FILE_MRU_FILE12 = 0xE11B, - ID_FILE_MRU_FILE13 = 0xE11C, - ID_FILE_MRU_FILE14 = 0xE11D, - ID_FILE_MRU_FILE15 = 0xE11E, - ID_FILE_MRU_FILE16 = 0xE11F, - ID_FILE_MRU_LAST = 0xE11F, - ID_EDIT_CLEAR = 0xE120, - ID_EDIT_CLEAR_ALL = 0xE121, - ID_EDIT_COPY = 0xE122, - ID_EDIT_CUT = 0xE123, - ID_EDIT_FIND = 0xE124, - ID_EDIT_PASTE = 0xE125, - ID_EDIT_PASTE_LINK = 0xE126, - ID_EDIT_PASTE_SPECIAL = 0xE127, - ID_EDIT_REPEAT = 0xE128, - ID_EDIT_REPLACE = 0xE129, - ID_EDIT_SELECT_ALL = 0xE12A, - ID_EDIT_UNDO = 0xE12B, - ID_EDIT_REDO = 0xE12C, - ID_WINDOW_NEW = 0xE130, - ID_WINDOW_ARRANGE = 0xE131, - ID_WINDOW_CASCADE = 0xE132, - ID_WINDOW_TILE_HORZ = 0xE133, - ID_WINDOW_TILE_VERT = 0xE134, - ID_WINDOW_SPLIT = 0xE135, - AFX_IDM_WINDOW_FIRST = 0xE130, - AFX_IDM_WINDOW_LAST = 0xE13F, - AFX_IDM_FIRST_MDICHILD = 0xFF00, // window list starts here - ID_APP_ABOUT = 0xE140, - ID_APP_EXIT = 0xE141, - ID_HELP_INDEX = 0xE142, - ID_HELP_FINDER = 0xE143, - ID_HELP_USING = 0xE144, - ID_CONTEXT_HELP = 0xE145, // shift-F1 - ID_HELP = 0xE146, // first attempt for F1 - ID_DEFAULT_HELP = 0xE147, // last attempt - ID_NEXT_PANE = 0xE150, - ID_PREV_PANE = 0xE151, - ID_FORMAT_FONT = 0xE160, - ID_OLE_INSERT_NEW = 0xE200, - ID_OLE_EDIT_LINKS = 0xE201, - ID_OLE_EDIT_CONVERT = 0xE202, - ID_OLE_EDIT_CHANGE_ICON = 0xE203, - ID_OLE_EDIT_PROPERTIES = 0xE204, - ID_OLE_VERB_FIRST = 0xE210, // range - 16 max - ID_OLE_VERB_LAST = 0xE21F, - AFX_ID_PREVIEW_CLOSE = 0xE300, - AFX_ID_PREVIEW_NUMPAGE = 0xE301, // One/Two Page button - AFX_ID_PREVIEW_NEXT = 0xE302, - AFX_ID_PREVIEW_PREV = 0xE303, - AFX_ID_PREVIEW_PRINT = 0xE304, - AFX_ID_PREVIEW_ZOOMIN = 0xE305, - AFX_ID_PREVIEW_ZOOMOUT = 0xE306, - ID_VIEW_TOOLBAR = 0xE800, - ID_VIEW_STATUS_BAR = 0xE801, - ID_VIEW_REBAR = 0xE804, - ID_VIEW_AUTOARRANGE = 0xE805, - ID_VIEW_SMALLICON = 0xE810, - ID_VIEW_LARGEICON = 0xE811, - ID_VIEW_LIST = 0xE812, - ID_VIEW_DETAILS = 0xE813, - ID_VIEW_LINEUP = 0xE814, - ID_VIEW_BYNAME = 0xE815, - ID_RECORD_FIRST = 0xE900, - ID_RECORD_LAST = 0xE901, - ID_RECORD_NEXT = 0xE902, - ID_RECORD_PREV = 0xE903, - IDC_STATIC = (-1); // all static controls - -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/TestMFC.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/TestMFC.java deleted file mode 100644 index f4500db1d..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/TestMFC.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cpp.mfc; - -import org.bridj.Pointer; - -import static org.bridj.cpp.mfc.OnMessage.Type.*; -import static org.bridj.cpp.mfc.StandardAfxCommands.*; - -/** - * - * @author Olivier - */ -public class TestMFC { - public static void main(String[] args) { - - CWnd wnd = new CWnd() { - @OnMessage(WM_KEYDOWN) - //@AfxMsg(WM_KEYDOWN) - public void OnKeyDown(int a, int b, int c) { - - } - @OnCommand(ID_FILE_NEW) - //@AfxCommand - public void OnSomething() { - - } - - @OnCommandEx({ID_FILE_SAVE, ID_FILE_PRINT}) - public boolean OnSomethingEx(int id) { - return true; - } - - @OnUpdateCommand(ID_FILE_NEW) - //@AfxCommandUpdate - public void OnUpdateSomething(Pointer pCmdUI) { - if (pCmdUI == null) - return; - - pCmdUI.get().Enable(true); - } - - @OnRegisteredMessage("MYAPP_MYMESSAGE") - //@OnRegisteredMessage("MYAPP_MYMESSAGE") // RegisterWindowMessage - public void OnMyMessage(int a, int b, int c) { - - } - }; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/package-info.java deleted file mode 100644 index 603021be0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/mfc/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** -BridJ Windows MFC runtime (not working properly yet). -

-The aim is to be able to create a C++ window with automatic commands routing, but we're not there yet. -*/ -package org.bridj.cpp.mfc; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cpp/package-info.java deleted file mode 100644 index 105d3cce9..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** -BridJ C++ runtime. -

-BridJ does not permit C++ subclassing yet, nor does it support templates properly. -

-See the Current State page on BridJ's wiki for more information. -*/ -package org.bridj.cpp; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/std/STL.java b/libraries/BridJ/src/main/java/org/bridj/cpp/std/STL.java deleted file mode 100644 index 915568901..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/std/STL.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bridj.cpp.std; - -import org.bridj.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html - -/** - * Util methods for STL bindings in BridJ, intended for internal use only. - * @author ochafik - */ -public final class STL extends StructIO.DefaultCustomizer { - /** - * Perform platform-dependent structure bindings adjustments - */ - @Override - public void afterBuild(StructIO io) { - Class c = io.getStructClass(); - if (c == vector.class) { - if (Platform.isWindows()) { - // On Windows, vector begins by 3 pointers, before the start+finish+end pointers : - io.prependBytes(3 * Pointer.SIZE); - } - } - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/std/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cpp/std/package-info.java deleted file mode 100644 index 7da2e7123..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/std/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -Bindings for some C++ STL class templates. -*/ -package org.bridj.cpp.std; diff --git a/libraries/BridJ/src/main/java/org/bridj/cpp/std/vector.java b/libraries/BridJ/src/main/java/org/bridj/cpp/std/vector.java deleted file mode 100644 index dbfeb988e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cpp/std/vector.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bridj.cpp.std; - -import org.bridj.ann.Template; -import org.bridj.cpp.CPPObject; - - -import org.bridj.BridJ; -import org.bridj.Pointer; -import org.bridj.ann.Field; -import org.bridj.ann.Struct; -import org.bridj.cpp.CPPRuntime; - -import java.lang.reflect.Type; -import org.bridj.BridJRuntime; - -import static org.bridj.Pointer.*; - -/** - * Binding for STL's std::vector class. - * @author ochafik - * @param - */ -@Template({ Type.class }) -@Struct(customizer = STL.class) -public class vector extends CPPObject { - @Deprecated - @Field(0) - public Pointer _M_start() { - return io.getPointerField(this, 0); - } - @Deprecated - @Field(1) - public Pointer _M_finish() { - return io.getPointerField(this, 1); - } - @Deprecated - @Field(2) - public Pointer _M_end_of_storage() { - return io.getPointerField(this, 2); - } - //@Constructor(-1) - public vector(Type t) { - super((Void)null, CPPRuntime.SKIP_CONSTRUCTOR, t); - } - public vector(Pointer> peer) { - super(peer); - if (!isValid()) - throw new RuntimeException("Invalid vector internal data ! Are you trying to use an unsupported version of the STL ?"); - } - - protected boolean isValid() { - long start = getPeer(_M_start()); - long finish = getPeer(_M_finish()); - long eos = getPeer(_M_end_of_storage()); - if (start == 0 || finish == 0 || eos == 0) - return false; - return start <= finish && finish <= eos; - } - - public T get(long index) { - // TODO make this unnecessary - Pointer p = _M_start().as(T()); - return p.get(index); - } - public T get(int index) { - return get((long)index); - } - public void push_back(T value) { - throw new UnsupportedOperationException(); - } - protected Type T() { - return (Type)CPPRuntime.getInstance().getTemplateParameters(this, vector.class)[0]; - } - protected long byteSize() { - return _M_finish().getPeer() - _M_start().getPeer(); - } - - public long size() { - long byteSize = byteSize(); - long elementSize = BridJ.sizeOf(T()); - - return byteSize / elementSize; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/CSharpRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cs/CSharpRuntime.java deleted file mode 100644 index 404720045..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/CSharpRuntime.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cs; - -import org.bridj.BridJRuntime; - -/** - * - * @author Olivier - */ -public interface CSharpRuntime extends BridJRuntime { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/DotNetRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/DotNetRuntime.java deleted file mode 100644 index 90e1ddda7..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/DotNetRuntime.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cs.dotnet; - -import org.bridj.AbstractBridJRuntime; -import org.bridj.JNI; -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.cs.CSharpRuntime; -import java.lang.reflect.Type; -import org.bridj.Platform; - -/** - * @see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getdelegateforfunctionpointer(VS.80).aspx - * @author Olivier - */ -public class DotNetRuntime extends AbstractBridJRuntime implements CSharpRuntime { - - //@Override - public boolean isAvailable() { - return Platform.isWindows(); - } - - //@Override - public Class getActualInstanceClass(Pointer pInstance, Type officialType) { - throw new UnsupportedOperationException("Not supported yet."); - } - - //@Override - public void register(Type type) { - throw new UnsupportedOperationException("Not supported yet."); - } - - //@Override - public TypeInfo getTypeInfo(Type type) { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/package-info.java deleted file mode 100644 index ac6e49ea3..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/dotnet/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ C# support specific to Microsoft's .NET platform (stub, not implemented). -*/ -package org.bridj.cs.dotnet; diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/mono/MonoRuntime.java b/libraries/BridJ/src/main/java/org/bridj/cs/mono/MonoRuntime.java deleted file mode 100644 index 867381bc1..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/mono/MonoRuntime.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.cs.mono; - -import org.bridj.AbstractBridJRuntime; -import org.bridj.BridJ; -import static org.bridj.BridJ.*; -import org.bridj.NativeLibrary; -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.ann.Library; -import org.bridj.cs.CSharpRuntime; -import java.io.FileNotFoundException; -import java.lang.reflect.Type; - -/** - * Stub, not implemented (see this blog entry for a proof of concept). - * @author Olivier - */ -@Library("mono") -public class MonoRuntime extends AbstractBridJRuntime implements CSharpRuntime { - - public MonoRuntime() { - try { - BridJ.register(); - } catch (Exception ex) { - // Accept failure - info("Failed to register " + getClass().getName(), ex); - } - } - - //@Override - public boolean isAvailable() { - return getMonoLibrary() != null; - } - - //@Override - public Class getActualInstanceClass(Pointer pInstance, Type officialType) { - throw new UnsupportedOperationException("Not supported yet."); - } - - //@Override - public void register(Type type) { - throw new UnsupportedOperationException("Not supported yet."); - } - - NativeLibrary monoLibrary; - boolean fetchedLibrary; - private synchronized NativeLibrary getMonoLibrary() { - if (!fetchedLibrary && monoLibrary == null) { - try { - fetchedLibrary = true; - monoLibrary = BridJ.getNativeLibrary("mono"); - } catch (Exception ex) { - info(null, ex); - } - } - return monoLibrary; - } - - //@Override - public TypeInfo getTypeInfo(Type type) { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/mono/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cs/mono/package-info.java deleted file mode 100644 index 7ac1320e5..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/mono/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** -BridJ C# support specific to Novell's Mono platform (stub, not implemented). -

-See this blog entry for a proof of concept). -*/ -package org.bridj.cs.mono; diff --git a/libraries/BridJ/src/main/java/org/bridj/cs/package-info.java b/libraries/BridJ/src/main/java/org/bridj/cs/package-info.java deleted file mode 100644 index f6f1a67cf..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/cs/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** -BridJ C# support (stub, not implemented). -

-See this blog entry for a proof of concept). -*/ -package org.bridj.cs; diff --git a/libraries/BridJ/src/main/java/org/bridj/demangling/Demangler.java b/libraries/BridJ/src/main/java/org/bridj/demangling/Demangler.java deleted file mode 100644 index 91fd18dce..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/demangling/Demangler.java +++ /dev/null @@ -1,1076 +0,0 @@ -package org.bridj.demangling; - -import java.io.EOFException; -import org.bridj.ann.Convention.Style; -import java.lang.reflect.*; -import java.lang.annotation.*; -import java.util.Arrays; -import org.bridj.AbstractBridJRuntime; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.FlagSet; -import org.bridj.JNI; -import org.bridj.NativeLibrary; -import org.bridj.NativeObject; -import org.bridj.Platform; - -import org.bridj.Pointer; -import org.bridj.TimeT; -import org.bridj.SizeT; -import org.bridj.CLong; -import org.bridj.ValuedEnum; -import org.bridj.ann.Constructor; -import org.bridj.ann.Ptr; -import org.bridj.ann.Convention; -import org.bridj.ann.Name; -import org.bridj.ann.Template; -import org.bridj.util.AnnotationUtils; -import static org.bridj.util.AnnotationUtils.*; -import org.bridj.util.DefaultParameterizedType; -import org.bridj.util.Utils; - -/* -mvn compile exec:java -Dexec.mainClass=org.bridj.demangling.Demangler -e "-Dexec.args=?method_name@class_name@@QAEPAPADPAD0@Z" - -??4Class1@TestLib@@QAEAAV01@ABV01@@Z -?f@Class1@TestLib@@QAEPADPAD0@Z - -class TestLib::Class1 & TestLib::Class1::operator=(class TestLib::Class1 const &) -char * TestLib::Class1::f(char *,char *) -*/ -/** - * Base class and core structures for symbol demanglers (typically, for C++ symbols). - */ -public abstract class Demangler { - - public static void main(String[] args) { -// try { -//// String s = "?f@@YA?AW4E@@W41@@Z"; -// String s = "?f@@YAPADPADPAF1@Z"; // "byte* f(byte*, short*, short*)" -// //String s = "?m@C@@SAPAV1@XZ"; -// MemberRef mr = new VC9Demangler(null, s).parseSymbol(); -// System.out.println(mr); -// } catch (DemanglingException ex) { -// Logger.getLogger(Demangler.class.getName()).error(null, ex); -// } - for (String arg : args) { - try { - System.out.println("VC9: " + new VC9Demangler(null, arg).parseSymbol()); - } catch (Exception ex) { - ex.printStackTrace(); - } - try { - System.out.println("GCC4: " + new GCC4Demangler(null, arg).parseSymbol()); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public interface Annotations { - A getAnnotation(Class c); - boolean isAnnotationPresent(Class c); - } - public static Annotations annotations(final Annotation[] aa) { - return new Annotations() { - //@Override - public A getAnnotation(Class c) { - if (aa == null) - return null; - - for (Annotation a : aa) - if (c.isInstance(a)) - return (A)a; - return null; - } - - public boolean isAnnotationPresent(Class c) { - return AnnotationUtils.isAnnotationPresent(c, aa); - } - - }; - } - - public static Annotations annotations(final Type e) { - return annotations((AnnotatedElement)Utils.getClass(e)); - } - public static Annotations annotations(final AnnotatedElement e) { - return new Annotations() { - //@Override - public A getAnnotation(Class c) { - return e.getAnnotation(c); - } - - public boolean isAnnotationPresent(Class c) { - return AnnotationUtils.isAnnotationPresent(c, e); - } - - }; - } - - public static class DemanglingException extends Exception { - public DemanglingException(String mess) { - this(mess, null); - } - public DemanglingException(String mess, Throwable cause) { - super(mess, cause); - } - } - public abstract MemberRef parseSymbol() throws DemanglingException; - - protected final String str; - protected final int length; - protected int position = 0; - protected final NativeLibrary library; - public Demangler(NativeLibrary library, String str) { - this.str = str; - this.length = str.length(); - this.library = library; - } - - public String getString() { - return str; - } - - protected void expectChars(char... cs) throws DemanglingException { - for (char c : cs) { - char cc = consumeChar(); - if (cc != c) - throw error("Expected char '" + c + "', found '" + cc + "'"); - } - } - protected void expectAnyChar(char... cs) throws DemanglingException { - char cc = consumeChar(); - for (char c : cs) { - if (cc == c) - return; - } - throw error("Expected any of " + Arrays.toString(cs) + ", found '" + cc + "'"); - } - public static StringBuilder implode(StringBuilder b, Object[] items, String sep) { - return implode(b, Arrays.asList(items), sep); - } - public static StringBuilder implode(StringBuilder b, Iterable items, String sep) { - boolean first = true; - for (Object item : items) { - if (first) - first = false; - else - b.append(sep); - b.append(item); - } - return b; - } - protected char peekChar() { - return peekChar(1); - } - protected char peekChar(int dist) { - int p = position + dist - 1; - return p >= length ? 0 : str.charAt(p); - } - protected char lastChar() { - return position == 0 ? 0 : str.charAt(position - 1); - } - protected char consumeChar() throws DemanglingException { - char c = peekChar(); - if (c != 0) - position++; - else - throw new DemanglingException("Reached end of string '" + str + "'"); - return c; - } - protected boolean consumeCharsIf(char... nextChars) { - int initialPosition = position; - try { - for (char c : nextChars) { - char cc = consumeChar(); - if (cc != c) { - position = initialPosition; - return false; - } - } - return true; - } catch (DemanglingException ex) { - position = initialPosition; - return false; - } - } - protected boolean consumeCharIf(char... allowedChars) { - char c = peekChar(); - for (char allowedChar : allowedChars) - if (allowedChar == c) { - position++; - return true; - } - return false; - } - protected DemanglingException error(int deltaPosition) { - return error(null, deltaPosition); - } - protected DemanglingException error(String mess) { - return error(mess, -1); - } - protected DemanglingException error(String mess, int deltaPosition) { - StringBuilder err = new StringBuilder(position + 1); - int position = this.position + deltaPosition; - for (int i = 0; i < position; i++) - err.append(' '); - err.append('^'); - return new DemanglingException("Parsing error at position " + position + (mess == null ? "" : ": " + mess) + " \n\t" + str + "\n\t" + err); - } - - public interface TemplateArg { - public boolean matchesParam(Object param, Annotations annotations); - } - - public static String getMethodName(Method method) { - Name nameAnn = method.getAnnotation(Name.class); - if (nameAnn != null) - return nameAnn.value(); - - return method.getName(); - } - - public static class Symbol { - final String symbol; - long address; - MemberRef ref; - boolean refParsed; - final NativeLibrary library; - - public Symbol(String symbol, NativeLibrary library) { - this.symbol = symbol; - this.library = library; - - } - - public NativeLibrary getLibrary() { - return library; - } - - public MemberRef getRef() { - return ref; - } - - public Style getStyle() { - return style; - } - - public String getSymbol() { - return symbol; - } - - @Override - public String toString() { - return symbol + (ref == null ? "" : " (" + ref + ")"); - } - - - public long getAddress() { - if (address == 0) - address = library.getSymbolAddress(symbol); - return address; - } - - public void setAddress(long address) { - this.address = address; - } - - private Convention.Style style; - public Convention.Style getInferredCallingConvention() { - if (style == null) { - //System.out.println("Symbol " + symbol + " stdcall = " + symbol.matches("_.*?@\\d+")); - if (symbol.matches("_.*?@\\d+")) - style = Convention.Style.StdCall; - else if (symbol.matches("@.*?@\\d+")) - style = Convention.Style.FastCall; - else if (Platform.isWindows() && symbol.contains("@")) - try { - MemberRef mr = getParsedRef(); - if (mr != null) - style = mr.callingConvention; - } catch (Throwable th) {} - } - return style; - } - public boolean matches(Method method) { - if (!symbol.contains(getMethodName(method))) - return false; - - //if (!Modifier.isStatic(method.getModifiers()) && !symbol.contains(method.getDeclaringClass().getSimpleName())) - // return false; - - parse(); - - try { - if (ref != null) { - boolean res = ref.matches(method); - if (!res && BridJ.debug) { - System.err.println("Symbol " + symbol + " was a good candidate but expected demangled signature " + ref + " did not match the method " + method); - } - return res; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - public MemberRef getParsedRef() { - parse(); - return ref; - } - synchronized void parse() { - if (!refParsed) { - try { - ref = library.parseSymbol(symbol); - } catch (DemanglingException ex) { - if (BridJ.debug) - ex.printStackTrace(); - if (BridJ.verbose) - BridJ.warning("Symbol parsing failed : " + ex.getMessage()); - } - refParsed = true; - } - } - - public String getName() { - return symbol; - } - - public boolean matchesVirtualTable(Class type) { - if (!symbol.contains(type.getSimpleName())) - return false; - - parse(); - - try { - if (ref != null) { - return ref.matchesVirtualTable(type); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - public boolean matchesConstructor(Type type, java.lang.reflect.Constructor constr) { - if (!symbol.contains(Utils.getClass(type).getSimpleName())) - return false; - - parse(); - - try { - if (ref != null) { - return ref.matchesConstructor(type, constr); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - public boolean matchesDestructor(Class type) { - if (!symbol.contains(type.getSimpleName())) - return false; - - parse(); - - try { - if (ref != null) { - return ref.matchesDestructor(type); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - - public boolean isVirtualTable() { - // TODO Auto-generated method stub - return false; - } - - } - - - public static abstract class TypeRef implements TemplateArg { - public abstract StringBuilder getQualifiedName(StringBuilder b, boolean generic); - public boolean matchesParam(Object param, Annotations annotations) { - return (param instanceof Type) && matches((Type)param, annotations); - } - public boolean matches(Type type, Annotations annotations) { - String thisName = getQualifiedName(new StringBuilder(), false).toString(); - Class typeClass = getTypeClass(type); - String typeName = typeClass.getSimpleName(); - return thisName.equals(typeName) || thisName.equals(typeClass.getName()); - } - - @Override - public boolean equals(Object obj) { - return toString().equals(obj.toString()); - } - - } - - public static class Constant implements TemplateArg { - Object value; - - public Constant(Object value) { - this.value = value; - } - public boolean matchesParam(Object param, Annotations annotations) { - return value.equals(param); - } - - @Override - public String toString() { - return value.toString(); - } - } - - public static class NamespaceRef extends TypeRef { - Object[] namespace; - public NamespaceRef(Object[] namespace) { - this.namespace = namespace; - } - public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { - return implode(b, namespace, "."); - } - - @Override - public String toString() { - return getQualifiedName(new StringBuilder(), true).toString(); - } - - } - - public static class PointerTypeRef extends TypeRef { - - public TypeRef pointedType; - - public PointerTypeRef(TypeRef pointedType) { - this.pointedType = pointedType; - } - - @Override - public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { - return b.append("org.bridj.Pointer"); - } - @Override - public String toString() { - return pointedType + "*"; - } - } - - protected static TypeRef pointerType(TypeRef tr) { - return new PointerTypeRef(tr); - } - protected static TypeRef classType(final Class c, Class... annotations) { - return classType(c, null, annotations); - } - protected static TypeRef classType(final Class c, final java.lang.reflect.Type[] genericTypes, Class... annotations) { - JavaTypeRef tr = new JavaTypeRef(); - if (genericTypes == null) - tr.type = c; - else - tr.type = new DefaultParameterizedType(c, genericTypes); - - tr.annotations = annotations; - return tr; - } - protected static TypeRef simpleType(String name, TemplateArg... args) { - return new ClassRef(new Ident(name, args)); - } - protected static TypeRef simpleType(Ident ident) { - return new ClassRef(ident); - } - static Class getTypeClass(Type type) { - - if (type instanceof Class) - return (Class)type; - if (type instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType)type; - Class c = (Class)pt.getRawType(); - if (ValuedEnum.class.isAssignableFrom(c)) { - Type[] types = pt.getActualTypeArguments(); - if (types == null || types.length != 1) - c = int.class; - else - c = getTypeClass(pt.getActualTypeArguments()[0]); - } - return c; - } - if (type instanceof GenericArrayType) { - if (Object.class.isAssignableFrom(getTypeClass(((GenericArrayType)type).getGenericComponentType()))) - return Object[].class; - } - throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName()); - } - static boolean equivalentTypes(Type a, Class ac, Annotations aAnnotations, Type b, Class bc, Annotations bAnnotations) { - if (a.equals(b)) - return true; - - int as = getIntegralSize(a, ac, aAnnotations); - int bs = getIntegralSize(b, bc, bAnnotations); - - //System.out.println("a = " + a + ", b = " + b + ", as = " + as + ", bs = " + bs + ", equiv = " + (as != -1 && as == bs)); - return as != -1 && as == bs; - } - static int getIntegralSize(Type type, Class typec, Annotations annotations) { - if (type == int.class || type == Integer.class) - return 4; - if (type == long.class || type == Long.class) { - if (annotations != null) { - if (annotations.isAnnotationPresent(Ptr.class)) - return SizeT.SIZE; - if (annotations.isAnnotationPresent(org.bridj.ann.CLong.class)) - return CLong.SIZE; - } - return 8; - } - if (type == CLong.class) - return CLong.SIZE; - if (type == SizeT.class) - return SizeT.SIZE; - if (type == TimeT.class) - return TimeT.SIZE; - if (type == byte.class || type == Byte.class) - return 1; - if (type == char.class || type == Character.class || type == short.class || type == Short.class) - return 2; - if (ValuedEnum.class.isAssignableFrom(typec)) - return 4; - if (Pointer.class.isAssignableFrom(typec)) - return SizeT.SIZE; - return -1; - } - public static boolean equivalentTypes(Type a, Type b) { - return equivalentTypes(a, getTypeClass(a), null, b, getTypeClass(b), null); - } - - - public static class JavaTypeRef extends TypeRef { - - java.lang.reflect.Type type; - Class[] annotations; - - @Override - public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { - return b.append(getTypeClass(this.type).getName()); - } - @Override - public boolean matches(Type type, Annotations annotations) { - Class tc = getTypeClass(this.type); - Class typec = getTypeClass(type); - if (tc == typec || tc.equals(typec)) - return true; - - if ((type == Long.TYPE && Pointer.class.isAssignableFrom(tc)) || - (Pointer.class.isAssignableFrom(typec) && tc == Long.TYPE)) - return true; - - return equivalentTypes(type, typec, annotations, this.type, tc, null); // TODO isAssignableFrom or the opposite, depending on context - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - for (Class ann : annotations) - b.append(ann.getSimpleName()).append(' '); - b.append((type instanceof Class) ? ((Class)type).getSimpleName() : type.toString()); - return b.toString(); - } - - } - public interface IdentLike { - - } - public static class Ident implements IdentLike { - Object simpleName; - TemplateArg[] templateArguments; - - public Ident(String simpleName, TemplateArg... templateArguments) { - this.simpleName = simpleName; - this.templateArguments = templateArguments; - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof Ident)) - return false; - - Ident ident = (Ident)o; - if (!simpleName.equals(ident.simpleName)) - return false; - - int n = templateArguments.length; - if (ident.templateArguments.length != n) - return false; - - for (int i = 0; i < n; i++) - if (!templateArguments[i].equals(ident.templateArguments[i])) - return false; - - return true; - } - - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - - b.append(simpleName); - appendTemplateArgs(b, templateArguments); - return b.toString(); - } - } - public static class ClassRef extends TypeRef { - private TypeRef enclosingType; - //private Object simpleName; - //TemplateArg[] templateArguments; - final Ident ident; - - public ClassRef(Ident ident) { - this.ident = ident; - } - public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { - if (getEnclosingType() instanceof ClassRef) { - getEnclosingType().getQualifiedName(b, generic).append('$'); - } else if (getEnclosingType() instanceof NamespaceRef) { - getEnclosingType().getQualifiedName(b, generic).append('.'); - } - b.append(ident.simpleName); - if (generic && ident.templateArguments != null) { - int args = 0; - for (int i = 0, n = ident.templateArguments.length; i < n; i++) { - TemplateArg arg = ident.templateArguments[i]; - if (!(arg instanceof TypeRef)) - continue; - - if (args == 0) - b.append('<'); - else - b.append(", "); - ((TypeRef)arg).getQualifiedName(b, generic); - args++; - } - if (args > 0) - b.append('>'); - } - return b; - } - - public Ident getIdent() { - return ident; - } - - - public void setEnclosingType(TypeRef enclosingType) { - this.enclosingType = enclosingType; - } - - public TypeRef getEnclosingType() { - return enclosingType; - } - - @Override - public boolean matches(Type type, Annotations annotations) { - if (getTypeClass(type).getSimpleName().equals(ident.simpleName)) - return true; - - return false; - } - - - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - - if (enclosingType != null) - b.append(enclosingType).append('.'); - - b.append(ident); - return b.toString(); - } - - - } - static void appendTemplateArgs(StringBuilder b, Object[] params) { - if (params == null || params.length == 0) - return; - appendArgs(b, '<', '>', params); - } - static void appendArgs(StringBuilder b, char pre, char post, Object[] params) { - b.append(pre); - if (params != null) - for (int i = 0; i < params.length; i++) { - if (i != 0) - b.append(", "); - b.append(params[i]); - } - b.append(post); - } - public static class FunctionTypeRef extends TypeRef { - MemberRef function; - - public FunctionTypeRef(MemberRef function) { - this.function = function; - } - @Override - public StringBuilder getQualifiedName(StringBuilder b, boolean generic) { - // TODO Auto-generated method stub - return null; - } - - - @Override - public String toString() { - return function.toString(); - } - } - public enum SpecialName implements IdentLike { - Constructor("", true, true), - SpecialConstructor("", true, true), - Destructor("", true, true), - SelfishDestructor("", true, true), - DeletingDestructor("", true, true), - New("new", true, true), - Delete("delete", true, true), - NewArray("new[]", true, true), - DeleteArray("delete[]", true, true), - VFTable("vftable", false, true), - VBTable("vbtable", false, true), - VCall("vcall", false, false), // What is that ??? - TypeOf("typeof", false, false), - ScalarDeletingDestructor("'scalar deleting destructor'", true, true), - VectorDeletingDestructor("'vector deleting destructor'", true, true), - - OperatorAssign("operator=", true, true), - OperatorRShift("operator>>", true, true), - OperatorDivideAssign("operator/=", true, true), - OperatorModuloAssign("operator%=", true, true), - OperatorRShiftAssign("operator>>=", true, true), - OperatorLShiftAssign("operator<<=", true, true), - OperatorBitAndAssign("operator&=", true, true), - OperatorBitOrAssign("operator|=", true, true), - OperatorXORAssign("operator^=", true, true), - OperatorLShift("operator<<", true, true), - OperatorLogicNot("operator!", true, true), - OperatorEquals("operator==", true, true), - OperatorDifferent("operator!=", true, true), - OperatorSquareBrackets("operator[]", true, true), - OperatorCast("'some cast operator'", true, true), - OperatorArrow("operator->", true, true), - OperatorMultiply("operator*", true, true), - OperatorIncrement("operator++", true, true), - OperatorDecrement("operator--", true, true), - OperatorSubstract("operator-", true, true), - OperatorAdd("operator+", true, true), - OperatorBitAnd("operator&=", true, true), - /// Member pointer selector - OperatorArrowStar("operator->*", true, true), - OperatorDivide("operator/", true, true), - OperatorModulo("operator%", true, true), - OperatorLower("operator<", true, true), - OperatorLowerEquals("operator<=", true, true), - OperatorGreater("operator>", true, true), - OperatorGreaterEquals("operator>=", true, true), - OperatorComma("operator,", true, true), - OperatorParenthesis("operator()", true, true), - OperatorBitNot("operator~", true, true), - OperatorXOR("operator^", true, true), - OperatorBitOr("operator|", true, true), - OperatorLogicAnd("operator&&", true, true), - OperatorLogicOr("operator||", true, true), - OperatorMultiplyAssign("operator*=", true, true), - OperatorAddAssign("operator+=", true, true), - OperatorSubstractAssign("operator-=", true, true); - - private SpecialName(String name, boolean isFunction, boolean isMember) { - this.name = name; - this.isFunction = isFunction; - this.isMember = isMember; - } - final String name; - final boolean isFunction; - final boolean isMember; - - @Override - public String toString() { - return name; - } - - public boolean isFunction() { - return isFunction; - } - - public boolean isMember() { - return isMember; - } - - - - - } - public static class MemberRef { - - private Integer argumentsStackSize; - private TypeRef enclosingType; - private TypeRef valueType; - private IdentLike memberName; - Boolean isStatic, isProtected, isPrivate; - public int modifiers; - public TypeRef[] paramTypes, throwTypes; - TemplateArg[] templateArguments; - public Style callingConvention; - - public void setTemplateArguments(TemplateArg[] templateArguments) { - this.templateArguments = templateArguments; - } - - public Integer getArgumentsStackSize() { - return argumentsStackSize; - } - - public void setArgumentsStackSize(Integer argumentsStackSize) { - this.argumentsStackSize = argumentsStackSize; - } - - protected boolean matchesEnclosingType(Type type) { - return getEnclosingType() != null && getEnclosingType().matches(type, annotations(type)); - } - - protected boolean matchesVirtualTable(Type type) { - return memberName == SpecialName.VFTable && matchesEnclosingType(type); - } - protected boolean matchesConstructor(Type type, java.lang.reflect.Constructor constr) { - if (memberName != SpecialName.Constructor) - return false; - - if (!matchesEnclosingType(type)) - return false; - - Template temp = Utils.getClass(type).getAnnotation(Template.class); - Annotation[][] anns = constr.getParameterAnnotations(); - Type[] parameterTypes = constr.getGenericParameterTypes(); - - int overrideOffset = Utils.getEnclosedConstructorParametersOffset(constr); - if (!matchesArgs(parameterTypes, anns, overrideOffset + (temp == null ? 0 : temp.value().length))) - return false; - - return true; - } - protected boolean matchesDestructor(Type type) { - return memberName == SpecialName.Destructor && matchesEnclosingType(type); - } - static boolean hasInstance(Object[] array, Class... cs) { - for (Object o : array) - for (Class c : cs) - if (c.isInstance(o)) - return true; - return false; - } - static int getArgumentsStackSize(Method method) { - int total = 0; - Type[] paramTypes = method.getGenericParameterTypes(); - Annotation[][] anns = method.getParameterAnnotations(); - for (int iArg = 0, nArgs = paramTypes.length; iArg < nArgs; iArg++) { - Class paramType = getTypeClass(paramTypes[iArg]); - if (paramType == int.class) - total += 4; - else if (paramType == long.class) { - Annotation[] as = anns[iArg]; - if (isAnnotationPresent(Ptr.class, as) || isAnnotationPresent(org.bridj.ann.CLong.class, as)) - //if (hasInstance(anns[iArg], Ptr.class, CLong.class)) - total += Pointer.SIZE; - else - total += 8; - } else if (paramType == float.class) - total += 4; - else if (paramType == double.class) - total += 8; - else if (paramType == byte.class) - total += 1; - else if (paramType == char.class) - total += Platform.WCHAR_T_SIZE; - else if (paramType == CLong.class) - total += Platform.CLONG_SIZE; - else if (paramType == SizeT.class) - total += Platform.SIZE_T_SIZE; - else if (paramType == TimeT.class) - total += Platform.TIME_T_SIZE; - else if (paramType == short.class) - total += 2; - else if (paramType == boolean.class) - total += 1; - else if (Pointer.class.isAssignableFrom(paramType)) - total += Pointer.SIZE; - else if (NativeObject.class.isAssignableFrom(paramType)) - total += ((CRuntime)BridJ.getRuntime(paramType)).sizeOf(paramTypes[iArg], null); - else if (FlagSet.class.isAssignableFrom(paramType)) - total += 4; // TODO - else - throw new RuntimeException("Type not handled : " + paramType.getName()); - } - return total; - } - protected boolean matches(Method method) { - - if (memberName instanceof SpecialName) - return false; // use matchesConstructor... - - if (!matchesEnclosingType(method)) - return false; - - return matchesSignature(method); - } - public boolean matchesEnclosingType(Method method) { - TypeRef et = getEnclosingType(); - if (et == null) - return true; - - Annotations annotations = annotations(method); - Class dc = method.getDeclaringClass(); - do { - if (et.matches(dc, annotations)) - return true; - - dc = dc.getSuperclass(); - } while (dc != null && dc != Object.class); - - return false; - } - public boolean matchesSignature(Method method) { - - if (getArgumentsStackSize() != null && getArgumentsStackSize().intValue() != getArgumentsStackSize(method)) - return false; - - if (getMemberName() != null && !getMemberName().toString().equals(getMethodName(method))) - return false; - - if (getValueType() != null && !getValueType().matches(method.getReturnType(), annotations(method))) - return false; - - Template temp = method.getAnnotation(Template.class); - Annotation[][] anns = method.getParameterAnnotations(); -// Class[] methodArgTypes = method.getParameterTypes(); - Type[] parameterTypes = method.getGenericParameterTypes(); - //boolean hasThisAsFirstArgument = BridJ.hasThisAsFirstArgument(method);//methodArgTypes, anns, true); - - if (paramTypes != null && !matchesArgs(parameterTypes, anns, temp == null ? 0 : temp.value().length))///*, hasThisAsFirstArgument*/)) - return false; - - //int thisDirac = hasThisAsFirstArgument ? 1 : 0; - /* - switch (type) { - case Constructor: - case Destructor: - Annotation ann = method.getAnnotation(type == SpecialName.Constructor ? Constructor.class : Destructor.class); - if (ann == null) - return false; - if (!hasThisAsFirstArgument) - return false; - if (methodArgTypes.length - thisDirac != 0 ) - return false; - break; - case InstanceMethod: - if (!hasThisAsFirstArgument) - return false; - break; - case StaticMethod: - if (hasThisAsFirstArgument) - return false; - break; - }*/ - - return true; - } - private boolean matchesArgs(Type[] parameterTypes, Annotation[][] anns, int offset) { - int totalArgs = offset; - for (int i = 0, n = templateArguments == null ? 0 : templateArguments.length; i < n; i++) { - if (totalArgs >= parameterTypes.length) - return false; - - Type paramType = parameterTypes[offset + i]; - - TemplateArg arg = templateArguments[i]; - if (arg instanceof TypeRef) { - if (!paramType.equals(Class.class)) - return false; - } else if (arg instanceof Constant) { - try { - getTypeClass(paramType).cast(((Constant)arg).value); - } catch (ClassCastException ex) { - return false; - } - } - totalArgs++; - } - - for (int i = 0, n = paramTypes == null ? 0 : paramTypes.length; i < n; i++) { - if (totalArgs >= parameterTypes.length) - return false; - - TypeRef paramType = paramTypes[i]; - Type parameterType = parameterTypes[totalArgs]; - if (!paramType.matches(parameterType, annotations(anns == null ? null : anns[i]))) - return false; - - totalArgs++; - } - - if (totalArgs != parameterTypes.length) { - System.err.println("Not enough args for " + this); - return false; - } - - return true; - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - - b.append(valueType).append(' '); - boolean nameWritten = false; - if (enclosingType != null) { - b.append(enclosingType); - b.append('.'); - if (memberName instanceof SpecialName) { - switch ((SpecialName)memberName) { - case Destructor: - b.append('~'); - case Constructor: - b.append(((ClassRef)enclosingType).ident.simpleName); - nameWritten = true; - break; - } - } - } - if (!nameWritten) - b.append(memberName); - - appendTemplateArgs(b, templateArguments); - appendArgs(b, '(', ')', paramTypes); - return b.toString(); - } - - public void setMemberName(IdentLike memberName) { - this.memberName = memberName; - } - public IdentLike getMemberName() { - return memberName; - } - public void setValueType(TypeRef valueType) { - this.valueType = valueType; - } - public TypeRef getValueType() { - return valueType; - } - public void setEnclosingType(TypeRef enclosingType) { - this.enclosingType = enclosingType; - } - public TypeRef getEnclosingType() { - return enclosingType; - } - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/demangling/GCC4Demangler.java b/libraries/BridJ/src/main/java/org/bridj/demangling/GCC4Demangler.java deleted file mode 100644 index 58a0b20df..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/demangling/GCC4Demangler.java +++ /dev/null @@ -1,419 +0,0 @@ -package org.bridj.demangling; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bridj.CLong; -import org.bridj.NativeLibrary; -import org.bridj.demangling.Demangler.ClassRef; -import org.bridj.demangling.Demangler.DemanglingException; -import org.bridj.demangling.Demangler.Ident; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.demangling.Demangler.NamespaceRef; -import org.bridj.demangling.Demangler.TypeRef; -import org.bridj.demangling.Demangler.SpecialName; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class GCC4Demangler extends Demangler { - - public GCC4Demangler(NativeLibrary library, String symbol) { - super(library, symbol); - } - private Map> prefixShortcuts = new HashMap>() { - - { - - // prefix shortcut: e.g. St is for std:: - put("t", Arrays.asList((IdentLike) new Ident("std"))); - put("a", Arrays.asList((IdentLike) new Ident("std"), new Ident("allocator"))); - put("b", Arrays.asList((IdentLike) new Ident("std"), new Ident("basic_string"))); - TypeRef chartype = classType(Byte.TYPE); - ClassRef charTraitsOfChar = enclosed("std", new ClassRef(new Ident("char_traits", new TemplateArg[]{chartype}))); - ClassRef allocatorOfChar = enclosed("std", new ClassRef(new Ident("allocator", new TemplateArg[]{chartype}))); - put("d", Arrays.asList((IdentLike) new Ident("std"), new Ident("basic_iostream", new TemplateArg[]{chartype, charTraitsOfChar}))); - put("i", Arrays.asList((IdentLike) new Ident("std"), new Ident("basic_istream", new TemplateArg[]{chartype, charTraitsOfChar}))); - put("o", Arrays.asList((IdentLike) new Ident("std"), new Ident("basic_ostream", new TemplateArg[]{chartype, charTraitsOfChar}))); - // Ss == std::string == std::basic_string, std::allocator > - put("s", Arrays.asList((IdentLike) new Ident("std"), new Ident("basic_string", new TemplateArg[]{classType(Byte.TYPE), charTraitsOfChar, allocatorOfChar}))); - - // used, as an helper: for i in a b c d e f g h i j k l m o p q r s t u v w x y z; do c++filt _Z1_S$i; done - } - - private ClassRef enclosed(String ns, ClassRef classRef) { - classRef.setEnclosingType(new NamespaceRef(new Object[]{ns})); - return classRef; - } - }; - private Set shouldContinueAfterPrefix = new HashSet(Arrays.asList("t")); - private Map typeShortcuts = new HashMap(); - - private T ensureOfType(Object o, Class type) throws DemanglingException { - if (type.isInstance(o)) { - return type.cast(o); - } else { - throw new DemanglingException("Internal error in demangler: trying to cast to " + type.getCanonicalName() + " the object '" + o.toString() + "'"); - } - } - int nextShortcutId = -1; - - private String nextShortcutId() { - int n = nextShortcutId++; - return n == -1 ? "_" : Integer.toString(n, 36).toUpperCase() + "_"; - } - - private TypeRef parsePointerType() throws DemanglingException { - TypeRef pointed = parseType(); - TypeRef res = pointerType(pointed); - String id = nextShortcutId(); - typeShortcuts.put(id, res); - return res; - } - - public TemplateArg parseTemplateArg() throws DemanglingException { - if (consumeCharIf('L')) { - TypeRef tr = parseType(); - StringBuffer b = new StringBuffer(); - char c; - while (Character.isDigit(c = peekChar())) { - consumeChar(); - b.append(c); - } - expectChars('E'); - // TODO switch on type ! - return new Constant(Integer.parseInt(b.toString())); - } else { - return parseType(); - } - } - - public TypeRef parseType() throws DemanglingException { - if (Character.isDigit(peekChar())) { - Ident name = ensureOfType(parseNonCompoundIdent(), Ident.class); - String id = nextShortcutId(); // we get the id before parsing the part (might be template parameters and we need to get the ids in the right order) - TypeRef res = simpleType(name); - typeShortcuts.put(id, res); - return res; - } - - char c = consumeChar(); - switch (c) { - case 'S': { // here we first check if we have a type shorcut saved, if not we fallback to the (compound) identifier case - char cc = peekChar(); - int delta = 0; - if (Character.isDigit(cc) || Character.isUpperCase(cc) || cc == '_') { - String id = ""; - while ((c = peekChar()) != '_' && c != 0) { - id += consumeChar(); - delta++; - } - if (peekChar() == 0) { - throw new DemanglingException("Encountered a unexpected end in gcc mangler shortcut '" + id + "' " + prefixShortcuts.keySet()); - } - id += consumeChar(); // the '_' - delta++; - if (typeShortcuts.containsKey(id)) { - if (peekChar() != 'I') { - // just a shortcut - return typeShortcuts.get(id); - } else { - // shortcut but templated - List nsPath = new ArrayList(prefixShortcuts.get(id)); - String templatedId = parsePossibleTemplateArguments(nsPath); - if (templatedId != null) { - return typeShortcuts.get(templatedId); - } - } - } - position -= delta; - } - } - // WARNING/INFO/NB: we intentionally continue to the N case - case 'N': - position--; // I actually would peek() - { - List ns = new ArrayList(); - String newShortcutId = parseSimpleOrComplexIdentInto(ns, false); - ClassRef res = new ClassRef(ensureOfType(ns.remove(ns.size() - 1), Ident.class)); - if (!ns.isEmpty()) { - res.setEnclosingType(new NamespaceRef(ns.toArray(new Ident[ns.size()]))); - } - if (newShortcutId != null) { - typeShortcuts.put(newShortcutId, res); - } - return res; - } - case 'P': - return parsePointerType(); - case 'F': - // TODO parse function type correctly !!! - while (consumeChar() != 'E') { - } - - return null; - case 'K': - return parseType(); - case 'v': // char - return classType(Void.TYPE); - case 'c': - case 'a': - case 'h': // unsigned - return classType(Byte.TYPE); - case 'b': // bool - return classType(Boolean.TYPE); - case 'l': - case 'm': // unsigned - return classType(CLong.class); - //return classType(Platform.is64Bits() ? Long.TYPE : Integer.TYPE); - case 'x': - case 'y': // unsigned - return classType(Long.TYPE); - case 'i': - case 'j': // unsigned - return classType(Integer.TYPE); - case 's': - case 't': // unsigned - return classType(Short.TYPE); - case 'f': - return classType(Float.TYPE); - case 'd': - return classType(Double.TYPE); - case 'z': // varargs - return classType(Object[].class); - default: - throw error("Unexpected type char '" + c + "'", -1); - } - } - - String parseName() throws DemanglingException { // parses a plain name, e.g. "4plop" (the 4 is the length) - char c; - StringBuilder b = new StringBuilder(); - while (Character.isDigit(c = peekChar())) { - consumeChar(); - b.append(c); - } - int len; - try { - len = Integer.parseInt(b.toString()); - } catch (NumberFormatException ex) { - throw error("Expected a number", 0); - } - b.setLength(0); - for (int i = 0; i < len; i++) { - b.append(consumeChar()); - } - return b.toString(); - } - - private String parseSimpleOrComplexIdentInto(List res, boolean isParsingNonShortcutableElement) throws DemanglingException { - String newlyAddedShortcutForThisType = null; - boolean shouldContinue = false; - boolean expectEInTheEnd = false; - if (consumeCharIf('N')) { // complex (NB: they don't recursively nest (they actually can within a template parameter but not elsewhere)) - if (consumeCharIf('S')) { // it uses some shortcut prefix or type - parseShortcutInto(res); - } - shouldContinue = true; - expectEInTheEnd = true; - } else { // simple - if (consumeCharIf('S')) { // it uses some shortcut prefix or type - shouldContinue = parseShortcutInto(res); - } else { - res.add(parseNonCompoundIdent()); - } - } - if (shouldContinue) { - do { - String id = nextShortcutId(); // we get the id before parsing the part (might be template parameters and we need to get the ids in the right order) - newlyAddedShortcutForThisType = id; - IdentLike part = parseNonCompoundIdent(); - res.add(part); - prefixShortcuts.put(id, new ArrayList(res)); // the current compound name is saved by gcc as a shortcut (we do the same) - parsePossibleTemplateArguments(res); - } while (Character.isDigit(peekChar()) || peekChar() == 'C' || peekChar() == 'D'); - if (isParsingNonShortcutableElement) { - //prefixShortcuts.remove(previousShortcutId()); // correct the fact that we parsed one too much - nextShortcutId--; - } - } - parsePossibleTemplateArguments(res); - if (expectEInTheEnd) { - expectAnyChar('E'); - } - return newlyAddedShortcutForThisType; - } - - /** - * - * @param res a list of identlikes with the namespace elements and finished with an Ident which will be replaced by a new one enriched with template info - * @return null if res was untouched, or the new id created because of the presence of template arguments - */ - private String parsePossibleTemplateArguments(List res) throws DemanglingException { - if (consumeCharIf('I')) { - List args = new ArrayList(); - while (!consumeCharIf('E')) { - args.add(parseTemplateArg()); - } - String id = nextShortcutId(); // we get the id after parsing the template parameters - // It is very important that we create a new Ident as the other one has most probably been added as a shortcut and should be immutable from then - Ident templatedIdent = new Ident(ensureOfType(res.remove(res.size() - 1), Ident.class).toString(), args.toArray(new TemplateArg[args.size()])); - res.add(templatedIdent); - prefixShortcuts.put(id, new ArrayList(res)); - { - List ns = new ArrayList(res); - ClassRef clss = new ClassRef(ensureOfType(ns.remove(ns.size() - 1), Ident.class)); - if (!ns.isEmpty()) { - clss.setEnclosingType(new NamespaceRef(ns.toArray(new Ident[ns.size()]))); - } - typeShortcuts.put(id, clss); - } - return id; - } - return null; - } - - /** - * @return whether we should expect more parsing after this shortcut (e.g. std::vector<...> is actually not NSt6vectorI...EE but St6vectorI...E (without trailing N) - */ - private boolean parseShortcutInto(List res) throws DemanglingException { - char c = peekChar(); - // GCC builds shortcuts for each encountered type, they appear in the mangling as: S_, S0_, S1_, ..., SA_, SB_, ..., SZ_, S10_ - if (c == '_') { // we encounter S_ - List toAdd = prefixShortcuts.get(Character.toString(consumeChar())); - if (toAdd == null) { - throw new DemanglingException("Encountered a yet undefined gcc mangler shortcut S_ (first one), i.e. '_' " + prefixShortcuts.keySet()); - } - res.addAll(toAdd); - return false; - } else if (Character.isDigit(c) || Character.isUpperCase(c)) { // memory shorcut S[0-9A-Z]+_ - String id = ""; - while ((c = peekChar()) != '_' && c != 0) { - id += consumeChar(); - } - if (peekChar() == 0) { - throw new DemanglingException("Encountered a unexpected end in gcc mangler shortcut '" + id + "' " + prefixShortcuts.keySet()); - } - id += consumeChar(); // the '_' - List toAdd = prefixShortcuts.get(id); - if (toAdd == null) { - throw new DemanglingException("Encountered a unexpected gcc mangler shortcut '" + id + "' " + prefixShortcuts.keySet()); - } - res.addAll(toAdd); - return false; - } else if (Character.isLowerCase(c)) { // other, single character built-in shorcuts. We suppose for now that all shortcuts are lower case (e.g. Ss, St, ...) - String id = Character.toString(consumeChar()); - List toAdd = prefixShortcuts.get(id); - if (toAdd == null) { - throw new DemanglingException("Encountered a unexpected gcc mangler built-in shortcut '" + id + "' " + prefixShortcuts.keySet()); - } - res.addAll(toAdd); - return shouldContinueAfterPrefix.contains(id); - } else { - throw new DemanglingException("Encountered a unexpected gcc unknown shortcut '" + c + "' " + prefixShortcuts.keySet()); - } - } - - IdentLike parseNonCompoundIdent() throws DemanglingException { // This is a plain name with possible template parameters (or special like constructor C1, C2, ...) - if (consumeCharIf('C')) { - if (consumeCharIf('1')) { - return SpecialName.Constructor; - } else if (consumeCharIf('2')) { - return SpecialName.SpecialConstructor; - } else { - throw error("Unknown constructor type 'C" + peekChar() + "'"); - } - } else if (consumeCharIf('D')) { - // see http://zedcode.blogspot.com/2007/02/gcc-c-link-problems-on-small-embedded.html - if (consumeCharIf('0')) { - return SpecialName.DeletingDestructor; - } else if (consumeCharIf('1')) { - return SpecialName.Destructor; - } else if (consumeCharIf('2')) { - return SpecialName.SelfishDestructor; - } else { - throw error("Unknown destructor type 'D" + peekChar() + "'"); - } - } else { - String n = parseName(); - return new Ident(n); - } - } - - @Override - public MemberRef parseSymbol() throws DemanglingException { - MemberRef mr = new MemberRef(); - if (!consumeCharIf('_')) { - mr.setMemberName(new Ident(str)); - return mr; - } - consumeCharIf('_'); - expectChars('Z'); - - if (consumeCharIf('T')) { - if (consumeCharIf('V')) { - mr.setEnclosingType(ensureOfType(parseType(), ClassRef.class)); - mr.setMemberName(SpecialName.VFTable); - return mr; - } - return null; // can be a type info, a virtual table or strange things like that - } - /* - Reverse engineering of C++ operators : - delete[] = __ZdaPv - delete = __ZdlPv - new[] = __Znam - new = __Znwm - */ - if (consumeCharsIf('d', 'l', 'P', 'v')) { - mr.setMemberName(SpecialName.Delete); - return mr; - } - if (consumeCharsIf('d', 'a', 'P', 'v')) { - mr.setMemberName(SpecialName.DeleteArray); - return mr; - } - if (consumeCharsIf('n', 'w', 'm')) { - mr.setMemberName(SpecialName.New); - return mr; - } - if (consumeCharsIf('n', 'a', 'm')) { - mr.setMemberName(SpecialName.NewArray); - return mr; - } - - { - List ns = new ArrayList(); - parseSimpleOrComplexIdentInto(ns, true); - mr.setMemberName(ns.remove(ns.size() - 1)); - if (!ns.isEmpty()) { - ClassRef parent = new ClassRef(ensureOfType(ns.remove(ns.size() - 1), Ident.class)); - if (!ns.isEmpty()) { - parent.setEnclosingType(new NamespaceRef(ns.toArray(new Ident[ns.size()]))); - } - mr.setEnclosingType(parent); - } - } - - //System.out.println("mr = " + mr + ", peekChar = " + peekChar()); - - //mr.isStatic = - //boolean isMethod = consumeCharIf('E'); - - if (consumeCharIf('v')) { - if (position < length) { - error("Expected end of symbol", 0); - } - mr.paramTypes = new TypeRef[0]; - } else { - List paramTypes = new ArrayList(); - while (position < length) {// && !consumeCharIf('E')) { - paramTypes.add(parseType()); - } - mr.paramTypes = paramTypes.toArray(new TypeRef[paramTypes.size()]); - } - return mr; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/demangling/VC9Demangler.java b/libraries/BridJ/src/main/java/org/bridj/demangling/VC9Demangler.java deleted file mode 100644 index 5eb6b4fe0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/demangling/VC9Demangler.java +++ /dev/null @@ -1,819 +0,0 @@ -package org.bridj.demangling; - -import org.bridj.ann.Convention.Style; -import java.lang.reflect.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bridj.NativeLibrary; -import org.bridj.demangling.Demangler.ClassRef; -import org.bridj.demangling.Demangler.DemanglingException; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.demangling.Demangler.NamespaceRef; -import org.bridj.demangling.Demangler.Ident; -import org.bridj.demangling.Demangler.IdentLike; -import org.bridj.demangling.Demangler.TypeRef; -import org.bridj.demangling.Demangler.SpecialName; -import org.bridj.CLong; -import org.bridj.ann.Convention; -import java.math.BigInteger; -import java.util.Collection; - -public class VC9Demangler extends Demangler { - public VC9Demangler(NativeLibrary library, String str) { - super(library, str); - } - - private AccessLevelAndStorageClass parseAccessLevelAndStorageClass() throws DemanglingException { - AccessLevelAndStorageClass ac = new AccessLevelAndStorageClass(); - switch (consumeChar()) { - case 'A': - case 'B': - ac.modifiers = Modifier.PRIVATE; - break; - case 'C': - case 'D': - ac.modifiers = Modifier.PRIVATE | Modifier.STATIC; - break; - case 'E': - case 'F': - ac.modifiers = Modifier.PRIVATE; - ac.isVirtual = true; - break; - case 'G': - case 'H': - ac.modifiers = Modifier.PRIVATE; - ac.isThunk = true; - break; - case 'I': - case 'J': - ac.modifiers = Modifier.PROTECTED; - break; - case 'K': - case 'L': - ac.modifiers = Modifier.PROTECTED | Modifier.STATIC; - break; - case 'M': - case 'N': - ac.modifiers = Modifier.PROTECTED; - ac.isVirtual = true; - break; - case 'O': - case 'P': - ac.modifiers = Modifier.PROTECTED; - ac.isThunk = true; - break; - case 'Q': - case 'R': - ac.modifiers = Modifier.PUBLIC; - break; - case 'S': - case 'T': - ac.modifiers = Modifier.PUBLIC | Modifier.STATIC; - break; - case 'U': - case 'V': - ac.modifiers = Modifier.PUBLIC; - ac.isVirtual = true; - break; - case 'W': - case 'X': - ac.modifiers = Modifier.PUBLIC; - ac.isThunk = true; - break; - case 'Y': - case 'Z': - // No modifier, no storage class - ac.modifiers = 0; - break; - default: - throw error("Unknown access level + storage class"); - } - return ac; - } - - private ClassRef parseTemplateType() throws DemanglingException { - //System.out.println("# START OF parseTemplateParams()"); - String name = parseNameFragment(); - //return withEmptyQualifiedNames(new DemanglingOp() { public ClassRef run() throws DemanglingException { - List args = parseTemplateParams(); - - List names = parseNameQualifications(); - - //String ns = parseNameFragment(); - - //System.out.println("parseTemplateParams() = " + args + ", ns = " + names); - ClassRef tr = new ClassRef(new Ident(name, args.toArray(new TemplateArg[args.size()]))); - tr.setEnclosingType(reverseNamespace(names)); - - addBackRef(tr); - - return tr; - //}}); - } - - private void parseFunctionProperty(MemberRef mr) throws DemanglingException { - mr.callingConvention = parseCallingConvention(); - TypeRef returnType = consumeCharIf('@') ? classType(void.class) : parseType(true); -// allQualifiedNames.clear(); - //withEmptyQualifiedNames(new DemanglingRunnable() { public void run() throws DemanglingException { - List paramTypes = parseParams(); - mr.paramTypes = paramTypes.toArray(new TypeRef[paramTypes.size()]); - if (!consumeCharIf('Z')) { - List throwTypes = parseParams(); - mr.throwTypes = throwTypes.toArray(new TypeRef[throwTypes.size()]); - } - - mr.setValueType(returnType); - //}}); - } - - static class AnonymousTemplateArg implements TemplateArg { - public AnonymousTemplateArg(String v) { - this.v = v; - } - String v; - - //@Override - public boolean matchesParam(Object param, Annotations annotations) { - return true; // TODO wtf ? - } - @Override - public String toString() { - return v; - } - - } - - private TemplateArg parseTemplateParameter() throws DemanglingException { - switch (peekChar()) { - case '?': - consumeChar(); - return new AnonymousTemplateArg("'anonymous template param " + parseNumber(false) + "'"); - case '$': - consumeChar(); - switch (consumeChar()) { - case '0': - return new Constant(parseNumber(true)); - case '2': - int a = parseNumber(true); - int b = parseNumber(true); - return new Constant(a * Math.exp(10 * (int)Math.log(b - Math.log10(a) + 1))); - case 'D': - return new AnonymousTemplateArg("'anonymous template param " + parseNumber(false) + "'"); - case 'F': - return new AnonymousTemplateArg("'tuple (" + parseNumber(true) + ", " + parseNumber(true) + ")'"); - case 'G': - return new AnonymousTemplateArg("'tuple (" + parseNumber(true) + ", " + parseNumber(true) + ", " + parseNumber(true) + ")'"); - case 'Q': - return new AnonymousTemplateArg("'anonymous non-type template param " + parseNumber(false) + "'"); - } - break; - default: - //error("Unexpected template param value"); - } - return parseType(true); - } - static class AccessLevelAndStorageClass { - int modifiers; - boolean isVirtual = false, isThunk = false; - - } - public MemberRef parseSymbol() throws DemanglingException { - MemberRef mr = new MemberRef(); - - int iAt = str.indexOf('@'); - if (iAt >= 0 && consumeCharIf('_')) { - if (iAt > 0) { - mr.setMemberName(new Ident(str.substring(1, iAt))); - mr.setArgumentsStackSize(Integer.parseInt(str.substring(iAt + 1))); - return mr; - } - } - if (consumeCharIf('?')) { - consumeCharsIf('@', '?'); - - IdentLike memberName = parseFirstQualifiedTypeNameComponent(); - if (memberName instanceof SpecialName) { - SpecialName specialName = (SpecialName)memberName; - if (!specialName.isFunction()) - return null; - } - mr.setMemberName(memberName); - List qNames = parseNameQualifications(); - - //TypeRef qualifiedName = parseQualifiedTypeName(); - - AccessLevelAndStorageClass ac = parseAccessLevelAndStorageClass(); - CVClassModifier cvMod = null; - if (ac.modifiers != 0 && !Modifier.isStatic(ac.modifiers)) - cvMod = parseCVClassModifier(); - - // Function property : - //allQualifiedNames.clear(); // TODO fix this !! - TypeRef encl; - if (cvMod != null && (cvMod.isMember || (memberName instanceof SpecialName) || Modifier.isPublic(ac.modifiers))) { - Object r = qNames.get(0); - ClassRef tr = r instanceof ClassRef ? (ClassRef)r : new ClassRef(new Ident((String)r)); - //tr.setSimpleName(qNames.get(0)); - qNames.remove(0); - tr.setEnclosingType(reverseNamespace(qNames)); - encl = tr; - } else { - encl = reverseNamespace(qNames); - } - - addBackRef(encl); - mr.setEnclosingType(encl); - - parseFunctionProperty(mr); - - if (position != length) - error("Failed to demangle the whole symbol"); - } else { - mr.setMemberName(new Ident(str)); - } - return mr; - } - - - TypeRef parseReturnType() throws DemanglingException { - TypeRef tr = parseType(true); - return tr; - } - int parseNumber(boolean allowSign) throws DemanglingException { - int sign = allowSign && consumeCharIf('?') ? -1 : 1; - if (Character.isDigit(peekChar())) { - char c = consumeChar(); - return sign * (int)(c - '0'); - } - if (peekChar() == '@') - return 0; - - char c; - StringBuilder b = new StringBuilder(); - long n = 0; - while (((c = consumeChar()) >= 'A' && c <= 'P') && c != '@') - n += 16 * (c - 'A'); - - String s = b.toString().trim(); - if (c != '@' || s.length() == 0) - throw error("Expected a number here", -b.length()); - return sign * Integer.parseInt(s, 16); - } - TypeRef consumeIfBackRef() throws DemanglingException { - char c = peekChar(); - if (Character.isDigit(c)) { - consumeChar(); - int iBack = (int)(c - '0'); - return getBackRef(iBack); - } - return null; - } - TypeRef parseType(boolean allowVoid) throws DemanglingException { - TypeRef backRef = consumeIfBackRef(); - if (backRef != null) - return backRef; - - char c = consumeChar(); - switch (c) { - case '_': - TypeRef tr; - switch (consumeChar()) { - case 'D': // __int8 - case 'E': // unsigned __int8 - tr = classType(byte.class); - break; - case 'F': // __int16 - case 'G': // unsigned __int16 - tr = classType(short.class); - break; - case 'H': // __int32 - case 'I': // unsigned __int32 - tr = classType(int.class); - break; - case 'J': // __int64 - case 'K': // unsigned __int64 - tr = classType(long.class); - break; - case 'L': // __int128 - tr = classType(BigInteger.class); - break; - case 'N': // bool - tr = classType(boolean.class); - break; - case '0': // array ?? - parseCVClassModifier(); - parseType(false); - tr = classType(Object[].class); - break; - case 'W': - tr = classType(char.class);//, Wide.class); - break; - default: - throw error(-1); - } - addBackRef(tr); - return tr; - case 'Z': - return classType(Object[].class); - case 'O': - throw error("'long double' type cannot be mapped !", -1); - case 'C': // signed char - case 'D': // char - case 'E': // unsigned char - return classType(byte.class); - case 'F': // short - case 'G': // unsigned short - return classType(short.class); - case 'H': // int - case 'I': // unsigned int - return classType(int.class); - case 'J': // long - case 'K': // unsigned long - return classType(CLong.class); - case 'M': // float - return classType(float.class); - case 'N': // double - return classType(double.class); - case 'Y': - throw error("TODO handle cointerfaces", -1); - case 'X': - // TODO handle coclass case - if (!allowVoid) - return null; - return classType(void.class); - case '?': - parseCVClassModifier(); // TODO do something with this ! - return parseType(allowVoid); - case 'A': // reference - case 'B': // volatile reference - case 'P': // pointer - case 'Q': // const pointer - case 'R': // volatile pointer - case 'S': // const volatile pointer - if (!consumeCharsIf('$', 'A')) // __gc - consumeCharsIf('$', 'B'); // __pin - - CVClassModifier cvMods = parseCVClassModifier(); - if (cvMods.isVariable) { - if (consumeCharIf('Y')) { - int dimensions = parseNumber(false); - int[] indices = new int[dimensions]; - for (int i = 0; i < dimensions; i++) - indices[i] = parseNumber(false); - } - tr = pointerType(parseType(true)); - } else { - MemberRef mr = new MemberRef(); - parseFunctionProperty(mr); - tr = pointerType(new FunctionTypeRef(mr)); - } - addBackRef(tr); - return tr; - case 'V': // class - case 'U': // struct - case 'T': // union - //System.out.println("Found struct, class or union"); - return parseQualifiedTypeName(); - case 'W': // enum - Class cl; - switch (consumeChar()) { - case '0': - case '1': - cl = byte.class; - break; - case '2': - case '3': - cl = short.class; - break; - case '4': - case '5': - cl = int.class; - break; - case '6': - case '7': // CLong : int on win32 and win64 ! - cl = int.class; - break; - default: - throw error("Unfinished enum", -1); - } - TypeRef qn = parseQualifiedTypeName(); - addBackRef(qn); - return classType(cl); - default: - throw error(-1); - } - } - static NamespaceRef reverseNamespace(List names) { - if (names == null || names.isEmpty()) - return null; - Collections.reverse(names); - return new NamespaceRef(names.toArray(new Object[names.size()])); - } - List allQualifiedNames = new ArrayList(); - interface DemanglingOp { - T run() throws DemanglingException; - } - T withEmptyQualifiedNames(DemanglingOp action) throws DemanglingException { - List list = allQualifiedNames; - try { - allQualifiedNames = new ArrayList(); - return action.run(); - } finally { - allQualifiedNames = list; - } - } - - IdentLike parseFirstQualifiedTypeNameComponent() throws DemanglingException { - if (consumeCharIf('?')) { - if (consumeCharIf('$')) - return parseTemplateType().getIdent(); - else - return parseSpecialName(); - } - else - return new Ident(parseNameFragment()); - } - TypeRef parseQualifiedTypeName() throws DemanglingException { - TypeRef backRef = consumeIfBackRef(); - if (backRef != null) - return backRef; - - char c = peekChar(); - List names = parseNameQualifications(); - - // TODO fix this : - //names.add(0, parseFirstQualifiedTypeNameComponent()); - Object first = names.get(0); - names.set(0, first instanceof String ? new Ident((String)first) : ((ClassRef)first).getIdent()); - - if (names.size() == 1 && (names.get(0) instanceof TypeRef)) { - return (TypeRef)names.get(0); - } - - /* - if (Character.isDigit(c)) { - consumeChar(); - int i = (int)(c - '0'); - if (i < 0 || i >= allQualifiedNames.size()) - throw error("Invalid back reference " + i + " (knows only " + allQualifiedNames + ")", -1); - names = new ArrayList(allQualifiedNames.get(i)); - } else { - names = parseNames(); - }*/ - - ClassRef tr = new ClassRef((Ident)names.get(0)); - names.remove(0); - tr.setEnclosingType(reverseNamespace(names)); - return tr; - } - - public IdentLike parseSpecialName() throws DemanglingException { - switch (consumeChar()) { - case '0': - return SpecialName.Constructor; - case '1': - return SpecialName.Destructor; - case '2': - return SpecialName.New; - case '3': - return SpecialName.Delete; - case '4': - return SpecialName.OperatorAssign; - case '5': - return SpecialName.OperatorRShift; - case '6': - return SpecialName.OperatorLShift; - case '7': - return SpecialName.OperatorLogicNot; - case '8': - return SpecialName.OperatorEquals; - case '9': - return SpecialName.OperatorDifferent; - case 'A': - return SpecialName.OperatorSquareBrackets; - case 'B': - return SpecialName.OperatorCast; - case 'C': - return SpecialName.OperatorArrow; - case 'D': - return SpecialName.OperatorMultiply; - case 'E': - return SpecialName.OperatorIncrement; - case 'F': - return SpecialName.OperatorDecrement; - case 'G': - return SpecialName.OperatorSubstract; - case 'H': - return SpecialName.OperatorAdd; - case 'I': - return SpecialName.OperatorBitAnd; - case 'J': - return SpecialName.OperatorArrowStar; - case 'K': - return SpecialName.OperatorDivide; - case 'L': - return SpecialName.OperatorModulo; - case 'M': - return SpecialName.OperatorLower; - case 'N': - return SpecialName.OperatorLowerEquals; - case 'O': - return SpecialName.OperatorGreater; - case 'P': - return SpecialName.OperatorGreaterEquals; - case 'Q': - return SpecialName.OperatorComma; - case 'R': - return SpecialName.OperatorParenthesis; - case 'S': - return SpecialName.OperatorBitNot; - case 'T': - return SpecialName.OperatorXOR; - case 'U': - return SpecialName.OperatorBitOr; - case 'V': - return SpecialName.OperatorLogicAnd; - case 'W': - return SpecialName.OperatorLogicOr; - case 'X': - return SpecialName.OperatorMultiplyAssign; - case 'Y': - return SpecialName.OperatorAddAssign; - case 'Z': - return SpecialName.OperatorSubstractAssign; - case '_': - switch (consumeChar()) { - case '0': - return SpecialName.OperatorDivideAssign; - case '1': - return SpecialName.OperatorModuloAssign; - case '2': - return SpecialName.OperatorLShiftAssign; - case '3': - return SpecialName.OperatorRShiftAssign; - case '4': - return SpecialName.OperatorBitAndAssign; - case '5': - return SpecialName.OperatorBitOrAssign; - case '6': - return SpecialName.OperatorXORAssign; - case '7': - return SpecialName.VFTable; - case '8': - return SpecialName.VBTable; - case '9': - return SpecialName.VCall; - case 'E': - return SpecialName.VectorDeletingDestructor; - case 'G': - return SpecialName.ScalarDeletingDestructor; - default: - throw error("unhandled extended special name"); - } - - default: - throw error("Invalid special name"); - } - } - - private List parseParams() throws DemanglingException { - List paramTypes = new ArrayList(); - if (!consumeCharIf('X')) { - char c; - while ((c = peekChar()) != '@' && c != 0 && (c != 'Z' || peekChar(2) == 'Z')) { - TypeRef tr = parseType(false); - if (tr == null) - continue; - paramTypes.add(tr); - } - if (c == 'Z') - consumeChar(); - //break; - if (c == '@') - consumeChar(); - } - return paramTypes; - } - private List parseTemplateParams() throws DemanglingException { - return withEmptyQualifiedNames(new DemanglingOp>() { public List run() throws DemanglingException { - List paramTypes = new ArrayList(); - if (!consumeCharIf('X')) { - char c; - while ((c = peekChar()) != '@' && c != 0) { - TemplateArg tr = parseTemplateParameter(); - if (tr == null) - continue; - paramTypes.add(tr); - } - } - return paramTypes; - }}); - } - - String parseNameFragment() throws DemanglingException { - StringBuilder b = new StringBuilder(); - char c; - - while ((c = consumeChar()) != '@') - b.append(c); - - if (b.length() == 0) - throw new DemanglingException("Unexpected empty name fragment"); - - String name = b.toString(); -// allQualifiedNames.add(Collections.singletonList(name)); - return name; - } - - void addBackRef(TypeRef tr) { - if (tr == null || allQualifiedNames.contains(tr)) - return; - - allQualifiedNames.add(tr); - } - - - TypeRef getBackRef(int i) throws DemanglingException { - if (i == allQualifiedNames.size()) - i--; // TODO fix this !!! - - if (i < 0 || i >= allQualifiedNames.size()) - throw error("Invalid back references in name qualifications", -1); - return allQualifiedNames.get(i); - } - private List parseNameQualifications() throws DemanglingException { - List names = new ArrayList(); - - if (Character.isDigit(peekChar())) { - try { - int i = consumeChar() - '0'; - names.add(getBackRef(i)); - expectChars('@'); - return names; - } catch (Exception ex) { - throw error("Invalid back references in name qualifications", -1); - } - } - - while (peekChar() != '@') { - names.add(parseNameQualification()); - } - - expectChars('@'); - return names; - } - Object parseNameQualification() throws DemanglingException { - if (consumeCharIf('?')) { - if (consumeCharIf('$')) - return parseTemplateType(); - else { - if (peekChar() == 'A') - throw error("Anonymous numbered namespaces not handled yet"); - int namespaceNumber = parseNumber(false); - return String.valueOf(namespaceNumber); - } - } else - return parseNameFragment(); - } - - Style parseCallingConvention() throws DemanglingException { - Convention.Style cc; - boolean exported = true; - switch (consumeChar()) { - case 'A': - exported = false; - case 'B': - cc = Convention.Style.CDecl; - break; - case 'C': - exported = false; - case 'D': - cc = Convention.Style.Pascal; - break; - case 'E': - exported = false; - case 'F': - cc = Convention.Style.ThisCall; - break; - case 'G': - exported = false; - case 'H': - cc = Convention.Style.StdCall; - break; - case 'I': - exported = false; - case 'J': - cc = Convention.Style.FastCall; - break; - case 'K': - exported = false; - case 'L': - cc = null; - break; - case 'N': - cc = Convention.Style.CLRCall; - break; - default: - throw error("Unknown calling convention"); - } - return cc; - } - static class CVClassModifier { - boolean isVariable; - boolean isMember; - boolean isBased; - } - CVClassModifier parseCVClassModifier() throws DemanglingException { - CVClassModifier mod = new CVClassModifier(); - switch (peekChar()) { - case 'E': // __ptr64 - case 'F': // __unaligned - case 'I': // __restrict - consumeChar(); - break; - } - boolean based = false; - switch (consumeChar()) { - case 'M': // __based - case 'N': // __based - case 'O': // __based - case 'P': // __based - mod.isBased = true; - case 'A': - case 'B': - case 'J': - case 'C': - case 'G': - case 'K': - case 'D': - case 'H': - case 'L': - mod.isVariable = true; - mod.isMember = false; - break; - case '2': // __based - case '3': // __based - case '4': // __based - case '5': // __based - mod.isBased = true; - case 'Q': - case 'U': - case 'Y': - case 'R': - case 'V': - case 'Z': - case 'S': - case 'W': - case '0': - case 'T': - case 'X': - case '1': - mod.isVariable = true; - mod.isMember = true; - break; - case '_': // __based - mod.isBased = true; - switch (consumeChar()) { - case 'A': - case 'B': - mod.isVariable = false; - break; - case 'C': - case 'D': - mod.isVariable = false; - mod.isMember = true; - break; - default: - throw error("Unknown extended __based class modifier", -1); - } - break; - case '6': - case '7': - mod.isVariable = false; - mod.isMember = false; - break; - case '8': - case '9': - mod.isVariable = false; - mod.isMember = true; - break; - default: - throw error("Unknown CV class modifier", -1); - } - if (mod.isBased) { - switch (consumeChar()) { - case '0': // __based(void) - break; - case '2': - parseNameQualifications(); - break; - case '5': // no __based() ?? - break; - } - } - return mod; - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/demangling/package-info.java b/libraries/BridJ/src/main/java/org/bridj/demangling/package-info.java deleted file mode 100644 index a0d54674c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/demangling/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/** -BridJ symbols demanglers. -

-BridJ adheres to a "reverse burder of proof" philosophy : rather than asking binding makers (including JNAerator) to write/generate the exact expected symbols in {@link org.bridj.ann.Symbol} annotations, it parses the mangled symbols and sees how / if they match binding signatures. Manual specification of exact symbols is still possible in case of ambiguity or when demangling fails. -

-As a consequence, BridJ needs symbols demanglers, which have to parse symbols and spit out (partial) methods and types signatures.
-It currently has demanglers for : -

    -
  • Microsoft Visual C++ (2008, 2010) -
  • GCC 4.x (which mangling scheme is fortunately shared by Intel's C++ compiler) : its mangling scheme does not include the return type of functions / methods, which is infortunate (would have allowed dynamic languages to call C++ without explicit bindings, otherwise :-( ) -
  • -
-*/ -package org.bridj.demangling; diff --git a/libraries/BridJ/src/main/java/org/bridj/dyncall/DyncallLibrary.java b/libraries/BridJ/src/main/java/org/bridj/dyncall/DyncallLibrary.java deleted file mode 100644 index 9c2d0375f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/dyncall/DyncallLibrary.java +++ /dev/null @@ -1,190 +0,0 @@ -package org.bridj.dyncall; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.ann.CLong; -import org.bridj.ann.Library; -import org.bridj.ann.Optional; -import org.bridj.ann.Ptr; -import org.bridj.ann.Runtime; -/** - * Wrapper for library dyncall
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("bridj") -@Runtime(CRuntime.class) -public class DyncallLibrary { - static { - BridJ.register(); - } - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_FLOAT = (char)'f'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_DEFAULT = (int)0; - /// native declaration : dyncall.h - public static final int DC_CALL_C_PPC32_OSX = (int)9; - /// native declaration : dyncall.h - public static final int DC_CALL_C_PPC32_SYSV = (int)13; - /// native declaration : dyncall.h - public static final int DC_CALL_C_PPC32_DARWIN = (int)9; - /// native declaration : dyncall.h - public static final int DC_ERROR_UNSUPPORTED_MODE = (int)-1; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ELLIPSIS_VARARGS = (int)101; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_WIN32_THIS_MS = (int)5; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ARM_ARM_EABI = (int)10; - /// native declaration : dyncall.h - public static final int DC_CALL_SYS_X86_INT80H_BSD = (int)202; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_ELLIPSIS = (char)'e'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X64_SYSV = (int)8; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_POINTER = (char)'p'; - /// native declaration : dyncall.h - public static final int DEFAULT_ALIGNMENT = (int)0; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_FASTCALL_GNU = (char)'f'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_UINT = (char)'I'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_ENDARG = (char)')'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_VOID = (char)'v'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_UCHAR = (char)'C'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_MIPS32_O32 = (int)16; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_INT = (char)'i'; - /// native declaration : dyncall.h - public static final int DC_CALL_SYS_X86_INT80H_LINUX = (int)201; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_DOUBLE = (char)'d'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X64_WIN64 = (int)7; - /// native declaration : dyncall.h - public static final int DC_CALL_C_SPARC32 = (int)20; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ARM_THUMB_EABI = (int)11; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_STRUCT = (char)'T'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_WIN32_THIS_GNU = (int)6; - /// native declaration : dyncall.h - public static final int DC_CALL_SYS_DEFAULT = (int)200; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_STDCALL = (char)'s'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ELLIPSIS = (int)100; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_PLAN9 = (int)19; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ARM_THUMB = (int)15; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_FASTCALL_MS = (char)'F'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_STRING = (char)'Z'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_MIPS32_EABI = (int)12; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_WIN32_FAST_GNU = (int)4; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_LONGLONG = (char)'l'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_SHORT = (char)'s'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_ULONGLONG = (char)'L'; - /// native declaration : dyncall.h - public static final int DC_ERROR_NONE = (int)0; - /// native declaration : dyncall.h - public static final int DC_CALL_C_SPARC64 = (int)21; - /// native declaration : dyncall.h - public static final int DC_CALL_C_PPC32_LINUX = (int)13; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_ULONG = (char)'J'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CHAR = (char)'c'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_PREFIX = (char)'_'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_LONG = (char)'j'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_MIPS64_N32 = (int)17; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_WIN32_STD = (int)2; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_CC_THISCALL_MS = (char)'+'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_CDECL = (int)1; - /// native declaration : dyncall.h - public static final int DC_CALL_C_X86_WIN32_FAST_MS = (int)3; - /// native declaration : dyncall.h - public static final int DC_CALL_C_ARM_ARM = (int)14; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_USHORT = (char)'S'; - /// native declaration : dyncall_signature.h - public static final char DC_SIGCHAR_BOOL = (char)'B'; - /// native declaration : dyncall.h - public static final int DC_CALL_C_MIPS64_N64 = (int)18; - public static native Pointer dcNewCallVM(@Ptr long size); - public static native void dcFree(Pointer vm); - public static native void dcReset(Pointer vm); - public static native void dcMode(Pointer vm, int mode); - public static native void dcArgBool(Pointer vm, int value); - public static native void dcArgChar(Pointer vm, byte value); - public static native void dcArgShort(Pointer vm, short value); - public static native void dcArgInt(Pointer vm, int value); - public static native void dcArgLong(Pointer vm, @CLong long value); - public static native void dcArgLongLong(Pointer vm, long value); - public static native void dcArgFloat(Pointer vm, float value); - public static native void dcArgDouble(Pointer vm, double value); - public static native void dcArgPointer(Pointer vm, Pointer value); - @Optional - public static native void dcArgStruct(Pointer vm, Pointer s, Pointer value); - public static native void dcCallVoid(Pointer vm, Pointer funcptr); - public static native int dcCallBool(Pointer vm, Pointer funcptr); - public static native byte dcCallChar(Pointer vm, Pointer funcptr); - public static native short dcCallShort(Pointer vm, Pointer funcptr); - public static native int dcCallInt(Pointer vm, Pointer funcptr); - @CLong - public static native long dcCallLong(Pointer vm, Pointer funcptr); - public static native long dcCallLongLong(Pointer vm, Pointer funcptr); - public static native float dcCallFloat(Pointer vm, Pointer funcptr); - public static native double dcCallDouble(Pointer vm, Pointer funcptr); - public static native Pointer dcCallPointer(Pointer vm, Pointer funcptr); - @Optional - public static native void dcCallStruct(Pointer vm, Pointer funcptr, Pointer s, Pointer returnValue); - public static native int dcGetError(Pointer vm); - @Optional - public static native Pointer dcNewStruct(@Ptr long fieldCount, int alignment); - @Optional - public static native void dcStructField(Pointer s, int type, int alignment, @Ptr long arrayLength); - @Optional - public static native void dcSubStruct(Pointer s, @Ptr long fieldCount, int alignment, @Ptr long arrayLength); - @Optional - public static native void dcCloseStruct(Pointer s); - @Optional - @Ptr - public static native long dcStructSize(Pointer s); - @Optional - @Ptr - public static native long dcStructAlignment(Pointer s); - @Optional - public static native void dcFreeStruct(Pointer s); - @Optional - public static native Pointer dcDefineStruct(Pointer signature); - - /// Undefined type - public static interface DCstruct { - - }; - /// Undefined type - public static interface DCCallVM { - - }; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/func/Fun0.java b/libraries/BridJ/src/main/java/org/bridj/func/Fun0.java deleted file mode 100644 index 4a6299778..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/func/Fun0.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bridj.func; - -public interface Fun0 { - T apply(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/func/Fun1.java b/libraries/BridJ/src/main/java/org/bridj/func/Fun1.java deleted file mode 100644 index c09e61c21..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/func/Fun1.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bridj.func; - -public interface Fun1 { - T apply(A1 a1); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/func/Fun2.java b/libraries/BridJ/src/main/java/org/bridj/func/Fun2.java deleted file mode 100644 index 1b16ef38c..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/func/Fun2.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bridj.func; - -public interface Fun2 { - T apply(A1 a1, A2 a2); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/func/package-info.java b/libraries/BridJ/src/main/java/org/bridj/func/package-info.java deleted file mode 100644 index f6846d04a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/func/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -Dummy typed functions interfaces. -*/ -package org.bridj.func; diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT.java deleted file mode 100644 index 7a58269a0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bridj.jawt; -import org.bridj.Callback; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.jawt.JawtLibrary.JNIEnv; -import org.bridj.ann.Convention; -/** - * native declaration : jawt.h
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("jawt") -@Convention(Convention.Style.StdCall) -public class JAWT extends StructObject { - /** - * Version of this structure. This must always be set before
- * calling JAWT_GetAWT() - */ - @Field(0) - public int version() { - return this.io.getIntField(this, 0); - } - /** - * Version of this structure. This must always be set before
- * calling JAWT_GetAWT() - */ - @Field(0) - public JAWT version(int version) { - this.io.setIntField(this, 0, version); - return this; - } - - @Field(1) - public Pointer GetDrawingSurface() { - return this.io.getPointerField(this, 1); - } - @Field(2) - public Pointer FreeDrawingSurface() { - return this.io.getPointerField(this, 2); - } - @Field(3) - public Pointer Lock() { - return this.io.getPointerField(this, 3); - } - @Field(4) - public Pointer Unlock() { - return this.io.getPointerField(this, 4); - } - @Field(5) - public Pointer GetComponent() { - return this.io.getPointerField(this, 5); - } - - public static abstract class GetDrawingSurface_callback extends Callback { - public abstract Pointer invoke(Pointer env, Pointer target); - }; - /// native declaration : jawt.h:236 - public static abstract class FreeDrawingSurface_callback extends Callback { - public abstract void invoke(Pointer ds); - }; - /// native declaration : jawt.h:242 - public static abstract class Lock_callback extends Callback { - public abstract void invoke(Pointer env); - }; - /// native declaration : jawt.h:247 - public static abstract class Unlock_callback extends Callback { - public abstract void invoke(Pointer env); - }; - /// native declaration : jawt.h:259 - public static abstract class GetComponent_callback extends Callback { - public abstract Pointer invoke(Pointer env, Pointer platformInfo); - }; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWTUtils.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JAWTUtils.java deleted file mode 100644 index ed284cb04..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWTUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.bridj.jawt; -import static org.bridj.jawt.JawtLibrary.*; -import org.bridj.BridJ; -import org.bridj.JNI; -import org.bridj.NativeLibrary; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import java.awt.*; -import java.io.File; -import org.bridj.Platform; - -import org.bridj.ann.Convention; -/** - * Contains a method that returns the native peer handle of an AWT component : BridJ JAWT utilities {@link org.bridj.jawt.JAWTUtils#getNativePeerHandle(java.awt.Component)} - */ -public class JAWTUtils { - - public static JNIEnv getJNIEnv() { - return new JNIEnv(JNI.getEnv()); - } - - public static JAWT getJAWT(JNIEnv env) { - if (GraphicsEnvironment.isHeadless()) - throw new HeadlessException("No native peers in headless mode."); - - JAWT awt = new JAWT().version(JAWT_VERSION_1_4); - Pointer pAwt = pointerTo(awt); - if (!JAWT_GetAWT(env, pAwt)) - throw new RuntimeException("Failed to get JAWT pointer !"); - - return pAwt.get(); - } - - public interface LockedComponentRunnable { - void run(Component component, long peer); - } - - public static void withLockedSurface(JNIEnv env, JAWT awt, Component component, LockedComponentRunnable runnable) { - if (component.isLightweight()) - throw new IllegalArgumentException("Lightweight components do not have native peers."); - - if (!component.isDisplayable()) - throw new IllegalArgumentException("Component that are not displayable do not have native peers."); - - Pointer componentPointer = JNI.getGlobalPointer(component); - - Pointer pSurface = awt.GetDrawingSurface().get().invoke(env, componentPointer).as(JAWT_DrawingSurface.class); - if (pSurface == null) - throw new RuntimeException("Cannot get drawing surface from " + component); - - JAWT_DrawingSurface surface = pSurface.get(); - - try { - int lock = surface.Lock().get().invoke(pSurface); - if ((lock & JAWT_LOCK_ERROR) != 0) - throw new RuntimeException("Cannot lock drawing surface of " + component); - try { - Pointer cb = surface.GetDrawingSurfaceInfo().as(JAWT_DrawingSurface.GetDrawingSurfaceInfo_callback.class); - Pointer pInfo = cb.get().invoke(pSurface); - if (pInfo != null) - pInfo = pInfo.as(JAWT_DrawingSurfaceInfo.class); - Pointer platformInfo = pInfo.get().platformInfo(); - long peer = platformInfo.getSizeT(); // on win, mac, x11 platforms, the relevant field is the first in the struct ! - runnable.run(component, peer); - } finally { - surface.Unlock().get().invoke(pSurface); - } - } finally { - awt.FreeDrawingSurface().get().invoke(pSurface); - } - } - /** - * - */ - public static long getNativePeerHandle(Component component) { - try { - JNIEnv env = getJNIEnv(); - JAWT awt = getJAWT(env); - final long ret[] = new long[1]; - withLockedSurface(env, awt, component, new LockedComponentRunnable() { - public void run(Component component, long peer) { - ret[0] = peer; - } - }); - return ret[0]; - } catch (Throwable ex) { - ex.printStackTrace(); - return 0; - } - } - -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurface.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurface.java deleted file mode 100644 index d1804a44b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurface.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bridj.jawt; -import org.bridj.Callback; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Convention; -/** - * native declaration : jawt.h
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("jawt") -@Convention(Convention.Style.StdCall) -public class JAWT_DrawingSurface extends StructObject { - /** - * Cached reference to the Java environment of the calling thread.
- * If Lock(), Unlock(), GetDrawingSurfaceInfo() or
- * FreeDrawingSurfaceInfo() are called from a different thread,
- * this data member should be set before calling those functions.
- * C type : JNIEnv* - */ - @Field(0) - public Pointer env() { - return this.io.getPointerField(this, 0); - } - /** - * Cached reference to the target object
- * C type : void* - */ - @Field(1) - public Pointer target() { - return this.io.getPointerField(this, 1); - } - @Field(2) - public Pointer Lock() { - return this.io.getPointerField(this, 2); - } - @Field(3) - public Pointer GetDrawingSurfaceInfo() { - return this.io.getPointerField(this, 3); - } - @Field(4) - public Pointer FreeDrawingSurfaceInfo() { - return this.io.getPointerField(this, 4); - } - @Field(5) - public Pointer Unlock() { - return this.io.getPointerField(this, 5); - } - - /// Conversion Error : Lock_callback (Unsupported type) - /// Conversion Error : GetDrawingSurfaceInfo_callback (Unsupported type) - /// Conversion Error : FreeDrawingSurfaceInfo_callback (Unsupported type) - /// Conversion Error : Unlock_callback (Unsupported type) - /// native declaration : jawt.h:187 - public static abstract class Lock_callback extends Callback { - public abstract int invoke(Pointer ds); - }; - /// native declaration : jawt.h:198 - public static abstract class GetDrawingSurfaceInfo_callback extends Callback { - public abstract Pointer invoke(Pointer ds); - }; - /// native declaration : jawt.h:203 - public static abstract class FreeDrawingSurfaceInfo_callback extends Callback { - public abstract void invoke(Pointer dsi); - }; - /// native declaration : jawt.h:208 - public static abstract class Unlock_callback extends Callback { - public abstract void invoke(Pointer ds); - }; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurfaceInfo.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurfaceInfo.java deleted file mode 100644 index 785e24916..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_DrawingSurfaceInfo.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bridj.jawt; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -/** - * native declaration : jawt.h
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("jawt") -public class JAWT_DrawingSurfaceInfo extends StructObject { - /** - * Pointer to the platform-specific information. This can be safely
- * cast to a JAWT_Win32DrawingSurfaceInfo on Windows or a
- * JAWT_X11DrawingSurfaceInfo on Solaris. See jawt_md.h for details.
- * C type : void* - */ - @Field(0) - public Pointer platformInfo() { - return this.io.getPointerField(this, 0); - } - /** - * Cached pointer to the underlying drawing surface
- * C type : jawt_DrawingSurface* - */ - @Field(1) - public Pointer ds() { - return this.io.getPointerField(this, 1); - } - /** - * Bounding rectangle of the drawing surface
- * C type : JAWT_Rectangle - */ - @Field(2) - public org.bridj.jawt.JAWT_Rectangle bounds() { - return this.io.getNativeObjectField(this, 2); - } - /// Number of rectangles in the clip - @Field(3) - public int clipSize() { - return this.io.getIntField(this, 3); - } - /** - * Clip rectangle array
- * C type : JAWT_Rectangle* - */ - @Field(4) - public org.bridj.jawt.JAWT_Rectangle clip() { - return this.io.getNativeObjectField(this, 4); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_Rectangle.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_Rectangle.java deleted file mode 100644 index bb5071b01..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JAWT_Rectangle.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bridj.jawt; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -/** - * native declaration : jawt.h
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("jawt") -public class JAWT_Rectangle extends StructObject { - @Field(0) - public int x() { - return this.io.getIntField(this, 0); - } - @Field(1) - public int y() { - return this.io.getIntField(this, 1); - } - @Field(2) - public int width() { - return this.io.getIntField(this, 2); - } - @Field(3) - public int height() { - return this.io.getIntField(this, 3); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/JawtLibrary.java b/libraries/BridJ/src/main/java/org/bridj/jawt/JawtLibrary.java deleted file mode 100644 index fc37b892a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/JawtLibrary.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bridj.jawt; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import org.bridj.TypedPointer; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.Platform; -import java.io.File; -/** - * Wrapper for library jawt
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("jawt") -@Runtime(CRuntime.class) -public class JawtLibrary { - static { - try { - //if (Platform.isLinux()) - // SystemBridJ.getNativeLibrary("headless/libmawt"); - } catch (Throwable th) {} - BridJ.register(); - } - /// native declaration : jawt.h - public static final int JAWT_LOCK_CLIP_CHANGED = 2; - /// native declaration : jawt.h - public static final int JAWT_VERSION_1_4 = 65540; - /// native declaration : jawt.h - public static final int JAWT_VERSION_1_3 = 65539; - /// native declaration : jawt.h - public static final int JAWT_LOCK_SURFACE_CHANGED = 8; - /// native declaration : jawt.h - public static final int JAWT_LOCK_ERROR = 1; - /// native declaration : jawt.h - public static final int JAWT_LOCK_BOUNDS_CHANGED = 4; - public native static boolean JAWT_GetAWT(Pointer env, Pointer awt); - /// Pointer to unknown (opaque) type - public static class JNIEnv extends TypedPointer { - public JNIEnv(long address) { - super(address); - } - public JNIEnv(Pointer address) { - super(address); - } - }; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/jawt/package-info.java b/libraries/BridJ/src/main/java/org/bridj/jawt/package-info.java deleted file mode 100644 index b162a634f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/jawt/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ JAWT utilities (to get the native peer handle of an AWT {@link java.awt.Component}). -*/ -package org.bridj.jawt; diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/FoundationLibrary.java b/libraries/BridJ/src/main/java/org/bridj/objc/FoundationLibrary.java deleted file mode 100644 index 77815bde7..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/FoundationLibrary.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.objc; - -import java.nio.charset.Charset; -import java.util.Map; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import org.bridj.Pointer.StringType; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; - -@Library("Foundation") -@org.bridj.ann.Runtime(CRuntime.class) -public class FoundationLibrary { - static { - BridJ.register(); - } - - public static final int - kCFStringEncodingASCII = 0x0600, - kCFStringEncodingUnicode = 0x0100, - kCFStringEncodingUTF8 = 0x08000100; - - public static native Pointer CFStringCreateWithBytes(Pointer alloc, Pointer bytes, @Ptr long numBytes, int encoding, boolean isExternalRepresentation); - - - public static Pointer pointerToNSString(String s) { - Pointer p = Pointer.pointerToString(s, StringType.C, Charset.forName("utf-8")); - assert p != null; - Pointer ps = CFStringCreateWithBytes(null, p, p.getValidBytes() - 1 /* remove the trailing NULL */, kCFStringEncodingUTF8, false); - assert ps != null; - return ps; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/IMP.java b/libraries/BridJ/src/main/java/org/bridj/objc/IMP.java deleted file mode 100644 index 0fce33c6f..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/IMP.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bridj.objc; -import org.bridj.*; -import static org.bridj.Pointer.*; -import static org.bridj.objc.ObjectiveCRuntime.*; - -public class IMP extends TypedPointer { - public IMP(long peer) { super(peer); } - public IMP(Pointer ptr) { super(ptr); } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSAutoreleasePool.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSAutoreleasePool.java deleted file mode 100644 index 2c1dcd4f2..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSAutoreleasePool.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bridj.objc; - -import org.bridj.BridJ; -import org.bridj.Pointer; -import org.bridj.ann.Library; - -@Library("Foundation") -public class NSAutoreleasePool extends NSObject { - static { - BridJ.register(); - } - public static native Pointer new_(); - public native void drain(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSCalendar.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSCalendar.java deleted file mode 100644 index 7e3ab9574..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSCalendar.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bridj.objc; - -import org.bridj.BridJ; -import org.bridj.NativeObject; -import org.bridj.Pointer; -import org.bridj.ann.Library; - -@Library("Foundation") -public class NSCalendar extends ObjCObject { - static { - BridJ.register(); - } - -// public NSCalendar(Pointer peer) { -// super(peer); -// } - - public NSCalendar() { - super(); - } - - public static native Pointer currentCalendar(); - public native Pointer calendarIdentifier(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSDictionary.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSDictionary.java deleted file mode 100644 index f47ff9469..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSDictionary.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.objc; - -import java.util.HashMap; -import org.bridj.Pointer; -import java.util.Map; -import org.bridj.BridJ; -import static org.bridj.objc.FoundationLibrary.*; -import static org.bridj.Pointer.*; - -/** - * - * @author ochafik - */ -public class NSDictionary extends NSObject { - static { - BridJ.register(); - } - public NSDictionary() { - super(); - } -// public NSDictionary(Map map) { -// super(pointerToNSDictionary(map)); -// } - - public native Pointer valueForKey(Pointer key); - public native Pointer objectForKey(Pointer key); - public native int count(); - - public native void getObjects_andKeys(Pointer> objects, Pointer> keys); - public static native Pointer dictionaryWithContentsOfFile(Pointer path); - - public static native Pointer dictionaryWithObjects_forKeys_count(Pointer> objects, Pointer> keys, int count); - - public static Pointer pointerToNSDictionary(Map map) { - int n = map.size(); - Pointer> objects = allocatePointers(NSObject.class, n); - Pointer> keys = allocatePointers(NSObject.class, n); - - int i = 0; - for (Map.Entry e : map.entrySet()) { - keys.set(i, (Pointer)pointerToNSString(e.getKey())); - objects.set(i, pointerTo(e.getValue())); - i++; - } - - return dictionaryWithObjects_forKeys_count(objects, keys, n); - } - public static NSDictionary valueOf(Map map) { - return pointerToNSDictionary(map).get(); - } - public Map toMap() { - int n = count(); - Pointer> objects = allocatePointers(NSObject.class, n); - Pointer> keys = allocatePointers(NSString.class, n); - - getObjects_andKeys(objects, (Pointer)keys); - - Map ret = new HashMap(); - for (int i = 0; i < n; i++) { - Pointer key = keys.get(i); - Pointer value = objects.get(i); - - ret.put(key.get().toString(), value == null ? null : value.get()); - } - return ret; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSInvocation.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSInvocation.java deleted file mode 100644 index 32127a04a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSInvocation.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bridj.objc; -import org.bridj.ann.Ptr; -import org.bridj.*; -import org.bridj.Pointer.StringType; -import org.bridj.ann.Library; -import java.nio.charset.*; -import static org.bridj.objc.FoundationLibrary.*; - -@Library("Foundation") -public class NSInvocation extends NSObject { - static { BridJ.register(); } - - public native SEL selector(); - public native void setSelector(SEL selector); - - public native Pointer target(); - public native void setTarget(Pointer target); - - public native void setArgument_atIndex(Pointer buffer, @Ptr long index); - public native void getArgument_atIndex(Pointer buffer, @Ptr long index); - - public native void setReturnValue(Pointer buffer); - public native void getReturnValue(Pointer buffer); - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSMethodSignature.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSMethodSignature.java deleted file mode 100644 index 30b2244e2..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSMethodSignature.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bridj.objc; -import org.bridj.ann.Ptr; -import org.bridj.*; -import org.bridj.Pointer.StringType; -import org.bridj.ann.Library; -import java.nio.charset.*; -import static org.bridj.objc.FoundationLibrary.*; - -@Library("Foundation") -public class NSMethodSignature extends NSObject { - static { BridJ.register(); } - - public static native Pointer signatureWithObjCTypes(Pointer types); - - public native Pointer methodReturnType(); - public native @Ptr long numberOfArguments(); - public native boolean isOneway(); - public native Pointer getArgumentTypeAtIndex(@Ptr long index); - public native @Ptr long frameLength(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSNumber.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSNumber.java deleted file mode 100644 index ef3be02d8..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSNumber.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bridj.objc; -import org.bridj.*; -import org.bridj.objc.*; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.cpp.com.*; -import static org.bridj.Pointer.*; -import static org.bridj.BridJ.*; - -@Library("Foundation") -public class NSNumber extends NSObject { - static { - BridJ.register(); - } - - public static native Pointer numberWithBool(boolean value); - public static native Pointer numberWithInt(int value); - public static native Pointer numberWithDouble(double e); - public static native Pointer numberWithLong(long value); - public static native Pointer numberWithFloat(float value); - - public native short shortValue(); - public native int intValue(); - public native long longValue(); - public native float floatValue(); - public native double doubleValue(); - public native int compare(Pointer another); - - public native boolean isEqualToNumber(Pointer another); - - @Override - public boolean equals(Object o) { - if (!(o instanceof NSNumber)) - return false; - - NSNumber nn = (NSNumber)o; - return isEqualToNumber(pointerTo(nn)); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSObject.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSObject.java deleted file mode 100644 index 456827a50..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSObject.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bridj.objc; - -import org.bridj.Pointer; -import org.bridj.NativeObject; -import org.bridj.objc.*; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.cpp.com.*; -import static org.bridj.Pointer.*; -import static org.bridj.BridJ.*; - -@Library("Foundation") -public class NSObject extends ObjCObject { - public NSObject(Pointer peer) { - super(peer); - } - - public NSObject() { - super(); - } - - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/NSString.java b/libraries/BridJ/src/main/java/org/bridj/objc/NSString.java deleted file mode 100644 index 2d208b546..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/NSString.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bridj.objc; -import org.bridj.Pointer; -import org.bridj.Pointer.StringType; -import org.bridj.ann.Library; -import java.nio.charset.*; -import static org.bridj.objc.FoundationLibrary.*; - -@Library("Foundation") -public class NSString extends NSObject { - - public native int length(); - public native boolean isAbsolutePath(); - public native Pointer UTF8String(); - - public NSString() { - super(); - } - public NSString(String s) { - super(pointerToNSString(s)); - } - public String toString() { - return UTF8String().getString(StringType.C, Charset.forName("utf-8")); - } - public int hashCode() { - return toString().hashCode(); - } - - /* - public boolean equals(Object o) { - if (!(o instanceof NSString)) - return false; - return o.toString().equals(toString()); - } - */ - - public static NSString valueOf(String s) { - return pointerToNSString(s).get(); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCBlock.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCBlock.java deleted file mode 100644 index adfdd228a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCBlock.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bridj.objc; - -import org.bridj.*; - -public abstract class ObjCBlock/**/ extends ObjCObject implements CallbackInterface { - Pointer pCallback; - //static final int CALLBACK_CONSTRUCTOR_ID = -2; - /*protected C callback; - public ObjCBlock(C callback) { - super(CALLBACK_CONSTRUCTOR_ID, callback); - this.callback = callback; // retain a reference - } - public ObjCBlock() { - super(); - assert callback != null; // set by parent constructor - } - * - */ -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCClass.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCClass.java deleted file mode 100644 index f87bda1c3..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCClass.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bridj.objc; - -import org.bridj.*; - -public class ObjCClass extends ObjCObject { - static { - BridJ.register(); - } - public native Pointer alloc(); - @Selector("new") - public native Pointer new$(); - - public native boolean instancesRespondTo(SEL sel); - //public native boolean respondsTo(SEL sel); - public native IMP instanceMethodFor(SEL aSelector); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCDelegate.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCDelegate.java deleted file mode 100644 index 27c6a6d5a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCDelegate.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.objc; - -import org.bridj.NativeObjectInterface; - -/** - * Base interface for Objective-C delegates.
- * @author ochafik - */ -public interface ObjCDelegate extends NativeObjectInterface { - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCJNI.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCJNI.java deleted file mode 100644 index 4194d0ae1..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCJNI.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bridj.objc; -import org.bridj.*; - -public class ObjCJNI { - - @Deprecated - public static synchronized native Pointer createObjCProxyPeer(ObjCProxy javaInstance); - - static synchronized native long createObjCBlockWithFunctionPointer(long fptr); - static synchronized native long getObjCBlockFunctionPointer(long blockPtr); - static synchronized native void releaseObjCBlock(long blockPtr); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCObject.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCObject.java deleted file mode 100644 index a48980ef6..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCObject.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bridj.objc; - -import org.bridj.NativeObject; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import org.bridj.BridJ; - -@org.bridj.ann.Runtime(ObjectiveCRuntime.class) -public class ObjCObject extends NativeObject { - static { - BridJ.register(); - } - - ObjCObject type; - - //public native Pointer create(); - public native Pointer init(); - public native Pointer stringValue(); - public native Pointer description(); - - public native int hash(); - public native boolean isEqual(Pointer anObject); - - public native boolean isKindOf(Pointer aClassObject); - public native boolean isMemberOf(Pointer aClassObject); - public native boolean isKindOfClassNamed(Pointer aClassName); - public native boolean isMemberOfClassNamed(Pointer aClassName); - - public native boolean respondsTo(SEL aSelector); - public native IMP methodFor(SEL aSelector); - - public native Pointer perform(SEL aSelector); - public native Pointer perform$with(SEL aSelector, Pointer anObject); - public native Pointer perform$with$with(SEL aSelector, Pointer object1, Pointer object2); - - public ObjCObject(Pointer peer) { - super(peer); - } - - public ObjCObject() { - super(); - } - - public ObjCObject(int constructorId, Object... args) { - super(constructorId, args); - } - - @Override - public String toString() { - Pointer p = description(); - if (p == null) - p = stringValue(); - - return p.get().toString(); - } - @Override - public boolean equals(Object o) { - if (!(o instanceof ObjCObject)) - return false; - - Pointer p = pointerTo((ObjCObject)o); - return isEqual(p); - } - @Override - public int hashCode() { - return hash(); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCProxy.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjCProxy.java deleted file mode 100644 index 70a28a962..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjCProxy.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.bridj.objc; - -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import org.bridj.*; -import static org.bridj.Pointer.*; -import static org.bridj.objc.ObjCJNI.*; -import static org.bridj.Platform.*; -import static org.bridj.objc.ObjectiveCRuntime.*; -import java.util.*; -import org.bridj.util.Pair; -import org.bridj.util.Utils; - -public class ObjCProxy extends ObjCObject { - final Map> signatures = new HashMap>(); - final Object invocationTarget; - final static String PROXY_OBJC_CLASS_NAME = "ObjCProxy"; - - protected ObjCProxy() { - super(null); - peer = createObjCProxyPeer(this); - assert getClass() != ObjCProxy.class; - this.invocationTarget = this; - } - public ObjCProxy(Object invocationTarget) { - super(null); - peer = createObjCProxyPeer(this); - assert invocationTarget != null; - this.invocationTarget = invocationTarget; - } - - public void addProtocol(String name) throws ClassNotFoundException { - Pointer protocol = objc_getProtocol(pointerToCString(name)); - if (protocol == null) - throw new ClassNotFoundException("Protocol " + name + " not found !"); - Pointer cls = getObjCClass(PROXY_OBJC_CLASS_NAME); - if (!class_addProtocol(cls, protocol)) - throw new RuntimeException("Failed to add protocol " + name + " to class " + PROXY_OBJC_CLASS_NAME); - } - public Object getInvocationTarget() { - return invocationTarget; - } - public Pointer methodSignatureForSelector(SEL sel) { - Pair sig = getMethodAndSignature(sel); - return sig == null ? null : pointerTo(sig.getFirst()); - } - public synchronized Pair getMethodAndSignature(SEL sel) { - Pair sig = signatures.get(sel); - if (sig == null) { - try { - sig = computeMethodAndSignature(sel); - if (sig != null) - signatures.put(sel, sig); - } catch (Throwable th) { - BridJ.error("Failed to compute Objective-C signature for selector " + sel + ": " + th, th); - } - } - return sig; - } - Pair computeMethodAndSignature(SEL sel) { - String name = sel.getName(); - ObjectiveCRuntime rt = ObjectiveCRuntime.getInstance(); - for (Method method : invocationTarget.getClass().getMethods()) { - String msel = rt.getSelector(method); - //System.out.println("Selector for method " + method.getName() + " is '" + msel + "' (vs. sel = '" + sel + "')"); - if (msel.equals(name)) { - String sig = rt.getMethodSignature(method); - if (BridJ.debug) - BridJ.info("Objective-C signature for method " + method + " = '" + sig + "'"); - NSMethodSignature ms = NSMethodSignature.signatureWithObjCTypes(pointerToCString(sig)).get(); - long nArgs = ms.numberOfArguments() - 2; - if (nArgs != method.getParameterTypes().length) - throw new RuntimeException("Bad method signature (mismatching arg types) : '" + sig + "' for " + method); - return new Pair(ms, method); - } - } - //if (BridJ.debug) - BridJ.error("Missing method for " + sel + " in class " + classHierarchyToString(getInvocationTarget().getClass())); - - return null; - } - static String classHierarchyToString(Class c) { - String s = Utils.toString(c); - Type p = c.getGenericSuperclass(); - while (p != null && p != Object.class && p != ObjCProxy.class) { - s += " extends " + Utils.toString(p); - p = Utils.getClass(p).getGenericSuperclass(); - } - return s; - } - /* - static Type promote(Type type) { - if (type == byte.class || type == short.class || type == char.class || type == boolean.class) - return int.class; - if (type == float.class) - return double.class; - return type; - } - */ - /* - static final Map wrapperClasses = new HashMap(); - static { - wrapperClasses.put(int.class, Integer.class); - wrapperClasses.put(short.class, Short.class); - wrapperClasses.put(long.class, Long.class); - wrapperClasses.put(char.class, Character.class); - wrapperClasses.put(byte.class, Byte.class); - wrapperClasses.put(boolean.class, Boolean.class); - wrapperClasses.put(double.class, Double.class); - wrapperClasses.put(float.class, Float.class); - } - */ - /* - static Object constrain(Object value, Type type) { - Class c = Utils.getClass(type); - if (c.isPrimitive()) - c = wrapperClasses.get(c); - if (c.isInstance(value)) - return value; - - // Assume value is an Integer or a Double - if (type == byte.class) - return ((Integer)value).byteValue(); - if (type == short.class) - return ((Integer)value).shortValue(); - if (type == char.class) - return (char)((Integer)value).shortValue(); - if (type == boolean.class) - return ((Integer)value).byteValue() != 0; - if (type == float.class) - return ((Double)value).floatValue(); - - throw new UnsupportedOperationException("Don't know how to constrain value " + value + " to type " + Utils.toString(type)); - } - */ - public synchronized void forwardInvocation(Pointer pInvocation) { - NSInvocation invocation = pInvocation.get(); - SEL sel = invocation.selector(); - Pair sigMet = getMethodAndSignature(sel); - NSMethodSignature sig = sigMet.getFirst(); - Method method = sigMet.getSecond(); - - //System.out.println("forwardInvocation(" + invocation + ") : sel = " + sel); - Type[] paramTypes = method.getGenericParameterTypes(); - int nArgs = paramTypes.length;//(int)sig.numberOfArguments(); - Object[] args = new Object[nArgs]; - for (int i = 0; i < nArgs; i++) { - Type paramType = paramTypes[i]; - PointerIO paramIO = PointerIO.getInstance(paramType);//promote(paramType)); - Pointer pArg = allocate(paramIO); - invocation.getArgument_atIndex(pArg, i + 2); - Object arg = pArg.get(); - args[i] = arg;//constrain(arg, paramType); - } - try { - method.setAccessible(true); - Object ret = method.invoke(getInvocationTarget(), args); - //System.out.println("Invoked " + method + " : " + ret); - Type returnType = method.getGenericReturnType(); - if (returnType == void.class) { - assert ret == null; - } else { - PointerIO returnIO = PointerIO.getInstance(returnType); - Pointer pRet = (Pointer)allocate(returnIO); - pRet.set(ret); - invocation.setReturnValue(pRet); - } - } catch (Throwable ex) { - throw new RuntimeException("Failed to forward invocation from Objective-C to Java invocation target " + getInvocationTarget() + " for method " + method + " : " + ex, ex); - } - } - - -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/ObjectiveCRuntime.java b/libraries/BridJ/src/main/java/org/bridj/objc/ObjectiveCRuntime.java deleted file mode 100644 index e90544ecf..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/ObjectiveCRuntime.java +++ /dev/null @@ -1,361 +0,0 @@ -package org.bridj.objc; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.util.*; - -import org.bridj.*; -import static org.bridj.Pointer.*; -import org.bridj.NativeEntities.Builder; -import org.bridj.util.Utils; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import org.bridj.Platform; - -/// http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html -@Library("/usr/lib/libobjc.A.dylib") -public class ObjectiveCRuntime extends CRuntime { - - public boolean isAvailable() { - return Platform.isMacOSX(); - } - Map> - nativeClassesByObjCName = new HashMap>(), - nativeMetaClassesByObjCName = new HashMap>(); - - public ObjectiveCRuntime() { - BridJ.register(); - rootCallbackClasses.add(ObjCBlock.class); - } - - T realCast(Pointer id) { - if (id == null) - return null; - Pointer cn = object_getClassName(id); - if (cn == null) - throw new RuntimeException("Null class name for this ObjectiveC object pointer !"); - - String n = cn.getCString(); - - Class c = bridjClassesByObjCName.get(n); - if (c == null) - throw new RuntimeException("Class " + n + " was not registered yet in the BridJ runtime ! (TODO : auto create by scanning path, then reflection !)"); - return (T)id.getNativeObject(c); - } - /* - - public static class Class extends Pointer { - - public Class(long peer) { - super(peer); - } - - public Class(Pointer ptr) { - super(ptr); - } - }*/ - - protected static native Pointer object_getClass(Pointer obj); - - protected static native Pointer objc_getClass(Pointer name); - - protected static native Pointer objc_getMetaClass(Pointer name); - - protected static native Pointer object_getClassName(Pointer obj); - - protected static native Pointer class_createInstance(Pointer cls, @Ptr long extraBytes); - - public static native Pointer objc_getProtocol(Pointer name); - - public static native boolean class_addProtocol(Pointer cls, Pointer protocol); - - protected static native boolean class_respondsToSelector(Pointer cls, SEL sel); - - protected static native SEL sel_registerName(Pointer name); - protected static native Pointer sel_getName(SEL sel); - - public String getMethodSignature(Method method) { - return getMethodSignature(method.getGenericReturnType(), method.getGenericParameterTypes()); - } - public String getMethodSignature(Type returnType, Type... paramTypes) { - StringBuilder b = new StringBuilder(); - - b.append(getTypeSignature(returnType)); - b.append(getTypeSignature(Pointer.class)); // implicit self - b.append(getTypeSignature(SEL.class)); // implicit selector - for (Type paramType : paramTypes) - b.append(getTypeSignature(paramType)); - return b.toString(); - } - - char getTypeSignature(Type type) { - Character c = signatureByType.get(type); - if (c == null) - c = signatureByType.get(Utils.getClass(type)); - if (c == null) - throw new RuntimeException("Unknown type for Objective-C signatures : " + Utils.toString(type)); - return c; - } - - static final Map signatureByType = new HashMap(); - static final Map> typesBySignature = new HashMap>(); - static { - initSignatures(); - } - - static void addSignature(char sig, Type... types) { - List typesList = typesBySignature.get(sig); - if (typesList == null) - typesBySignature.put(sig, typesList = new ArrayList()); - - for (Type type : types) { - signatureByType.put(type, sig); - - if (type != null && !typesList.contains(type)) - typesList.add(type); - } - } - static void initSignatures() { - boolean is32 = CLong.SIZE == 4; - addSignature('q', long.class, !is32 ? CLong.class : null); - addSignature('i', int.class, is32 ? CLong.class : null); - addSignature('I', int.class, is32 ? CLong.class : null); - addSignature('s', short.class, char.class); - addSignature('c', byte.class, boolean.class); - addSignature('f', float.class); - addSignature('d', double.class); - addSignature('v', void.class); - addSignature('@', Pointer.class); - addSignature(':', SEL.class); - } - - synchronized Pointer getObjCClass(String name, boolean meta) throws ClassNotFoundException { - if (name.equals("")) - return null; - Map> map = meta ? nativeMetaClassesByObjCName : nativeClassesByObjCName; - Pointer c = map.get(name); - if (c == null) { - Pointer pName = pointerToCString(name); - c = meta ? objc_getMetaClass(pName) : objc_getClass(pName); - if (c != null) { - assert object_getClassName(c).getCString().equals(name); - map.put(name, c); - } - } - if (c == null) - throw new ClassNotFoundException("Objective C class not found : " + name); - - return c; - } - - @Override - protected NativeLibrary getNativeLibrary(Class type) throws IOException { - Library libAnn = type.getAnnotation(Library.class); - if (libAnn != null) { - try { - String name = libAnn.value(); - return BridJ.getNativeLibrary(name, new File("/System/Library/Frameworks/" + name + ".framework/" + name)); - } catch (FileNotFoundException ex) { - } - } - - return super.getNativeLibrary(type); - } - - Map> bridjClassesByObjCName = new HashMap>(); - - @Override - public void register(Type type) { - Class typeClass = Utils.getClass(type); - typeClass.getAnnotation(Library.class); - Library libAnn = typeClass.getAnnotation(Library.class); - if (libAnn != null) { - String name = libAnn.value(); - File libraryFile = BridJ.getNativeLibraryFile(name); - if (libraryFile != null) { - System.load(libraryFile.toString()); - } - if (ObjCObject.class.isAssignableFrom(typeClass)) { - bridjClassesByObjCName.put(typeClass.getSimpleName(), (Class)typeClass); - } - } - - super.register(type); - } - - public String getSelector(Method method) { - Selector selAnn = method.getAnnotation(Selector.class); - if (selAnn != null) - return selAnn.value(); - - String n = method.getName(); - if (n.endsWith("_")) - n = n.substring(0, n.length() - 1); - - if (method.getParameterTypes().length > 0) - n += ":"; - - n = n.replace('_', ':'); - return n; - } - - @Override - protected void registerNativeMethod( - Class type, - NativeLibrary typeLibrary, - Method method, - NativeLibrary methodLibrary, - Builder builder, - MethodCallInfoBuilder methodCallInfoBuilder - ) throws FileNotFoundException - { - - if (method == null) - return; - - if (!ObjCObject.class.isAssignableFrom(type) || ObjCBlock.class.isAssignableFrom(type)) { - super.registerNativeMethod(type, typeLibrary, method, methodLibrary, builder, methodCallInfoBuilder); - return; - } - - try { - MethodCallInfo mci = methodCallInfoBuilder.apply(method); - boolean isStatic = Modifier.isStatic(method.getModifiers()); - - if (isStatic) { - Pointer pObjcClass = getObjCClass((Class) type).as(ObjCClass.class); - ObjCClass objcClass = pObjcClass.get(); - mci.setNativeClass(pObjcClass.getPeer()); - } - - mci.setSymbolName(getSelector(method)); - builder.addObjCMethod(mci); - } catch (ClassNotFoundException ex) { - throw new RuntimeException("Failed to register method " + method + " : " + ex, ex); - } - } - - public static ObjectiveCRuntime getInstance() { - return BridJ.getRuntimeByRuntimeClass(ObjectiveCRuntime.class); - } - - public static Type getBlockCallbackType(Class blockClass) { - if (!ObjCBlock.class.isAssignableFrom(blockClass) || ObjCBlock.class == blockClass) - throw new RuntimeException("Class " + blockClass.getName() + " should be a subclass of " + ObjCBlock.class.getName()); - - Type p = blockClass.getGenericSuperclass(); - if (Utils.getClass(p) == (Class)ObjCBlock.class) { - Type callbackType = Utils.getUniqueParameterizedTypeParameter(p); - if (callbackType == null || !(callbackType instanceof Class || callbackType instanceof ParameterizedType)) - throw new RuntimeException("Class " + blockClass.getName() + " should inherit from " + ObjCBlock.class.getName() + " with a valid single type parameter (found " + Utils.toString(p) + ")"); - - return callbackType; - } - throw new RuntimeException("Unexpected failure in getBlockCallbackType"); - } - - static final Pointer.Releaser ObjCBlockReleaser = new Pointer.Releaser() { - public void release(Pointer p) { - ObjCJNI.releaseObjCBlock(p.getPeer()); - } - }; - - @Override - public TypeInfo getTypeInfo(final Type type) { - return new CTypeInfo(type) { - - @Override - public void initialize(T instance) { - if (!BridJ.isCastingNativeObjectInCurrentThread()) { - if (instance instanceof ObjCBlock) { - final Pointer pcb = registerCallbackInstance((CallbackInterface)instance); - ((ObjCBlock)instance).pCallback = pcb; - - Pointer pBlock = pointerToAddress(ObjCJNI.createObjCBlockWithFunctionPointer(pcb.getPeer()), type); - pBlock = pBlock.withReleaser(new Releaser() { - public void release(Pointer p) { - pcb.release(); - ObjCJNI.releaseObjCBlock(p.getPeer()); - } - }); - - setNativeObjectPeer(instance, pBlock); - } else { - super.initialize(instance); - } - } else { - super.initialize(instance); - } - } - - - @Override - public void initialize(T instance, Pointer peer) { - if (instance instanceof ObjCClass) { - setNativeObjectPeer(instance, peer); - } /*else if (instance instanceof ObjCBlock) { - setNativeObjectPeer(instance, peer); - ObjCBlock block = (ObjCBlock)instance; - - Type callbackType = getBlockCallbackType(instance.getClass()); - Pointer p = pointerToAddress(ObjCJNI.getObjCBlockFunctionPointer(peer.getPeer()), callbackType); - block.callback = p.get(); // TODO take type information somewhere - } */else { - super.initialize(instance, peer); - } - } - - @Override - public void initialize(T instance, int constructorId, Object... args) { - try { - - /*if (instance instanceof ObjCBlock) { - Object firstArg; - if (constructorId != ObjCBlock.CALLBACK_CONSTRUCTOR_ID || args.length != 1 || !((firstArg = args[0]) instanceof Callback)) - throw new RuntimeException("Block constructor should have id " + ObjCBlock.CALLBACK_CONSTRUCTOR_ID + " (got " + constructorId + " ) and only one callback argument (got " + args.length + ")"); - - Callback cb = (Callback)firstArg; - Pointer pcb = pointerTo(cb); - Pointer peer = (Pointer)pointerToAddress(ObjCJNI.createObjCBlockWithFunctionPointer(pcb.getPeer()), type).withReleaser(ObjCBlockReleaser);; - if (peer == null) - throw new RuntimeException("Failed to create Objective-C block for callback " + cb); - - setNativeObjectPeer(instance, peer); - } else*/ { - Pointer c = ObjectiveCRuntime.this.getObjCClass(typeClass); - if (c == null) { - throw new RuntimeException("Failed to get Objective-C class for type " + typeClass.getName()); - } - Pointer pc = c.as(ObjCClass.class); - Pointer p = pc.get().new$(); //.alloc(); - if (constructorId == -1) { - p = p.get().init(); - } else { - throw new UnsupportedOperationException("TODO handle constructors !"); - } - setNativeObjectPeer(instance, p); - } - } catch (ClassNotFoundException ex) { - throw new RuntimeException("Failed to initialize instance of type " + Utils.toString(type) + " : " + ex, ex); - } - } - }; - } - - public static Pointer getObjCClass(String name) throws ClassNotFoundException { - return getInstance().getObjCClass(name, false); - } - private Pointer getObjCClass(Class cls) throws ClassNotFoundException { - if (cls == ObjCClass.class) - return getObjCClass("NSObject", true); - else if (cls == ObjCObject.class) - return getObjCClass("NSObject", false); - - return getObjCClass(cls.getSimpleName(), false); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/SEL.java b/libraries/BridJ/src/main/java/org/bridj/objc/SEL.java deleted file mode 100644 index 22ce7c4a1..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/SEL.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bridj.objc; -import org.bridj.*; -import static org.bridj.Pointer.*; -import static org.bridj.objc.ObjectiveCRuntime.*; - -public class SEL extends TypedPointer { - public SEL(long peer) { super(peer); } - public SEL(Pointer ptr) { super(ptr); } - - public static SEL valueOf(String name) { - return sel_registerName(pointerToCString(name)); - } - - protected volatile String name; - public String getName() { - if (name == null) - name = sel_getName(this).getCString(); - return name; - } - public String toString() { - return "@selector(" + getName() + ")"; - } - public boolean equals(Object o) { - if (!(o instanceof SEL)) - return false; - return getName().equals(((SEL)o).getName()); - } - public int hashCode() { - return getName().hashCode(); - } -} - diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/Selector.java b/libraries/BridJ/src/main/java/org/bridj/objc/Selector.java deleted file mode 100644 index 60adda3a0..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/Selector.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bridj.objc; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -public @interface Selector { - String value(); -} diff --git a/libraries/BridJ/src/main/java/org/bridj/objc/package-info.java b/libraries/BridJ/src/main/java/org/bridj/objc/package-info.java deleted file mode 100644 index baadf71a8..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/objc/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** -BridJ Objective-C runtime (MacOS X only, not working properly yet). -*/ -package org.bridj.objc; diff --git a/libraries/BridJ/src/main/java/org/bridj/package-info.java b/libraries/BridJ/src/main/java/org/bridj/package-info.java deleted file mode 100644 index e057a52b7..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** -BridJ core classes and C runtime ({@link org.bridj.Pointer}, {@link org.bridj.BridJ}, {@link org.bridj.SizeT}, {@link org.bridj.Platform}, {@link org.bridj.LastError}...). -

-See BridJ's wiki for more information. -*/ -package org.bridj; diff --git a/libraries/BridJ/src/main/java/org/bridj/util/ASMUtils.java b/libraries/BridJ/src/main/java/org/bridj/util/ASMUtils.java deleted file mode 100644 index 74ad9b6b2..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/ASMUtils.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; -import java.io.IOException; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import org.bridj.Pointer; -import org.objectweb.asm.*; -import static org.objectweb.asm.Opcodes.*; - -/** - * Utilities for ASM. - * @author ochafik - */ -public class ASMUtils { - - public static String typeDesc(java.lang.reflect.Type t) { - if (t instanceof Class) { - Class c = (Class)t; - if (c == Pointer.class) - return "Pointer"; - if (c.isPrimitive()) { - String s = c.getSimpleName(); - return Character.toUpperCase(s.charAt(0)) + s.substring(1); - } else if (c.isArray()) { - return typeDesc(c.getComponentType()) + "Array"; - } - return c.getName().replace('.', '_'); - } else { - ParameterizedType p = (ParameterizedType)t; - StringBuilder b = new StringBuilder(typeDesc(p.getRawType())); - for (java.lang.reflect.Type pp : p.getActualTypeArguments()) - b.append("_").append(typeDesc(pp)); - return b.toString(); - } - } - public static void addSuperCall(ClassVisitor cv, String superClassInternalName) { - MethodVisitor mv = cv.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, superClassInternalName, "", "()V"); - mv.visitInsn(RETURN); - mv.visitMaxs(1, 1); - mv.visitEnd(); - } - public static Class createSubclassWithSynchronizedNativeMethodsAndNoStaticFields(Class original, ClassDefiner classDefiner) throws IOException { - String suffix = "$SynchronizedNative"; - final String originalInternalName = JNIUtils.getNativeName(original); - final String synchronizedName = original.getName() + suffix; - final String synchronizedInternalName = originalInternalName + suffix; - - ClassWriter classWriter = new ClassWriter(0); - //TraceClassVisitor traceVisitor = new TraceClassVisitor(classWriter, new PrintWriter(System.out)); - ClassVisitor cv = new ClassVisitor(ASM4, classWriter) { - - @Override - public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { - super.visit(version, access, synchronizedInternalName, null, originalInternalName, new String[0]); - addSuperCall(cv, originalInternalName); - } - - @Override - public void visitInnerClass(String name, String outerName, String innerName, int access) { - // Do nothing. - } - - @Override - public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { - return null; - } - - @Override - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - if (!Modifier.isNative(access)) - return null; - - return super.visitMethod(access | Modifier.SYNCHRONIZED, name, desc, signature, exceptions); - } - }; - - ClassReader classReader = new ClassReader(original.getName()); - classReader.accept(cv, 0); - return (Class) classDefiner.defineClass(synchronizedName, classWriter.toByteArray()); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/AnnotationUtils.java b/libraries/BridJ/src/main/java/org/bridj/util/AnnotationUtils.java deleted file mode 100644 index 89afa2c4e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/AnnotationUtils.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Member; -import java.lang.reflect.Proxy; -import org.bridj.ann.Forwardable; - -/** - * Util methods for annotations (inheritable annotations, forwarded annotations, annotations from AnnotatedElements and/or direct annotation arrays...) - * @author ochafik - */ -public class AnnotationUtils { - - public static A getInheritableAnnotation(Class ac, AnnotatedElement m, Annotation... directAnnotations) { - return getAnnotation(ac, true, m, directAnnotations); - } - public static A getAnnotation(Class ac, AnnotatedElement m, Annotation... directAnnotations) { - return getAnnotation(ac, false, m, directAnnotations); - } - private static boolean isForwardable(Class ac) { - return ac.isAnnotationPresent(Forwardable.class); - } - public static boolean isAnnotationPresent(Class ac, Annotation... annotations) { - return isAnnotationPresent(ac, isForwardable(ac), annotations); - } - private static boolean isAnnotationPresent(Class ac, boolean isForwardable, Annotation... annotations) { - for (Annotation ann : annotations) { - if (ac.isInstance(ann)) - return true; - - if (isForwardable) { - if (ann.annotationType().isAnnotationPresent(ac)) - return true; - } - } - return false; - } - public static boolean isAnnotationPresent(Class ac, AnnotatedElement m, Annotation... directAnnotations) { - boolean isForwardable = isForwardable(ac); - if (m != null) { - if (isForwardable) { - if (isAnnotationPresent(ac, true, m.getAnnotations())) - return true; - } else { - if (m.isAnnotationPresent(ac)) - return true; - } - } - if (directAnnotations != null) - return isAnnotationPresent(ac, isForwardable, directAnnotations); - - return false; - } - - private static A getAnnotation(Class ac, boolean inherit, AnnotatedElement m, Annotation... directAnnotations) { - if (directAnnotations != null) { - for (Annotation ann : directAnnotations) { - if (ac.isInstance(ann)) { - return ac.cast(ann); - } - } - } - - if (m == null) { - return null; - } - A a = m.getAnnotation(ac); - if (a != null) { - return a; - } - - if (inherit) { - if (m instanceof Member) { - return getAnnotation(ac, inherit, ((Member) m).getDeclaringClass()); - } - - if (m instanceof Class) { - Class c = (Class) m, dc = c.getDeclaringClass(); - Class p = c.getSuperclass(); - while (p != null) { - a = getAnnotation(ac, true, p); - if (a != null) - return a; - p = p.getSuperclass(); - } - - if (dc != null) { - return getAnnotation(ac, inherit, dc); - } - } - } - return null; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/BytecodeAnalyzer.java b/libraries/BridJ/src/main/java/org/bridj/util/BytecodeAnalyzer.java deleted file mode 100644 index bdd09a95a..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/BytecodeAnalyzer.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.bridj.util; -import org.bridj.Platform; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; - -import org.objectweb.asm.*; -import static org.objectweb.asm.ClassReader.*; -/** - * Util class that scavenges through a class' bytecode to retrieve the original order of fields and methods, as defined in the sources (unlike what the reflection APIs return : they don't guarantee the order). - * @author ochafik - */ -public final class BytecodeAnalyzer { - private BytecodeAnalyzer() {} - - /** - * Returns array of String[] { declaringClassInternalName, methodName, signature } - */ - public static List getNativeMethodSignatures(Class c) throws IOException { - return getNativeMethodSignatures(getInternalName(c), Platform.getClassLoader(c)); - } - /** - * Returns array of String[] { declaringClassInternalName, methodName, signature } - */ - public static List getNativeMethodSignatures(String internalName, ClassLoader classLoader) throws IOException { - return getNativeMethodSignatures(internalName, classLoader, new ArrayList()); - } - private static List getNativeMethodSignatures(final String internalName, ClassLoader classLoader, final List ret) throws IOException { - ClassReader r = new ClassReader(readByteCode(internalName, classLoader)); - String p = r.getSuperName(); - if (p != null && !p.equals("java/lang/Object")) - getNativeMethodSignatures(p, classLoader, ret); - - r.accept(new EmptyVisitor() { - @Override - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - if (Modifier.isNative(access)) { - ret.add(new String[] { internalName, name, desc }); - } - return null; - } - }, SKIP_DEBUG | SKIP_FRAMES | SKIP_CODE); - - return ret; - } - - private static List getFieldNames(final String internalName, String recurseToInternalName, ClassLoader classLoader, final List ret) throws IOException { - ClassReader r = new ClassReader(readByteCode(internalName, classLoader)); - String p = r.getSuperName(); - if (p != null && !p.equals("java/lang/Object") && !recurseToInternalName.equals(internalName)) - getFieldNames(p, recurseToInternalName, classLoader, ret); - - r.accept(new EmptyVisitor() { - @Override - public FieldVisitor visitField(int i, String name, String string1, String string2, Object o) { - ret.add(name); - return null; - } - }, SKIP_DEBUG | SKIP_FRAMES | SKIP_CODE); - - return ret; - } - - private static List getMethodNames(final String internalName, String recurseToInternalName, ClassLoader classLoader, final List ret) throws IOException { - ClassReader r = new ClassReader(readByteCode(internalName, classLoader)); - String p = r.getSuperName(); - if (p != null && !p.equals("java/lang/Object") && !recurseToInternalName.equals(internalName)) - getMethodNames(p, recurseToInternalName, classLoader, ret); - - r.accept(new EmptyVisitor() { - @Override - public MethodVisitor visitMethod(int i, String name, String string1, String string2, String[] strings) { - ret.add(name); - return null; - } - }, SKIP_DEBUG | SKIP_FRAMES | SKIP_CODE); - - return ret; - } - - static String getInternalName(Class c) { - return c.getName().replace('.', '/'); - } - static URL getClassResource(Class c) throws FileNotFoundException { - return getClassResource(getInternalName(c), Platform.getClassLoader(c)); - } - static URL getClassResource(String internalClassName, ClassLoader classLoader) throws FileNotFoundException { - String p = internalClassName + ".class"; - URL u = classLoader.getResource(p); - if (u == null) - throw new FileNotFoundException("Resource '" + p + "'"); - return u; - } - static byte[] readByteCode(String classInternalName, ClassLoader classLoader) throws FileNotFoundException, IOException { - return readBytes(getClassResource(classInternalName, classLoader).openStream(), true); - } - static byte[] readBytes(InputStream in, boolean close) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int len; - while ((len = in.read(b)) > 0) { - out.write(b, 0, len); - } - if (close) - in.close(); - return out.toByteArray(); - } - - public static List getFieldNames(Class c, Class recurseTo) throws IOException { - return getFieldNames(getInternalName(c), getInternalName(recurseTo), Platform.getClassLoader(c), new ArrayList()); - } - public static List getMethodNames(Class c, Class recurseTo) throws IOException { - return getMethodNames(getInternalName(c), getInternalName(recurseTo), Platform.getClassLoader(c), new ArrayList()); - } - static class EmptyVisitor extends ClassVisitor { - - public EmptyVisitor() { - super(Opcodes.ASM4); - } - public void visit(int i, int i1, String string, String string1, String string2, String[] strings) { - - } - - public void visitSource(String string, String string1) { - - } - - public void visitOuterClass(String string, String string1, String string2) { - - } - - public AnnotationVisitor visitAnnotation(String string, boolean bln) { - return null; - } - - public void visitAttribute(Attribute atrbt) { - - } - - public void visitInnerClass(String string, String string1, String string2, int i) { - - } - - public FieldVisitor visitField(int i, String string, String string1, String string2, Object o) { - return null; - } - - public MethodVisitor visitMethod(int i, String string, String string1, String string2, String[] strings) { - return null; - } - - public void visitEnd() { - - } - - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/ClassDefiner.java b/libraries/BridJ/src/main/java/org/bridj/util/ClassDefiner.java deleted file mode 100644 index 314bf6843..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/ClassDefiner.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -/** - * - * @author ochafik - */ -public interface ClassDefiner { - Class defineClass(String className, byte[] data) throws ClassFormatError; -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/ConcurrentCache.java b/libraries/BridJ/src/main/java/org/bridj/util/ConcurrentCache.java deleted file mode 100644 index f3c031449..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/ConcurrentCache.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bridj.util; - -import java.lang.reflect.Constructor; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Cache that creates its missing values automatically, using the value class' default constructor (override {@link ConcurrentCache#newInstance(Object)} to call another constructor) - */ -public class ConcurrentCache { - protected final ConcurrentHashMap map = new ConcurrentHashMap(); - protected final Class valueClass; - - public ConcurrentCache(Class valueClass) { - this.valueClass = valueClass; - } - - private volatile Constructor valueConstructor; - private Constructor getValueConstructor() { - if (valueConstructor == null) { - try { - valueConstructor = valueClass.getConstructor(); - if (valueConstructor != null && valueConstructor.isAccessible()) - valueConstructor.setAccessible(true); - } catch (Exception ex) { - throw new RuntimeException("No accessible default constructor in class " + (valueClass == null ? "null" : valueClass.getName()), ex); - } - } - return valueConstructor; - } - - protected V newInstance(K key) { - try { - return getValueConstructor().newInstance(); - } catch (Exception ex) { - throw new RuntimeException("Failed to call constructor " + valueConstructor, ex); - } - } - - public V get(K key) { - V v = map.get(key); - if (v == null) { - V newV = newInstance(key); - V oldV = map.putIfAbsent(key, newV); - if (oldV != null) - v = oldV; - else - v = newV; - } - return v; - } - - public void clear() { - map.clear(); - } - - public Iterable> entrySet() { - return map.entrySet(); - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/util/DefaultParameterizedType.java b/libraries/BridJ/src/main/java/org/bridj/util/DefaultParameterizedType.java deleted file mode 100644 index 3c2a5b2bf..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/DefaultParameterizedType.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.util; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -/** - * Default implementation of {@link java.lang.reflect.ParameterizedType} - * @author Olivier - */ -public class DefaultParameterizedType implements ParameterizedType { - private final Type[] actualTypeArguments; - private final Type ownerType; - private final Type rawType; - - public DefaultParameterizedType(Type ownerType, Type rawType, Type[] actualTypeArguments) { - this.ownerType = ownerType; - this.actualTypeArguments = actualTypeArguments; - this.rawType = rawType; - } - public DefaultParameterizedType(Type rawType, Type... actualTypeArguments) { - this(null, rawType, actualTypeArguments); - } - - @Override - public String toString() { - StringBuilder b = new StringBuilder(); - if (ownerType != null) - b.append(Utils.toString(ownerType)).append("."); - b.append(rawType); - if (actualTypeArguments.length > 0) { - b.append("<"); - for (int i = 0; i < actualTypeArguments.length; i++) { - if (i > 0) - b.append(", "); - b.append(Utils.toString(actualTypeArguments[i])); - } - b.append(">"); - } - return b.toString(); - } - public static Type paramType(Type rawType, Type... actualTypeArguments) { - return new DefaultParameterizedType(rawType, actualTypeArguments); - } - - //@Override - public Type[] getActualTypeArguments() { - return actualTypeArguments.clone(); - } - - //@Override - public java.lang.reflect.Type getOwnerType() { - return ownerType; - } - - //@Override - public java.lang.reflect.Type getRawType() { - return rawType; - } - - - //@Override - public int hashCode() { - int h = getRawType().hashCode(); - if (getOwnerType() != null) - h ^= getOwnerType().hashCode(); - for (int i = 0, n = actualTypeArguments.length; i < n; i++) - h ^= actualTypeArguments[i].hashCode(); - return h; - } - - static boolean eq(Object a, Object b) { - if ((a == null) != (b == null)) - return false; - if (a != null && !a.equals(b)) - return false; - return true; - } - //@Override - public boolean equals(Object o) { - if (o == null || !(o instanceof DefaultParameterizedType)) - return false; - - DefaultParameterizedType t = (DefaultParameterizedType)o; - if (!eq(getRawType(), t.getRawType())) - return false; - if (!eq(getOwnerType(), t.getOwnerType())) - return false; - - Object[] tp = t.actualTypeArguments; - if (actualTypeArguments.length != tp.length) - return false; - - for (int i = 0, n = actualTypeArguments.length; i < n; i++) - if (!eq(actualTypeArguments[i], tp[i])) - return false; - - return true; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/JNIUtils.java b/libraries/BridJ/src/main/java/org/bridj/util/JNIUtils.java deleted file mode 100644 index 1ebbfa05b..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/JNIUtils.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.regex.Pattern; -import org.bridj.BridJ; -import org.bridj.Platform; -import org.bridj.Version; - -/** - * - * @author ochafik - */ -public class JNIUtils { - - private static class NativeMethodsCache { - Map signatures = new HashMap(); - public NativeMethodsCache(String internalClassName) throws IOException { - for (String[] sig : BytecodeAnalyzer.getNativeMethodSignatures(internalClassName, Platform.getClassLoader())) { - signatures.put(sig[1], sig[2]); - } - } - public String get(String name) { - return signatures.get(name); - } - public Set getNames() { - return signatures.keySet(); - } - } - private static Map nativeMethodsCache = new WeakHashMap(); - private static synchronized NativeMethodsCache getNativeMethodsCache(String internalClassName) throws IOException { - NativeMethodsCache cache = nativeMethodsCache.get(internalClassName); - if (cache == null) - nativeMethodsCache.put(internalClassName, cache = new NativeMethodsCache(internalClassName)); - return cache; - } - private static final String bridjPackage = BridJ.class.getPackage().getName(); - - private static final String bridjNormalPackagePrefix = bridjPackage.endsWith(Version.VERSION_SPECIFIC_SUB_PACKAGE) ? bridjPackage.substring(0, bridjPackage.length() - Version.VERSION_SPECIFIC_SUB_PACKAGE.length()) : bridjPackage + "."; - private static final String bridjVersionSpecificPackagePrefix = bridjPackage + "."; - - static int findLastNonEscapeUnderscore(String s) { - int len = s.length(), i = len; - do { - i = s.lastIndexOf("_", i - 1); - if (i >= 0 && (i == len - 1 || !Character.isDigit(s.charAt(i + 1)))) - return i; - } while (i > 0); - return -1; - } - public static String decodeVersionSpecificMethodNameClassAndSignature(String symbolName, Object[] nameAndSigArray) throws NoSuchMethodException, IOException { - return decodeMethodNameClassAndSignature(symbolName, nameAndSigArray, bridjNormalPackagePrefix, bridjVersionSpecificPackagePrefix); - } - - static String decodeMethodNameClassAndSignature(String symbolName, Object[] nameAndSigArray, String normalClassPrefix, String replacementClassPrefix) throws NoSuchMethodException, IOException { - if (symbolName.startsWith("_")) - symbolName = symbolName.substring(1); - if (symbolName.startsWith("Java_")) - symbolName = symbolName.substring("Java_".length()); - - int i = findLastNonEscapeUnderscore(symbolName); - String className = symbolName.substring(0, i).replace('_', '.'); - if (normalClassPrefix != null) { - if (className.startsWith(normalClassPrefix) && !className.startsWith(replacementClassPrefix)) - className = replacementClassPrefix + className.substring(normalClassPrefix.length()); - } - String methodName = symbolName.substring(i + 1).replaceAll("_1", "_"); - - NativeMethodsCache mc = getNativeMethodsCache(className.replace('.', '/')); - String sig = mc.get(methodName); - if (sig == null) - throw new NoSuchMethodException("Method " + methodName + " not found in class " + className + " : known method names = " + StringUtils.implode(mc.getNames(), ", ")); - - nameAndSigArray[0] = methodName; - nameAndSigArray[1] = sig; - - String internalClassName = className.replace('.', '/'); - return internalClassName;//className; - - } - public static String getNativeName(Class c) { - return c.getName().replace('.', '/'); - } - public static String getNativeSignature(Method m) { - StringBuffer b = new StringBuffer(); - b.append('('); - for (Class c : m.getParameterTypes()) - b.append(getNativeSignature(c)); - b.append(')'); - b.append(getNativeSignature(m.getReturnType())); - return b.toString(); - } - public static String getNativeSignature(Class c) { - if (c.isPrimitive()) { - if (c == int.class) - return "I"; - if (c == long.class) - return "J"; - if (c == short.class) - return "S"; - if (c == byte.class) - return "B"; - if (c == boolean.class) - return "Z"; - if (c == double.class) - return "D"; - if (c == float.class) - return "F"; - if (c == char.class) - return "C"; - if (c == void.class) - return "V"; - - throw new RuntimeException("unexpected case"); - } - if (c.isArray()) - return "[" + getNativeSignature(c.getComponentType()); - return "L" + getNativeName(c) + ";"; - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/Pair.java b/libraries/BridJ/src/main/java/org/bridj/util/Pair.java deleted file mode 100644 index ae159c302..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/Pair.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.bridj.util; - -import java.util.Map; - -public class Pair implements Comparable>, Map.Entry { - private U first; - private V second; - - public Pair(U first, V second) { - this.first = first; - this.second = second; - } - - public Pair() {} - - public U getFirst() { - return first; - } - - public V getSecond() { - return second; - } - - public void setFirst(U first) { - this.first = first; - } - - public void setSecond(V second) { - this.second = second; - } - - @SuppressWarnings("unchecked") - public int compareTo(Pair o) { - Comparable cu = (Comparable)getFirst(); - if (cu == null) { - if (first != null) - return 1; - } else { - int d = cu.compareTo(o.getFirst()); - if (d != 0) - return d; - } - - Comparable cv = (Comparable)getSecond(); - if (cv == null) - return second != null ? 1 : -1; - return cv.compareTo(o.getSecond()); - } - - @Override - public String toString() { - return "Pair("+first+", "+second+")"; - } - - public U getKey() { - return first; - } - - public V getValue() { - return second; - } - - public V setValue(V value) { - V oldValue = second; - second = value; - return oldValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Pair other = (Pair) obj; - if (first == null) { - if (other.first != null) - return false; - } else if (!first.equals(other.first)) - return false; - if (second == null) { - if (other.second != null) - return false; - } else if (!second.equals(other.second)) - return false; - return true; - } - - public boolean isFull() { - return getFirst() != null && getSecond() != null; - } - - public boolean isEmpty() { - return getFirst() == null && getSecond() == null; - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/main/java/org/bridj/util/ProcessUtils.java b/libraries/BridJ/src/main/java/org/bridj/util/ProcessUtils.java deleted file mode 100644 index cfb1d750e..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/ProcessUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -import org.bridj.ann.Library; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.bridj.BridJ; -import org.bridj.Platform; -import org.bridj.ann.Convention; -import static java.lang.System.getProperty; - -/** - * Util methods to : query the process id from the current process, launch processes (including JVM processes) - * @author Olivier - */ -public class ProcessUtils { - - @Library("kernel32") - @Convention(Convention.Style.StdCall) - static class Kernel32 { - public static native int GetCurrentProcessId(); - } - @Library("c") - static class LibC { - public static native int getpid(); - } - - /** - * Get the current process native id - */ - public static int getCurrentProcessId() { - if (Platform.isWindows()) { - BridJ.register(Kernel32.class); - return Kernel32.GetCurrentProcessId(); - } else { - BridJ.register(LibC.class); - return LibC.getpid(); - } - } - - public static String[] computeJavaProcessArgs(Class mainClass, List mainArgs) { - List args = new ArrayList(); - args.add(new File(new File(getProperty("java.home")), "bin" + File.separator + "java").toString()); - args.add("-cp"); - args.add(getProperty("java.class.path")); - args.add(mainClass.getName()); - for (Object arg : mainArgs) - args.add(arg.toString()); - - return args.toArray(new String[args.size()]); - } - public static Process startJavaProcess(Class mainClass, List mainArgs) throws IOException { - ProcessBuilder b = new ProcessBuilder(); - b.command(computeJavaProcessArgs(mainClass, mainArgs)); - b.redirectErrorStream(true); - return b.start(); - } - -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/StringUtils.java b/libraries/BridJ/src/main/java/org/bridj/util/StringUtils.java deleted file mode 100644 index 49d753036..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/StringUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bridj.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -public class StringUtils { - public static String implode(double[] array, String separator) { - StringBuffer out = new StringBuffer(); - boolean first = true; - for (double v : array) { - if (first) first = false; - else out.append(separator); - out.append(v); - } - return out.toString(); - } - - public static String implode(Object[] values) { - return implode(values, ", "); - } - public static String implode(Object[] values, Object separator) { - return implode(Arrays.asList(values), separator); - } - public static final String implode(Iterable elements, Object separator) { - String sepStr = separator.toString(); - StringBuilder out = new StringBuilder(); - boolean first = true; - for (Object s : elements) { - if (s == null) - continue; - - if (first) - first = false; - else - out.append(sepStr); - out.append(s); - } - return out.toString(); - } - public static final String implode(Iterable strings) { - return implode(strings, ", "); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/Tuple.java b/libraries/BridJ/src/main/java/org/bridj/util/Tuple.java deleted file mode 100644 index c55f03add..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/Tuple.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bridj.util; - -public class Tuple { - protected final Object[] data; - public Tuple(Object[] data) { - this.data = data; - } - public Tuple(int n) { - this.data = new Object[n]; - } - @Override - public int hashCode() { - int h = 0; - for (int i = 0, n = size(); i < n; i++) { - Object o = get(i); - if (o == null) - continue; - h ^= o.hashCode(); - } - return h; - } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Tuple)) - return false; - Tuple t = (Tuple)obj; - int s = size(); - if (t.size() != s) - return false; - for (int i = 0; i < s; i++) { - Object o1 = get(i), o2 = t.get(i); - if (o1 == null) { - if (o2 != null) - return false; - } else if (!o1.equals(o2)) - return false; - } - return true; - } - public Object get(int index) { - return data[index]; - } - public void set(int index, Object value) { - data[index] = value; - } - public int size() { - return data.length; - } - @Override - public String toString() { - StringBuilder b = new StringBuilder("{"); - for (int i = 0, n = size(); i < n; i++) { - if (i != 0) - b.append(','); - b.append('\n'); - b.append('\t').append(get(i)); - } - b.append("\n}"); - return b.toString(); - } -} diff --git a/libraries/BridJ/src/main/java/org/bridj/util/Utils.java b/libraries/BridJ/src/main/java/org/bridj/util/Utils.java deleted file mode 100644 index 95010cf76..000000000 --- a/libraries/BridJ/src/main/java/org/bridj/util/Utils.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.Method; -import java.io.*; -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.nio.*; - -/** - * Miscellaneous utility methods. - * @author ochafik - */ -public class Utils { - public static int getEnclosedConstructorParametersOffset(Constructor c) { - Class enclosingClass = c.getDeclaringClass().getEnclosingClass(); - Class[] params = c.getParameterTypes(); - int overrideOffset = params.length > 0 && enclosingClass != null && enclosingClass == params[0] ? 1 : 0; - return overrideOffset; - } - public static boolean isDirect(Buffer b) { - if (b instanceof ByteBuffer) - return ((ByteBuffer)b).isDirect(); - if (b instanceof IntBuffer) - return ((IntBuffer)b).isDirect(); - if (b instanceof LongBuffer) - return ((LongBuffer)b).isDirect(); - if (b instanceof DoubleBuffer) - return ((DoubleBuffer)b).isDirect(); - if (b instanceof FloatBuffer) - return ((FloatBuffer)b).isDirect(); - if (b instanceof ShortBuffer) - return ((ShortBuffer)b).isDirect(); - if (b instanceof CharBuffer) - return ((CharBuffer)b).isDirect(); - return false; - } - - public static boolean isSignedIntegral(Type tpe) { - return - tpe == int.class || tpe == Integer.class || - tpe == long.class || tpe == Long.class || - tpe == short.class || tpe == Short.class || - tpe == byte.class || tpe == Byte.class; - } - - public static String toString(Type t) { - if (t == null) - return "?"; - if (t instanceof Class) - return ((Class)t).getName(); - return t.toString(); - } - public static String toString(Throwable th) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - th.printStackTrace(pw); - return sw.toString(); - } - - public static boolean eq(Object a, Object b) { - if ((a == null) != (b == null)) - return false; - return !(a != null && !a.equals(b)); - } - public static Class getClass(Type type) { - if (type == null) - return null; - if (type instanceof Class) - return (Class)type; - if (type instanceof ParameterizedType) - return getClass(((ParameterizedType)type).getRawType()); - if (type instanceof GenericArrayType) - return (Class)Array.newInstance(getClass(((GenericArrayType)type).getGenericComponentType()), 0).getClass(); - if (type instanceof WildcardType) - return null; - if (type instanceof TypeVariable) { - Type[] bounds = ((TypeVariable)type).getBounds(); - return getClass(bounds[0]); - } - throw new UnsupportedOperationException("Cannot infer class from type " + type); - } - - public static Type getParent(Type type) { - if (type instanceof Class) - return ((Class)type).getSuperclass(); - else - // TODO handle templates !!! - return getParent(getClass(type)); - } - - public static Class[] getClasses(Type[] types) { - int n = types.length; - Class[] ret = new Class[n]; - for (int i = 0; i < n; i++) - ret[i] = getClass(types[i]); - return ret; - } - - public static Type getUniqueParameterizedTypeParameter(Type type) { - return (type instanceof ParameterizedType) ? ((ParameterizedType)type).getActualTypeArguments()[0] : null; - } -} diff --git a/libraries/BridJ/src/main/javadoc/overview.html b/libraries/BridJ/src/main/javadoc/overview.html deleted file mode 100644 index a4d489ad9..000000000 --- a/libraries/BridJ/src/main/javadoc/overview.html +++ /dev/null @@ -1,13 +0,0 @@ - - -BridJ: ultimate native interoperability library for Java (call C, C++, Objective-C, C# with style and performance). -

-Don't panic ! While there are indeed many classes in BridJ, the only ones you need to know about are : -

    -
  • {@link org.bridj.Pointer} : your vital friend in this native mess
  • -
  • {@link org.bridj.BridJ} : to tune the native libraries resolution process, amongst other things
  • -
  • All the classes generated by JNAerator : they will look like your original C / C++ code anyway.
  • -
-See BridJ's Wiki for more information. - - diff --git a/libraries/BridJ/src/main/jnaerator/config.jnaerator b/libraries/BridJ/src/main/jnaerator/config.jnaerator deleted file mode 100644 index 0605ab9db..000000000 --- a/libraries/BridJ/src/main/jnaerator/config.jnaerator +++ /dev/null @@ -1,28 +0,0 @@ --runtime BridJ --noJar --noComp --nocpp - --DJNICALL= --Djboolean=bool --Djint=int --Djobject=void* -"-Djlong=long long" - -/* --library jawt --package org.bridj.jawt - "-I$(JAVA_HOME)/include" - "-I$(JAVA_HOME)/include/win32" - "$(JAVA_HOME)/include/jawt.h" - "$(JAVA_HOME)/include/win32/jawt_md.h" - //-o "$(DIR)/../../../target/generated-sources/java" -*/ - --library dyncall --package org.bridj.dyncall - "-I$(DYNCALL_HOME)/dyncall/dyncall" - "$(DYNCALL_HOME)/dyncall/dyncall/dyncall.h" - "$(DYNCALL_HOME)/dyncall/dyncall/dyncall_signature.h" - - diff --git a/libraries/BridJ/src/main/old/Functional.java b/libraries/BridJ/src/main/old/Functional.java deleted file mode 100644 index 24fa736db..000000000 --- a/libraries/BridJ/src/main/old/Functional.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bridj; - -import java.util.*; - -public class Functional { - - /*static void checkLengths(int len, List... lists) { - for (List list : lists) - if (list.size() != len) - throw new IllegalArgumentException("Expected list of length " + len + ", got length " + list.size() + " instead (" + list + ")"); - }*/ - -#foreach ($n in [0..7]) - - /** - * Generic interface for functions that take #if ($n == 0)no#else$n#end arguments. - * Use generic return type java.lang.Void and return null for functions with void return type. - */ - public interface Func$n 0)#foreach ($i in [1..$n]), A$i#end#end> { - R apply(#if($n > 0)#foreach ($i in [1..$n])#if($i > 1), #end A$i a$i#end#end); - } - -#if ($n > 0) - public static List apply(Func$n f #foreach ($i in [1..$n]), A$i#if($n == 1)...#else[]#end array$i#end) { - return apply(f#foreach ($i in [1..$n]), Arrays.asList(array$i)#end); - } - public static List apply(Func$n f #foreach ($i in [1..$n]), Iterable iterable$i#end) { - List ret; - if (iterable1 instanceof List) - ret = new ArrayList(((List)iterable1).size()); - else - ret = new LinkedList(); -#if ($n > 1) -#foreach ($i in [2..$n]) - Iterator it$i = iterable${i}.iterator(); -#end -#end - for (A1 a1 : iterable1) { - R r = f.apply(a1#if ($n > 1)#foreach ($i in [2..$n]), it${i}.next()#end#end); - ret.add(r); - } - return ret; - } -#end - -#if ($n > 0) - public static <#foreach ($i in [1..$n])#if($i > 1),#end A$i#end> boolean foreach(Func$n f #foreach ($i in [1..$n]), A$i#if($n == 1)...#else[]#end array$i#end) { - - return foreach(f#foreach ($i in [1..$n]), Arrays.asList(array$i)#end); - } - public static <#foreach ($i in [1..$n])#if($i > 1),#end A$i#end> boolean foreach(Func$n f #foreach ($i in [1..$n]), Iterable iterable$i#end) { -#if ($n > 1) -#foreach ($i in [2..$n]) - Iterator it$i = iterable${i}.iterator(); -#end -#end - for (A1 a1 : iterable1) { - Boolean r = f.apply(a1#if ($n > 1)#foreach ($i in [2..$n]), it${i}.next()#end#end); - if (r != Boolean.TRUE) - return false; - } - return true; - } -#end - -#end -} diff --git a/libraries/BridJ/src/main/resources/lib/armeabi/libbridj.so b/libraries/BridJ/src/main/resources/lib/armeabi/libbridj.so deleted file mode 100755 index 6d6880f8e..000000000 Binary files a/libraries/BridJ/src/main/resources/lib/armeabi/libbridj.so and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/darwin_universal/libbridj.dylib b/libraries/BridJ/src/main/resources/org/bridj/lib/darwin_universal/libbridj.dylib deleted file mode 100755 index 67b703366..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/darwin_universal/libbridj.dylib and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_arm32_arm/bridj.so b/libraries/BridJ/src/main/resources/org/bridj/lib/linux_arm32_arm/bridj.so deleted file mode 100755 index 54067ceb8..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_arm32_arm/bridj.so and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x64/bridj.so b/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x64/bridj.so deleted file mode 100755 index 288c0ae27..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x64/bridj.so and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x86/bridj.so b/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x86/bridj.so deleted file mode 100755 index 49e465798..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/linux_x86/bridj.so and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/sunos_x86/bridj.so b/libraries/BridJ/src/main/resources/org/bridj/lib/sunos_x86/bridj.so deleted file mode 100755 index a3e5f1fd0..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/sunos_x86/bridj.so and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/win32/bridj.dll b/libraries/BridJ/src/main/resources/org/bridj/lib/win32/bridj.dll deleted file mode 100644 index f3699cf6c..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/win32/bridj.dll and /dev/null differ diff --git a/libraries/BridJ/src/main/resources/org/bridj/lib/win64/bridj.dll b/libraries/BridJ/src/main/resources/org/bridj/lib/win64/bridj.dll deleted file mode 100644 index 28b29d880..000000000 Binary files a/libraries/BridJ/src/main/resources/org/bridj/lib/win64/bridj.dll and /dev/null differ diff --git a/libraries/BridJ/src/main/velocity/org/bridj/CommonPointerIOs.java b/libraries/BridJ/src/main/velocity/org/bridj/CommonPointerIOs.java deleted file mode 100644 index b535d6aa8..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/CommonPointerIOs.java +++ /dev/null @@ -1,320 +0,0 @@ -package org.bridj; -import java.util.concurrent.atomic.AtomicLong; -import org.bridj.util.*; -import java.util.*; -import java.nio.*; -import java.lang.reflect.Type; -import static org.bridj.util.DefaultParameterizedType.*; - -class CommonPointerIOs { - - static class NativeObjectPointerIO extends PointerIO { - protected volatile long targetSize = -1, targetAlignment = -1; - protected Type nativeObjectType; - public NativeObjectPointerIO(Type nativeObjectType) { - super(nativeObjectType, -1, null); - this.nativeObjectType = nativeObjectType; - } - - - protected long computeTargetSize() { - return BridJ.sizeOf(nativeObjectType); - } - protected long computeTargetAlignment() { - return getTargetSize(); - } - @Override - public long getTargetSize() { - if (targetSize < 0) - targetSize = computeTargetSize(); - - return targetSize; - } - @Override - public long getTargetAlignment() { - if (targetAlignment < 0) - targetAlignment = computeTargetAlignment(); - - return targetAlignment; - } - - @Override - public N get(Pointer pointer, long index) { - return (N)pointer.getNativeObjectAtOffset(index * getTargetSize(), nativeObjectType); - } - @Override - public void set(Pointer pointer, long index, N value) { - Pointer ps = Pointer.pointerTo(value); - ps.copyTo(pointer.offset(index * getTargetSize())); - } - } - static class StructPointerIO extends NativeObjectPointerIO { - final StructIO structIO; - public StructPointerIO(StructIO structIO) { - super(structIO.getStructType()); - this.structIO = structIO; - } - - @Override - protected long computeTargetSize() { - structIO.build(); - return structIO.getStructSize(); - } - @Override - protected long computeTargetAlignment() { - structIO.build(); - return structIO.getStructAlignment(); - } - } - - static class PointerPointerIO extends PointerIO> { - final PointerIO underlyingIO; - - public PointerPointerIO(PointerIO underlyingIO) { - super(underlyingIO == null ? Pointer.class : paramType(Pointer.class, new Type[] {underlyingIO.getTargetType()}), Pointer.SIZE, null); - this.underlyingIO = underlyingIO; - } - - @Override - public Pointer get(Pointer> pointer, long index) { - return pointer.getPointerAtOffset(index * Pointer.SIZE, underlyingIO); - } - - @Override - public void set(Pointer> pointer, long index, Pointer value) { - pointer.setPointerAtOffset(index * Pointer.SIZE, value); - } - } - - static class PointerArrayIO extends PointerIO> { - final PointerIO underlyingIO; - final long[] dimensions; - final long totalRemainingDims; - final int iDimension; - - static Type arrayPtrType(Type elementType, long... dimensions) { - Type type = elementType; - for (int i = 0; i < dimensions.length; i++) - type = paramType(Pointer.class, type); - return type; - } - static long getTotalRemainingDims(long[] dimensions, int iDimension) { - long d = 1; - for (int i = iDimension + 1; i < dimensions.length; i++) - d *= dimensions[i]; - return d; - } - - public PointerArrayIO(PointerIO underlyingIO, long[] dimensions, int iDimension) { - super( - //underlyingIO.getTargetType(),// - underlyingIO == null ? null : arrayPtrType(underlyingIO.getTargetType(), dimensions), - -1, - null - ); - //if (iDimension >= dimensions.length) { - this.underlyingIO = underlyingIO; - /*} else { - this.underlyingIO = new PointerArrayIO(underlyingIO, dimensions, iDimension + 1); - }*/ - this.dimensions = dimensions; - this.iDimension = iDimension; - totalRemainingDims = getTotalRemainingDims(dimensions, iDimension); - } - - @Override - public long getTargetSize() { - long subSize = underlyingIO.getTargetSize(); - return dimensions[iDimension + 1] * subSize;// * totalRemainingDims; - } - - @Override - public Pointer get(Pointer> pointer, long index) { - //long offset = getOffset(index); - long targetSize = getTargetSize();//underlyingIO.getTargetSize(); - return pointer.offset(index * targetSize).as(underlyingIO); - } - - long getOffset(long index) { - assert iDimension < dimensions.length; - return index * totalRemainingDims; - } - @Override - public void set(Pointer> pointer, long index, Pointer value) { - throw new RuntimeException("Cannot set a multi-dimensional array's sub-arrays pointers !"); - } - } - - static class CallbackPointerIO extends PointerIO { - final Class callbackClass; - - public CallbackPointerIO(Class callbackClass) { - super(callbackClass, Pointer.SIZE, null); - this.callbackClass = callbackClass; - } - - @Override - public T get(Pointer pointer, long index) { - if (index != 0) - throw new UnsupportedOperationException("Cannot get function pointer at index different from 0"); - //return pointer.getPointerAtOffset(index * Pointer.SIZE, (Class)null).getNativeObject(0, callbackClass); - return (T)pointer.getNativeObjectAtOffset(0, callbackClass); - } - - @Override - public void set(Pointer pointer, long index, T value) { - throw new UnsupportedOperationException("Cannot write to body of function"); - //pointer.setPointer(index * Pointer.SIZE, Pointer.getPointer(value, callbackClass)); - } - } - - static class IntValuedEnumPointerIO> extends PointerIO> { - final Class enumClass; - - public IntValuedEnumPointerIO(Class enumClass) { - super(IntValuedEnum.class, 4, null); - this.enumClass = enumClass; - } - - @Override - public IntValuedEnum get(Pointer> pointer, long index) { - return FlagSet.fromValue(pointer.getIntAtOffset(4 * index), enumClass); - } - - @Override - public void set(Pointer> pointer, long index, IntValuedEnum value) { - pointer.setIntAtOffset(4 * index, (int)value.value()); - } - } - - static class TypedPointerPointerIO

extends PointerIO

{ - final java.lang.reflect.Constructor cons; - //final java.lang.reflect.Constructor cons2; - final Class

pointerClass; - public TypedPointerPointerIO(Class

pointerClass) { - super(pointerClass, Pointer.SIZE, null); - this.pointerClass = pointerClass; - try { - cons = pointerClass.getConstructor(long.class); - //cons2 = pointerClass.getConstructor(Pointer.class); - } catch (Exception ex) { - throw new RuntimeException("Cannot find constructor for " + pointerClass.getName(), ex); - } - } - - @Override - public P castTarget(long peer) { - if (peer == 0) - return null; - try { - return (P)cons.newInstance(peer); - } catch (Exception ex) { - throw new RuntimeException("Cannot create pointer of type " + pointerClass.getName(), ex); - } - } - - @Override - public P get(Pointer

pointer, long index) { - return castTarget(pointer.getSizeTAtOffset(index * Pointer.SIZE)); - } - - @Override - public void set(Pointer

pointer, long index, P value) { - pointer.setPointerAtOffset(index * Pointer.SIZE, value); - } - } - -#foreach ($prim in $primitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - - public static final PointerIO<${prim.WrapperName}> ${prim.Name}IO = new PointerIO<${prim.WrapperName}>(${prim.WrapperName}.class, ${primSize}, null) { - @Override - public ${prim.WrapperName} get(Pointer<${prim.WrapperName}> pointer, long index) { - return pointer.get${prim.CapName}AtOffset(index * ${primSize}); - } - - @Override - public void set(Pointer<${prim.WrapperName}> pointer, long index, ${prim.WrapperName} value) { - pointer.set${prim.CapName}AtOffset(index * ${primSize}, value); - } - - @Override - public B getBuffer(Pointer<${prim.WrapperName}> pointer, long byteOffset, int length) { - #if ($prim.Name == "char") - throw new UnsupportedOperationException("Creating direct char buffers in a cross-platform way is tricky, so it's currently disabled"); - #else - return (B)pointer.get${prim.BufferName}AtOffset(byteOffset, length); - #end - } - - @Override - public Object getArray(Pointer<${prim.WrapperName}> pointer, long byteOffset, int length) { - return pointer.get${prim.CapName}sAtOffset(byteOffset, length); - } - - @Override - public void setArray(Pointer<${prim.WrapperName}> pointer, long byteOffset, Object array) { - if (array instanceof ${prim.Name}[]) - pointer.set${prim.CapName}sAtOffset(byteOffset, (${prim.Name}[])array); - else - super.setArray(pointer, byteOffset, array); - } - - }; - -#end - - public static final PointerIO sizeTIO = new PointerIO(SizeT.class, SizeT.SIZE, null) { - @Override - public SizeT get(Pointer pointer, long index) { - return new SizeT(pointer.getSizeTAtOffset(index * SizeT.SIZE)); - } - @Override - public void set(Pointer pointer, long index, SizeT value) { - pointer.setSizeTAtOffset(index * SizeT.SIZE, value == null ? 0 : value.longValue()); - } - }; - - public static final PointerIO timeTIO = new PointerIO(TimeT.class, TimeT.SIZE, null) { - @Override - public TimeT get(Pointer pointer, long index) { - long offset = index * TimeT.SIZE; - return new TimeT(TimeT.SIZE == 4 ? pointer.getIntAtOffset(offset) : pointer.getLongAtOffset(offset)); - } - @Override - public void set(Pointer pointer, long index, TimeT value) { - long offset = index * TimeT.SIZE; - if (TimeT.SIZE == 4) - pointer.setIntAtOffset(offset, value == null ? 0 : value.intValue()); - else - pointer.setLongAtOffset(offset, value == null ? 0 : value.longValue()); - } - }; - - public static final PointerIO clongIO = new PointerIO(CLong.class, CLong.SIZE, null) { - @Override - public CLong get(Pointer pointer, long index) { - return new CLong(pointer.getCLongAtOffset(index * CLong.SIZE)); - } - @Override - public void set(Pointer pointer, long index, CLong value) { - pointer.setCLongAtOffset(index * CLong.SIZE, value == null ? 0 : value.longValue()); - } - }; - - - - /*public static final PointerIO intIO = new PointerIO(Integer.class, 4, null) { - @Override - public Integer get(Pointer pointer, long index) { - return pointer.getIntAtOffset(index * 4); - } - - @Override - public void set(Pointer pointer, long index, Integer value) { - pointer.setIntAtOffset(index * 4, value); - } - };*/ - -} - diff --git a/libraries/BridJ/src/main/velocity/org/bridj/DefaultPointer.java b/libraries/BridJ/src/main/velocity/org/bridj/DefaultPointer.java deleted file mode 100644 index 1d54fe662..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/DefaultPointer.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bridj; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.nio.*; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; - -class DefaultPointer -{ - -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/Init.c b/libraries/BridJ/src/main/velocity/org/bridj/Init.c deleted file mode 100644 index 7e29969a6..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/Init.c +++ /dev/null @@ -1,113 +0,0 @@ -#set ($replacedSubPackage = $versionSpecificSubPackage.replaceAll("_", "_1")) - -\#include "../autovar/autovar_OS.h" -\#include "../autovar/autovar_OSFAMILY.h" - -\#if defined(OS_Darwin) -\#include - -JNIEXPORT void JNICALL Java_org_bridj_${replacedSubPackage}_Platform_init(JNIEnv *env, jclass clazz); - -const char* getBridJLibPath() -{ - const char* libPath; - Dl_info info; - dladdr(Java_org_bridj_${replacedSubPackage}_Platform_init, &info); - libPath = info.dli_fname; - printf("INFO: BridJ library = '%s'\n", libPath); - return libPath; -} -\#else -const char* getBridJLibPath() -{ - printf("WARN: NOT DARWIN\n"); - return NULL; -} -#endif - -\#if defined(OSFAMILY_Unix) -\#include - -void* getSelfSymbol(DLLib* pLib, const char* name) { - void *sym, *handle; -\#if defined(OS_Darwin) - handle = RTLD_SELF; -\#else - handle = RTLD_DEFAULT; -#endif - - sym = dlsym(handle, name); - if (!sym && *name == '_') - sym = dlsym(handle, name + 1); - - return sym; -} -\#else -void* getSelfSymbol(DLLib* pLib, const char* name) { - return dlFindSymbol(pLib, name); -} -#endif - -JNIEXPORT void JNICALL Java_org_bridj_${replacedSubPackage}_Platform_init(JNIEnv *env, jclass clazz) -{ - const char* libPath = getBridJLibPath(); - DLLib* pLib = dlLoadLibrary(libPath); - DLSyms* pSyms = dlSymsInit(libPath); - const char* packagePattern = "Java_org_bridj_"; - size_t packagePatternLen = strlen(packagePattern); - int iSym, nSyms = dlSymsCount(pSyms); - - jclass objectClass = (*env)->FindClass(env, "java/lang/Object"); - jclass signatureHelperClass = (*env)->FindClass(env, "org/bridj/$versionSpecificSubPackage/util/JNIUtils"); - jmethodID decodeVersionSpecificMethodNameClassAndSignatureMethod = (*env)->GetStaticMethodID(env, signatureHelperClass, "decodeVersionSpecificMethodNameClassAndSignature", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;"); - jobjectArray nameAndSigArray = (*env)->NewObjectArray(env, 2, objectClass, NULL); - - JNINativeMethod meth; - memset(&meth, 0, sizeof(JNINativeMethod)); - - //printf("INFO: Found %d symbols\n", nSyms); - for (iSym = 0; iSym < nSyms; iSym++) { - const char* symbolName = dlSymsName(pSyms, iSym); - if (!strcmp(*symbolName == '_' ? symbolName + 1 : symbolName, "Java_org_bridj_${replacedSubPackage}_Platform_init")) - continue; - - if (strstr(symbolName, packagePattern)) { - if (meth.fnPtr = getSelfSymbol(pLib, symbolName)) { - jstring declaringClassName = (*env)->CallStaticObjectMethod(env, signatureHelperClass, decodeVersionSpecificMethodNameClassAndSignatureMethod, (*env)->NewStringUTF(env, symbolName), nameAndSigArray); - - if ((*env)->ExceptionCheck(env)) { - printf("ERROR: Exception when trying to find method for symbol '%s'\n", symbolName); - goto version_specific_init_failed; - } - - if (declaringClassName) { - jstring methodName = (*env)->GetObjectArrayElement(env, nameAndSigArray, 0); - jstring methodSignature = (*env)->GetObjectArrayElement(env, nameAndSigArray, 1); - const char* declaringClassNameStr = (char*)GET_CHARS(declaringClassName); - jclass declaringClass = (*env)->FindClass(env, declaringClassNameStr); - meth.name = (char*)GET_CHARS(methodName); - meth.signature = (char*)GET_CHARS(methodSignature); - - //printf("INFO: Registering %s.%s with signature %s as %s\n", declaringClassNameStr, meth.name, meth.signature, symbolName); - (*env)->RegisterNatives(env, declaringClass, &meth, 1); - - RELEASE_CHARS(methodName, meth.name); - RELEASE_CHARS(methodSignature, meth.signature); - RELEASE_CHARS(declaringClassName, declaringClassNameStr); - } else { - printf("ERROR: Failed to find method for symbol '%s'\n", symbolName); - } - } else { - printf("ERROR: Could not find symbol %s\n", symbolName); - } - } - } - - Java_org_bridj_Platform_init(env, clazz); - -version_specific_init_failed: - //printf("INFO: Finished binding of symbols\n"); - - //dlFreeLibrary(pLib); // TODO ? - dlSymsCleanup(pSyms); -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/JNI.java b/libraries/BridJ/src/main/velocity/org/bridj/JNI.java deleted file mode 100644 index 5a2ce707b..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/JNI.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.bridj; - -import java.io.*; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.nio.Buffer; -import static org.bridj.dyncall.DyncallLibrary.*; -import static org.bridj.Pointer.*; -import java.nio.ByteBuffer; -import java.util.List; -import static org.bridj.Platform.*; -import org.bridj.objc.*; - -/** - * Low-level calls to JNI and to BridJ's native library. - * @author ochafik - * @deprecated These methods can cause serious issues (segmentation fault, system crashes) if used without care : there are little to no checks performed on the arguments. - */ -@Deprecated -public class JNI { - static { - Platform.initLibrary(); - } - @Deprecated - public static native long getEnv(); - @Deprecated - public static native long getJVM(); - @Deprecated - public static native Object refToObject(long refPeer); - - static native long loadLibrary(String path); - static native void freeLibrary(long libHandle); - static native long loadLibrarySymbols(String libPath); - static native void freeLibrarySymbols(long symbolsHandle); - static native long findSymbolInLibrary(long libHandle, String name); - static native String[] getLibrarySymbols(long libHandle, long symbolsHandle); - static native String findSymbolName(long libHandle, long symbolsHandle, long address); - - /** - * Create a JNI global reference to a Java object : long value that can be safely passed to C programs and stored, which prevent the object from being garbage-collected and which validity runs until {@link JNI#deleteGlobalRef(long)} is called - */ - public static native long newGlobalRef(Object object); - /** - * Delete a global reference created by {@link JNI#newGlobalRef(java.lang.Object)} - */ - public static native void deleteGlobalRef(long reference); - - public static Pointer getGlobalPointer(Object object) { - return pointerToAddress(newGlobalRef(object), new Pointer.Releaser() { - public void release(Pointer p) { - deleteGlobalRef(p.getPeer()); - } - }); - } - - /** - * Create a JNI weak global reference to a Java object : long value that can be safely passed to C programs and stored, which validity runs until {@link JNI#deleteWeakGlobalRef(long)} is called.
- * Unlike global references, weak global references don't prevent objects from being garbage-collected. - */ - public static native long newWeakGlobalRef(Object object); - /** - * Delete a weak global reference created by {@link JNI#newWeakGlobalRef(java.lang.Object)} - */ - public static native void deleteWeakGlobalRef(long reference); - - /** - * Wrap a native address as a direct byte buffer of the specified byte capacity.
- * Memory is not reclaimed when the buffer is garbage-collected. - */ - public static native ByteBuffer newDirectByteBuffer(long address, long capacity); - /** - * Get the native address pointed to by a direct buffer. - */ - public static native long getDirectBufferAddress(Buffer b); - /** - * Get the capacity in bytes of a direct buffer. - */ - public static native long getDirectBufferCapacity(Buffer b); - -#foreach ($prim in $primitives) - - @Deprecated - static native long get${prim.CapName}ArrayElements(${prim.Name}[] array, boolean[] pIsCopy); - @Deprecated - static native void release${prim.CapName}ArrayElements(${prim.Name}[] array, long pointer, int mode); - - @Deprecated - static native ${prim.Name} get_${prim.Name}(long peer); - @Deprecated - static native void set_${prim.Name}(long peer, ${prim.Name} value); - @Deprecated - static native ${prim.Name}[] get_${prim.Name}_array(long peer, int length); - @Deprecated - static native void set_${prim.Name}_array(long peer, ${prim.Name}[] values, int valuesOffset, int length); - - #if ($prim.Name != "byte" && $prim.Name != "boolean") - @Deprecated - static native ${prim.Name} get_${prim.Name}_disordered(long peer); - @Deprecated - static native void set_${prim.Name}_disordered(long peer, ${prim.Name} value); - @Deprecated - static native ${prim.Name}[] get_${prim.Name}_array_disordered(long peer, int length); - @Deprecated - static native void set_${prim.Name}_array_disordered(long peer, ${prim.Name}[] values, int valuesOffset, int length); - #end -#end - - public static native void callSinglePointerArgVoidFunction(long functionPointer, long pointerArg, int callMode); - - static native long createCToJavaCallback(MethodCallInfo info); - static native long getActualCToJavaCallback(long handle); - - static native long bindJavaMethodsToObjCMethods(MethodCallInfo... infos); - static native long bindJavaToCCallbacks(MethodCallInfo... infos); - static native long bindJavaMethodsToCFunctions(MethodCallInfo... infos); - static native long bindJavaMethodsToVirtualMethods(MethodCallInfo... infos); - - static native void freeCToJavaCallback(long handle); - static native void freeObjCMethodBindings(long handle, int size); - static native void freeJavaToCCallbacks(long handle, int size); - static native void freeCFunctionBindings(long handle, int size); - static native void freeVirtualMethodBindings(long handle, int size); - - static native long createCallTempStruct(); - static native void deleteCallTempStruct(long handle); - - static native long mallocNulled(long size); - static native long mallocNulledAligned(long size, int alignment); - - static native long malloc(long size); - static native void free(long pointer); - static native long strlen(long pointer); - static native long wcslen(long pointer); - static native void memcpy(long dest, long source, long size); - static native void memmove(long dest, long source, long size); - static native long memchr(long ptr, byte value, long num); - static native long memmem(long haystack, long haystackLength, long needle, long needleLength); - static native long memmem_last(long haystack, long haystackLength, long needle, long needleLength); - static native int memcmp(long ptr1, long ptr2, long num); - static native void memset(long ptr, byte value, long num); -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/Pointer.java b/libraries/BridJ/src/main/velocity/org/bridj/Pointer.java deleted file mode 100644 index b9a30514b..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/Pointer.java +++ /dev/null @@ -1,3290 +0,0 @@ -package org.bridj; -import org.bridj.util.*; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.nio.*; -import java.lang.annotation.Annotation; -import java.util.*; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import static org.bridj.SizeT.safeIntCast; - -/** - * Pointer to a native memory location.
- * Pointer is the entry point of any pointer-related operation in BridJ. - *

- * Manipulating memory - *

- *

    - *
  • Wrapping a memory address as a pointer : {@link Pointer#pointerToAddress(long)} - *
  • - *
  • Reading / writing a primitive from / to the pointed memory location :
    -#foreach ($prim in $primitives) - * {@link Pointer#get${prim.CapName}()} / {@link Pointer#set${prim.CapName}(${prim.Name})}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#get${sizePrim}()} / {@link Pointer#set${sizePrim}(long)}
    -#end - *
  • - *
  • Reading / writing the nth contiguous primitive value from / to the pointed memory location :
    -#foreach ($prim in $primitives) - * {@link Pointer#get${prim.CapName}AtIndex(long)} / {@link Pointer#set${prim.CapName}AtIndex(long, ${prim.Name})}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#get${sizePrim}AtIndex(long)} / {@link Pointer#set${sizePrim}AtIndex(long, long)}
    -#end - *
  • - *
  • Reading / writing a primitive from / to the pointed memory location with a byte offset:
    -#foreach ($prim in $primitives) - * {@link Pointer#get${prim.CapName}AtOffset(long)} / {@link Pointer#set${prim.CapName}AtOffset(long, ${prim.Name})}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#get${sizePrim}AtOffset(long)} / {@link Pointer#set${sizePrim}AtOffset(long, long)}
    -#end - *
  • - *
  • Reading / writing an array of primitives from / to the pointed memory location :
    -#foreach ($prim in $primitives) - * {@link Pointer#get${prim.CapName}s(int)} / {@link Pointer#set${prim.CapName}s(${prim.Name}[])} ; With an offset : {@link Pointer#get${prim.CapName}sAtOffset(long, int)} / {@link Pointer#set${prim.CapName}sAtOffset(long, ${prim.Name}[])}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#get${sizePrim}s(int)} / {@link Pointer#set${sizePrim}s(long[])} ; With an offset : {@link Pointer#get${sizePrim}sAtOffset(long, int)} / {@link Pointer#set${sizePrim}sAtOffset(long, long[])}
    -#end - *
  • - *
  • Reading / writing an NIO buffer of primitives from / to the pointed memory location :
    -#foreach ($prim in $primitivesNoBool) -#if ($prim.Name != "char")* {@link Pointer#get${prim.BufferName}(long)} (can be used for writing as well) / {@link Pointer#set${prim.CapName}s(${prim.BufferName})}
    -#end -#end - *
  • - *
  • Reading / writing a String from / to the pointed memory location using the default charset :
    -#foreach ($string in ["C", "WideC"]) -* {@link Pointer#get${string}String()} / {@link Pointer#set${string}String(String)} ; With an offset : {@link Pointer#get${string}StringAtOffset(long)} / {@link Pointer#set${string}StringAtOffset(long, String)}
    -#end - *
  • - *
  • Reading / writing a String with control on the charset :
    - * {@link Pointer#getStringAtOffset(long, StringType, Charset)} / {@link Pointer#setStringAtOffset(long, String, StringType, Charset)}
    - *
- *

- * Allocating memory - *

- *

    - *
  • Getting the pointer to a struct / a C++ class / a COM object : - * {@link Pointer#pointerTo(NativeObject)} - *
  • - *
  • Allocating a dynamic callback (without a static {@link Callback} definition, which would be the preferred way) :
    - * {@link Pointer#allocateDynamicCallback(DynamicCallback, org.bridj.ann.Convention.Style, Type, Type[])} - *
  • - *
  • Allocating a primitive with / without an initial value (zero-initialized) :
    -#foreach ($prim in $primitives) - * {@link Pointer#pointerTo${prim.CapName}(${prim.Name})} / {@link Pointer#allocate${prim.CapName}()}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#pointerTo${sizePrim}(long)} / {@link Pointer#allocate${sizePrim}()}
    -#end - *
  • - *
  • Allocating an array of primitives with / without initial values (zero-initialized) :
    -#foreach ($prim in $primitivesNoBool) - * {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])} or {@link Pointer#pointerTo${prim.CapName}s(${prim.BufferName})} / {@link Pointer#allocate${prim.CapName}s(long)}
    -#end -#foreach ($sizePrim in ["SizeT", "CLong"]) - * {@link Pointer#pointerTo${sizePrim}s(long[])} / {@link Pointer#allocate${sizePrim}s(long)}
    -#end - * {@link Pointer#pointerToBuffer(Buffer)} / n/a
    - *
  • - *
  • Allocating a native String :
    -#foreach ($string in ["C", "WideC"]) -* {@link Pointer#pointerTo${string}String(String) } (default charset)
    -#end - * {@link Pointer#pointerToString(String, StringType, Charset) }
    - *
  • - *
  • Allocating a {@link ListType#Dynamic} Java {@link java.util.List} that uses native memory storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list):
    - * {@link Pointer#allocateList(Class, long) } - *
  • - *
  • Transforming a pointer to a Java {@link java.util.List} that uses the pointer as storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list, if it's {@link ListType#Dynamic}) :
    - * {@link Pointer#asList(ListType) }
    - * {@link Pointer#asList() }
    - *
  • - *
- *

- * Casting pointers - *

- *

    - *
  • Cast a pointer to a {@link DynamicFunction} :
    - * {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } - *
  • - *
  • Cast a pointer to a {@link StructObject} or a {@link Callback} (as the ones generated by JNAerator)
    : - * {@link Pointer#as(Class) } - *
  • - *
  • Cast a pointer to a complex type pointer (use {@link org.bridj.cpp.CPPType#getCPPType(Object[])} to create a C++ template type, for instance) :
    - * {@link Pointer#as(Type) } - *
  • - *
  • Get an untyped pointer :
    - * {@link Pointer#asUntyped() } - *
  • - *
- *

- * Dealing with pointer bounds - *

- *

    - *
  • Pointers to memory allocated through Pointer.pointerTo*, Pointer.allocate* have validity bounds that help prevent buffer overflows, at least when the Pointer API is used - *
  • - *
  • {@link Pointer#offset(long)}, {@link Pointer#next(long)} and other similar methods retain pointer bounds - *
  • - *
  • {@link Pointer#getValidBytes()} and {@link Pointer#getValidElements()} return the amount of valid memory readable from the pointer - *
  • - *
  • Bounds can be declared manually with {@link Pointer#validBytes(long)} (useful for memory allocated by native code) - *
  • - *
- */ -public abstract class Pointer implements Comparable>, Iterable -{ - -#macro (declareCheckedPeer $validityCheckLength) - long checkedPeer = peer; - if (validStart != UNKNOWN_VALIDITY) - checkPeer(checkedPeer, $validityCheckLength); -#end - -#macro (declareCheckedPeerAtOffset $byteOffset $validityCheckLength) - long checkedPeer = peer + $byteOffset; - if (validStart != UNKNOWN_VALIDITY) - checkPeer(checkedPeer, $validityCheckLength); -#end - - -#macro (docAllocateCopy $cPrimName $primWrapper) - /** - * Allocate enough memory for a single $cPrimName value, copy the value provided in argument into it and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * @param value initial value for the created memory location - * @return pointer to a new memory location that initially contains the $cPrimName value given in argument - */ -#end -#macro (docAllocateArrayCopy $cPrimName $primWrapper) - /** - * Allocate enough memory for values.length $cPrimName values, copy the values provided as argument into it and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon : -
{@code
-     for (float f : pointerTo(1f, 2f, 3.3f))
-     	System.out.println(f); }
- * @param values initial values for the created memory location - * @return pointer to a new memory location that initially contains the $cPrimName consecutive values provided in argument - */ -#end -#macro (docAllocateArray2DCopy $cPrimName $primWrapper) - /** - * Allocate enough memory for all the values in the 2D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.
- * Assumes that all of the subarrays of the provided array are non null and have the same size.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * @param values initial values for the created memory location - * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 2D C array would be - */ -#end -#macro (docAllocateArray3DCopy $cPrimName $primWrapper) - /** - * Allocate enough memory for all the values in the 3D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.
- * Assumes that all of the subarrays of the provided array are non null and have the same size.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * @param values initial values for the created memory location - * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 3D C array would be - */ -#end -#macro (docAllocate $cPrimName $primWrapper) - /** - * Allocate enough memory for a $cPrimName value and return a pointer to it.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * @return pointer to a single zero-initialized $cPrimName value - */ -#end -#macro (docAllocateArray $cPrimName $primWrapper) - /** - * Allocate enough memory for arrayLength $cPrimName values and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon. - * @return pointer to arrayLength zero-initialized $cPrimName consecutive values - */ -#end -#macro (docAllocateArray2D $cPrimName $primWrapper) - /** - * Allocate enough memory for dim1 * dim2 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * @return pointer to dim1 * dim2 zero-initialized $cPrimName consecutive values - */ -#end -#macro (docAllocateArray3D $cPrimName $primWrapper) - /** - * Allocate enough memory for dim1 * dim2 * dim3 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * @return pointer to dim1 * dim2 * dim3 zero-initialized $cPrimName consecutive values - */ -#end -#macro (docGet $cPrimName $primWrapper) - /** - * Read a $cPrimName value from the pointed memory location - */ -#end -#macro (docGetOffset $cPrimName $primWrapper $signatureWithoutOffset) - /** - * Read a $cPrimName value from the pointed memory location shifted by a byte offset - * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. - */ -#end -#macro (docGetIndex $typeName $equivalentOffsetCall) - /** - * Read the nth contiguous $typeName value from the pointed memory location.
- * Equivalent to ${equivalentOffsetCall}. - * @param valueIndex index of the value to read - */ -#end -#macro (docGetArray $cPrimName $primWrapper) - /** - * Read an array of $cPrimName values of the specified length from the pointed memory location - */ -#end -#macro (docGetRemainingArray $cPrimName $primWrapper) - /** - * Read the array of remaining $cPrimName values from the pointed memory location - */ -#end -#macro (docGetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) - /** - * Read an array of $cPrimName values of the specified length from the pointed memory location shifted by a byte offset - * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. - */ -#end -#macro (docSet $cPrimName $primWrapper) - /** - * Write a $cPrimName value to the pointed memory location - */ -#end -#macro (docSetOffset $cPrimName $primWrapper $signatureWithoutOffset) - /** - * Write a $cPrimName value to the pointed memory location shifted by a byte offset - * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. - */ -#end -#macro (docSetIndex $typeName $equivalentOffsetCall) - /** - * Write the nth contiguous $typeName value to the pointed memory location.
- * Equivalent to ${equivalentOffsetCall}. - * @param valueIndex index of the value to write - * @param value $typeName value to write - */ -#end -#macro (docSetArray $cPrimName $primWrapper) - /** - * Write an array of $cPrimName values to the pointed memory location - */ -#end -#macro (docSetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) - /** - * Write an array of $cPrimName values to the pointed memory location shifted by a byte offset - * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. - */ -#end - - /** The NULL pointer is always Java's null value */ - public static final Pointer NULL = null; - - /** - * Size of a pointer in bytes.
- * This is 4 bytes in a 32 bits environment and 8 bytes in a 64 bits environment.
- * Note that some 64 bits environments allow for 32 bits JVM execution (using the -d32 command line argument for Sun's JVM, for instance). In that case, Java programs will believe they're executed in a 32 bits environment. - */ - public static final int SIZE = Platform.POINTER_SIZE; - - static { - Platform.initLibrary(); - } - - - protected static long UNKNOWN_VALIDITY = -1; - protected static long NO_PARENT = 0/*-1*/; - - /** - * Default alignment used to allocate memory from the static factory methods in Pointer class (any value lower or equal to 1 means no alignment) - */ - public static final int defaultAlignment = Integer.parseInt(Platform.getenvOrProperty("BRIDJ_DEFAULT_ALIGNMENT", "bridj.defaultAlignment", "-1")); - - protected final PointerIO io; - protected final long peer, offsetInParent; - protected final Pointer parent; - protected volatile Object sibling; - protected final long validStart, validEnd; - - /** - * Object responsible for reclamation of some pointed memory when it's not used anymore. - */ - public interface Releaser { - void release(Pointer p); - } - - Pointer(PointerIO io, long peer, long validStart, long validEnd, Pointer parent, long offsetInParent, Object sibling) { - this.io = io; - this.peer = peer; - this.validStart = validStart; - this.validEnd = validEnd; - this.parent = parent; - this.offsetInParent = offsetInParent; - this.sibling = sibling; - if (peer == 0) - throw new IllegalArgumentException("Pointer instance cannot have NULL peer ! (use null Pointer instead)"); - if (BridJ.debugPointers) - creationTrace = new RuntimeException().fillInStackTrace(); - } - Throwable creationTrace; - -#foreach ($data in [ ["Ordered", true, ""], ["Disordered", false, "_disordered"] ]) -#set ($orderingPrefix = $data.get(0)) -#set ($ordered = $data.get(1)) -#set ($nativeSuffix = $data.get(2)) - - static class ${orderingPrefix}Pointer extends Pointer { - ${orderingPrefix}Pointer(PointerIO io, long peer, long validStart, long validEnd, Pointer parent, long offsetInParent, Object sibling) { - super(io, peer, validStart, validEnd, parent, offsetInParent, sibling); - } - - @Override - public boolean isOrdered() { - return $ordered; - } - -#foreach ($prim in $primitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - - @Override - public Pointer set${prim.CapName}(${prim.Name} value) { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return setInt((int)value); - #end - - #declareCheckedPeer(${primSize}) - #if ($prim.Name != "byte" && $prim.Name != "boolean") - JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); - #else - JNI.set_${prim.Name}(checkedPeer, value); - #end - return this; - } - - @Override - public Pointer set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value) { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return setIntAtOffset(byteOffset, (int)value); - #end - #declareCheckedPeerAtOffset("byteOffset" "${primSize}") - #if ($prim.Name != "byte" && $prim.Name != "boolean") - JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); - #else - JNI.set_${prim.Name}(checkedPeer, value); - #end - return this; - } - - @Override - public ${prim.Name} get${prim.CapName}() { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return (char)getInt(); - #end - #declareCheckedPeer(${primSize}) - #if ($prim.Name != "byte" && $prim.Name != "boolean") - return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); - #else - return JNI.get_${prim.Name}(checkedPeer); - #end - } - - @Override - public ${prim.Name} get${prim.CapName}AtOffset(long byteOffset) { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return (char)getIntAtOffset(byteOffset); - #end - #declareCheckedPeerAtOffset("byteOffset" "${primSize}") - #if ($prim.Name != "byte" && $prim.Name != "boolean") - return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); - #else - return JNI.get_${prim.Name}(checkedPeer); - #end - } -#end - - -#foreach ($sizePrim in ["SizeT", "CLong"]) - -#macro (setPrimitiveValue $primName $peer $value) - #if ($primName != "byte" && $primName != "boolean") - JNI.set_${primName}${nativeSuffix}($peer, $value); - #else - JNI.set_${primName}($peer, value); - #end -#end - - @Override - public Pointer set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length) { - if (values == null) - throw new IllegalArgumentException("Null values"); - if (${sizePrim}.SIZE == 8) { - setLongsAtOffset(byteOffset, values, valuesOffset, length); - } else { - int n = length; - #declareCheckedPeerAtOffset("byteOffset" "n * 4") - - long peer = checkedPeer; - int valuesIndex = valuesOffset; - for (int i = 0; i < n; i++) { - int value = (int)values[valuesIndex]; - #setPrimitiveValue("int" "peer" "value") - peer += 4; - valuesIndex++; - } - } - return this; - } -#docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") - public Pointer set${sizePrim}sAtOffset(long byteOffset, int[] values) { - if (${sizePrim}.SIZE == 4) { - setIntsAtOffset(byteOffset, values); - } else { - int n = values.length; - #declareCheckedPeerAtOffset("byteOffset" "n * 8") - - long peer = checkedPeer; - for (int i = 0; i < n; i++) { - int value = values[i]; - #setPrimitiveValue("long" "peer" "value") - peer += 8; - } - } - return this; - } -#end - } -#end - - /** - * Create a {@code Pointer} type.
- * For Instance, {@code Pointer.pointerType(Integer.class) } returns a type that represents {@code Pointer } - */ - public static Type pointerType(Type targetType) { - return org.bridj.util.DefaultParameterizedType.paramType(Pointer.class, targetType); - } - /** - * Create a {@code IntValuedEnum} type.
- * For Instance, {@code Pointer.intEnumType(SomeEnum.class) } returns a type that represents {@code IntValuedEnum } - */ - public static > Type intEnumType(Class> targetType) { - return org.bridj.util.DefaultParameterizedType.paramType(IntValuedEnum.class, targetType); - } - - /** - * Manually release the memory pointed by this pointer if it was allocated on the Java side.
- * If the pointer is an offset version of another pointer (using {@link Pointer#offset(long)} or {@link Pointer#next(long)}, for instance), this method tries to release the original pointer.
- * If the memory was not allocated from the Java side, this method does nothing either.
- * If the memory was already successfully released, this throws a RuntimeException. - * @throws RuntimeException if the pointer was already released - */ - public synchronized void release() { - Object sibling = this.sibling; - this.sibling = null; - if (sibling instanceof Pointer) - ((Pointer)sibling).release(); - } - - /** - * Compare to another pointer based on pointed addresses. - * @param p other pointer - * @return 1 if this pointer's address is greater than p's (or if p is null), -1 if the opposite is true, 0 if this and p point to the same memory location. - */ - //@Override - public int compareTo(Pointer p) { - if (p == null) - return 1; - - long p1 = getPeer(), p2 = p.getPeer(); - return p1 == p2 ? 0 : p1 < p2 ? -1 : 1; - } - - /** - * Compare the byteCount bytes at the memory location pointed by this pointer to the byteCount bytes at the memory location pointer by other using the C @see memcmp function.
- * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. - */ - public int compareBytes(Pointer other, long byteCount) { - return compareBytesAtOffset(0, other, 0, byteCount); - } - - /** - * Compare the byteCount bytes at the memory location pointed by this pointer shifted by byteOffset to the byteCount bytes at the memory location pointer by other shifted by otherByteOffset using the C @see memcmp function.
- * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues) - * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. - */ - public int compareBytesAtOffset(long byteOffset, Pointer other, long otherByteOffset, long byteCount) { - #declareCheckedPeerAtOffset("byteOffset" "byteCount") - return JNI.memcmp(checkedPeer, other.getCheckedPeer(otherByteOffset, byteCount), byteCount); - } - - /** - * Compute a hash code based on pointed address. - */ - @Override - public int hashCode() { - int hc = new Long(getPeer()).hashCode(); - return hc; - } - - @Override - public String toString() { - return "Pointer(peer = 0x" + Long.toHexString(getPeer()) + ", targetType = " + Utils.toString(getTargetType()) + ", order = " + order() + ")"; - } - - protected final void checkPeer(long peer, long validityCheckLength) { - if (peer < validStart || (peer + validityCheckLength) > validEnd) { - throw new IndexOutOfBoundsException("Cannot access to memory data of length " + validityCheckLength + " at offset " + (peer - getPeer()) + " : valid memory start is " + validStart + ", valid memory size is " + (validEnd - validStart)); - } - } - - private final long getCheckedPeer(long byteOffset, long validityCheckLength) { - #declareCheckedPeerAtOffset("byteOffset" "validityCheckLength") - return checkedPeer; - } - - /** - * Returns a pointer which address value was obtained by this pointer's by adding a byte offset.
- * The returned pointer will prevent the memory associated to this pointer from being automatically reclaimed as long as it lives, unless Pointer.release() is called on the originally-allocated pointer. - * @param byteOffset offset in bytes of the new pointer vs. this pointer. The expression {@code p.offset(byteOffset).getPeer() - p.getPeer() == byteOffset} is always true. - */ - public Pointer offset(long byteOffset) { - return offset(byteOffset, getIO()); - } - - Pointer offset(long byteOffset, PointerIO pio) { - if (byteOffset == 0) - return pio == this.io ? (Pointer)this : as(pio); - - long newPeer = getPeer() + byteOffset; - - Object newSibling = getSibling() != null ? getSibling() : this; - if (validStart == UNKNOWN_VALIDITY) - return newPointer(pio, newPeer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, newSibling); - if (newPeer > validEnd || newPeer < validStart) - throw new IndexOutOfBoundsException("Invalid pointer offset : " + byteOffset + " (validBytes = " + getValidBytes() + ") !"); - - return newPointer(pio, newPeer, isOrdered(), validStart, validEnd, null, NO_PARENT, null, newSibling); - } - - /** - * Creates a pointer that has the given number of valid bytes ahead.
- * If the pointer was already bound, the valid bytes must be lower or equal to the current getValidBytes() value. - */ - public Pointer validBytes(long byteCount) { - long peer = getPeer(); - long newValidEnd = peer + byteCount; - if (validStart == peer && validEnd == newValidEnd) - return this; - - if (validEnd != UNKNOWN_VALIDITY && newValidEnd > validEnd) - throw new IndexOutOfBoundsException("Cannot extend validity of pointed memory from " + validEnd + " to " + newValidEnd); - - Object newSibling = getSibling() != null ? getSibling() : this; - return newPointer(getIO(), peer, isOrdered(), validStart, newValidEnd, parent, offsetInParent, null, newSibling); - } - - /** - * Creates a pointer that forgot any memory validity information.
- * Such pointers are typically faster than validity-aware pointers, since they perform less checks at each operation, but they're more prone to crashes if misused. - * @deprecated Pointers obtained via this method are faster but unsafe and are likely to cause crashes hard to debug if your logic is wrong. - */ - @Deprecated - public Pointer withoutValidityInformation() { - long peer = getPeer(); - if (validStart == UNKNOWN_VALIDITY) - return this; - - Object newSibling = getSibling() != null ? getSibling() : this; - return newPointer(getIO(), peer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, parent, offsetInParent, null, newSibling); - } - - /** - * Creates a copy of the pointed memory location (allocates a new area of memory) and returns a pointer to it.
- * The pointer's bounds must be known (see {@link Pointer#getValidBytes()}, {@link Pointer#validBytes(long)} or {@link Pointer#validElements(long)}). - */ - public Pointer clone() { - long length = getValidElements(); - if (length < 0) - throw new UnsupportedOperationException("Number of bytes unknown, unable to clone memory (use validBytes(long))"); - - Pointer c = allocateArray(getIO(), length); - copyTo(c); - return c; - } - - /** - * Creates a pointer that has the given number of valid elements ahead.
- * If the pointer was already bound, elementCount must be lower or equal to the current getValidElements() value. - */ - public Pointer validElements(long elementCount) { - return validBytes(elementCount * getIO("Cannot define elements validity").getTargetSize()); - } - - /** - * Returns a pointer to this pointer.
- * It will only succeed if this pointer was dereferenced from another pointer.
- * Let's take the following C++ code : - *
{@code
-	int** pp = ...;
-	int* p = pp[10];
-	int** ref = &p;
-	ASSERT(pp == ref);
-	 }
- * Here is its equivalent Java code : - *
{@code
-	Pointer> pp = ...;
-	Pointer p = pp.get(10);
-	Pointer> ref = p.getReference();
-	assert pp.equals(ref);
-	 }
- */ - public Pointer> getReference() { - if (parent == null) - throw new UnsupportedOperationException("Cannot get reference to this pointer, it wasn't created from Pointer.getPointer(offset) or from a similar method."); - - PointerIO io = getIO(); - return parent.offset(offsetInParent).as(io == null ? null : io.getReferenceIO()); - } - - /** - * Get the address of the memory pointed to by this pointer ("cast this pointer to long", in C jargon).
- * This is equivalent to the C code {@code (size_t)&pointer} - * @return Address of the memory pointed to by this pointer - */ - public final long getPeer() { - return peer; - } - - /** - * Create a native callback which signature corresponds to the provided calling convention, return type and parameter types, and which redirects calls to the provided Java {@link org.bridj.DynamicCallback} handler.
- * For instance, a callback of C signature double (*)(float, int) that adds its two arguments can be created with :
- * {@code - * Pointer callback = Pointer.allocateDynamicCallback( - * new DynamicCallback() { - * public Double apply(Object... args) { - * float a = (Float)args[0]; - * int b = (Integer)args[1]; - * return (double)(a + b); - * } - * }, - * null, // Use the platform's default calling convention - * int.class, // return type - * float.class, double.class // parameter types - * ); - * }
- * For the void return type, you can use {@link java.lang.Void} :
- * {@code - * Pointer callback = Pointer.allocateDynamicCallback( - * new DynamicCallback() { - * public Void apply(Object... args) { - * ... - * return null; // Void cannot be instantiated anyway ;-) - * } - * }, - * null, // Use the platform's default calling convention - * int.class, // return type - * float.class, double.class // parameter types - * ); - * }
- * @return Pointer to a native callback that redirects calls to the provided Java callback instance, and that will be destroyed whenever the pointer is released (make sure you keep a reference to it !) - */ - public static Pointer> allocateDynamicCallback(DynamicCallback callback, org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { - if (callback == null) - throw new IllegalArgumentException("Java callback handler cannot be null !"); - if (returnType == null) - throw new IllegalArgumentException("Callback return type cannot be null !"); - if (parameterTypes == null) - throw new IllegalArgumentException("Invalid (null) list of parameter types !"); - try { - MethodCallInfo mci = new MethodCallInfo(returnType, parameterTypes, false); - Method method = DynamicCallback.class.getMethod("apply", Object[].class); - mci.setMethod(method); - mci.setJavaSignature("([Ljava/lang/Object;)Ljava/lang/Object;"); - mci.setCallingConvention(callingConvention); - mci.setGenericCallback(true); - mci.setJavaCallback(callback); - - //System.out.println("Java sig - - return CRuntime.createCToJavaCallback(mci, DynamicCallback.class); - } catch (Exception ex) { - throw new RuntimeException("Failed to allocate dynamic callback for convention " + callingConvention + ", return type " + Utils.toString(returnType) + " and parameter types " + Arrays.asList(parameterTypes) + " : " + ex, ex); - } - } - - /** - * Cast this pointer to another pointer type - * @param newIO - */ - public Pointer as(PointerIO newIO) { - return viewAs(isOrdered(), newIO); - } - /** - * Create a view of this pointer that has the byte order provided in argument, or return this if this pointer already uses the requested byte order. - * @param order byte order (endianness) of the returned pointer - */ - public Pointer order(ByteOrder order) { - if (order.equals(ByteOrder.nativeOrder()) == isOrdered()) - return this; - - return viewAs(!isOrdered(), getIO()); - } - - /** - * Get the byte order (endianness) of this pointer. - */ - public ByteOrder order() { - ByteOrder order = isOrdered() ? ByteOrder.nativeOrder() : ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - return order; - } - - Pointer viewAs(boolean ordered, PointerIO newIO) { - if (newIO == io && ordered == isOrdered()) - return (Pointer)this; - else - return newPointer(newIO, getPeer(), ordered, getValidStart(), getValidEnd(), getParent(), getOffsetInParent(), null, getSibling() != null ? getSibling() : this); - } - - /** - * Get the PointerIO instance used by this pointer to get and set pointed values. - */ - public final PointerIO getIO() { - return io; - } - - /** - * Whether this pointer reads data in the system's native byte order or not. - * See {@link Pointer#order()}, {@link Pointer#order(ByteOrder)} - */ - public abstract boolean isOrdered(); - - final long getOffsetInParent() { - return offsetInParent; - } - final Pointer getParent() { - return parent; - } - final Object getSibling() { - return sibling; - } - - final long getValidEnd() { - return validEnd; - } - final long getValidStart() { - return validStart; - } - - /** - * Cast this pointer to another pointer type
- * Synonym of {@link Pointer#as(Class)}
- * The following C code :
- * {@code - * T* pointerT = ...; - * U* pointerU = (U*)pointerT; - * }
- * Can be translated to the following Java code :
- * {@code - * Pointer pointerT = ...; - * Pointer pointerU = pointerT.as(U.class); - * }
- * @param type of the elements pointed by the returned pointer - * @param type type of the elements pointed by the returned pointer - * @return pointer to type U elements at the same address as this pointer - */ - public Pointer as(Type type) { - PointerIO pio = PointerIO.getInstance(type); - return as(pio); - } - - /** - * Cast this pointer to another pointer type.
- * Synonym of {@link Pointer#as(Type)}
- * The following C code :
- * {@code - * T* pointerT = ...; - * U* pointerU = (U*)pointerT; - * }
- * Can be translated to the following Java code :
- * {@code - * Pointer pointerT = ...; - * Pointer pointerU = pointerT.as(U.class); // or pointerT.as(U.class); - * }
- * @param type of the elements pointed by the returned pointer - * @param type type of the elements pointed by the returned pointer - * @return pointer to type U elements at the same address as this pointer - */ - public Pointer as(Class type) { - return as((Type)type); - } - - /** - * Cast this pointer as a function pointer to a function that returns the specified return type and takes the specified parameter types.
- * See for instance the following C code that uses a function pointer : - *
{@code
-     *	  double (*ptr)(int, const char*) = someAddress;
-     *    double result = ptr(10, "hello");
-     * }
- * Its Java equivalent with BridJ is the following : - *
{@code
-     *	  DynamicFunction ptr = someAddress.asDynamicFunction(null, double.class, int.class, Pointer.class);
-     *    double result = (Double)ptr.apply(10, pointerToCString("hello"));
-     * }
- * Also see {@link CRuntime#getDynamicFunctionFactory(org.bridj.NativeLibrary, org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } for more options. - * @param callingConvention calling convention used by the function (if null, default is typically {@link org.bridj.ann.Convention.Style#CDecl}) - * @param returnType return type of the function - * @param parameterTypes parameter types of the function - */ - public DynamicFunction asDynamicFunction(org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { - return CRuntime.getInstance().getDynamicFunctionFactory(null, callingConvention, returnType, parameterTypes).newInstance(this); - } - - /** - * Cast this pointer to an untyped pointer.
- * Synonym of {@code ptr.as((Class)null)}.
- * See {@link Pointer#as(Class)}
- * The following C code :
- * {@code - * T* pointerT = ...; - * void* pointer = (void*)pointerT; - * }
- * Can be translated to the following Java code :
- * {@code - * Pointer pointerT = ...; - * Pointer pointer = pointerT.asUntyped(); // or pointerT.as((Class)null); - * }
- * @return untyped pointer pointing to the same address as this pointer - */ - public Pointer asUntyped() { - return as((Class)null); - } - - /** - * Get the amount of memory known to be valid from this pointer, or -1 if it is unknown.
- * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) - * @return amount of bytes that can be safely read or written from this pointer, or -1 if this amount is unknown - */ - public long getValidBytes() { - long ve = getValidEnd(); - return ve == UNKNOWN_VALIDITY ? -1 : ve - getPeer(); - } - - /** - * Get the amount of memory known to be valid from this pointer (expressed in elements of the target type, see {@link Pointer#getTargetType()}) or -1 if it is unknown.
- * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) - * @return amount of elements that can be safely read or written from this pointer, or -1 if this amount is unknown - */ - public long getValidElements() { - long bytes = getValidBytes(); - long elementSize = getTargetSize(); - if (bytes < 0 || elementSize <= 0) - return -1; - return bytes / elementSize; - } - - /** - * Returns an iterator over the elements pointed by this pointer.
- * If this pointer was allocated from Java with the allocateXXX, pointerToXXX methods (or is a view or a clone of such a pointer), the iteration is safely bounded.
- * If this iterator is just a wrapper for a native-allocated pointer (or a view / clone of such a pointer), iteration will go forever (until illegal areas of memory are reached and cause a JVM crash). - */ - public ListIterator iterator() { - return new ListIterator() { - Pointer next = Pointer.this.getValidElements() != 0 ? Pointer.this : null; - Pointer previous; - //@Override - public T next() { - if (next == null) - throw new NoSuchElementException(); - T value = next.get(); - previous = next; - long valid = next.getValidElements(); - next = valid < 0 || valid > 1 ? next.next(1) : null; - return value; - } - //@Override - public void remove() { - throw new UnsupportedOperationException(); - } - //@Override - public boolean hasNext() { - long rem; - return next != null && ((rem = next.getValidBytes()) < 0 || rem > 0); - } - //@Override - public void add(T o) { - throw new UnsupportedOperationException(); - } - //@Override - public boolean hasPrevious() { - return previous != null; - } - //@Override - public int nextIndex() { - throw new UnsupportedOperationException(); - } - //@Override - public T previous() { - //TODO return previous; - throw new UnsupportedOperationException(); - } - //@Override - public int previousIndex() { - throw new UnsupportedOperationException(); - } - //@Override - public void set(T o) { - if (previous == null) - throw new NoSuchElementException("You haven't called next() prior to calling ListIterator.set(E)"); - previous.set(o); - } - }; - } - - - /** - * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) - */ - public static Pointer pointerTo(N instance) { - return pointerTo(instance, null); - } - /** - * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) - */ - public static Pointer pointerTo(N instance) { - return (Pointer)pointerTo((NativeObject)instance); - } - - /** - * Get a pointer to a native object, specifying the type of the pointer's target.
- * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. - */ - public static Pointer pointerTo(NativeObject instance, Type targetType) { - return instance == null ? null : (Pointer)instance.peer; - } - /** - * Get the address of a native object, specifying the type of the pointer's target (same as {@code pointerTo(instance, targetType).getPeer()}, see {@link Pointer#pointerTo(NativeObject, Type)}).
- * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. - */ - public static long getAddress(NativeObject instance, Class targetType) { - return getPeer(pointerTo(instance, targetType)); - } - -#docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Type)") - public O getNativeObjectAtOffset(long byteOffset, Type type) { - return (O)BridJ.createNativeObjectFromPointer((Pointer)(byteOffset == 0 ? this : offset(byteOffset)), type); - } -#docSet("native object", "O extends NativeObject") - public Pointer setNativeObject(O value, Type type) { - BridJ.copyNativeObjectToAddress(value, type, (Pointer)this); - return this; - } -#docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Class)") - public O getNativeObjectAtOffset(long byteOffset, Class type) { - return (O)getNativeObjectAtOffset(byteOffset, (Type)type); - } -#docGet("native object", "O extends NativeObject") - public O getNativeObject(Class type) { - return (O)getNativeObject((Type)type); - } -#docGet("native object", "O extends NativeObject") - public O getNativeObject(Type type) { - O o = (O)getNativeObjectAtOffset(0, type); - return o; - } - - /** - * Check that the pointer's peer is aligned to the target type alignment. - * @throws RuntimeException If the target type of this pointer is unknown - * @return getPeer() % alignment == 0 - */ - public boolean isAligned() { - return isAligned(getIO("Cannot check alignment").getTargetAlignment()); - } - - /** - * Check that the pointer's peer is aligned to the given alignment. - * If the pointer has no peer, this method returns true. - * @return getPeer() % alignment == 0 - */ - public boolean isAligned(long alignment) { - return isAligned(getPeer(), alignment); - } - - /** - * Check that the provided address is aligned to the given alignment. - * @return address % alignment == 0 - */ - protected static boolean isAligned(long address, long alignment) { - return computeRemainder(address, alignment) == 0; - } - - protected static int computeRemainder(long address, long alignment) { - switch ((int)alignment) { - case -1: - case 0: - case 1: - return 0; - case 2: - return (int)(address & 1); - case 4: - return (int)(address & 3); - case 8: - return (int)(address & 7); - case 16: - return (int)(address & 15); - case 32: - return (int)(address & 31); - case 64: - return (int)(address & 63); - default: - if (alignment < 0) - return 0; - return (int)(address % alignment); - } - } - - /** - * Dereference this pointer (*ptr).
- Take the following C++ code fragment : -
{@code
-     int* array = new int[10];
-     for (int index = 0; index < 10; index++, array++) 
-     	printf("%i\n", *array);
-     }
- Here is its equivalent in Java : -
{@code
-     import static org.bridj.Pointer.*;
-     ...
-     Pointer array = allocateInts(10);
-     for (int index = 0; index < 10; index++) { 
-     	System.out.println("%i\n".format(array.get()));
-     	array = array.next();
-	 }
-     }
- Here is a simpler equivalent in Java : -
{@code
-     import static org.bridj.Pointer.*;
-     ...
-     Pointer array = allocateInts(10);
-     for (int value : array) // array knows its size, so we can iterate on it
-     	System.out.println("%i\n".format(value));
-     }
- @throws RuntimeException if called on an untyped {@code Pointer} instance (see {@link Pointer#getTargetType()}) - */ - public T get() { - return get(0); - } - - /** - * Returns null if pointer is null, otherwise dereferences the pointer (calls pointer.get()). - */ - public static T get(Pointer pointer) { - return pointer == null ? null : pointer.get(); - } - - /** - Gets the n-th element from this pointer.
- This is equivalent to the C/C++ square bracket syntax.
- Take the following C++ code fragment : -
{@code
-	int* array = new int[10];
-	int index = 5;
-	int value = array[index];
-     }
- Here is its equivalent in Java : -
{@code
-	import static org.bridj.Pointer.*;
-	...
-	Pointer array = allocateInts(10);
-	int index = 5;
-	int value = array.get(index);
-     }
- @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. - @throws RuntimeException if called on an untyped {@code Pointer} instance ({@link Pointer#getTargetType()}) - */ - public T get(long index) { - return getIO("Cannot get pointed value").get(this, index); - } - - /** - Assign a value to the pointed memory location, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).
- Take the following C++ code fragment : -
{@code
-	int* array = new int[10];
-	for (int index = 0; index < 10; index++, array++) { 
-		int value = index;
-		*array = value;
-	}
-     }
- Here is its equivalent in Java : -
{@code
-	import static org.bridj.Pointer.*;
-	...
-	Pointer array = allocateInts(10);
-	for (int index = 0; index < 10; index++) {
-		int value = index;
-		array.set(value);
-		array = array.next();
-	}
-     }
- @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) - @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) - */ - public T set(T value) { - return set(0, value); - } - - private static long getTargetSizeToAllocateArrayOrThrow(PointerIO io) { - long targetSize = -1; - if (io == null || (targetSize = io.getTargetSize()) < 0) - throwBecauseUntyped("Cannot allocate array "); - return targetSize; - } - - private static void throwBecauseUntyped(String message) { - throw new RuntimeException("Pointer is not typed (call Pointer.as(Type) to create a typed pointer) : " + message); - } - static void throwUnexpected(Throwable ex) { - throw new RuntimeException("Unexpected error", ex); - } - /** - Sets the n-th element from this pointer, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).
- This is equivalent to the C/C++ square bracket assignment syntax.
- Take the following C++ code fragment : -
{@code
-     float* array = new float[10];
-     int index = 5;
-     float value = 12;
-     array[index] = value;
-     }
- Here is its equivalent in Java : -
{@code
-     import static org.bridj.Pointer.*;
-     ...
-     Pointer array = allocateFloats(10);
-     int index = 5;
-     float value = 12;
-     array.set(index, value);
-     }
- @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. - @param value value to set at pointed memory location - @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) - @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) - */ - public T set(long index, T value) { - getIO("Cannot set pointed value").set(this, index, value); - return value; - } - - /** - * Get a pointer's peer (see {@link Pointer#getPeer}), or zero if the pointer is null. - */ - public static long getPeer(Pointer pointer) { - return pointer == null ? 0 : pointer.getPeer(); - } - - /** - * Get the unitary size of the pointed elements in bytes. - * @throws RuntimeException if the target type is unknown (see {@link Pointer#getTargetType()}) - */ - public long getTargetSize() { - return getIO("Cannot compute target size").getTargetSize(); - } - - /** - * Returns a pointer to the next target. - * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. - * @return next(1) - */ - public Pointer next() { - return next(1); - } - - /** - * Returns a pointer to the n-th next (or previous) target. - * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. - * @return offset(getTargetSize() * delta) - */ - public Pointer next(long delta) { - return offset(getIO("Cannot get pointers to next or previous targets").getTargetSize() * delta); - } - - /** - * Release pointers, if they're not null (see {@link Pointer#release}). - */ - public static void release(Pointer... pointers) { - for (Pointer pointer : pointers) - if (pointer != null) - pointer.release(); - } - - /** - * Test equality of the pointer using the address.
- * @return true if and only if obj is a Pointer instance and {@code obj.getPeer() == this.getPeer() } - */ - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Pointer)) - return false; - - Pointer p = (Pointer)obj; - return getPeer() == p.getPeer(); - } - - /** - * Create a pointer out of a native memory address - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == address } - */ - @Deprecated - public static Pointer pointerToAddress(long peer) { - return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); - } - - /** - * Create a pointer out of a native memory address - * @param size number of bytes known to be readable at the pointed address - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - @Deprecated - public static Pointer pointerToAddress(long peer, long size) { - return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, null, null); - } - - /** - * Create a pointer out of a native memory address - * @param targetClass type of the elements pointed by the resulting pointer - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - public static

Pointer

pointerToAddress(long peer, Class

targetClass, final Releaser releaser) { - return pointerToAddress(peer, (Type)targetClass, releaser); - } - /** - * Create a pointer out of a native memory address - * @param targetType type of the elements pointed by the resulting pointer - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - public static

Pointer

pointerToAddress(long peer, Type targetType, final Releaser releaser) { - PointerIO

pio = PointerIO.getInstance(targetType); - return newPointer(pio, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, releaser, null); - } - /** - * Create a pointer out of a native memory address - * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - public static

Pointer

pointerToAddress(long peer, PointerIO

io) { - return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); - } - /** - * Create a pointer out of a native memory address - * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - static

Pointer

pointerToAddress(long peer, PointerIO

io, Releaser releaser) { - return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); - } - - /** - * Create a pointer out of a native memory address - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - @Deprecated - public static Pointer pointerToAddress(long peer, Releaser releaser) { - return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); - } - - /** - * Create a pointer out of a native memory address - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param size number of bytes known to be readable at the pointed address - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - public static Pointer pointerToAddress(long peer, long size, Releaser releaser) { - return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); - } - - /** - * Create a pointer out of a native memory address - * @param targetClass type of the elements pointed by the resulting pointer - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - @Deprecated - public static

Pointer

pointerToAddress(long peer, Class

targetClass) { - return pointerToAddress(peer, (Type)targetClass); - } - - /** - * Create a pointer out of a native memory address - * @param targetType type of the elements pointed by the resulting pointer - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - @Deprecated - public static

Pointer

pointerToAddress(long peer, Type targetType) { - return newPointer((PointerIO

)PointerIO.getInstance(targetType), peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, null, null); - } - - /** - * Create a pointer out of a native memory address - * @param size number of bytes known to be readable at the pointed address - * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - static Pointer pointerToAddress(long peer, long size, PointerIO io) { - return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, null, null); - } - - /** - * Create a pointer out of a native memory address - * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected - * @param peer native memory address that is to be converted to a pointer - * @return a pointer with the provided address : {@code pointer.getPeer() == peer } - */ - static Pointer newPointer( - PointerIO io, - long peer, - boolean ordered, - long validStart, - long validEnd, - Pointer parent, - long offsetInParent, - final Releaser releaser, - Object sibling) - { - if (peer == 0) - return null; - - if (validEnd != UNKNOWN_VALIDITY) { - long size = validEnd - validStart; - if (size <= 0) - return null; - } - - if (releaser == null) { - if (ordered) { - return new OrderedPointer(io, peer, validStart, validEnd, parent, offsetInParent, sibling); - } else { - return new DisorderedPointer(io, peer, validStart, validEnd, parent, offsetInParent, sibling); - } - } else { - assert sibling == null; -#macro (bodyOfPointerWithReleaser) - private volatile Releaser rel = releaser; - //@Override - public synchronized void release() { - if (rel != null) { - Releaser rel = this.rel; - this.rel = null; - rel.release(this); - } - } - protected void finalize() { - release(); - } - - @Deprecated - public synchronized Pointer withReleaser(final Releaser beforeDeallocation) { - final Releaser thisReleaser = rel; - rel = null; - return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation == null ? thisReleaser : new Releaser() { - //@Override - public void release(Pointer p) { - beforeDeallocation.release(p); - if (thisReleaser != null) - thisReleaser.release(p); - } - }, null); - } -#end - if (ordered) { - return new OrderedPointer(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { - #bodyOfPointerWithReleaser() - }; - } else { - return new DisorderedPointer(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { - #bodyOfPointerWithReleaser() - }; - } - } - } - -#docAllocate("typed pointer", "P extends TypedPointer") - public static

Pointer

allocateTypedPointer(Class

type) { - return (Pointer

)(Pointer)allocate(PointerIO.getInstance(type)); - } -#docAllocateArray("typed pointer", "P extends TypedPointer") - public static

Pointer

allocateTypedPointers(Class

type, long arrayLength) { - return (Pointer

)(Pointer)allocateArray(PointerIO.getInstance(type), arrayLength); - } - /** - * Create a memory area large enough to hold a pointer. - * @param targetType target type of the pointer values to be stored in the allocated memory - * @return a pointer to a new memory area large enough to hold a single typed pointer - */ - public static

Pointer> allocatePointer(Class

targetType) { - return allocatePointer((Type)targetType); - } - /** - * Create a memory area large enough to hold a pointer. - * @param targetType target type of the pointer values to be stored in the allocated memory - * @return a pointer to a new memory area large enough to hold a single typed pointer - */ - public static

Pointer> allocatePointer(Type targetType) { - return (Pointer>)(Pointer)allocate(PointerIO.getPointerInstance(targetType)); - } - /** - * Create a memory area large enough to hold a pointer to a pointer - * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory - * @return a pointer to a new memory area large enough to hold a single typed pointer - */ - public static

Pointer>> allocatePointerPointer(Type targetType) { - return allocatePointer(pointerType(targetType)); - }/** - * Create a memory area large enough to hold a pointer to a pointer - * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory - * @return a pointer to a new memory area large enough to hold a single typed pointer - */ - public static

Pointer>> allocatePointerPointer(Class

targetType) { - return allocatePointerPointer((Type)targetType); - } -#docAllocate("untyped pointer", "Pointer") - /** - * Create a memory area large enough to hold an untyped pointer. - * @return a pointer to a new memory area large enough to hold a single untyped pointer - */ - public static Pointer> allocatePointer() { - return (Pointer)allocate(PointerIO.getPointerInstance()); - } -#docAllocateArray("untyped pointer", "Pointer") - public static Pointer> allocatePointers(int arrayLength) { - return (Pointer>)(Pointer)allocateArray(PointerIO.getPointerInstance(), arrayLength); - } - - /** - * Create a memory area large enough to hold an array of arrayLength typed pointers. - * @param targetType target type of element pointers in the resulting pointer array. - * @param arrayLength size of the allocated array, in elements - * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers - */ - public static

Pointer> allocatePointers(Class

targetType, int arrayLength) { - return allocatePointers((Type)targetType, arrayLength); - } - - /** - * Create a memory area large enough to hold an array of arrayLength typed pointers. - * @param targetType target type of element pointers in the resulting pointer array. - * @param arrayLength size of the allocated array, in elements - * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers - */ - public static

Pointer> allocatePointers(Type targetType, int arrayLength) { - return (Pointer>)(Pointer)allocateArray(PointerIO.getPointerInstance(targetType), arrayLength); // TODO - } - - - /** - * Create a memory area large enough to a single items of type elementClass. - * @param elementClass type of the array elements - * @return a pointer to a new memory area large enough to hold a single item of type elementClass. - */ - public static Pointer allocate(Class elementClass) { - return allocate((Type)elementClass); - } - - /** - * Create a memory area large enough to a single items of type elementClass. - * @param elementClass type of the array elements - * @return a pointer to a new memory area large enough to hold a single item of type elementClass. - */ - public static Pointer allocate(Type elementClass) { - return allocateArray(elementClass, 1); - } - - /** - * Create a memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - * @param io PointerIO instance able to store and retrieve the element - * @return a pointer to a new memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - */ - public static Pointer allocate(PointerIO io) { - return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io), null); - } - /** - * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - * @param io PointerIO instance able to store and retrieve elements of the array - * @param arrayLength length of the array in elements - * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - */ - public static Pointer allocateArray(PointerIO io, long arrayLength) { - return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, null); - } - /** - * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - * @param io PointerIO instance able to store and retrieve elements of the array - * @param arrayLength length of the array in elements - * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor - * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - */ - public static Pointer allocateArray(PointerIO io, long arrayLength, final Releaser beforeDeallocation) { - return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, beforeDeallocation); - } - /** - * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) - * @param io PointerIO instance able to store and retrieve elements of the array - * @param byteSize length of the array in bytes - * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor - * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes - */ - public static Pointer allocateBytes(PointerIO io, long byteSize, final Releaser beforeDeallocation) { - return allocateAlignedBytes(io, byteSize, defaultAlignment, beforeDeallocation); - } - - /** - * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}), ensuring the pointer to the memory is aligned to the provided boundary. - * @param io PointerIO instance able to store and retrieve elements of the array - * @param byteSize length of the array in bytes - * @param alignment boundary to which the returned pointer should be aligned - * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor - * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes - */ - public static Pointer allocateAlignedBytes(PointerIO io, long byteSize, int alignment, final Releaser beforeDeallocation) { - if (byteSize == 0) - return null; - if (byteSize < 0) - throw new IllegalArgumentException("Cannot allocate a negative amount of memory !"); - - long address, offset = 0; - if (alignment <= 1) - address = JNI.mallocNulled(byteSize); - else { - //address = JNI.mallocNulledAligned(byteSize, alignment); - //if (address == 0) - { - // invalid alignment (< sizeof(void*) or not a power of 2 - address = JNI.mallocNulled(byteSize + alignment - 1); - long remainder = address % alignment; - if (remainder > 0) - offset = alignment - remainder; - } - } - - if (address == 0) - throw new RuntimeException("Failed to allocate " + byteSize); - - Pointer ptr = newPointer(io, address, true, address, address + byteSize + offset, null, NO_PARENT, beforeDeallocation == null ? freeReleaser : new Releaser() { - //@Override - public void release(Pointer p) { - beforeDeallocation.release(p); - freeReleaser.release(p); - } - }, null); - - if (offset > 0) - ptr = ptr.offset(offset); - - return ptr; - } - - /** - * Create a pointer that depends on this pointer and will call a releaser prior to release this pointer, when it is GC'd.
- * This pointer MUST NOT be used anymore. - * @deprecated This method can easily be misused and is reserved to advanced users. - * @param beforeDeallocation releaser that should be run before this pointer's releaser (if any). - * @return a new pointer to the same memory location as this pointer - */ - @Deprecated - public synchronized Pointer withReleaser(final Releaser beforeDeallocation) { - return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation, null); - } - static Releaser freeReleaser = new FreeReleaser(); - static class FreeReleaser implements Releaser { - //@Override - public void release(Pointer p) { - assert p.getSibling() == null; - assert p.validStart == p.getPeer(); - - if (BridJ.debugPointers) - BridJ.info("Freeing pointer " + p + "\n(Creation trace = \n\t" + Utils.toString(p.creationTrace).replaceAll("\n", "\n\t") + "\n)", new RuntimeException().fillInStackTrace()); - - if (!BridJ.debugNeverFree) - JNI.free(p.getPeer()); - } - } - - /** - * Create a memory area large enough to hold arrayLength items of type elementClass. - * @param elementClass type of the array elements - * @param arrayLength length of the array in elements - * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. - */ - public static Pointer allocateArray(Class elementClass, long arrayLength) { - return allocateArray((Type)elementClass, arrayLength); - } - /** - * Create a memory area large enough to hold arrayLength items of type elementClass. - * @param elementClass type of the array elements - * @param arrayLength length of the array in elements - * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. - */ - public static Pointer allocateArray(Type elementClass, long arrayLength) { - if (arrayLength == 0) - return null; - - PointerIO pio = PointerIO.getInstance(elementClass); - if (pio == null) - throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); - return (Pointer)allocateArray(pio, arrayLength); - } - - - /** - * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. - * @param elementClass type of the array elements - * @param arrayLength length of the array in elements - * @param alignment boundary to which the returned pointer should be aligned - * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. - */ - public static Pointer allocateAlignedArray(Class elementClass, long arrayLength, int alignment) { - return allocateAlignedArray((Type)elementClass, arrayLength, alignment); - } - - /** - * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. - * @param elementClass type of the array elements - * @param arrayLength length of the array in elements - * @param alignment boundary to which the returned pointer should be aligned - * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. - */ - public static Pointer allocateAlignedArray(Type elementClass, long arrayLength, int alignment) { - PointerIO io = PointerIO.getInstance(elementClass); - if (io == null) - throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); - return allocateAlignedBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, alignment, null); - } - - /** - * Create a pointer to the memory location used by a direct NIO buffer.
- * If the NIO buffer is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerToArray(Object)}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.
- * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer. - */ - public static Pointer pointerToBuffer(Buffer buffer) { - if (buffer == null) - return null; - - #foreach ($prim in $primitivesNoBool) - if (buffer instanceof ${prim.BufferName}) - return (Pointer)pointerTo${prim.CapName}s((${prim.BufferName})buffer); - #end - throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); - } - - /** - * When a pointer was created with {@link Pointer#pointerToBuffer(Buffer)} on a non-direct buffer, a native copy of the buffer data was made. - * This method updates the original buffer with the native memory, and does nothing if the buffer is direct and points to the same memory location as this pointer.
- * @throws IllegalArgumentException if buffer is direct and does not point to the exact same location as this Pointer instance - */ - public void updateBuffer(Buffer buffer) { - if (buffer == null) - throw new IllegalArgumentException("Cannot update a null Buffer !"); - - if (Utils.isDirect(buffer)) { - long address = JNI.getDirectBufferAddress(buffer); - if (address != getPeer()) { - throw new IllegalArgumentException("Direct buffer does not point to the same location as this Pointer instance, updating it makes no sense !"); - } - } else { - #foreach ($prim in $primitivesNoBool) - #if ($prim.Name != "char") - if (buffer instanceof ${prim.BufferName}) { - ((${prim.BufferName})buffer).duplicate().put(get${prim.BufferName}()); - return; - } - #end - #end - throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); - } - } - -#foreach ($prim in $primitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - -//-- primitive: $prim.Name -- - - #docAllocateCopy($prim.Name $prim.WrapperName) - public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}(${prim.Name} value) { - Pointer<${prim.WrapperName}> mem = allocate(PointerIO.get${prim.CapName}Instance()); - mem.set${prim.CapName}(value); - return mem; - } - -#docAllocateArrayCopy($prim.Name $prim.WrapperName) - public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.Name}... values) { - if (values == null) - return null; - Pointer<${prim.WrapperName}> mem = allocateArray(PointerIO.get${prim.CapName}Instance(), values.length); - mem.set${prim.CapName}sAtOffset(0, values, 0, values.length); - return mem; - } - - #docAllocateArray2DCopy($prim.Name $prim.WrapperName) - public static Pointer> pointerTo${prim.CapName}s(${prim.Name}[][] values) { - if (values == null) - return null; - int dim1 = values.length, dim2 = values[0].length; - Pointer> mem = allocate${prim.CapName}s(dim1, dim2); - for (int i1 = 0; i1 < dim1; i1++) - mem.set${prim.CapName}sAtOffset(i1 * dim2 * ${primSize}, values[i1], 0, dim2); - return mem; - } - - #docAllocateArray3DCopy($prim.Name $prim.WrapperName) - public static Pointer>> pointerTo${prim.CapName}s(${prim.Name}[][][] values) { - if (values == null) - return null; - int dim1 = values.length, dim2 = values[0].length, dim3 = values[0][0].length; - Pointer>> mem = allocate${prim.CapName}s(dim1, dim2, dim3); - for (int i1 = 0; i1 < dim1; i1++) { - int offset1 = i1 * dim2; - for (int i2 = 0; i2 < dim2; i2++) { - int offset2 = (offset1 + i2) * dim3; - mem.set${prim.CapName}sAtOffset(offset2 * ${primSize}, values[i1][i2], 0, dim3); - } - } - return mem; - } - - #docAllocate($prim.Name $prim.WrapperName) - public static Pointer<${prim.WrapperName}> allocate${prim.CapName}() { - return allocate(PointerIO.get${prim.CapName}Instance()); - } - #docAllocateArray($prim.Name $prim.WrapperName) - public static Pointer<${prim.WrapperName}> allocate${prim.CapName}s(long arrayLength) { - return allocateArray(PointerIO.get${prim.CapName}Instance(), arrayLength); - } - - #docAllocateArray2D($prim.Name $prim.WrapperName) - public static Pointer> allocate${prim.CapName}s(long dim1, long dim2) { - return allocateArray(PointerIO.getArrayInstance(PointerIO.get${prim.CapName}Instance(), new long[] { dim1, dim2 }, 0), dim1); - - } - #docAllocateArray3D($prim.Name $prim.WrapperName) - public static Pointer>> allocate${prim.CapName}s(long dim1, long dim2, long dim3) { - long[] dims = new long[] { dim1, dim2, dim3 }; - return - allocateArray( - PointerIO.getArrayInstance( - //PointerIO.get${prim.CapName}Instance(), - PointerIO.getArrayInstance( - PointerIO.get${prim.CapName}Instance(), - dims, - 1 - ), - dims, - 0 - ), - dim1 - ) - ; - } - -#end -#foreach ($prim in $primitivesNoBool) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end -//-- primitive (no bool): $prim.Name -- - - /** - * Create a pointer to the memory location used by a direct NIO ${prim.BufferName}.
- * If the NIO ${prim.BufferName} is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.
- * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer.
- */ - public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.BufferName} buffer) { - if (buffer == null) - return null; - - if (!buffer.isDirect()) { - return pointerTo${prim.CapName}s(buffer.array()); - //throw new UnsupportedOperationException("Cannot create pointers to indirect ${prim.BufferName} buffers"); - } - - long address = JNI.getDirectBufferAddress(buffer); - long size = JNI.getDirectBufferCapacity(buffer); - - // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! - size *= ${primSize}; - //System.out.println("Buffer capacity = " + size); - - if (address == 0 || size == 0) - return null; - - PointerIO<${prim.WrapperName}> io = CommonPointerIOs.${prim.Name}IO; - boolean ordered = buffer.order().equals(ByteOrder.nativeOrder()); - return newPointer(io, address, ordered, address, address + size, null, NO_PARENT, null, buffer); - } - -#end - - /** - * Get the type of pointed elements. - */ - public Type getTargetType() { - PointerIO io = getIO(); - return io == null ? null : io.getTargetType(); - } - - /** - * Read an untyped pointer value from the pointed memory location - * @deprecated Avoid using untyped pointers, if possible. - */ - @Deprecated - public Pointer getPointer() { - return getPointerAtOffset(0, (PointerIO)null); - } - - /** - * Read a pointer value from the pointed memory location shifted by a byte offset - */ - public Pointer getPointerAtOffset(long byteOffset) { - return getPointerAtOffset(byteOffset, (PointerIO)null); - } - -#docGetIndex("pointer" "getPointerAtOffset(valueIndex * Pointer.SIZE)") - public Pointer getPointerAtIndex(long valueIndex) { - return getPointerAtOffset(valueIndex * Pointer.SIZE); - } - - /** - * Read a pointer value from the pointed memory location.
- * @param c class of the elements pointed by the resulting pointer - */ - public Pointer getPointer(Class c) { - return getPointerAtOffset(0, (PointerIO)PointerIO.getInstance(c)); - } - - /** - * Read a pointer value from the pointed memory location - * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer - */ - public Pointer getPointer(PointerIO pio) { - return getPointerAtOffset(0, pio); - } - - /** - * Read a pointer value from the pointed memory location shifted by a byte offset - * @param c class of the elements pointed by the resulting pointer - */ - public Pointer getPointerAtOffset(long byteOffset, Class c) { - return getPointerAtOffset(byteOffset, (Type)c); - } - - /** - * Read a pointer value from the pointed memory location shifted by a byte offset - * @param t type of the elements pointed by the resulting pointer - */ - public Pointer getPointerAtOffset(long byteOffset, Type t) { - return getPointerAtOffset(byteOffset, t == null ? null : (PointerIO)PointerIO.getInstance(t)); - } - - /** - * Read a pointer value from the pointed memory location shifted by a byte offset - * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer - */ - public Pointer getPointerAtOffset(long byteOffset, PointerIO pio) { - long value = getSizeTAtOffset(byteOffset); - if (value == 0) - return null; - return newPointer(pio, value, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, this, byteOffset, null, null); - } - - /** - * Write a pointer value to the pointed memory location - */ - public Pointer setPointer(Pointer value) { - return setPointerAtOffset(0, value); - } - - /** - * Write a pointer value to the pointed memory location shifted by a byte offset - */ - public Pointer setPointerAtOffset(long byteOffset, Pointer value) { - setSizeTAtOffset(byteOffset, value == null ? 0 : value.getPeer()); - return this; - } - -#docSetIndex("pointer" "setPointerAtOffset(valueIndex * Pointer.SIZE, value)") - public Pointer setPointerAtIndex(long valueIndex, Pointer value) { - setPointerAtOffset(valueIndex * Pointer.SIZE, value); - return this; - } - - /** - * Read an array of untyped pointer values from the pointed memory location shifted by a byte offset - * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} - */ - public Pointer[] getPointersAtOffset(long byteOffset, int arrayLength) { - return getPointersAtOffset(byteOffset, arrayLength, (PointerIO)null); - } - /** - * Read the array of remaining untyped pointer values from the pointed memory location - * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} - */ - @Deprecated - public Pointer[] getPointers() { - long rem = getValidElements("Cannot create array if remaining length is not known. Please use getPointers(int length) instead."); - return getPointersAtOffset(0L, (int)rem); - } - /** - * Read an array of untyped pointer values from the pointed memory location - * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} - */ - @Deprecated - public Pointer[] getPointers(int arrayLength) { - return getPointersAtOffset(0, arrayLength); - } - /** - * Read an array of pointer values from the pointed memory location shifted by a byte offset - * @param t type of the elements pointed by the resulting pointer - */ - public Pointer[] getPointersAtOffset(long byteOffset, int arrayLength, Type t) { - return getPointersAtOffset(byteOffset, arrayLength, t == null ? null : (PointerIO)PointerIO.getInstance(t)); - } - /** - * Read an array of pointer values from the pointed memory location shifted by a byte offset - * @param t class of the elements pointed by the resulting pointer - */ - public Pointer[] getPointersAtOffset(long byteOffset, int arrayLength, Class t) { - return getPointersAtOffset(byteOffset, arrayLength, (Type)t); - } - - /** - * Read an array of pointer values from the pointed memory location shifted by a byte offset - * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer - */ - public Pointer[] getPointersAtOffset(long byteOffset, int arrayLength, PointerIO pio) { - Pointer[] values = (Pointer[])new Pointer[arrayLength]; - int s = Platform.POINTER_SIZE; - for (int i = 0; i < arrayLength; i++) - values[i] = getPointerAtOffset(byteOffset + i * s, pio); - return values; - } - /** - * Write an array of pointer values to the pointed memory location shifted by a byte offset - */ - public Pointer setPointersAtOffset(long byteOffset, Pointer[] values) { - return setPointersAtOffset(byteOffset, values, 0, values.length); - } - - /** - * Write length pointer values from the given array (starting at the given value offset) to the pointed memory location shifted by a byte offset - */ - public Pointer setPointersAtOffset(long byteOffset, Pointer[] values, int valuesOffset, int length) { - if (values == null) - throw new IllegalArgumentException("Null values"); - int n = length, s = Platform.POINTER_SIZE; - for (int i = 0; i < n; i++) - setPointerAtOffset(byteOffset + i * s, values[valuesOffset + i]); - return this; - } - - /** - * Write an array of pointer values to the pointed memory location - */ - public Pointer setPointers(Pointer[] values) { - return setPointersAtOffset(0, values); - } - - /** - * Read an array of elements from the pointed memory location shifted by a byte offset.
- * For pointers to primitive types (e.g. {@code Pointer }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) - * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type - */ - public Object getArrayAtOffset(long byteOffset, int length) { - return getIO("Cannot create sublist").getArray(this, byteOffset, length); - } - - /** - * Read an array of elements from the pointed memory location.
- * For pointers to primitive types (e.g. {@code Pointer }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) - * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type - */ - public Object getArray(int length) { - return getArrayAtOffset(0L, length); - } - - /** - * Read the array of remaining elements from the pointed memory location.
- * For pointers to primitive types (e.g. {@code Pointer }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) - * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type - */ - public Object getArray() { - return getArray((int)getValidElements()); - } - - /** - * Read an NIO {@link Buffer} of elements from the pointed memory location shifted by a byte offset.
- * @return an NIO {@link Buffer} of values of the requested length. - * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. - */ - public B getBufferAtOffset(long byteOffset, int length) { - return (B)getIO("Cannot create Buffer").getBuffer(this, byteOffset, length); - } - - /** - * Read an NIO {@link Buffer} of elements from the pointed memory location.
- * @return an NIO {@link Buffer} of values of the requested length. - * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. - */ - public B getBuffer(int length) { - return (B)getBufferAtOffset(0L, length); - } - - /** - * Read the NIO {@link Buffer} of remaining elements from the pointed memory location.
- * @return an array of values of the requested length. - * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. - */ - public B getBuffer() { - return (B)getBuffer((int)getValidElements()); - } - - /** - * Write an array of elements to the pointed memory location shifted by a byte offset.
- * For pointers to primitive types (e.g. {@code Pointer }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) - */ - public Pointer setArrayAtOffset(long byteOffset, Object array) { - getIO("Cannot create sublist").setArray(this, byteOffset, array); - return this; - } - - /** - * Allocate enough memory for array.length values, copy the values of the array provided as argument into it and return a pointer to that memory.
- * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.
- * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).
- * For pointers to primitive types (e.g. {@code Pointer }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) - * @param array primitive array containing the initial values for the created memory area - * @return pointer to a new memory location that initially contains the consecutive values provided in argument - */ - public static Pointer pointerToArray(Object array) { - if (array == null) - return null; - - PointerIO io = PointerIO.getArrayIO(array); - if (io == null) - throwBecauseUntyped("Cannot create pointer to array"); - - Pointer ptr = allocateArray(io, java.lang.reflect.Array.getLength(array)); - io.setArray(ptr, 0, array); - return ptr; - } - - /** - * Write an array of elements to the pointed memory location.
- * For pointers to primitive types (e.g. {@code Pointer }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) - */ - public Pointer setArray(Object array) { - return setArrayAtOffset(0L, array); - } - - #foreach ($sizePrim in ["SizeT", "CLong"]) -//-- size primitive: $sizePrim -- - -#docAllocateCopy($sizePrim $sizePrim) - public static Pointer<${sizePrim}> pointerTo${sizePrim}(long value) { - Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); - p.set${sizePrim}(value); - return p; - } -#docAllocateCopy($sizePrim $sizePrim) - public static Pointer<${sizePrim}> pointerTo${sizePrim}(${sizePrim} value) { - Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); - p.set${sizePrim}(value); - return p; - } -#docAllocateArrayCopy($sizePrim $sizePrim) - public static Pointer<${sizePrim}> pointerTo${sizePrim}s(long... values) { - if (values == null) - return null; - return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); - } -#docAllocateArrayCopy($sizePrim $sizePrim) - public static Pointer<${sizePrim}> pointerTo${sizePrim}s(${sizePrim}... values) { - if (values == null) - return null; - return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); - } - -#docAllocateArrayCopy($sizePrim $sizePrim) - public static Pointer<${sizePrim}> pointerTo${sizePrim}s(int[] values) { - if (values == null) - return null; - return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); - } - -#docAllocateArray($sizePrim $sizePrim) - public static Pointer<${sizePrim}> allocate${sizePrim}s(long arrayLength) { - return allocateArray(PointerIO.get${sizePrim}Instance(), arrayLength); - } -#docAllocate($sizePrim $sizePrim) - public static Pointer<${sizePrim}> allocate${sizePrim}() { - return allocate(PointerIO.get${sizePrim}Instance()); - } - -#docGet($sizePrim $sizePrim) - public long get${sizePrim}() { - return ${sizePrim}.SIZE == 8 ? - getLong() : - getInt(); - } -#docGetOffset($sizePrim $sizePrim "Pointer#get${sizePrim}()") - public long get${sizePrim}AtOffset(long byteOffset) { - return ${sizePrim}.SIZE == 8 ? - getLongAtOffset(byteOffset) : - getIntAtOffset(byteOffset); - } -#docGetIndex($sizePrim "get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE") - public long get${sizePrim}AtIndex(long valueIndex) { - return get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE); - } -#docGetRemainingArray($sizePrim $sizePrim) - public long[] get${sizePrim}s() { - long rem = getValidElements("Cannot create array if remaining length is not known. Please use get${sizePrim}s(int length) instead."); - if (${sizePrim}.SIZE == 8) - return getLongs((int)rem); - return get${sizePrim}s((int)rem); - } -#docGetArray($sizePrim $sizePrim) - public long[] get${sizePrim}s(int arrayLength) { - if (${sizePrim}.SIZE == 8) - return getLongs(arrayLength); - return get${sizePrim}sAtOffset(0, arrayLength); - } -#docGetArrayOffset($sizePrim $sizePrim "Pointer#get${sizePrim}s(int)") - public long[] get${sizePrim}sAtOffset(long byteOffset, int arrayLength) { - if (${sizePrim}.SIZE == 8) - return getLongsAtOffset(byteOffset, arrayLength); - - int[] values = getIntsAtOffset(byteOffset, arrayLength); - long[] ret = new long[arrayLength]; - for (int i = 0; i < arrayLength; i++) { - ret[i] = //0xffffffffL & - values[i]; - } - return ret; - } - -#docSet($sizePrim $sizePrim) - public Pointer set${sizePrim}(long value) { - if (${sizePrim}.SIZE == 8) - setLong(value); - else { - setInt(SizeT.safeIntCast(value)); - } - return this; - } -#docSet($sizePrim $sizePrim) - public Pointer set${sizePrim}(${sizePrim} value) { - return set${sizePrim}(value.longValue()); - } -#docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(long)") - public Pointer set${sizePrim}AtOffset(long byteOffset, long value) { - if (${sizePrim}.SIZE == 8) - setLongAtOffset(byteOffset, value); - else { - setIntAtOffset(byteOffset, SizeT.safeIntCast(value)); - } - return this; - } -#docSetIndex($sizePrim "set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value)") - public Pointer set${sizePrim}AtIndex(long valueIndex, long value) { - return set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value); - } - -#docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(${sizePrim})") - public Pointer set${sizePrim}AtOffset(long byteOffset, ${sizePrim} value) { - return set${sizePrim}AtOffset(byteOffset, value.longValue()); - } -#docSetArray($sizePrim $sizePrim) - public Pointer set${sizePrim}s(long[] values) { - if (${sizePrim}.SIZE == 8) - return setLongs(values); - return set${sizePrim}sAtOffset(0, values); - } -#docSetArray($sizePrim $sizePrim) - public Pointer set${sizePrim}s(int[] values) { - if (${sizePrim}.SIZE == 4) - return setInts(values); - return set${sizePrim}sAtOffset(0, values); - } -#docSetArray($sizePrim $sizePrim) - public Pointer set${sizePrim}s(${sizePrim}[] values) { - return set${sizePrim}sAtOffset(0, values); - } -#docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") - public Pointer set${sizePrim}sAtOffset(long byteOffset, long[] values) { - return set${sizePrim}sAtOffset(byteOffset, values, 0, values.length); - } -#docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") - public abstract Pointer set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length); -#docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(${sizePrim}...)") - public Pointer set${sizePrim}sAtOffset(long byteOffset, ${sizePrim}... values) { - if (values == null) - throw new IllegalArgumentException("Null values"); - int n = values.length, s = ${sizePrim}.SIZE; - for (int i = 0; i < n; i++) - set${sizePrim}AtOffset(byteOffset + i * s, values[i].longValue()); - return this; - } -#docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") - public abstract Pointer set${sizePrim}sAtOffset(long byteOffset, int[] values); - - #end - - void setSignedIntegralAtOffset(long byteOffset, long value, long sizeOfIntegral) { - switch ((int)sizeOfIntegral) { - case 1: - if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) - throw new RuntimeException("Value out of byte bounds : " + value); - setByteAtOffset(byteOffset, (byte)value); - break; - case 2: - if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) - throw new RuntimeException("Value out of short bounds : " + value); - setShortAtOffset(byteOffset, (short)value); - break; - case 4: - if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) - throw new RuntimeException("Value out of int bounds : " + value); - setIntAtOffset(byteOffset, (int)value); - break; - case 8: - setLongAtOffset(byteOffset, value); - break; - default: - throw new IllegalArgumentException("Cannot write integral type of size " + sizeOfIntegral + " (value = " + value + ")"); - } - } - long getSignedIntegralAtOffset(long byteOffset, long sizeOfIntegral) { - switch ((int)sizeOfIntegral) { - case 1: - return getByteAtOffset(byteOffset); - case 2: - return getShortAtOffset(byteOffset); - case 4: - return getIntAtOffset(byteOffset); - case 8: - return getLongAtOffset(byteOffset); - default: - throw new IllegalArgumentException("Cannot read integral type of size " + sizeOfIntegral); - } - } - -#docAllocateCopy("pointer", "Pointer") - public static Pointer> pointerToPointer(Pointer value) { - Pointer> p = (Pointer>)(Pointer)allocate(PointerIO.getPointerInstance()); - p.setPointerAtOffset(0, value); - return p; - } - -#docAllocateArrayCopy("pointer", "Pointer") - public static Pointer> pointerToPointers(Pointer... values) { - if (values == null) - return null; - int n = values.length, s = Pointer.SIZE; - PointerIO pio = PointerIO.getPointerInstance(); // TODO get actual pointer instances PointerIO !!! - Pointer> p = (Pointer>)(Pointer)allocateArray(pio, n); - for (int i = 0; i < n; i++) { - p.setPointerAtOffset(i * s, values[i]); - } - return p; - } - - /** - * Copy all values from an NIO buffer to the pointed memory location shifted by a byte offset - */ - public Pointer setValuesAtOffset(long byteOffset, Buffer values) { - #foreach ($prim in $primitivesNoBool) - if (values instanceof ${prim.BufferName}) { - set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values); - return this; - } - #end - throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); - } - - /** - * Copy length values from an NIO buffer (beginning at element at valuesOffset index) to the pointed memory location shifted by a byte offset - */ - public Pointer setValuesAtOffset(long byteOffset, Buffer values, int valuesOffset, int length) { - #foreach ($prim in $primitivesNoBool) - if (values instanceof ${prim.BufferName}) { - set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values, valuesOffset, length); - return this; - } - #end - throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); - } - - /** - * Copy values from an NIO buffer to the pointed memory location - */ - public Pointer setValues(Buffer values) { - #foreach ($prim in $primitivesNoBool) - if (values instanceof ${prim.BufferName}) { - set${prim.CapName}s((${prim.BufferName})values); - return this; - } - #end - throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); - } - - /** - * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see memcpy C function.
- * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead. - */ - @Deprecated - public Pointer copyBytesAtOffsetTo(long byteOffset, Pointer destination, long byteOffsetInDestination, long byteCount) { - #declareCheckedPeerAtOffset("byteOffset" "byteCount") - JNI.memcpy(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); - return this; - } - - /** - * Copy bytes from the memory location indicated by this pointer to that of another pointer using the @see memcpy C function.
- * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead.
- * See {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)} for more options. - */ - @Deprecated - public Pointer copyBytesTo(Pointer destination, long byteCount) { - return copyBytesAtOffsetTo(0, destination, 0, byteCount); - } - - /** - * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see memmove C function.
- * Works even if the destination and source memory locations are overlapping. - */ - @Deprecated - public Pointer moveBytesAtOffsetTo(long byteOffset, Pointer destination, long byteOffsetInDestination, long byteCount) { - #declareCheckedPeerAtOffset("byteOffset" "byteCount") - JNI.memmove(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); - return this; - } - - /** - * Copy bytes from the memory location indicated by this pointer to that of another pointer, using the @see memmove C function.
- * Works even if the destination and source memory locations are overlapping. - */ - public Pointer moveBytesTo(Pointer destination, long byteCount) { - return moveBytesAtOffsetTo(0, destination, 0, byteCount); - } - - /** - * Copy all valid bytes from the memory location indicated by this pointer to that of another pointer, using the @see memmove C function.
- * Works even if the destination and source memory locations are overlapping. - */ - public Pointer moveBytesTo(Pointer destination) { - return moveBytesTo(destination, getValidBytes("Cannot move an unbounded memory location. Please use validBytes(long).")); - } - - final long getValidBytes(String error) { - long rem = getValidBytes(); - if (rem < 0) - throw new IndexOutOfBoundsException(error); - - return rem; - } - final long getValidElements(String error) { - long rem = getValidElements(); - if (rem < 0) - throw new IndexOutOfBoundsException(error); - - return rem; - } - final PointerIO getIO(String error) { - PointerIO io = getIO(); - if (io == null) - throwBecauseUntyped(error); - return io; - } - - /** - * Copy remaining bytes from this pointer to a destination using the @see memcpy C function (see {@link Pointer#copyBytesTo(Pointer, long)}, {@link Pointer#getValidBytes()}) - */ - public Pointer copyTo(Pointer destination) { - return copyTo(destination, getValidElements()); - } - - /** - * Copy remaining elements from this pointer to a destination using the @see memcpy C function (see {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)}, {@link Pointer#getValidBytes}) - */ - public Pointer copyTo(Pointer destination, long elementCount) { - PointerIO io = getIO("Cannot copy untyped pointer without byte count information. Please use copyBytesAtOffsetTo(offset, destination, destinationOffset, byteCount) instead"); - return copyBytesAtOffsetTo(0, destination, 0, elementCount * io.getTargetSize()); - } - - /** - * Find the first appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (behaviour equivalent to memmem, which is used underneath on platforms where it is available) - */ - public Pointer find(Pointer needle) { - if (needle == null) - return null; - long firstOccurrence = JNI.memmem( - getPeer(), - getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), - needle.getPeer(), - needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") - ); - return pointerToAddress(firstOccurrence, io); - } - - /** - * Find the last appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (also see {@link Pointer#find(Pointer)}). - */ - public Pointer findLast(Pointer needle) { - if (needle == null) - return null; - long lastOccurrence = JNI.memmem_last( - getPeer(), - getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), - needle.getPeer(), - needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") - ); - return pointerToAddress(lastOccurrence, io); - } - - -#foreach ($prim in $primitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end -//-- primitive: $prim.Name -- - -#docSet(${prim.Name} ${prim.WrapperName}) - public abstract Pointer set${prim.CapName}(${prim.Name} value); - -#docSetOffset(${prim.Name} ${prim.WrapperName} "Pointer#set${prim.CapName}(${prim.Name})") - public abstract Pointer set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value); - -#docSetIndex(${prim.Name} "set${prim.CapName}AtOffset(valueIndex * $primSize, value)") - public Pointer set${prim.CapName}AtIndex(long valueIndex, ${prim.Name} value) { - return set${prim.CapName}AtOffset(valueIndex * $primSize, value); - } - - /** - * Write an array of ${prim.Name} values of the specified length to the pointed memory location - */ - public Pointer set${prim.CapName}s(${prim.Name}[] values) { - return set${prim.CapName}sAtOffset(0, values, 0, values.length); - } - - /** - * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset - */ - public Pointer set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values) { - return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.length); - } - - /** - * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given array offset and for the given length from the provided array. - */ - public Pointer set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values, int valuesOffset, int length) { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return setIntsAtOffset(byteOffset, wcharsToInts(values, valuesOffset, length)); - #end - #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") - #if ($prim.Name != "byte" && $prim.Name != "boolean") - if (!isOrdered()) { - JNI.set_${prim.Name}_array_disordered(checkedPeer, values, valuesOffset, length); - return this; - } - #end - JNI.set_${prim.Name}_array(checkedPeer, values, valuesOffset, length); - return this; - } - -#docGet(${prim.Name} ${prim.WrapperName}) - public abstract ${prim.Name} get${prim.CapName}(); - -#docGetOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}()") - public abstract ${prim.Name} get${prim.CapName}AtOffset(long byteOffset); - -#docGetIndex(${prim.Name} "get${prim.CapName}AtOffset(valueIndex * $primSize)") - public ${prim.Name} get${prim.CapName}AtIndex(long valueIndex) { - return get${prim.CapName}AtOffset(valueIndex * $primSize); - } - -#docGetArray(${prim.Name} ${prim.WrapperName}) - public ${prim.Name}[] get${prim.CapName}s(int length) { - return get${prim.CapName}sAtOffset(0, length); - } - - -#docGetRemainingArray(${prim.Name} ${prim.WrapperName}) - public ${prim.Name}[] get${prim.CapName}s() { - long validBytes = getValidBytes("Cannot create array if remaining length is not known. Please use get${prim.CapName}s(int length) instead."); - return get${prim.CapName}s((int)(validBytes / ${primSize})); - } - -#docGetArrayOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}s(int)") - public ${prim.Name}[] get${prim.CapName}sAtOffset(long byteOffset, int length) { - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) - return intsToWChars(getIntsAtOffset(byteOffset, length)); - #end - #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") - #if ($prim.Name != "byte" && $prim.Name != "boolean") - if (!isOrdered()) - return JNI.get_${prim.Name}_array_disordered(checkedPeer, length); - #end - return JNI.get_${prim.Name}_array(checkedPeer, length); - } - -#end -#foreach ($prim in $primitivesNoBool) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end -//-- primitive (no bool): $prim.Name -- - - #if ($prim.Name != "char") - /** - * Read ${prim.Name} values into the specified destination array from the pointed memory location - */ - public void get${prim.CapName}s(${prim.Name}[] dest) { - get${prim.BufferName}().get(dest); - } - - /** - * Read ${prim.Name} values into the specified destination buffer from the pointed memory location - */ - public void get${prim.CapName}s(${prim.BufferName} dest) { - dest.duplicate().put(get${prim.BufferName}()); - } - - /** - * Read length ${prim.Name} values into the specified destination array from the pointed memory location shifted by a byte offset, storing values after the provided destination offset. - */ - public void get${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] dest, int destOffset, int length) { - get${prim.BufferName}AtOffset(byteOffset, length).get(dest, destOffset, length); - } - #end - - /** - * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location - */ - public Pointer set${prim.CapName}s(${prim.BufferName} values) { - return set${prim.CapName}sAtOffset(0, values, 0, values.capacity()); - } - - /** - * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset - */ - public Pointer set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values) { - return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.capacity()); - } - - /** - * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given buffer offset and for the given length from the provided buffer. - */ - public Pointer set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values, long valuesOffset, long length) { - if (values == null) - throw new IllegalArgumentException("Null values"); - #if ($prim.Name == "char") - if (Platform.WCHAR_T_SIZE == 4) { - for (int i = 0; i < length; i++) - setCharAtOffset(byteOffset + i, values.get((int)(valuesOffset + i))); - return this; - } - #end - if (values.isDirect()) { - long len = length * ${primSize}, off = valuesOffset * ${primSize}; - long cap = JNI.getDirectBufferCapacity(values); - // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! - cap *= ${primSize}; - - if (cap < off + len) - throw new IndexOutOfBoundsException("The provided buffer has a capacity (" + cap + " bytes) smaller than the requested write operation (" + len + " bytes starting at byte offset " + off + ")"); - - - #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") - JNI.memcpy(checkedPeer, JNI.getDirectBufferAddress(values) + off, len); - } - #if ($prim.Name != "char") - else if (values.isReadOnly()) { - get${prim.BufferName}AtOffset(byteOffset, length).put(values.duplicate()); - } - #end - else { - set${prim.CapName}sAtOffset(byteOffset, values.array(), (int)(values.arrayOffset() + valuesOffset), (int)length); - } - return this; - } - - #if ($prim.Name != "char") - /** - * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location - */ - public ${prim.BufferName} get${prim.BufferName}(long length) { - return get${prim.BufferName}AtOffset(0, length); - } - - /** - * Get a direct buffer of ${prim.Name} values that points to this pointer's target memory locations - */ - public ${prim.BufferName} get${prim.BufferName}() { - long validBytes = getValidBytes("Cannot create buffer if remaining length is not known. Please use get${prim.BufferName}(long length) instead."); - return get${prim.BufferName}AtOffset(0, validBytes / ${primSize}); - } - - /** - * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location shifted by a byte offset - */ - public ${prim.BufferName} get${prim.BufferName}AtOffset(long byteOffset, long length) { - long blen = ${primSize} * length; - #declareCheckedPeerAtOffset("byteOffset" "blen") - ByteBuffer buffer = JNI.newDirectByteBuffer(checkedPeer, blen); - buffer.order(order()); // mutates buffer order - #if ($prim.Name == "byte") - return buffer; - #else - return buffer.as${prim.BufferName}(); - #end - } - #end - -#end - - /** - * Type of a native character string.
- * In the native world, there are several ways to represent a string.
- * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} - */ - public enum StringType { - /** - * C strings (a.k.a "NULL-terminated strings") have no size limit and are the most used strings in the C world. - * They are stored with the bytes of the string (using either a single-byte encoding such as ASCII, ISO-8859 or windows-1252 or a C-string compatible multi-byte encoding, such as UTF-8), followed with a zero byte that indicates the end of the string.
- * Corresponding C types : {@code char* }, {@code const char* }, {@code LPCSTR }
- * Corresponding Pascal type : {@code PChar }
- * See {@link Pointer#pointerToCString(String)}, {@link Pointer#getCString()} and {@link Pointer#setCString(String)} - */ - C(false, true), - /** - * Wide C strings are stored as C strings (see {@link StringType#C}) except they are composed of shorts instead of bytes (and are ended by one zero short value = two zero byte values). - * This allows the use of two-bytes encodings, which is why this kind of strings is often found in modern Unicode-aware system APIs.
- * Corresponding C types : {@code wchar_t* }, {@code const wchar_t* }, {@code LPCWSTR }
- * See {@link Pointer#pointerToWideCString(String)}, {@link Pointer#getWideCString()} and {@link Pointer#setWideCString(String)} - */ - WideC(true, true), - /** - * Pascal strings can be up to 255 characters long.
- * They are stored with a first byte that indicates the length of the string, followed by the ascii or extended ascii chars of the string (no support for multibyte encoding).
- * They are often used in very old Mac OS programs and / or Pascal programs.
- * Usual corresponding C types : {@code unsigned char* } and {@code const unsigned char* }
- * Corresponding Pascal type : {@code ShortString } (see @see http://www.codexterity.com/delphistrings.htm)
- * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - PascalShort(false, true), - /** - * Wide Pascal strings are ref-counted unicode strings that look like WideC strings but are prepended with a ref count and length (both 32 bits ints).
- * They are the current default in Delphi (2010).
- * Corresponding Pascal type : {@code WideString } (see @see http://www.codexterity.com/delphistrings.htm)
- * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - PascalWide(true, true), - /** - * Pascal ANSI strings are ref-counted single-byte strings that look like C strings but are prepended with a ref count and length (both 32 bits ints).
- * Corresponding Pascal type : {@code AnsiString } (see @see http://www.codexterity.com/delphistrings.htm)
- * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - PascalAnsi(false, true), - /** - * Microsoft's BSTR strings, used in COM, OLE, MS.NET Interop and MS.NET Automation functions.
- * See @see http://msdn.microsoft.com/en-us/library/ms221069.aspx for more details.
- * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - BSTR(true, true), - /** - * STL strings have compiler- and STL library-specific implementations and memory layouts.
- * BridJ support reading and writing to / from pointers to most implementation's STL strings, though. - * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - STL(false, false), - /** - * STL wide strings have compiler- and STL library-specific implementations and memory layouts.
- * BridJ supports reading and writing to / from pointers to most implementation's STL strings, though. - * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, - */ - WideSTL(true, false); - //MFCCString, - //CComBSTR, - //_bstr_t - - final boolean isWide, canCreate; - StringType(boolean isWide, boolean canCreate) { - this.isWide = isWide; - this.canCreate = canCreate; - } - - } - - private static void notAString(StringType type, String reason) { - throw new RuntimeException("There is no " + type + " String here ! (" + reason + ")"); - } - - protected void checkIntRefCount(StringType type, long byteOffset) { - int refCount = getIntAtOffset(byteOffset); - if (refCount <= 0) - notAString(type, "invalid refcount: " + refCount); - } - - /** - * Read a native string from the pointed memory location using the default charset.
- * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. - * @param type Type of the native String to read. See {@link StringType} for details on the supported types. - * @return string read from native memory - */ - public String getString(StringType type) { - return getStringAtOffset(0, type, null); - } - - /** - * Read a native string from the pointed memory location, using the provided charset or the system's default if not provided. - * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. - * @param type Type of the native String to read. See {@link StringType} for details on the supported types. - * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used - * @return string read from native memory - */ - public String getString(StringType type, Charset charset) { - return getStringAtOffset(0, type, charset); - } - - - String getSTLStringAtOffset(long byteOffset, StringType type, Charset charset) { - // Assume the following layout : - // - fixed buff of 16 chars - // - ptr to dynamic array if the string is bigger - // - size of the string (size_t) - // - max allowed size of the string without the need for reallocation - boolean wide = type == StringType.WideSTL; - - int fixedBuffLength = 16; - int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; - long length = getSizeTAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); - long pOff; - Pointer p; - if (length < fixedBuffLength - 1) { - pOff = byteOffset; - p = this; - } else { - pOff = 0; - p = getPointerAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); - } - int endChar = wide ? p.getCharAtOffset(pOff + length * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + length); - if (endChar != 0) - notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + length); - return p.getStringAtOffset(pOff, wide ? StringType.WideC : StringType.C, charset); - } - - static Pointer setSTLString(Pointer pointer, long byteOffset, String s, StringType type, Charset charset) { - boolean wide = type == StringType.WideSTL; - - int fixedBuffLength = 16; - int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; - long lengthOffset = byteOffset + fixedBuffSize + Pointer.SIZE; - long capacityOffset = lengthOffset + Pointer.SIZE; - - long length = s.length(); - if (pointer == null)// { && length > fixedBuffLength - 1) - throw new UnsupportedOperationException("Cannot create STL strings (yet)"); - - long currentLength = pointer.getSizeTAtOffset(lengthOffset); - long currentCapacity = pointer.getSizeTAtOffset(capacityOffset); - - if (currentLength < 0 || currentCapacity < 0 || currentLength > currentCapacity) - notAString(type, "STL string format not recognized : currentLength = " + currentLength + ", currentCapacity = " + currentCapacity); - - if (length > currentCapacity) - throw new RuntimeException("The target STL string is not large enough to write a string of length " + length + " (current capacity = " + currentCapacity + ")"); - - pointer.setSizeTAtOffset(lengthOffset, length); - - long pOff; - Pointer p; - if (length < fixedBuffLength - 1) { - pOff = byteOffset; - p = pointer; - } else { - pOff = 0; - p = pointer.getPointerAtOffset(byteOffset + fixedBuffSize + SizeT.SIZE); - } - - int endChar = wide ? p.getCharAtOffset(pOff + currentLength * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + currentLength); - if (endChar != 0) - notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + currentLength); - - p.setStringAtOffset(pOff, s, wide ? StringType.WideC : StringType.C, charset); - return pointer; - } - - - /** - * Read a native string from the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. - * @param byteOffset - * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used - * @param type Type of the native String to read. See {@link StringType} for details on the supported types. - * @return string read from native memory - */ - public String getStringAtOffset(long byteOffset, StringType type, Charset charset) { - try { - long len; - - switch (type) { - case PascalShort: - len = getByteAtOffset(byteOffset) & 0xff; - return new String(getBytesAtOffset(byteOffset + 1, safeIntCast(len)), charset(charset)); - case PascalWide: - checkIntRefCount(type, byteOffset - 8); - case BSTR: - len = getIntAtOffset(byteOffset - 4); - if (len < 0 || ((len & 1) == 1)) - notAString(type, "invalid byte length: " + len); - //len = wcslen(byteOffset); - if (getCharAtOffset(byteOffset + len) != 0) - notAString(type, "no null short after the " + len + " declared bytes"); - return new String(getCharsAtOffset(byteOffset, safeIntCast(len / Platform.WCHAR_T_SIZE))); - case PascalAnsi: - checkIntRefCount(type, byteOffset - 8); - len = getIntAtOffset(byteOffset - 4); - if (len < 0) - notAString(type, "invalid byte length: " + len); - if (getByteAtOffset(byteOffset + len) != 0) - notAString(type, "no null short after the " + len + " declared bytes"); - return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); - case C: - len = strlen(byteOffset); - return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); - case WideC: - len = wcslen(byteOffset); - return new String(getCharsAtOffset(byteOffset, safeIntCast(len))); - case STL: - case WideSTL: - return getSTLStringAtOffset(byteOffset, type, charset); - default: - throw new RuntimeException("Unhandled string type : " + type); - } - } catch (UnsupportedEncodingException ex) { - throwUnexpected(ex); - return null; - } - } - - /** - * Write a native string to the pointed memory location using the default charset.
- * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options. - * @param s string to write - * @param type Type of the native String to write. See {@link StringType} for details on the supported types. - * @return this - */ - public Pointer setString(String s, StringType type) { - return setString(this, 0, s, type, null); - } - - - /** - * Write a native string to the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. - * @param byteOffset - * @param s string to write - * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used - * @param type Type of the native String to write. See {@link StringType} for details on the supported types. - * @return this - */ - public Pointer setStringAtOffset(long byteOffset, String s, StringType type, Charset charset) { - return setString(this, byteOffset, s, type, charset); - } - - private static String charset(Charset charset) { - return (charset == null ? Charset.defaultCharset() : charset).name(); - } - - static Pointer setString(Pointer pointer, long byteOffset, String s, StringType type, Charset charset) { - try { - if (s == null) - return null; - - byte[] bytes; - char[] chars; - int bytesCount, headerBytes; - int headerShift; - - switch (type) { - case PascalShort: - bytes = s.getBytes(charset(charset)); - bytesCount = bytes.length; - if (pointer == null) - pointer = (Pointer)allocateBytes(bytesCount + 1); - if (bytesCount > 255) - throw new IllegalArgumentException("Pascal strings cannot be more than 255 chars long (tried to write string of byte length " + bytesCount + ")"); - pointer.setByteAtOffset(byteOffset, (byte)bytesCount); - pointer.setBytesAtOffset(byteOffset + 1, bytes, 0, bytesCount); - break; - case C: - bytes = s.getBytes(charset(charset)); - bytesCount = bytes.length; - if (pointer == null) - pointer = (Pointer)allocateBytes(bytesCount + 1); - pointer.setBytesAtOffset(byteOffset, bytes, 0, bytesCount); - pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); - break; - case WideC: - chars = s.toCharArray(); - bytesCount = chars.length * Platform.WCHAR_T_SIZE; - if (pointer == null) - pointer = (Pointer)allocateChars(bytesCount + 2); - pointer.setCharsAtOffset(byteOffset, chars); - pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); - break; - case PascalWide: - headerBytes = 8; - chars = s.toCharArray(); - bytesCount = chars.length * Platform.WCHAR_T_SIZE; - if (pointer == null) { - pointer = (Pointer)allocateChars(headerBytes + bytesCount + 2); - byteOffset = headerShift = headerBytes; - } else - headerShift = 0; - pointer.setIntAtOffset(byteOffset - 8, 1); // refcount - pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header - pointer.setCharsAtOffset(byteOffset, chars); - pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); - // Return a pointer to the WideC string-compatible part of the Pascal WideString - return (Pointer)pointer.offset(headerShift); - case PascalAnsi: - headerBytes = 8; - bytes = s.getBytes(charset(charset)); - bytesCount = bytes.length; - if (pointer == null) { - pointer = (Pointer)allocateBytes(headerBytes + bytesCount + 1); - byteOffset = headerShift = headerBytes; - } else - headerShift = 0; - pointer.setIntAtOffset(byteOffset - 8, 1); // refcount - pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header - pointer.setBytesAtOffset(byteOffset, bytes); - pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); - // Return a pointer to the WideC string-compatible part of the Pascal WideString - return (Pointer)pointer.offset(headerShift); - case BSTR: - headerBytes = 4; - chars = s.toCharArray(); - bytesCount = chars.length * Platform.WCHAR_T_SIZE; - if (pointer == null) { - pointer = (Pointer)allocateChars(headerBytes + bytesCount + 2); - byteOffset = headerShift = headerBytes; - } else - headerShift = 0; - pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header IN BYTES - pointer.setCharsAtOffset(byteOffset, chars); - pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); - // Return a pointer to the WideC string-compatible part of the Pascal WideString - return (Pointer)pointer.offset(headerShift); - case STL: - case WideSTL: - return setSTLString(pointer, byteOffset, s, type, charset); - default: - throw new RuntimeException("Unhandled string type : " + type); - } - - return (Pointer)pointer; - } catch (UnsupportedEncodingException ex) { - throwUnexpected(ex); - return null; - } - } - - /** - * Allocate memory and write a string to it, using the system's default charset to convert the string (See {@link StringType} for details on the supported types).
- * See {@link Pointer#setString(String, StringType)}, {@link Pointer#getString(StringType)}. - * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used - * @param type Type of the native String to create. - */ - public static Pointer pointerToString(String string, StringType type, Charset charset) { - return setString(null, 0, string, type, charset); - } - -#macro (defPointerToString $string $eltWrapper) - /** - * Allocate memory and write a ${string} string to it, using the system's default charset to convert the string. (see {@link StringType#${string}}).
- * See {@link Pointer#set${string}String(String)}, {@link Pointer#get${string}String()}.
- * See {@link Pointer#pointerToString(String, StringType, Charset)} for choice of the String type or Charset. - */ - public static Pointer<$eltWrapper> pointerTo${string}String(String string) { - return setString(null, 0, string, StringType.${string}, null); - } - - /** - * The update will take place inside the release() call - */ - public static Pointer> pointerTo${string}Strings(final String... strings) { - if (strings == null) - return null; - final int len = strings.length; - final Pointer<$eltWrapper>[] pointers = (Pointer<$eltWrapper>[])new Pointer[len]; - Pointer> mem = allocateArray((PointerIO>)(PointerIO)PointerIO.getPointerInstance(${eltWrapper}.class), len, new Releaser() { - //@Override - public void release(Pointer p) { - Pointer> mem = (Pointer>)p; - for (int i = 0; i < len; i++) { - Pointer<$eltWrapper> pp = mem.get(i); - if (pp != null) - strings[i] = pp.get${string}String(); - pp = pointers[i]; - if (pp != null) - pp.release(); - } - } - }); - for (int i = 0; i < len; i++) - mem.set(i, pointers[i] = pointerTo${string}String(strings[i])); - - return mem; - } - -#end - -#defPointerToString("C" "Byte") -#defPointerToString("WideC" "Character") - - -#foreach ($string in ["C", "WideC"]) -//-- StringType: $string -- - - /** - * Read a ${string} string using the default charset from the pointed memory location (see {@link StringType#${string}}).
- * See {@link Pointer#get${string}StringAtOffset(long)}, {@link Pointer#getString(StringType)} and {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options - */ - public String get${string}String() { - return get${string}StringAtOffset(0); - } - - /** - * Read a ${string} string using the default charset from the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).
- * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options - */ - public String get${string}StringAtOffset(long byteOffset) { - return getStringAtOffset(byteOffset, StringType.${string}, null); - } - - /** - * Write a ${string} string using the default charset to the pointed memory location (see {@link StringType#${string}}).
- * See {@link Pointer#set${string}StringAtOffset(long, String)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options - */ - public Pointer set${string}String(String s) { - return set${string}StringAtOffset(0, s); - } - /** - * Write a ${string} string using the default charset to the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).
- * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options - */ - public Pointer set${string}StringAtOffset(long byteOffset, String s) { - return setStringAtOffset(byteOffset, s, StringType.${string}, null); - } - -#end - - /** - * Get the length of the C string at the pointed memory location shifted by a byte offset (see {@link StringType#C}). - */ - protected long strlen(long byteOffset) { - #declareCheckedPeerAtOffset("byteOffset" "1") - return JNI.strlen(checkedPeer); - } - - /** - * Get the length of the wide C string at the pointed memory location shifted by a byte offset (see {@link StringType#WideC}). - */ - protected long wcslen(long byteOffset) { - #declareCheckedPeerAtOffset("byteOffset" "Platform.WCHAR_T_SIZE") - return JNI.wcslen(checkedPeer); - } - - /** - * Write zero bytes to all of the valid bytes pointed by this pointer - */ - public void clearValidBytes() { - long bytes = getValidBytes(); - if (bytes < 0) - throw new UnsupportedOperationException("Number of valid bytes is unknown. Please use clearBytes(long) or validBytes(long)."); - clearBytes(bytes); - } - - /** - * Write zero bytes to the first length bytes pointed by this pointer - */ - public void clearBytes(long length) { - clearBytesAtOffset(0, length, (byte)0); - } - /** - * Write a byte {@code value} to each of the {@code length} bytes at the address pointed to by this pointer shifted by a {@code byteOffset} - */ - public void clearBytesAtOffset(long byteOffset, long length, byte value) { - #declareCheckedPeerAtOffset("byteOffset" "length") - JNI.memset(checkedPeer, value, length); - } - - /** - * Find the first occurrence of a value in the memory block of length searchLength bytes pointed by this pointer shifted by a byteOffset - */ - public Pointer findByte(long byteOffset, byte value, long searchLength) { - #declareCheckedPeerAtOffset("byteOffset" "searchLength") - long found = JNI.memchr(checkedPeer, value, searchLength); - return found == 0 ? null : offset(found - checkedPeer); - } - - /** - * Alias for {@link Pointer#get(long)} defined for more natural use from the Scala language. - */ - public final T apply(long index) { - return get(index); - } - - /** - * Alias for {@link Pointer\#set(long, Object)} defined for more natural use from the Scala language. - */ - public final void update(long index, T element) { - set(index, element); - } - - /** - * Create an array with all the values in the bounded memory area.
- * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. - * @throws IndexOutOfBoundsException if this pointer's bounds are unknown - */ - public T[] toArray() { - getIO("Cannot create array"); - return toArray((int)getValidElements("Length of pointed memory is unknown, cannot create array out of this pointer")); - } - - T[] toArray(int length) { - Class c = Utils.getClass(getIO("Cannot create array").getTargetType()); - if (c == null) - throw new RuntimeException("Unable to get the target type's class (target type = " + io.getTargetType() + ")"); - return (T[])toArray((Object[])Array.newInstance(c, length)); - } - - /** - * Create an array with all the values in the bounded memory area, reusing the provided array if its type is compatible and its size is big enough.
- * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. - * @throws IndexOutOfBoundsException if this pointer's bounds are unknown - */ - public U[] toArray(U[] array) { - int n = (int)getValidElements(); - if (n < 0) - throwBecauseUntyped("Cannot create array"); - - if (array.length != n) - return (U[])toArray(); - - for (int i = 0; i < n; i++) - array[i] = (U)get(i); - return array; - } - - /** - * Types of pointer-based list implementations that can be created through {@link Pointer#asList()} or {@link Pointer#asList(ListType)}. - */ - public enum ListType { - /** - * Read-only list - */ - Unmodifiable, - /** - * List is modifiable and can shrink, but capacity cannot be increased (some operations will hence throw UnsupportedOperationException when the capacity is unsufficient for the requested operation) - */ - FixedCapacity, - /** - * List is modifiable and its underlying memory will be reallocated if it needs to grow beyond its current capacity. - */ - Dynamic - } - - /** - * Create a {@link ListType#FixedCapacity} native list that uses this pointer as storage (and has this pointer's pointed valid elements as initial content).
- * Same as {@link Pointer#asList(ListType)}({@link ListType#FixedCapacity}). - */ - public NativeList asList() { - return asList(ListType.FixedCapacity); - } - /** - * Create a native list that uses this pointer as initial storage (and has this pointer's pointed valid elements as initial content).
- * If the list is {@link ListType#Dynamic} and if its capacity is grown at some point, this pointer will probably no longer point to the native memory storage of the list, so you need to get back the pointer with {@link NativeList#getPointer()} when you're done mutating the list. - */ - public NativeList asList(ListType type) { - return new DefaultNativeList(this, type); - } - /** - * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). - * @param io Type of the elements of the list - * @param capacity Initial capacity of the list - */ - public static NativeList allocateList(PointerIO io, long capacity) { - NativeList list = new DefaultNativeList(allocateArray(io, capacity), ListType.Dynamic); - list.clear(); - return list; - } - /** - * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). - * @param type Type of the elements of the list - * @param capacity Initial capacity of the list - */ - public static NativeList allocateList(Class type, long capacity) { - return allocateList((Type)type, capacity); - } - /** - * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). - * @param type Type of the elements of the list - * @param capacity Initial capacity of the list - */ - public static NativeList allocateList(Type type, long capacity) { - return (NativeList)allocateList(PointerIO.getInstance(type), capacity); - } - - private static char[] intsToWChars(int[] in) { - int n = in.length; - char[] out = new char[n]; - for (int i = 0; i < n; i++) - out[i] = (char)in[i]; - return out; - } - private static int[] wcharsToInts(char[] in, int valuesOffset, int length) { - int[] out = new int[length]; - for (int i = 0; i < length; i++) - out[i] = in[valuesOffset + i]; - return out; - } -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/PointerIO.java b/libraries/BridJ/src/main/velocity/org/bridj/PointerIO.java deleted file mode 100644 index 0b7a43a89..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/PointerIO.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.bridj; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; -import java.nio.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicReference; -import org.bridj.util.Utils; - -/** - * Helper class that knows how to read/write data from/to a {@link Pointer}.
- * End users don't need to use this class directly as ({@link Pointer} lets you work with {@link java.lang.reflect.Type} and {@link Class}). - * @author Olivier - */ -public abstract class PointerIO { - final Type targetType; - final Class typedPointerClass; - final int targetSize, targetAlignment = -1; - - public PointerIO(Type targetType, int targetSize, Class typedPointerClass) { - this.targetType = targetType; - this.targetSize = targetSize; - this.typedPointerClass = typedPointerClass; - } - abstract T get(Pointer pointer, long index); - abstract void set(Pointer pointer, long index, T value); - public Object getArray(Pointer pointer, long byteOffset, int length) { - return pointer.offset(byteOffset).toArray(length); - } - public B getBuffer(Pointer pointer, long byteOffset, int length) { - throw new UnsupportedOperationException("Cannot create a Buffer instance of elements of type " + getTargetType()); - } - public void setArray(Pointer pointer, long byteOffset, Object array) { - Object[] a = (Object[])array; - for (int i = 0, n = a.length; i < n; i++) - set(pointer, i, (T)a[i]); - } - - public T castTarget(long peer) { - throw new UnsupportedOperationException("Cannot cast pointer to " + targetType); - } - - PointerIO> getReferenceIO() { - return new CommonPointerIOs.PointerPointerIO(this); - } - public long getTargetSize() { - return targetSize; - } - public long getTargetAlignment() { - return targetAlignment < 0 ? getTargetSize() : targetAlignment; - } - public boolean isTypedPointer() { - return typedPointerClass != null; - } - public Class getTypedPointerClass() { - return typedPointerClass; - } - public Type getTargetType() { - return targetType; - } - - static Class getClass(Type type) { - if (type instanceof Class) - return (Class)type; - if (type instanceof ParameterizedType) - return getClass(((ParameterizedType)type).getRawType()); - return null; - } - - public static PointerIO> getPointerInstance(Type target) { - return getPointerInstance((PointerIO)getInstance(target)); - } - public static PointerIO> getPointerInstance(PointerIO targetIO) { - return new CommonPointerIOs.PointerPointerIO(targetIO); - } - public static PointerIO> getArrayInstance(PointerIO targetIO, long[] dimensions, int iDimension) { - return new CommonPointerIOs.PointerArrayIO(targetIO, dimensions, iDimension); - } - - static PointerIO getArrayIO(Object array) { - #foreach ($prim in $primitives) - if (array instanceof ${prim.Name}[]) - return (PointerIO)PointerIO.get${prim.CapName}Instance(); - #end - return PointerIO.getInstance(array.getClass().getComponentType()); - } - - private static final ConcurrentHashMap> structIOs = new ConcurrentHashMap>(); - public static PointerIO getInstance(StructIO s) { - PointerIO io = structIOs.get(s); - if (io == null) { - io = new CommonPointerIOs.StructPointerIO(s); - PointerIO previousIO = structIOs.putIfAbsent(s, io); - if (previousIO != null) - io = previousIO; - } - return io; - } - private static final ConcurrentHashMap> ios = new ConcurrentHashMap>(); - public static

PointerIO

getInstance(Type type) { - if (type == null) - return null; - - PointerIO io = ios.get(type); - if (io == null) { - final Class cl = Utils.getClass(type); - - #foreach ($prim in $primitives) - #if ($velocityCount > 1) else #end - if (type == ${prim.WrapperName}.TYPE || type == ${prim.WrapperName}.class) - io = CommonPointerIOs.${prim.Name}IO; - #end - else if (cl != null) { - if (TypedPointer.class.isAssignableFrom(cl)) - io = new CommonPointerIOs.TypedPointerPointerIO((Class)cl); - else if (Pointer.class.isAssignableFrom(cl)) { - if (Pointer.class.equals(type) || !(type instanceof ParameterizedType)) - io = getPointerInstance((PointerIO)null); - else - io = getPointerInstance(((ParameterizedType)type).getActualTypeArguments()[0]); - } - else if (SizeT.class.isAssignableFrom(cl)) - io = CommonPointerIOs.sizeTIO; - else if (TimeT.class.isAssignableFrom(cl)) - io = CommonPointerIOs.timeTIO; - else if (CLong.class.isAssignableFrom(cl)) - io = CommonPointerIOs.clongIO; - else if (StructObject.class.isAssignableFrom(cl)) - io = getInstance(StructIO.getInstance((Class)cl, type)); - else if (Callback.class.isAssignableFrom(cl)) - io = new CommonPointerIOs.CallbackPointerIO(cl); - else if (NativeObject.class.isAssignableFrom(cl)) - io = new CommonPointerIOs.NativeObjectPointerIO(type); - else if (IntValuedEnum.class.isAssignableFrom(cl)) { - if (type instanceof ParameterizedType) { - Type enumType = ((ParameterizedType)type).getActualTypeArguments()[0]; - if (enumType instanceof Class) - io = new CommonPointerIOs.IntValuedEnumPointerIO((Class)enumType); - } - } - } - //else - //throw new UnsupportedOperationException("Cannot create pointer io to type " + type + ((type instanceof Class) && ((Class)type).getSuperclass() != null ? " (parent type : " + ((Class)type).getSuperclass().getName() + ")" : "")); - //return null; // TODO throw here ? - - //if (io == null) - // throw new RuntimeException("Failed to create pointer io to type " + type); - if (io != null) { - PointerIO previousIO = ios.putIfAbsent(type, io); - if (previousIO != null) - io = previousIO; // created io twice : not important in general (expecially not compared to cost of contention on non-concurrent map) - } - } - return io; - } - - private static PointerIO atomicInstance(AtomicReference ref, Type type) { - PointerIO io = (PointerIO)ref.get(); - if (io != null) - return io; - - if (ref.compareAndSet(null, io = getInstance(type))) - return io; - - return (PointerIO)ref.get(); - } - -#foreach ($prim in $bridJPrimitives) - private static final AtomicReference> ${prim.Name}Instance = new AtomicReference>(); - public static PointerIO<${prim.WrapperName}> get${prim.CapName}Instance() { - return atomicInstance(${prim.Name}Instance, ${prim.WrapperName}.class); - } - /* PointerIO<${prim.WrapperName}> io = ${prim.Name}Instance.get(); - if (io != null) - return io; - - if (${prim.Name}Instance.compareAndSet(null, io = getInstance(${prim.WrapperName}.class))) - return io; - - return ${prim.Name}Instance.get(); - }*/ -#end - - public static

PointerIO

getBufferPrimitiveInstance(Buffer buffer) { - #foreach ($prim in $primitivesNoBool) - if (buffer instanceof ${prim.BufferName}) - return (PointerIO

)get${prim.CapName}Instance(); - #end - throw new UnsupportedOperationException(); - } - - private static final AtomicReference stringInstance = new AtomicReference(); - public static PointerIO getStringInstance() { - return atomicInstance(stringInstance, String.class);/* - PointerIO io = stringInstance.get(); - if (io != null) - return io; - - if (stringInstance.compareAndSet(null, io = getInstance(String.class))) - return io; - - return stringInstance.get();*/ - } - -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/StructIO.java b/libraries/BridJ/src/main/velocity/org/bridj/StructIO.java deleted file mode 100644 index 71b26f863..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/StructIO.java +++ /dev/null @@ -1,945 +0,0 @@ -package org.bridj; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import org.bridj.CallIO.NativeObjectHandler; -import org.bridj.util.*; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Member; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Type; -import java.nio.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.Set; -import org.bridj.ann.Virtual; -import org.bridj.ann.Array; -import org.bridj.ann.Union; -import org.bridj.ann.Bits; -import org.bridj.ann.Field; -import org.bridj.ann.Struct; -import org.bridj.ann.Alignment; -import static org.bridj.Pointer.*; -import static org.bridj.util.AnnotationUtils.*; - -/** - * Representation of a C struct's memory layout, built thanks to the annotations found in the Java bindings.
- * End-users should not use this class, it's used by runtimes.
- * Annotations currently used are {@link org.bridj.ann.Virtual}, {@link org.bridj.ann.Array}, {@link org.bridj.ann.Bits}, {@link org.bridj.ann.Field}, {@link org.bridj.ann.Alignment} and soon {@link org.bridj.ann.Struct} - * @author ochafik - */ -public class StructIO { - - static Map structIOs = new HashMap(); - - /** - * Interface for type customizers that can be used to perform platform-specific type adjustments or other hacks.
- * A type customizer can be specified with {@link Struct#customizer() }.
- * Each implementation must have a default constructor, and an unique instance of each implementation class will be cached by {@link StructIO#getCustomizer(java.lang.Class) }. - * @deprecated The StructIO API is subject to future changes. Use this with care and be prepared to migrate your code... - */ - @Deprecated - public interface Customizer { - /** - * Last chance to remove field declarations - */ - void beforeAggregation(StructIO io, List fieldDecls); - /** - * Last chance to remove aggregated fields - */ - void beforeLayout(StructIO io, List aggregatedFields); - /** - * This method can alter the aggregated fields and may even call again the performLayout(aggregatedFields) method. - * This is before field offsets and sizes are propagated to field declarations. - */ - void afterLayout(StructIO io, List aggregatedFields); - /** - * Called after everything is setup in the StructIO.
- * It is the most dangerous callback, here it's advised to only call the prependBytes, appendBytes and setFieldOffset methods. - */ - void afterBuild(StructIO io); - } - public static class DefaultCustomizer implements Customizer { - public void beforeAggregation(StructIO io, List fieldDecls) {} - public void beforeLayout(StructIO io, List aggregatedFields) {} - public void afterLayout(StructIO io, List aggregatedFields) {} - public void afterBuild(StructIO io) {} - }; - - static Customizer dummyCustomizer = new DefaultCustomizer(); - static Map customizers = new HashMap(); - static synchronized Customizer getCustomizer(Class structClass) { - Customizer c = customizers.get(structClass); - if (c == null) { - Struct s = structClass.getAnnotation(Struct.class); - if (s != null) { - Class customizerClass = s.customizer(); - if (customizerClass != null && customizerClass != Customizer.class) { - try { - c = customizerClass.newInstance(); - } catch (Throwable th) { - throw new RuntimeException("Failed to create customizer of class " + customizerClass.getName() + " for struct class " + structClass.getName() + " : " + th, th); - } - } - } - if (c == null) - c = dummyCustomizer; - customizers.put(structClass, c); - } - return c; - } - public static StructIO getInstance(Type structType) { - return getInstance(Utils.getClass(structType), structType); - } - public static StructIO getInstance(Class structClass, Type structType) { - synchronized (structIOs) { - StructIO io = structIOs.get(structType == null ? structClass : structType); - if (io == null) { - io = new StructIO(structClass, structType); - if (io != null) - registerStructIO(structClass, structType, io); - } - return (StructIO)io; - } - } - - public static synchronized StructIO registerStructIO(Class structClass, Type structType, StructIO io) { - structIOs.put(structType, io); - return io; - } - - /** - * Internal metadata on a struct field - */ - public static class FieldDesc { - public long alignment = -1; - public long byteOffset = -1, byteLength = -1; - public long bitOffset, bitLength = -1; - public long arrayLength = 1; - public boolean isArray, isNativeObject; - public Type nativeTypeOrPointerTargetType; - public java.lang.reflect.Field field; - Type valueType; - Method getter; - String name; - boolean isCLong, isSizeT; - - public void offset(long bytes) { - byteOffset += bytes; - } - @Override - public String toString() { - return "Field(byteOffset = " + byteOffset + ", byteLength = " + byteLength + ", bitOffset = " + bitOffset + ", bitLength = " + bitLength + (nativeTypeOrPointerTargetType == null ? "" : ", ttype = " + nativeTypeOrPointerTargetType) + ")"; - } - } - public static class FieldDecl { - final FieldDesc desc = new FieldDesc(); - Method setter; - long index = -1, unionWith = -1;//, byteOffset = -1; - Class valueClass; - Class declaringClass; - boolean isBitField; - - @Override - public String toString() { - return desc.name + " (index = " + index + (unionWith < 0 ? "" : ", unionWith = " + unionWith) + ", desc = " + desc + ")"; - } - } - public static class AggregatedFieldDesc extends FieldDesc { - public List fields = new ArrayList(); - } - - - static class SolidRanges { - long[] offsets, lengths; - static class Builder { - List offsets = new ArrayList(), lengths = new ArrayList(); - long lastOffset = -1, nextOffset = 0; - int count; - void add(FieldDesc f) { - long offset = f.byteOffset; - long length = f.byteLength; - - if (offset == lastOffset) { - lengths.set(count - 1, Math.max(lengths.get(count - 1), length)); - } else if (offset == nextOffset && count != 0) { - lengths.set(count - 1, lengths.get(count - 1) + length); - } else { - offsets.add(offset); - lengths.add(length); - count++; - } - lastOffset = offset; - nextOffset = offset + length; - } - SolidRanges toSolidRanges() { - SolidRanges r = new SolidRanges(); - r.offsets = new long[count]; - r.lengths = new long[count]; - for (int i = 0; i < count; i++) { - r.offsets[i] = offsets.get(i); - r.lengths[i] = lengths.get(i); - } - return r; - } - } - - } - protected PointerIO pointerIO; - protected volatile FieldDesc[] fields; - private long structSize = -1; - private long structAlignment = -1; - protected final Class structClass; - protected final Type structType; - protected boolean hasFieldFields; - - public void prependBytes(long bytes) { - build(); - for (FieldDesc field : fields) { - field.offset(bytes); - } - structSize += bytes; - } - public void appendBytes(long bytes) { - build(); - structSize += bytes; - } - public void setFieldOffset(String fieldName, long fieldOffset, boolean propagateChanges) { - build(); - - long propagatedOffset = 0; - for (FieldDesc field : fields) { - if (field.name.equals(fieldName)) { - propagatedOffset = fieldOffset - field.byteOffset; - field.offset(propagatedOffset); - if (!propagateChanges) - return; - structSize += propagatedOffset; - } else if (propagateChanges) - field.offset(propagatedOffset); - return; - } - } - - Customizer customizer; - public StructIO(Class structClass, Type structType) { - this.structClass = structClass; - this.structType = structType; - this.customizer = getCustomizer(structClass); - // Don't call build here, for recursive initialization cases (TODO test this) - } - - boolean isVirtual() { - for (Method m : structClass.getMethods()) { - if (m.getAnnotation(Virtual.class) != null) - return true; - } - return false; - } - public Class getStructClass() { - return structClass; - } - public Type getStructType() { - return structType; - } - - @Override - public String toString() { - return "StructIO(" + Utils.toString(structType) + ")"; - } - - public synchronized PointerIO getPointerIO() { - if (pointerIO == null) - pointerIO = new CommonPointerIOs.StructPointerIO(this); - - return pointerIO; - } - - protected long alignSize(long size, long alignment) { - if (alignment > 1) { - long r = size % alignment; - if (r != 0) - size += alignment - r; - } - return size; - } - - - /// Call whenever an instanceof a struct that depends on that StructIO is created - void build() { - if (fields == null) { - synchronized (this) { - if (fields == null) { - fields = computeStructLayout(); - if (fields.length == 0) { - if (BridJ.verbose) - BridJ.info("No fields found in " + Utils.toString(structType) + " (maybe they weren't declared as public ?)"); - } - customizer.afterBuild(this); - if (BridJ.debug) - BridJ.info(describe()); - } - } - } - } - - public final long getStructSize() { - build(); - return structSize; - } - - public final long getStructAlignment() { - build(); - return structAlignment; - } - - /** - * Orders the fields to match the actual structure layout - */ - protected void orderFields(List fields) { - Collections.sort(fields, new Comparator() { - - //@Override - public int compare(FieldDecl o1, FieldDecl o2) { - long d = o1.index - o2.index; - if (d != 0) - return d < 0 ? -1 : d == 0 ? 0 : 1; - - if (o1.declaringClass.isAssignableFrom(o2.declaringClass)) - return -1; - if (o2.declaringClass.isAssignableFrom(o1.declaringClass)) - return 1; - - throw new RuntimeException("Failed to order fields " + o2.desc.name + " and " + o2.desc.name); - } - - }); - } - - protected boolean acceptFieldGetter(Member member, boolean getter) { - if ((member instanceof Method) && ((Method)member).getParameterTypes().length != (getter ? 0 : 1)) - return false; - - if (((AnnotatedElement)member).getAnnotation(Field.class) == null) - return false; - - int modifiers = member.getModifiers(); - - return //Modifier.isNative(modifiers) && - !Modifier.isStatic(modifiers);// && - //!forbiddenGetterNames.contains(method.getName()); - } - - protected FieldDecl createFieldDecl(java.lang.reflect.Field getter) { - FieldDecl field = createFieldDecl((Member)getter); - field.desc.field = getter; - field.desc.valueType = getter.getGenericType(); - field.valueClass = getter.getType(); - return field; - } - protected FieldDecl createFieldDecl(Method getter) { - FieldDecl field = createFieldDecl((Member)getter); - field.desc.getter = getter; - field.desc.valueType = getter.getGenericReturnType(); - field.valueClass = getter.getReturnType(); - return field; - } - protected FieldDecl createFieldDecl(Member member) { - FieldDecl field = new FieldDecl(); - field.declaringClass = member.getDeclaringClass(); - - String name = member.getName(); - if (name.matches("get[A-Z].*")) - name = Character.toLowerCase(name.charAt(3)) + name.substring(4); - - field.desc.name = name; - - AnnotatedElement getter = (AnnotatedElement)member; - Field fil = getter.getAnnotation(Field.class); - Bits bits = getter.getAnnotation(Bits.class); - Array arr = getter.getAnnotation(Array.class); - if (fil != null) { - field.index = fil.value(); - //field.byteOffset = fil.offset(); - field.unionWith = fil.unionWith(); - } - if (field.unionWith < 0 && field.declaringClass.getAnnotation(Union.class) != null) - field.unionWith = 0; - - if (bits != null) - field.desc.bitLength = bits.value(); - if (arr != null) { - long length = 1; - for (long dim : arr.value()) - length *= dim; - field.desc.arrayLength = length; - field.desc.isArray = true; - } - field.desc.isCLong = isAnnotationPresent(org.bridj.ann.CLong.class, getter); - field.desc.isSizeT = isAnnotationPresent(org.bridj.ann.Ptr.class, getter); - return field; - } - - /** - * Creates a list of structure fields - */ - protected List listFields() { - List list = new ArrayList(); - for (Method method : structClass.getMethods()) { - if (acceptFieldGetter(method, true)) { - FieldDecl io = createFieldDecl(method); - try { - Method setter = structClass.getMethod(method.getName(), io.valueClass); - if (acceptFieldGetter(setter, false)) - io.setter = setter; - } catch (Exception ex) { - //assert BridJ.info("No setter for getter " + method); - } - if (io != null) - list.add(io); - } - } - - int nFieldFields = 0; - for (java.lang.reflect.Field field : structClass.getFields()) { - if (acceptFieldGetter(field, true)) { - FieldDecl io = createFieldDecl(field); - if (io != null) { - list.add(io); - nFieldFields++; - } - } - } - if (nFieldFields > 0) - BridJ.warning("Struct " + structClass.getName() + " has " + nFieldFields + " struct fields implemented as Java fields, which won't give the best performance and might require counter-intuitive calls to BridJ.readFromNative / .writeToNative. Please consider using JNAerator to generate your struct instead."); - - return list; - } - - protected static int primTypeLength(Class primType) { - if (primType == Integer.class || primType == int.class) - return 4; - else if(primType == Long.class || primType == long.class) - return 8; - else if(primType == Short.class || primType == short.class) - return 2; - else if(primType == Byte.class || primType == byte.class) - return 1; - else if(primType == Character.class || primType == char.class) - return 2; - else if(primType == Boolean.class || primType == boolean.class) { - /* - BOOL is int, not C++'s bool ! - if (Platform.isWindows()) - return 4; - else - */ - return 1; - } else if(primType == Float.class || primType == float.class) - return 4; - else if(primType == Double.class || primType == double.class) - return 8; - else if(Pointer.class.isAssignableFrom(primType)) - return Pointer.SIZE; - else - throw new UnsupportedOperationException("Field type " + primType.getName() + " not supported yet"); - - } - private List aggregatedFields; - - public List getAggregatedFields() { - build(); - return aggregatedFields; - } - - - - protected FieldDesc[] computeStructLayout() { - List fieldDecls = listFields(); - orderFields(fieldDecls); - - customizer.beforeAggregation(this, fieldDecls); - - Map, Long>, List> fieldsMap = new LinkedHashMap, Long>, List>(); - for (FieldDecl field : fieldDecls) { - if (field.index < 0) - throw new RuntimeException("Negative field index not allowed for field " + field.desc.name); - - long index = field.unionWith >= 0 ? field.unionWith : field.index; - Pair, Long> key = new Pair, Long>(field.declaringClass, index); - List siblings = fieldsMap.get(key); - if (siblings == null) - fieldsMap.put(key, siblings = new ArrayList()); - siblings.add(field); - } - - Alignment alignment = structClass.getAnnotation(Alignment.class); - structAlignment = alignment != null ? alignment.value() : 1; //TODO get platform default alignment - - aggregatedFields = new ArrayList(); - for (List fieldGroup : fieldsMap.values()) { - AggregatedFieldDesc aggregatedField = aggregateFields(fieldGroup); - if (aggregatedField != null) - aggregatedFields.add(aggregatedField); - } - - // Last chance to remove fields : - customizer.beforeLayout(this, aggregatedFields); - - performLayout(aggregatedFields); - customizer.afterLayout(this, aggregatedFields); - - List fieldDescs = new ArrayList(); - SolidRanges.Builder rangesBuilder = new SolidRanges.Builder(); - for (AggregatedFieldDesc aggregatedField : aggregatedFields) { - for (FieldDecl field : aggregatedField.fields) {//fieldGroup) { - // Propagate offsets of aggregated field descs to field decls's descs - FieldDesc desc = field.desc; - desc.byteOffset = aggregatedField.byteOffset; - desc.byteLength = aggregatedField.byteLength; - desc.bitOffset = aggregatedField.bitOffset; - - fieldDescs.add(desc); - rangesBuilder.add(desc); - - hasFieldFields = hasFieldFields || desc.field != null; - } - } - solidRanges = rangesBuilder.toSolidRanges(); - return fieldDescs.toArray(new FieldDesc[fieldDescs.size()]); - } - - protected long alignmentOf(Type tpe) { - Class c = PointerIO.getClass(tpe); - if (StructObject.class.isAssignableFrom(c)) - return StructIO.getInstance(c).getStructAlignment(); - return BridJ.sizeOf(tpe); - } - protected AggregatedFieldDesc aggregateFields(List fieldGroup) { - AggregatedFieldDesc aggregatedField = new AggregatedFieldDesc(); - boolean isMultiFields = fieldGroup.size() > 1; - aggregatedField.fields.addAll(fieldGroup); - for (FieldDecl field : fieldGroup) { - if (field.valueClass.isArray()) - throw new RuntimeException("Struct fields cannot be array types : please use a combination of Pointer and @Array (for instance, an int[10] is a @Array(10) Pointer)."); - if (field.valueClass.isPrimitive()) { - if (field.desc.isCLong) - field.desc.byteLength = CLong.SIZE; - else if (field.desc.isSizeT) - field.desc.byteLength = SizeT.SIZE; - else - field.desc.byteLength = primTypeLength(field.valueClass); - } else if (field.valueClass == CLong.class) { - field.desc.byteLength = CLong.SIZE; - } else if (field.valueClass == SizeT.class) { - field.desc.byteLength = SizeT.SIZE; - } else if (StructObject.class.isAssignableFrom(field.valueClass)) { - field.desc.nativeTypeOrPointerTargetType = field.desc.valueType; - StructIO io = StructIO.getInstance(field.valueClass, field.desc.valueType); - field.desc.byteLength = io.getStructSize(); - field.desc.alignment = io.getStructAlignment(); - field.desc.isNativeObject = true; - } else if (ValuedEnum.class.isAssignableFrom(field.valueClass)) { - field.desc.nativeTypeOrPointerTargetType = (field.desc.valueType instanceof ParameterizedType) ? PointerIO.getClass(((ParameterizedType)field.desc.valueType).getActualTypeArguments()[0]) : null; - Class c = PointerIO.getClass(field.desc.nativeTypeOrPointerTargetType); - if (IntValuedEnum.class.isAssignableFrom(c)) - field.desc.byteLength = 4; - else - throw new RuntimeException("Enum type unknown : " + c); - //field.callIO = CallIO.Utils.createPointerCallIO(field.valueClass, field.desc.valueType); - } else if (TypedPointer.class.isAssignableFrom(field.valueClass)) { - field.desc.nativeTypeOrPointerTargetType = field.desc.valueType; - if (field.desc.isArray) - throw new RuntimeException("Typed pointer field cannot be an array : " + field.desc.name); - field.desc.byteLength = Pointer.SIZE; - //field.callIO = CallIO.Utils.createPointerCallIO(field.valueClass, field.desc.valueType); - } else if (Pointer.class.isAssignableFrom(field.valueClass)) { - Type tpe = (field.desc.valueType instanceof ParameterizedType) ? ((ParameterizedType)field.desc.valueType).getActualTypeArguments()[0] : null; - if (!(tpe instanceof WildcardType) && !(tpe instanceof TypeVariable)) - field.desc.nativeTypeOrPointerTargetType = tpe; - if (field.desc.isArray) { - field.desc.byteLength = BridJ.sizeOf(field.desc.nativeTypeOrPointerTargetType); - field.desc.alignment = alignmentOf(field.desc.nativeTypeOrPointerTargetType); - } else - field.desc.byteLength = Pointer.SIZE; - //field.callIO = CallIO.Utils.createPointerCallIO(field.valueClass, field.desc.valueType); - } else if (Buffer.class.isAssignableFrom(field.valueClass)) { - if (field.valueClass == IntBuffer.class) - field.desc.byteLength = 4; - else if (field.valueClass == LongBuffer.class) - field.desc.byteLength = 8; - else if (field.valueClass == ShortBuffer.class) - field.desc.byteLength = 2; - else if (field.valueClass == ByteBuffer.class) - field.desc.byteLength = 1; - else if (field.valueClass == FloatBuffer.class) - field.desc.byteLength = 4; - else if (field.valueClass == DoubleBuffer.class) - field.desc.byteLength = 8; - else - throw new UnsupportedOperationException("Field array type " + field.valueClass.getName() + " not supported yet"); - } else if (field.valueClass.isArray() && field.valueClass.getComponentType().isPrimitive()) { - field.desc.byteLength = primTypeLength(field.valueClass.getComponentType()); - } else { - //throw new UnsupportedOperationException("Field type " + field.valueClass.getName() + " not supported yet"); - StructIO io = StructIO.getInstance(field.valueClass, field.desc.valueType); - long s = io.getStructSize(); - if (s > 0) - field.desc.byteLength = s; - else - throw new UnsupportedOperationException("Field type " + field.valueClass.getName() + " not supported yet"); - } - - aggregatedField.alignment = Math.max( - aggregatedField.alignment, - field.desc.alignment >= 0 ? - field.desc.alignment : - field.desc.byteLength - ); - - long length = field.desc.arrayLength * field.desc.byteLength; - if (length >= aggregatedField.byteLength) - aggregatedField.byteLength = length; - - if (field.desc.bitLength >= 0) { - if (isMultiFields) - throw new RuntimeException("No support for bit fields unions yet !"); - aggregatedField.bitLength = field.desc.bitLength; - aggregatedField.byteLength = (aggregatedField.bitLength >>> 3) + ((aggregatedField.bitLength & 7) != 0 ? 1 : 0); - } - - //if (!isMultiFields) { - //aggregatedField.isArray = field.desc.isArray; - //aggregatedField.isNativeObject = field.desc.isNativeObject; - //aggregatedField.nativeTypeOrPointerTargetType = field.desc.nativeTypeOrPointerTargetType; - //aggregatedField.name = field.desc.name; - //aggregatedField.valueType = field.desc.valueType; - //} - //if (fieldDeclaringType == null) - // fieldDeclaringType = field.declaringClass; - //else if (!fieldDeclaringType.equals(field.declaringClass)) - // throw new RuntimeException("Fields in the same field group must pertain to the same declaring class : " + fieldGroup); - - } - return aggregatedField; - } - - protected void performLayout(Iterable aggregatedFields) { - structSize = 0; - structAlignment = -1; - - Struct s = structClass.getAnnotation(Struct.class); - int pack = s != null ? s.pack() : -1; - - if (isVirtual()) { - structSize += Pointer.SIZE; - if (Pointer.SIZE >= structAlignment) - structAlignment = Pointer.SIZE; - } - - int cumulativeBitOffset = 0; - - for (FieldDesc aggregatedField : aggregatedFields) { - structAlignment = Math.max(structAlignment, aggregatedField.alignment); - - if (aggregatedField.bitLength < 0) { - // Align fields as appropriate - if (cumulativeBitOffset != 0) { - cumulativeBitOffset = 0; - structSize++; - } - //structAlignment = Math.max(structAlignment, aggregatedField.alignment); - structSize = alignSize(structSize, pack > 0 ? pack : aggregatedField.alignment); - } - long - fieldByteOffset = structSize, - fieldBitOffset = cumulativeBitOffset; - - if (aggregatedField.bitLength >= 0) { - //fieldByteLength = (aggregatedField.bitLength >>> 3) + ((aggregatedField.bitLength & 7) != 0 ? 1 : 0); - cumulativeBitOffset += aggregatedField.bitLength; - structSize += cumulativeBitOffset >>> 3; - cumulativeBitOffset &= 7; - } else { - structSize += aggregatedField.byteLength; - } - - aggregatedField.byteOffset = fieldByteOffset; - aggregatedField.bitOffset = fieldBitOffset; - } - - if (cumulativeBitOffset > 0) - structSize = alignSize(structSize + 1, structAlignment); - else if (structSize > 0) - structSize = alignSize(structSize, pack > 0 ? pack : structAlignment); - - } - - SolidRanges solidRanges; - - public boolean equal(StructObject a, StructObject b) { - return compare(a, b) == 0; - } - public int compare(StructObject a, StructObject b) { - Pointer pA = pointerTo(a), pB = pointerTo(b); - if (pA == null || pB == null) - return pA != null ? 1 : pB != null ? -1 : 0; - - long[] offsets = solidRanges.offsets, lengths = solidRanges.lengths; - for (int i = 0, n = offsets.length; i < n; i++) { - long offset = offsets[i], length = lengths[i]; - int cmp = pA.compareBytesAtOffset(offset, pB, offset, length); - if (cmp != 0) - return cmp; - } - return 0; - } - - public final String describe(StructObject struct) { - StringBuilder b = new StringBuilder(); - b.append(describe(structType)).append(" { "); - for (FieldDesc fd : fields) { - b.append("\n\t").append(fd.name).append(" = "); - try { - Object value; - if (fd.getter != null) - value = fd.getter.invoke(struct); - else - value = fd.field.get(struct); - - if (value instanceof String) - b.append('"').append(value.toString().replaceAll("\"", "\\\"")).append('"'); - else if (value instanceof Character) - b.append('\'').append(value).append('\''); - else if (value instanceof NativeObject) { - String d = BridJ.describe((NativeObject)value); - b.append(d.replaceAll("\n", "\n\t")); - } else - b.append(value); - } catch (Throwable th) { - if (BridJ.debug) - th.printStackTrace(); - b.append("?"); - } - b.append("; "); - } - b.append("\n}"); - return b.toString(); - } - static String describe(Type t) { - if (t == null) - return "?"; - if (t instanceof Class) - return ((Class)t).getSimpleName(); - return t.toString(). - replaceAll("\\bjava\\.lang\\.", ""). - replaceAll("\\borg\\.bridj\\.cpp\\.com\\.", ""). - replaceAll("\\borg\\.bridj\\.Pointer\\b", "Pointer"); - - } - - public final String describe() { - StringBuilder b = new StringBuilder(); - b.append("// "); - b.append("size = ").append(structSize).append(", "); - b.append("alignment = ").append(structAlignment); - b.append("\nstruct "); - b.append(describe(structType)).append(" { "); - for (int iField = 0, nFields = fields.length; iField < nFields; iField++) { - FieldDesc fd = fields[iField]; - b.append("\n\t"); - b.append("@Field(").append(iField).append(") "); - if (fd.isCLong) - b.append("@CLong "); - else if (fd.isSizeT) - b.append("@Ptr "); - b.append(describe(fd.valueType)).append(" ").append(fd.name).append("; "); - - b.append("// "); - b.append("offset = ").append(fd.byteOffset).append(", "); - b.append("length = ").append(fd.byteLength).append(", "); - if (fd.bitOffset != 0) - b.append("bitOffset = ").append(fd.bitOffset).append(", "); - if (fd.bitLength != -1) - b.append("bitLength = ").append(fd.bitLength).append(", "); - if (fd.arrayLength != 1) - b.append("arrayLength = ").append(fd.arrayLength).append(", "); - if (fd.alignment != 1) - b.append("alignment = ").append(fd.alignment);//.append(", "); - } - b.append("\n}"); - return b.toString(); - } - - /** - * Write struct fields implemented as Java fields to the corresponding native memory (Java fields are written to native memory).
- * This does not concern normal structs as generated by JNAerator (which use getters and setters methods that read and write the fields directly from / to the native memory), but rather structs that are in the JNA style. - */ - public final void writeFieldsToNative(StructObject struct) { - if (!hasFieldFields) - return; - try { - for (FieldDesc fd : fields) { - if (fd.field == null) - continue; - - if (fd.isArray) - continue; - - Object value = fd.field.get(struct); - if (value instanceof NativeObject) {//fd.isNativeObject) { - if (value != null) - BridJ.writeToNative((NativeObject)value); - continue; - } - Pointer ptr = struct.peer.offset(fd.byteOffset); - Type tpe = fd.isNativeObject || fd.isArray ? fd.nativeTypeOrPointerTargetType : fd.field.getGenericType(); - ptr = ptr.as(tpe); - ptr = fixIntegralTypeIOToMatchLength(ptr, fd.byteLength, fd.arrayLength); - - if (fd.isCLong && CLong.SIZE == 4 || fd.isSizeT && SizeT.SIZE == 4) - value = (int)(long)(Long)value; - - ptr.set(value); - } - } catch (Throwable th) { - throw new RuntimeException("Unexpected error while writing fields from struct " + Utils.toString(structType) + " (" + pointerTo(struct) + ")", th); - } - } - static Pointer fixIntegralTypeIOToMatchLength(Pointer ptr, long byteLength, long arrayLength) { - long targetSize = ptr.getTargetSize(); - if (targetSize * arrayLength == byteLength) - return ptr; - - Type targetType = ptr.getTargetType(); - if (!Utils.isSignedIntegral(targetType)) - return ptr; - //throw new UnsupportedOperationException("Cannot change byte length of non-signed-integral fields (field type = " + Utils.toString(targetType) + ", target size = " + ptr.getTargetSize() + ", byteLength = " + byteLength + ")"); - - switch ((int)byteLength) { - case 1: - return ptr.as(byte.class); - case 2: - return ptr.as(short.class); - case 4: - return ptr.as(int.class); - case 8: - return ptr.as(long.class); - default: - return ptr; // this case happens... TODO check // throw new RuntimeException("Invalid integral type byte length : " + byteLength); - } - } - /** - * Read struct fields implemented as Java fields from the corresponding native memory (Java fields are read from native memory).
- * This does not concern normal structs as generated by JNAerator (which use getters and setters methods that read and write the fields directly from / to the native memory), but rather structs that are in the JNA style. - */ - public final void readFieldsFromNative(StructObject struct) { - if (!hasFieldFields) - return; - try { - for (FieldDesc fd : fields) { - if (fd.field == null) - continue; - - Pointer ptr = struct.peer.offset(fd.byteOffset); - Type tpe = fd.isNativeObject || fd.isArray ? fd.nativeTypeOrPointerTargetType : fd.field.getGenericType(); - ptr = ptr.as(tpe); - ptr = fixIntegralTypeIOToMatchLength(ptr, fd.byteLength, fd.arrayLength); - Object value; - if (fd.isArray) { - ptr = ptr.validElements(fd.arrayLength); - value = ptr; - } else { - value = ptr.get(); - } - fd.field.set(struct, value); - - if (value instanceof NativeObject) {//if (fd.isNativeObject) { - if (value != null) - BridJ.readFromNative((NativeObject)value); - } - } - } catch (Throwable th) { - throw new RuntimeException("Unexpected error while reading fields from struct " + Utils.toString(structType) + " (" + pointerTo(struct) + ") : " + th, th); - } - } - public final Pointer getPointerField(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - Pointer p; - if (fd.isArray) { - p = struct.peer.offset(fd.byteOffset).as(fd.nativeTypeOrPointerTargetType); - p = p.validElements(fd.arrayLength); - } else { - p = struct.peer.getPointerAtOffset(fd.byteOffset, fd.nativeTypeOrPointerTargetType); - } - return p; - } - - public final void setPointerField(StructObject struct, int fieldIndex, Pointer value) { - FieldDesc fd = fields[fieldIndex]; - struct.peer.setPointerAtOffset(fd.byteOffset, value); - } - - public final T getTypedPointerField(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - PointerIO pio = PointerIO.getInstance(fd.nativeTypeOrPointerTargetType); - return pio.castTarget(struct.peer.getSizeTAtOffset(fd.byteOffset)); - } - public final O getNativeObjectField(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - return (O)struct.peer.offset(fd.byteOffset).getNativeObject(fd.nativeTypeOrPointerTargetType); - } - - public final void setNativeObjectField(StructObject struct, int fieldIndex, O value) { - FieldDesc fd = fields[fieldIndex]; - struct.peer.offset(fd.byteOffset).setNativeObject(value, fd.nativeTypeOrPointerTargetType); - } - - public final > IntValuedEnum getEnumField(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - return FlagSet.fromValue(struct.peer.getIntAtOffset(fd.byteOffset), (Class)fd.nativeTypeOrPointerTargetType); - } - - public final void setEnumField(StructObject struct, int fieldIndex, ValuedEnum value) { - FieldDesc fd = fields[fieldIndex]; - struct.peer.setIntAtOffset(fd.byteOffset, (int)value.value()); - } - -#foreach ($prim in $primitives) - public final void set${prim.CapName}Field(StructObject struct, int fieldIndex, ${prim.Name} value) { - FieldDesc fd = fields[fieldIndex]; - #if ($prim.isSignedIntegral()) - if ($prim.Size != fd.byteLength) - struct.peer.setSignedIntegralAtOffset(fd.byteOffset, value, fd.byteLength); - #end - struct.peer.set${prim.CapName}AtOffset(fd.byteOffset, value); - } - public final ${prim.Name} get${prim.CapName}Field(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - #if ($prim.isSignedIntegral()) - if ($prim.Size != fd.byteLength) - return (${prim.Name})struct.peer.getSignedIntegralAtOffset(fd.byteOffset, fd.byteLength); - #end - return struct.peer.get${prim.CapName}AtOffset(fd.byteOffset); - } -#end - -#foreach ($sizePrim in ["SizeT", "CLong"]) - public final void set${sizePrim}Field(StructObject struct, int fieldIndex, long value) { - FieldDesc fd = fields[fieldIndex]; - struct.peer.set${sizePrim}AtOffset(fd.byteOffset, value); - } - public final long get${sizePrim}Field(StructObject struct, int fieldIndex) { - FieldDesc fd = fields[fieldIndex]; - return struct.peer.get${sizePrim}AtOffset(fd.byteOffset); - } -#end -} diff --git a/libraries/BridJ/src/main/velocity/org/bridj/Version.java b/libraries/BridJ/src/main/velocity/org/bridj/Version.java deleted file mode 100644 index 47b1fe30a..000000000 --- a/libraries/BridJ/src/main/velocity/org/bridj/Version.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bridj; - -public final class Version { - public static final String MAVEN_VERSION = "${project_version}"; - public static final String VERSION_SPECIFIC_SUB_PACKAGE = "${versionSpecificSubPackage}"; -} diff --git a/libraries/BridJ/src/test/cpp/dependsOnTest/GNUmakefile b/libraries/BridJ/src/test/cpp/dependsOnTest/GNUmakefile deleted file mode 100644 index 9310c390a..000000000 --- a/libraries/BridJ/src/test/cpp/dependsOnTest/GNUmakefile +++ /dev/null @@ -1,21 +0,0 @@ -#BUILD_CONFIG=debug - -TOP = $(DYNCALL_HOME)/dyncall -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/prolog.gmake - -TARGET_DLL = dependsOnTest -INSTALL_LIB = 1 - -# uses some dyncall headers - no other dependencies. - -UNITS += test - -CPPFLAGS += -I../test - -LINK_LIBS += stdc++ -LINK_DIRS += ../test/$(BUILD_DIR) -LINK_LIBS += test - -LDFLAGS += -rpath - -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/epilog.gmake diff --git a/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/libdependsOnTest.dylib b/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/libdependsOnTest.dylib deleted file mode 100755 index 25ac0e7e0..000000000 Binary files a/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/libdependsOnTest.dylib and /dev/null differ diff --git a/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/test.o b/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/test.o deleted file mode 100644 index fac269cd9..000000000 Binary files a/libraries/BridJ/src/test/cpp/dependsOnTest/build_out/darwin_universal_gcc_release/test.o and /dev/null differ diff --git a/libraries/BridJ/src/test/cpp/dependsOnTest/test.cpp b/libraries/BridJ/src/test/cpp/dependsOnTest/test.cpp deleted file mode 100644 index 55f10c9cb..000000000 --- a/libraries/BridJ/src/test/cpp/dependsOnTest/test.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "test.h" - -int addThatDependsOnTest(int a, int b) { - return forwardCall(getAdder(), a, b); -} - diff --git a/libraries/BridJ/src/test/cpp/test/GNUmakefile b/libraries/BridJ/src/test/cpp/test/GNUmakefile deleted file mode 100644 index c282f9189..000000000 --- a/libraries/BridJ/src/test/cpp/test/GNUmakefile +++ /dev/null @@ -1,60 +0,0 @@ -#BUILD_CONFIG=debug - -TOP = $(DYNCALL_HOME)/dyncall -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/prolog.gmake - -TARGET_DLL = test -INSTALL_LIB = 1 - -# uses some dyncall headers - no other dependencies. - -UNITS += test -UNITS += structs -UNITS += templates -ifdef BUILD_OS_darwin -UNITS += objctest -endif - -#CPPFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -#LDFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden - -ifdef BUILD_OS_darwin -CPPFLAGS += -I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/ -#LDFLAGS += -lobjc -LDFLAGS += -framework Foundation -endif - -ifdef BUILD_OS_iphoneos -CPPFLAGS += -I/Users/ochafik/src/jamvm/src -LDFLAGS += -lobjc -endif - -ifdef BUILD_OS_linux -CPPFLAGS += -I/usr/lib/jvm/java-6-sun/include/ -CPPFLAGS += -I/usr/lib/jvm/java-6-sun/include/linux -CPPFLAGS += -I/usr/lib/jvm/java-6-openjdk/include/ -CPPFLAGS += -I/usr/lib/jvm/java-6-openjdk/include/linux -#LDFLAGS += -ljni -endif - -ifdef BUILD_OS_sunos -# http://gcc.gnu.org/onlinedocs/gcc/Solaris-2-Options.html -CPPFLAGS += -I/usr/jdk/instances/jdk1.5.0/include -CPPFLAGS += -I/usr/jdk/instances/jdk1.5.0/include/solaris -LDFLAGS += -mimpure-text -LDFLAGS += -L/opt/csw/gcc4/lib -endif - -ifdef BUILD_OS_windows -CPPFLAGS += "-IC:\Program Files\Microsoft SDKs\Windows\v6.0A\Include" -endif - -ifdef BUILD_OS_darwin -LDFLAGS += -install_name @rpath/libtest.dylib -else -LDFLAGS += -install_name @rpath/test.so -endif - -LINK_LIBS += stdc++ - -include $(DYNCALL_HOME)/dyncall/buildsys/gmake/epilog.gmake diff --git a/libraries/BridJ/src/test/cpp/test/dllmain.cpp b/libraries/BridJ/src/test/cpp/test/dllmain.cpp deleted file mode 100644 index c86a28578..000000000 --- a/libraries/BridJ/src/test/cpp/test/dllmain.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// dllmain.cpp : Définit le point d'entrée pour l'application DLL. -#include "stdafx.h" - -BOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - diff --git a/libraries/BridJ/src/test/cpp/test/objctest.h b/libraries/BridJ/src/test/cpp/test/objctest.h deleted file mode 100644 index 852c4a373..000000000 --- a/libraries/BridJ/src/test/cpp/test/objctest.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#ifndef _OBJC_PROXY_H -#define _OBJC_PROXY_H - -#include - -#import - -@class DelgHolder; - -@protocol Delg - @required - - (int)add:(int)a to:(int)b; -@end - -@interface DelgHolder : NSObject - { - id delegate; - } - @property (nonatomic, assign) id delegate; - - - (int)outerAdd:(int)a to:(int)b; -@end - -@interface DelgImpl : NSObject - - (int)add:(int)a to:(int)b; -@end - -int forwardBlockCallIntIntInt(int (^block)(int, int), int a, int b); - -#endif // _OBJC_PROXY_H diff --git a/libraries/BridJ/src/test/cpp/test/objctest.m b/libraries/BridJ/src/test/cpp/test/objctest.m deleted file mode 100644 index df14e2400..000000000 --- a/libraries/BridJ/src/test/cpp/test/objctest.m +++ /dev/null @@ -1,25 +0,0 @@ -#include "objctest.h" - -@implementation DelgHolder - - @synthesize delegate; - - - (int)outerAdd:(int)a to:(int)b { - return [[self delegate] add: a to: b]; - } -@end - -@implementation DelgImpl - - (int)add:(int)a to:(int)b { - return a + b; - } -@end - -//Foo *obj = [[Foo alloc] init]; -//[obj setDelegate:self]; - -int forwardBlockCallIntIntInt(int (^block)(int, int), int a, int b) -{ - return block(a, b); -} - diff --git a/libraries/BridJ/src/test/cpp/test/stdafx.cpp b/libraries/BridJ/src/test/cpp/test/stdafx.cpp deleted file mode 100644 index 804d0881d..000000000 --- a/libraries/BridJ/src/test/cpp/test/stdafx.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "stdafx.h" - diff --git a/libraries/BridJ/src/test/cpp/test/stdafx.h b/libraries/BridJ/src/test/cpp/test/stdafx.h deleted file mode 100644 index 33dc79f0d..000000000 --- a/libraries/BridJ/src/test/cpp/test/stdafx.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "targetver.h" - -#ifdef __GNUC__ - #include -#else - #define WIN32_LEAN_AND_MEAN - #include -#endif - -#endif // __STDAFX_H diff --git a/libraries/BridJ/src/test/cpp/test/structs.cpp b/libraries/BridJ/src/test/cpp/test/structs.cpp deleted file mode 100644 index 0b09b65e8..000000000 --- a/libraries/BridJ/src/test/cpp/test/structs.cpp +++ /dev/null @@ -1,45 +0,0 @@ - -#include "stdafx.h" -#include "test.h" -#include "jni.h" -#include "math.h" - -#include -#include -#include -#include - -using namespace std; - -struct S_int { - int a; -}; - -struct S_int2 { - int a, b; -}; - -struct S_jlong4 { - jlong a, b, c, d; -}; - -struct S_jlong10 { - jlong a[10]; -}; - -TEST_API jint incr(S_int s) { - return s.a + 1; -} -TEST_API jint sum(S_int2 s) { - return s.a + s.b; -} -TEST_API jlong sum(S_jlong4 s) { - return s.a + s.b + s.c + s.d; -} -TEST_API jlong sum(S_jlong10 s) { - jlong tot = 0; - for (int i = 0; i < 10; i++) - tot += s.a[i]; - return tot; -} - diff --git a/libraries/BridJ/src/test/cpp/test/targetver.h b/libraries/BridJ/src/test/cpp/test/targetver.h deleted file mode 100644 index 74b374591..000000000 --- a/libraries/BridJ/src/test/cpp/test/targetver.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -// Les macros suivantes définissent la plateforme minimale requise. La plateforme minimale requise -// est la version de Windows, Internet Explorer etc. qui dispose des fonctionnalités nécessaires pour exécuter -// votre application. Les macros fonctionnent en activant toutes les fonctionnalités disponibles sur les versions de la plateforme jusqu'à la -// version spécifiée. - -// Modifiez les définitions suivantes si vous devez cibler une plateforme avant celles spécifiées ci-dessous. -// Reportez-vous à MSDN pour obtenir les dernières informations sur les valeurs correspondantes pour les différentes plateformes. -#ifndef WINVER // Spécifie que la plateforme minimale requise est Windows Vista. -#define WINVER 0x0600 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions de Windows. -#endif - -#ifndef _WIN32_WINNT // Spécifie que la plateforme minimale requise est Windows Vista. -#define _WIN32_WINNT 0x0600 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions de Windows. -#endif - -#ifndef _WIN32_WINDOWS // Spécifie que la plateforme minimale requise est Windows 98. -#define _WIN32_WINDOWS 0x0410 // Attribuez la valeur appropriée à cet élément pour cibler Windows Me ou version ultérieure. -#endif - -#ifndef _WIN32_IE // Spécifie que la plateforme minimale requise est Internet Explorer 7.0. -#define _WIN32_IE 0x0700 // Attribuez la valeur appropriée à cet élément pour cibler d'autres versions d'Internet Explorer. -#endif diff --git a/libraries/BridJ/src/test/cpp/test/templates.cpp b/libraries/BridJ/src/test/cpp/test/templates.cpp deleted file mode 100644 index d88e550c8..000000000 --- a/libraries/BridJ/src/test/cpp/test/templates.cpp +++ /dev/null @@ -1,59 +0,0 @@ - -#include "stdafx.h" -#include "test.h" - -#include -#include -#include - -using namespace std; - - -template -vector newVector(int n) { - vector v; - for (int i = 0; i < n; i++) - v.push_back((T)i); - return v; -} -template -void push_back(vector& v, const T* value) { - v.push_back(*value); -} -template -void clear(vector& v) { - v.clear(); -} -template -void resize(vector& v, int n) { - v.resize(n); -} - - -template -int sizeofVector() { - return sizeof(vector); -} - -#define VECTOR_OPS(t) \ -template vector TEST_API newVector(int); - -VECTOR_OPS(int); -VECTOR_OPS(long long); -VECTOR_OPS(double); -VECTOR_OPS(float); - -template int TEST_API sizeofVector(); -template int TEST_API sizeofVector(); -template int TEST_API sizeofVector(); -template int TEST_API sizeofVector(); - -typedef vector (*IntVecFun)(int); -typedef int (*SizeTFun)(); - -extern "C" { -TEST_API IntVecFun newIntVector = newVector; -TEST_API SizeTFun sizeofIntVector = sizeofVector; -} - -TEST_API void toto() {} diff --git a/libraries/BridJ/src/test/cpp/test/test.cpp b/libraries/BridJ/src/test/cpp/test/test.cpp deleted file mode 100644 index 03673aed1..000000000 --- a/libraries/BridJ/src/test/cpp/test/test.cpp +++ /dev/null @@ -1,527 +0,0 @@ - -#include "stdafx.h" -#include "test.h" -#include "jni.h" -#include "math.h" -#include - -#ifdef _WIN32 -struct timeval { - long a; - long b; -}; -#endif - -#include -#include -#include -#include - -using namespace std; - -TEST_API int ntest=0; - -TEST_API void __cdecl voidTest() -{ - //printf("ok\n"); - //cout << "Ok\n"; -} -TEST_API double __cdecl sinInt(int d) -{ - return d;//sin((double)d); -} -//extern "C" { -TEST_API void passVarArgs(char* out, bool isInt, ...) { - va_list args; - va_start(args, isInt); - if (isInt) - *(long long*)out = va_arg(args, long long); - else - *(double*)out = va_arg(args, double); - va_end(args); -} -//} -TEST_API double __cdecl testSum(const double *values, size_t n) -{ - double total = 0; - for (size_t i = 0; i < n; i++) { - total += values[i]; - } - return total; -} -TEST_API double __cdecl testSumi(const double *values, int n) -{ - double total = 0; - for (int i = 0; i < n; i++) { - total += values[i]; - } - return total; -} -TEST_API long long __cdecl testSumll(const double *values, int n) -{ - long long value = (long long)testSumi(values, n); - return value; -} -TEST_API int __cdecl testSumInt(const double *values, int n) -{ - return (int)testSum(values, n); -} -TEST_API void __cdecl testInPlaceSquare(double *values, size_t n) -{ - for (size_t i = 0; i < n; i++) { - double value = values[i]; - values[i] = value * value; - } -} - -TEST_API jlong testAddJLongs(jlong a, jlong b) { - return a + b; -} -TEST_API long testAddCLongs(long a, long b) { - return a + b; -} - -extern "C" { - -void otherFunc() { - //cout << "other\n"; -} -JNIEXPORT jint JNICALL Java_org_bridj_PerfLib_testAddJNI(JNIEnv *, jclass, jint a, jint b) { - otherFunc(); - return a + b; -} -TEST_API int __cdecl testAddDyncall(int a, int b) -{ - //if (true) - // testAddDyncall(a, b); - otherFunc(); - return a + b; -} -TEST_API int __cdecl testAddJNA(int a, int b) -{ - otherFunc(); - return a + b; -} -JNIEXPORT jdouble JNICALL Java_org_bridj_PerfLib_testASinB(JNIEnv *, jclass, jint a, jint b) -{ - otherFunc(); - return a * sin((double)b); -} -TEST_API double __cdecl testASinB(int a, int b) -{ - otherFunc(); - return a * sin((double)b); -} - -} - -#if defined(DC__Arch_Intel_x86) -#include -#include -#include -#endif - -Ctest::Ctest() -{ - //cout << "Constructing Ctest instance\n"; - firstField = -123456; - secondField = 12; - -#if defined(DC__Arch_Intel_x86) -/* - dlopen("/System/Library/Frameworks/Foundation.framework/Foundation", RTLD_LAZY); - { - id clsPool = objc_getClass("NSAutoreleasePool"); - id poolInst = objc_msgSend(clsPool, sel_registerName("new")); - printf("#\n# poolInst in Ctest::Ctest : %ld\n#\n", (long int)poolInst); - } - */ -#endif - - //printf("Ctest::Ctest() (this = %ld)\n", (long int)(size_t)this); -} -Ctest::Ctest(int firstField) { - this->firstField = firstField; - this->secondField = 0; -} -Ctest::~Ctest() -{ - //cout << "Destructor of Ctest is called !\n"; -} - - -Ctest* Ctest::getInstance() { - return new Ctest(); -} -ETest* Ctest::getEnum() { - return new ETest[1]; -} -int* Ctest::getInt() { - return new int[1]; -} -const string& Ctest2::toString() { - static string s = ""; - return s; -} - -Ctest* Ctest2::getCtestInstance() { - return new Ctest(); -} - -TEST_API size_t __cdecl sizeOfCtest() { - return sizeof(Ctest); -} -TEST_API size_t __cdecl sizeOfCtest2() { - return sizeof(Ctest2); -} -int Ctest::testVirtualAdd(int a, int b) { - //printf("Ctest::testVirtualAdd(%d, %d) (this = %ld)\n", a, b, (long int)(size_t)this); - return a + b; -} - -int testIndirectVirtualAdd(Ctest* pTest, int a, int b) { - return pTest->testVirtualAdd(a, b); -} - -int Ctest::testAdd(int a, int b) { - //printf("Ctest::testAdd(%d, %d) (this = %ld)\n", a, b, (long int)(size_t)this); - return a + b; -} - -int Ctest::testAddStdCall(void* ptr, int a, int b) { - //printf("Ctest::testAddStdCall(ptr, %d, %d) (this = %ld, ptr = %ld)\n", a, b, (long int)(size_t)this, (long int)(size_t)ptr); - if (ptr) - return 0; - return a + b; -} - -int Ctest::testVirtualAddStdCall(void* ptr, int a, int b) { - //printf("Ctest::testVirtualAddStdCall(ptr, %d, %d) (this = %ld, ptr = %ld)\n", a, b, (long int)(size_t)this, (long int)(size_t)ptr); - if (ptr) - return 0; - return a + b; -} - -TEST_API ETest testEnum(ETest e) -{ - return e; -} -TEST_API ETest testEnumRetSecond() -{ - return eSecond; -} -TEST_API int testEnumArgSecond(ETest e) -{ - return e == eSecond; -} -TEST_API int testEnumArgs(ETest e, ETest f) -{ - return e == f; -} -TEST_API ETest testVoidEnum() -{ - return (ETest)0; -} -TEST_API ETest testIntEnum(int i, ETest e) -{ - return e; -} - -void Ctest::static_void() { - -} - -TEST_API Ctest* createTest() { - Ctest* test = new Ctest(); - return test; -} - -Ctest2::Ctest2() : Ctest(), fState(NULL), fDestructedState(0) -{ - //cout << "Constructing Ctest2 instance\n"; - //printf("Ctest2::Ctest2() (this = %ld)\n", (long int)(size_t)this); -} -Ctest2::~Ctest2() -{ - if (fState) - *fState = fDestructedState; - - //cout << "Destructing Ctest2 instance\n"; - -} -void Ctest2::setState(int* pState) { - fState = pState; -} -void Ctest2::setDestructedState(int destructedState) { - fDestructedState = destructedState; -} - -int Ctest2::testVirtualAdd(int a, int b) { - int ret = a + b * 2; - //printf("Ctest2::testVirtualAdd(%d, %d) = %d (this = %ld)\n", a, b, ret, (long int)(size_t)this); - return ret; -} -int Ctest2::testAdd(int a, int b) { - int ret = a + b * 2; - //printf("Ctest2::testAdd(%d, %d) = %d (this = %ld)\n", a, b, ret, (long int)(size_t)this); - return ret; -} - -template -InvisibleSourcesTemplate::InvisibleSourcesTemplate(int arg) { - cout << "Instantiating invisible sources template with arg " << arg << "\n"; -} -template -T* InvisibleSourcesTemplate::createSome() { - cout << "Creating some T\n"; - return new T(); -} -template -void InvisibleSourcesTemplate::deleteSome(T* pValue) { - cout << "Deleting some T\n"; - delete pValue; -} - -template class InvisibleSourcesTemplate<10, int>; -template class InvisibleSourcesTemplate<10, std::string>; - - - - -template -void Temp1::temp(T) {} - -template -void Temp2::temp(T1, T2) {} - -template -void TempV::temp(T) {} - -template class Temp1; -template class Temp1; - -template class Temp2; -template class Temp2; -template class Temp2; - -template class TempV; -template class TempV; - -TEST_API void* test_pvoid() { return NULL; } -TEST_API int* test_pint() { return NULL; } -TEST_API int test_int() { return 0; } -TEST_API void test_void_double() { return; } -TEST_API int test_int_double() { return 0; } -TEST_API int test_int_float(float) { return 0; } -TEST_API void test_void() { } - -typedef void (*fun_void)(); -typedef void (*fun_void_int)(int); -typedef int (*fun_int)(); -typedef int (*fun_int_float)(float); -TEST_API fun_void test_fun_void() { return NULL; } -TEST_API fun_void test_fun_void__double(double) { return NULL; } -TEST_API fun_void_int test_fun_void_int() { return NULL; } -TEST_API fun_int test_fun_int() { return NULL; } -TEST_API fun_int_float test_fun_int_float() { return NULL; } -TEST_API fun_int_float test_fun_int_float__double(double) { return NULL; } - - -TEST_API int test_int_short(short s) { return 0; } - -typedef int (*fun_iii)(int, int); -int add(int a, int b) { - return a + b; -} -TEST_API void* getAdder_pvoid() { - return (void*)(size_t)10; -} -TEST_API jlong getAdder_long() { - return (jlong)10; -} -TEST_API fun_iii getAdder() { - return add; -} -TEST_API fun_iii getAdder_raw() { - return add; -} -TEST_API int forwardCall(fun_iii f, int a, int b) { - int res = f(a, b); - return res; -} - -typedef void* (*fun_ppp)(void*, void*); -void* addPtrs(void* a, void* b) { - return (void*)((size_t)a + (size_t)b); -} -TEST_API fun_ppp getPtrAdder() { - return addPtrs; -} -TEST_API fun_ppp getPtrAdder_raw() { - return addPtrs; -} -TEST_API void* forwardPtrCall(fun_ppp f, void* a, void* b) { - void* res = f(a, b); - return res; -} - -TEST_API std::string* newString() { - return new std::string(); -} -TEST_API void appendToString(std::string* s, const char* a) { - (*s) += a; -} -TEST_API void reserveString(std::string* s, size_t reservedSize) { - s->reserve(reservedSize); -} -TEST_API void resizeString(std::string* s, size_t newSize) { - s->resize(newSize); -} -TEST_API void deleteString(std::string* s) { - delete s; -} -TEST_API const char* stringCStr(std::string* s) { - return s->c_str(); -} - -TEST_API std::wstring* newWString() { - return new std::wstring(); -} -TEST_API void appendToWString(std::wstring* s, const wchar_t* a) { - (*s) += a; -} -TEST_API void reserveWString(std::wstring* s, size_t reservedSize) { - s->reserve(reservedSize); -} -TEST_API void resizeWString(std::wstring* s, size_t newSize) { - s->resize(newSize); -} -TEST_API void deleteWString(std::wstring* s) { - delete s; -} -TEST_API const wchar_t* wstringCStr(std::wstring* s) { - return s->c_str(); -} - -TEST_API void crashIllegalAccess() { - ((char*)NULL)[0] = '0'; -} -class MyException : public std::exception { - std::string msg; -public: - MyException(const char* what) : msg(what) {} - virtual ~MyException() throw() {} - virtual const char* what() const throw() { - return msg.c_str(); - } -}; - -TEST_API void throwMyExceptionByValue(const char* message) { - throw MyException(message); -} -TEST_API void throwNewMyException(const char* message) { - throw new MyException(message); -} -TEST_API void throwInt(int value) { - throw value; -} -TEST_API time_t test_incr_timet(time_t value) { - return value + 1; -} -TEST_API size_t test_incr_sizet(size_t value) { - return value + 1; -} -TEST_API long test_incr_clong(long value) { - return value + 1; -} - -TEST_API size_t __cdecl sizeOfTimeval() { - return sizeof(timeval); -} - -enum MyEnum { - One, Two, Three -}; -TEST_API MyEnum __cdecl intToMyEnum(int value) { - return (MyEnum)value; -} - -TEST_API int __cdecl MyEnumToInt(MyEnum value) { - return (int)value; -} - -int Module::add(int a, int b) { - return a + b; -} -AModule::AModule() { -} -AModule::~AModule() {} -int AModule::add(int a, int b) { - return a + b; -} - -int AModule::subtract(int a, int b) { - return a - b; -} - -int testIVirtualAdd(IVirtual* pVirtual, int a, int b) { - return pVirtual->add(a, b); -} - -TEST_API const wchar_t* getSomeWString() { - return L"1234567890"; -} - -#include "../../../../target/generated-test-resources/org/bridj/CallTest.cpp" - -#ifdef _WIN32 - -#include "OAIdl.h" // for VARIANT -#include "Vfw.h" // for CAPDRIVERCAPS - -TEST_API size_t __cdecl sizeOfVARIANT() { - return sizeof(VARIANT); -} -TEST_API size_t __cdecl sizeOfDECIMAL() { - return sizeof(DECIMAL); -} -TEST_API size_t __cdecl sizeOfCAPDRIVERCAPS() { - return sizeof(CAPDRIVERCAPS); -} - -TEST_API void __cdecl setLastWindowsError() { - SetLastError(1); -} - -#endif - -typedef struct { - char part1[100]; - char part2[100]; - char part3[100]; -} stuff; - -typedef struct { - char type[100]; - char date[100]; - char time[100]; - stuff stuff1, stuff2; -} container; - -typedef struct { - char text[512]; - container cont[1]; -} message; - -TEST_API size_t sizeOf_message() { - return sizeof(message); -} - -TEST_API size_t sizeOf_stuff() { - return sizeof(stuff); -} - -TEST_API size_t sizeOf_container() { - return sizeof(container); -} - diff --git a/libraries/BridJ/src/test/cpp/test/test.h b/libraries/BridJ/src/test/cpp/test/test.h deleted file mode 100644 index b407b581f..000000000 --- a/libraries/BridJ/src/test/cpp/test/test.h +++ /dev/null @@ -1,138 +0,0 @@ -#ifdef __GNUC__ - #define TEST_API - #define __cdecl - #define __stdcall -#else - #ifdef TEST_EXPORTS - #define TEST_API __declspec(dllexport) - #else - #define TEST_API __declspec(dllimport) - #endif -#endif - -#include - -typedef enum ETest { - eFirst, - eSecond, - eThird -} ETest; - -class TEST_API Ctest { -public: - int firstField; - int secondField; - Ctest(); - Ctest(int firstField); - //virtual - ~Ctest(); - virtual int testVirtualAdd(int a, int b); - int testAdd(int a, int b); - virtual int __stdcall testVirtualAddStdCall(void* ptr, int a, int b); - int __stdcall testAddStdCall(void* ptr, int a, int b); - - static void static_void(); - static Ctest* getInstance(); - static ETest* getEnum(); - static int* getInt(); -}; - -TEST_API int testIndirectVirtualAdd(Ctest* pTest, int a, int b); - -class TEST_API Ctest2 : public Ctest { - int* fState; - int fDestructedState; -public: - Ctest2(); - //virtual - ~Ctest2(); - void setState(int* pState); - void setDestructedState(int destructedState); - virtual int testVirtualAdd(int a, int b); - int testAdd(int a, int b); - const std::string& toString(); - static Ctest* getCtestInstance(); -}; - -template -class TEST_API InvisibleSourcesTemplate { -public: - InvisibleSourcesTemplate(int arg); - T* createSome(); - void deleteSome(T* pValue); -}; - -template -class TEST_API Temp1 { -public: - virtual ~Temp1() {} - void temp(T); -}; - -template -class TEST_API Temp2 { -public: - virtual ~Temp2() {} - void temp(T1, T2); -}; - -template -class TEST_API TempV { -public: - virtual ~TempV() {} - void temp(T); -}; - -extern TEST_API int ntest; -TEST_API Ctest* createTest(); - -TEST_API ETest testEnum(ETest e); -TEST_API ETest testVoidEnum(); -TEST_API ETest testIntEnum(int i, ETest e); - -extern "C" { - TEST_API void __cdecl voidTest(); - TEST_API double __cdecl sinInt(int); - TEST_API double __cdecl testSum(const double *values, size_t n); - TEST_API double __cdecl testSumi(const double *values, int n); - TEST_API long long __cdecl testSumll(const double *values, int n); - TEST_API int __cdecl testSumInt(const double *values, int n); - TEST_API void __cdecl testInPlaceSquare(double *values, size_t n); - - TEST_API void __cdecl setLastWindowsError(); -} - -class TEST_API Module { -public: - virtual ~Module() {}; - virtual int add(int a, int b); -}; - -class TEST_API IModule { -public: - virtual ~IModule() {}; - virtual int add(int a, int b) = 0; - virtual int subtract(int a, int b) = 0; -}; - -class TEST_API AModule : public IModule { -public: - AModule(); - virtual ~AModule(); - virtual int add(int a, int b); - virtual int subtract(int a, int b); -}; - -class TEST_API IVirtual { -public: - virtual ~IVirtual() {} - virtual int add(int a, int b) = 0; -}; - -TEST_API int testIVirtualAdd(IVirtual* pVirtual, int a, int b); - - -typedef int (*fun_iii)(int, int); -TEST_API fun_iii getAdder(); -TEST_API int forwardCall(fun_iii f, int a, int b); - diff --git a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/project.pbxproj b/libraries/BridJ/src/test/cpp/test/test.xcodeproj/project.pbxproj deleted file mode 100644 index 79ad4ddb6..000000000 --- a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/project.pbxproj +++ /dev/null @@ -1,174 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXFileReference section */ - 90E6FC6315BC0D3B00A88421 /* dllmain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = dllmain.cpp; sourceTree = ""; }; - 90E6FC6415BC0D3B00A88421 /* GNUmakefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GNUmakefile; sourceTree = ""; }; - 90E6FC6515BC0D3B00A88421 /* objctest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = objctest.h; sourceTree = ""; }; - 90E6FC6615BC0D3B00A88421 /* objctest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = objctest.m; sourceTree = ""; }; - 90E6FC6715BC0D3B00A88421 /* stdafx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = stdafx.cpp; sourceTree = ""; }; - 90E6FC6815BC0D3B00A88421 /* stdafx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = stdafx.h; sourceTree = ""; }; - 90E6FC6915BC0D3B00A88421 /* structs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = structs.cpp; sourceTree = ""; }; - 90E6FC6A15BC0D3B00A88421 /* targetver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = targetver.h; sourceTree = ""; }; - 90E6FC6B15BC0D3B00A88421 /* templates.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = templates.cpp; sourceTree = ""; }; - 90E6FC6C15BC0D3B00A88421 /* test.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = test.cpp; sourceTree = ""; }; - 90E6FC6D15BC0D3B00A88421 /* test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = test.h; sourceTree = ""; }; - 90E6FC7315BC0D9400A88421 /* CallTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CallTest.cpp; path = "../../../../target/generated-test-resources/org/bridj/CallTest.cpp"; sourceTree = ""; }; - 90E6FC7515BC0F0D00A88421 /* libtest.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libtest.dylib; path = build_out/darwin_universal_gcc_release/libtest.dylib; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXGroup section */ - 90E6FC3B15BC0C7B00A88421 = { - isa = PBXGroup; - children = ( - 90E6FC7515BC0F0D00A88421 /* libtest.dylib */, - 90E6FC6315BC0D3B00A88421 /* dllmain.cpp */, - 90E6FC6415BC0D3B00A88421 /* GNUmakefile */, - 90E6FC6515BC0D3B00A88421 /* objctest.h */, - 90E6FC6615BC0D3B00A88421 /* objctest.m */, - 90E6FC6715BC0D3B00A88421 /* stdafx.cpp */, - 90E6FC6815BC0D3B00A88421 /* stdafx.h */, - 90E6FC7315BC0D9400A88421 /* CallTest.cpp */, - 90E6FC6915BC0D3B00A88421 /* structs.cpp */, - 90E6FC6A15BC0D3B00A88421 /* targetver.h */, - 90E6FC6B15BC0D3B00A88421 /* templates.cpp */, - 90E6FC6C15BC0D3B00A88421 /* test.cpp */, - 90E6FC6D15BC0D3B00A88421 /* test.h */, - ); - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXLegacyTarget section */ - 90E6FC4215BC0C7C00A88421 /* test */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "$(ACTION)"; - buildConfigurationList = 90E6FC4515BC0C7C00A88421 /* Build configuration list for PBXLegacyTarget "test" */; - buildPhases = ( - ); - buildToolPath = ./BuildNative; - buildWorkingDirectory = ../../../..; - dependencies = ( - ); - name = test; - passBuildSettingsInEnvironment = 1; - productName = test; - }; -/* End PBXLegacyTarget section */ - -/* Begin PBXProject section */ - 90E6FC3D15BC0C7B00A88421 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 90E6FC4015BC0C7B00A88421 /* Build configuration list for PBXProject "test" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 90E6FC3B15BC0C7B00A88421; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 90E6FC4215BC0C7C00A88421 /* test */, - ); - }; -/* End PBXProject section */ - -/* Begin XCBuildConfiguration section */ - 90E6FC4315BC0C7C00A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - }; - name = Debug; - }; - 90E6FC4415BC0C7C00A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - SDKROOT = macosx; - }; - name = Release; - }; - 90E6FC4615BC0C7C00A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEBUGGING_SYMBOLS = YES; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - OTHER_CFLAGS = ""; - OTHER_LDFLAGS = ""; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 90E6FC4715BC0C7C00A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - OTHER_CFLAGS = ""; - OTHER_LDFLAGS = ""; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 90E6FC4015BC0C7B00A88421 /* Build configuration list for PBXProject "test" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FC4315BC0C7C00A88421 /* Debug */, - 90E6FC4415BC0C7C00A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 90E6FC4515BC0C7C00A88421 /* Build configuration list for PBXLegacyTarget "test" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FC4615BC0C7C00A88421 /* Debug */, - 90E6FC4715BC0C7C00A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 90E6FC3D15BC0C7B00A88421 /* Project object */; -} diff --git a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/test.xcscheme b/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/test.xcscheme deleted file mode 100644 index 647e6e522..000000000 --- a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/test.xcscheme +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist b/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 7cf4eadf1..000000000 --- a/libraries/BridJ/src/test/cpp/test/test.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - test.xcscheme - - orderHint - 2 - - - SuppressBuildableAutocreation - - 90E6FC4215BC0C7C00A88421 - - primary - - - - - diff --git a/libraries/BridJ/src/test/cpp/test/test_extract.cpp b/libraries/BridJ/src/test/cpp/test/test_extract.cpp deleted file mode 100644 index b5c1662fe..000000000 --- a/libraries/BridJ/src/test/cpp/test/test_extract.cpp +++ /dev/null @@ -1,41 +0,0 @@ - -typedef struct { - char part1[100]; - char part2[100]; - char part3[100]; -} stuff_; - -typedef struct { - char part1[100]; - char part2[100]; - char part3[100]; -} something_; - -typedef struct { - char type[100]; - char date[100]; - char time[100]; - stuff_ stuff; - something_ something; -} container_; - -typedef struct { - char text[512]; - container_ container[1]; -} message_; - -TEST_API void Connect(message_ *Pmessage) -{ - char temp [512] ; - - printf("*********** START test **************\n"); - strcpy (temp, Pmessage->text); - - printf("text:%s\n",Pmessage->text); - strcpy(Pmessage->container[0].type,"Type1"); - printf("Type1=%s\n",Pmessage->container[0].type); - - strcpy(Pmessage->text,"Completed test"); - - printf("*********** END test**************\n"); -} diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.pbxproj b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.pbxproj deleted file mode 100644 index ed76517b7..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.pbxproj +++ /dev/null @@ -1,243 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 90E6FC7015BC0D5A00A88421 /* testexe.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 90E6FC6F15BC0D5A00A88421 /* testexe.cpp */; }; - 90E6FC8315BC1A7F00A88421 /* libtest.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 90E6FC8115BC1A6D00A88421 /* libtest.dylib */; }; - 90E6FC8415BC1A8200A88421 /* libbridj.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 90E6FC7F15BC1A5400A88421 /* libbridj.dylib */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 90E6FC2615BC0C3400A88421 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = /usr/share/man/man1/; - dstSubfolderSpec = 0; - files = ( - ); - runOnlyForDeploymentPostprocessing = 1; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 90E6FC2815BC0C3400A88421 /* testexe */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = testexe; sourceTree = BUILT_PRODUCTS_DIR; }; - 90E6FC6F15BC0D5A00A88421 /* testexe.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = testexe.cpp; path = ../../../main/cpp/buildsys/vs2008/testexe/testexe.cpp; sourceTree = ""; }; - 90E6FC7F15BC1A5400A88421 /* libbridj.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libbridj.dylib; path = ../../../main/cpp/bridj/build_out/darwin_universal_gcc_debug/libbridj.dylib; sourceTree = ""; }; - 90E6FC8115BC1A6D00A88421 /* libtest.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libtest.dylib; path = build_out/darwin_universal_gcc_debug/libtest.dylib; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 90E6FC2515BC0C3400A88421 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 90E6FC8315BC1A7F00A88421 /* libtest.dylib in Frameworks */, - 90E6FC8415BC1A8200A88421 /* libbridj.dylib in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 90E6FC1D15BC0C3400A88421 = { - isa = PBXGroup; - children = ( - 90E6FC8115BC1A6D00A88421 /* libtest.dylib */, - 90E6FC7F15BC1A5400A88421 /* libbridj.dylib */, - 90E6FC6F15BC0D5A00A88421 /* testexe.cpp */, - 90E6FC2915BC0C3400A88421 /* Products */, - ); - sourceTree = ""; - }; - 90E6FC2915BC0C3400A88421 /* Products */ = { - isa = PBXGroup; - children = ( - 90E6FC2815BC0C3400A88421 /* testexe */, - ); - name = Products; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 90E6FC2715BC0C3400A88421 /* testexe */ = { - isa = PBXNativeTarget; - buildConfigurationList = 90E6FC3215BC0C3400A88421 /* Build configuration list for PBXNativeTarget "testexe" */; - buildPhases = ( - 90E6FC8515BC1A9700A88421 /* ShellScript */, - 90E6FC2415BC0C3400A88421 /* Sources */, - 90E6FC2515BC0C3400A88421 /* Frameworks */, - 90E6FC2615BC0C3400A88421 /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = testexe; - productName = testexe; - productReference = 90E6FC2815BC0C3400A88421 /* testexe */; - productType = "com.apple.product-type.tool"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 90E6FC1F15BC0C3400A88421 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 90E6FC2215BC0C3400A88421 /* Build configuration list for PBXProject "testexe" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 90E6FC1D15BC0C3400A88421; - productRefGroup = 90E6FC2915BC0C3400A88421 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 90E6FC2715BC0C3400A88421 /* testexe */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXShellScriptBuildPhase section */ - 90E6FC8515BC1A9700A88421 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = /Users/ochafik/github/nativelibs4java2/libraries/BridJ/BuildNative_Debug; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 90E6FC2415BC0C3400A88421 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 90E6FC7015BC0D5A00A88421 /* testexe.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 90E6FC3015BC0C3400A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - }; - name = Debug; - }; - 90E6FC3115BC0C3400A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.7; - SDKROOT = macosx; - }; - name = Release; - }; - 90E6FC3315BC0C3400A88421 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - HEADER_SEARCH_PATHS = ( - "/Users/ochafik/src/dyncall/dyncall/**", - ../../../main/cpp/bridj, - /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/, - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../../main/cpp/bridj/build_out/darwin_universal_gcc_release\"", - "\"$(SRCROOT)/build_out/darwin_universal_gcc_release\"", - "\"$(SRCROOT)/../../../main/cpp/bridj/build_out/darwin_universal_gcc_debug\"", - "\"$(SRCROOT)/build_out/darwin_universal_gcc_debug\"", - ); - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 90E6FC3415BC0C3400A88421 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - HEADER_SEARCH_PATHS = ( - "/Users/ochafik/src/dyncall/dyncall/**", - ../../../main/cpp/bridj, - /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/, - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../../main/cpp/bridj/build_out/darwin_universal_gcc_release\"", - "\"$(SRCROOT)/build_out/darwin_universal_gcc_release\"", - "\"$(SRCROOT)/../../../main/cpp/bridj/build_out/darwin_universal_gcc_debug\"", - "\"$(SRCROOT)/build_out/darwin_universal_gcc_debug\"", - ); - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 90E6FC2215BC0C3400A88421 /* Build configuration list for PBXProject "testexe" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FC3015BC0C3400A88421 /* Debug */, - 90E6FC3115BC0C3400A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 90E6FC3215BC0C3400A88421 /* Build configuration list for PBXNativeTarget "testexe" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90E6FC3315BC0C3400A88421 /* Debug */, - 90E6FC3415BC0C3400A88421 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 90E6FC1F15BC0C3400A88421 /* Project object */; -} diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 3b1e527b8..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index 4a4fddcd8..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/project.xcworkspace/xcuserdata/ochafik.xcuserdatad/UserInterfaceState.xcuserstate +++ /dev/null @@ -1,4234 +0,0 @@ - - - - - $archiver - NSKeyedArchiver - $objects - - $null - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 2 - - - CF$UID - 3 - - - NS.objects - - - CF$UID - 4 - - - CF$UID - 210 - - - - IDEWorkspaceDocument - 20101392-D11B-468F-B225-38DF4B7040B0 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 5 - - - CF$UID - 6 - - - CF$UID - 7 - - - CF$UID - 8 - - - CF$UID - 9 - - - CF$UID - 10 - - - CF$UID - 11 - - - CF$UID - 12 - - - CF$UID - 13 - - - CF$UID - 14 - - - NS.objects - - - CF$UID - 15 - - - CF$UID - 16 - - - CF$UID - 141 - - - CF$UID - 157 - - - CF$UID - 162 - - - CF$UID - 165 - - - CF$UID - 197 - - - CF$UID - 198 - - - CF$UID - 102 - - - CF$UID - 102 - - - - BreakpointsActivated - DefaultEditorStatesForURLs - DebuggingWindowBehavior - ActiveRunDestination - ActiveScheme - LastCompletedPersistentSchemeBasedActivityReport - DocumentWindows - RecentEditorDocumentURLs - AppFocusInMiniDebugging - MiniDebuggingConsole - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 17 - - - CF$UID - 18 - - - CF$UID - 19 - - - CF$UID - 20 - - - NS.objects - - - CF$UID - 21 - - - CF$UID - 78 - - - CF$UID - 130 - - - CF$UID - 148 - - - - Xcode.Xcode3ProjectSupport.EditorDocument.Xcode3Project - Xcode.IDEKit.EditorDocument.SourceCode - IDEQuickLookEditor.Editor - Xcode.IDEKit.EditorDocument.LogDocument - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 22 - - - NS.objects - - - CF$UID - 26 - - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 23 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/ - - - $classes - - NSMutableString - NSString - NSObject - - $classname - NSMutableString - - - $classes - - NSURL - NSObject - - $classname - NSURL - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 27 - - - CF$UID - 28 - - - CF$UID - 29 - - - CF$UID - 30 - - - NS.objects - - - CF$UID - 31 - - - CF$UID - 44 - - - CF$UID - 45 - - - CF$UID - 59 - - - - Xcode3ProjectEditor.sourceList.splitview - Xcode3ProjectEditorPreviousTargetEditorClass - Xcode3ProjectEditorSelectedDocumentLocations - Xcode3ProjectEditor_Xcode3BuildPhasesEditor - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 33 - - - - DVTSplitViewItems - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 34 - - - CF$UID - 40 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 37 - - - CF$UID - 38 - - - - DVTIdentifier - DVTViewMagnitude - - 170 - - $classes - - NSDictionary - NSObject - - $classname - NSDictionary - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 37 - - - CF$UID - 41 - - - - 970 - - $classes - - NSMutableArray - NSArray - NSObject - - $classname - NSMutableArray - - - $classes - - NSMutableDictionary - NSDictionary - NSObject - - $classname - NSMutableDictionary - - Xcode3BuildPhasesEditor - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 46 - - - - - $class - - CF$UID - 58 - - documentURL - - CF$UID - 47 - - selection - - CF$UID - 49 - - timestamp - - CF$UID - 48 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/ - 364649260.27669698 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 50 - - - CF$UID - 51 - - - CF$UID - 52 - - - NS.objects - - - CF$UID - 53 - - - CF$UID - 54 - - - CF$UID - 55 - - - - Editor - Target - Xcode3BuildPhasesEditorLocations - Xcode3BuildPhasesEditor - testexe - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 56 - - - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $classes - - NSArray - NSObject - - $classname - NSArray - - - $classes - - Xcode3ProjectDocumentLocation - DVTDocumentLocation - NSObject - - $classname - Xcode3ProjectDocumentLocation - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 60 - - - CF$UID - 61 - - - CF$UID - 62 - - - CF$UID - 63 - - - CF$UID - 64 - - - CF$UID - 65 - - - CF$UID - 66 - - - CF$UID - 67 - - - NS.objects - - - CF$UID - 68 - - - CF$UID - 69 - - - CF$UID - 70 - - - CF$UID - 71 - - - CF$UID - 74 - - - CF$UID - 75 - - - CF$UID - 76 - - - CF$UID - 77 - - - - kXcode3BuildPhasesEditorScrollPointKey - Xcode3BuildPhasesEditorFilterKey - 90E6FC8515BC1A9700A88421 - Xcode3BuildPhasesEditorDisclosedNamesKey2.0 - 90E6FC2415BC0C3400A88421 - 90E6FC2615BC0C3400A88421 - 90E6FC2715BC0C3400A88421 - 90E6FC2515BC0C3400A88421 - {0, 0} - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 73 - - NS.objects - - - CF$UID - 72 - - - - Link Binary With Libraries - - $classes - - NSMutableSet - NSSet - NSObject - - $classname - NSMutableSet - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 79 - - - CF$UID - 81 - - - CF$UID - 83 - - - CF$UID - 85 - - - CF$UID - 87 - - - CF$UID - 89 - - - CF$UID - 91 - - - CF$UID - 93 - - - NS.objects - - - CF$UID - 95 - - - CF$UID - 104 - - - CF$UID - 108 - - - CF$UID - 111 - - - CF$UID - 115 - - - CF$UID - 119 - - - CF$UID - 123 - - - CF$UID - 127 - - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 80 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/JNI.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 82 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 84 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/jni.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 86 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 88 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/stdafx.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 90 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/src/dyncall/dyncall/dyncallback/dyncall_args.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 92 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/src/dyncallNew/dyncall/dyncall/dyncall.h - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 94 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/var/folders/2w/_9jzy4jd1fs2px9l2yjkmwfc0000gp/T/__dyld_dyld_fatal_error_disassembly_0x00007fff5fc0106d.s - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 100 - - - CF$UID - 101 - - - CF$UID - 102 - - - CF$UID - 103 - - - - PrimaryDocumentTimestamp - PrimaryDocumentVisibleCharacterRange - HideAllIssues - PrimaryDocumentSelectedCharacterRange - 364647141.23508602 - {0, 750} - - {697, 0} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 105 - - - CF$UID - 106 - - - CF$UID - 102 - - - CF$UID - 107 - - - - 364647050.883946 - {0, 433} - {84, 3} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 109 - - - CF$UID - 110 - - - CF$UID - 102 - - - CF$UID - 68 - - - - 364647157.42539197 - {0, 1665} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 112 - - - CF$UID - 113 - - - CF$UID - 102 - - - CF$UID - 114 - - - - 364649071.49966699 - {1316, 2026} - {1466, 0} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 116 - - - CF$UID - 117 - - - CF$UID - 102 - - - CF$UID - 118 - - - - 364646756.27577102 - {0, 368} - {234, 20} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 120 - - - CF$UID - 121 - - - CF$UID - 102 - - - CF$UID - 122 - - - - 364647043.93354601 - {0, 1981} - {1208, 0} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 124 - - - CF$UID - 125 - - - CF$UID - 102 - - - CF$UID - 126 - - - - 364648581.18227601 - {1901, 3249} - {4126, 69} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 96 - - - CF$UID - 97 - - - CF$UID - 98 - - - CF$UID - 99 - - - NS.objects - - - CF$UID - 128 - - - CF$UID - 129 - - - CF$UID - 102 - - - CF$UID - 68 - - - - 364648849.08131099 - {0, 73} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 131 - - - CF$UID - 133 - - - NS.objects - - - CF$UID - 135 - - - CF$UID - 143 - - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 132 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_release/libtest.dylib - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 134 - - - - $class - - CF$UID - 24 - - NS.string - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_debug/libtest.dylib - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 136 - - - NS.objects - - - CF$UID - 137 - - - - SelectedDocumentLocations - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 138 - - - - - $class - - CF$UID - 142 - - IDEQuickLookPageNumber - - CF$UID - 141 - - documentURL - - CF$UID - 139 - - timestamp - - CF$UID - 140 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_release/libtest.dylib - 364648860.43760598 - 0 - - $classes - - IDEQuickLookDocumentLocation - DVTDocumentLocation - NSObject - - $classname - IDEQuickLookDocumentLocation - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 136 - - - NS.objects - - - CF$UID - 144 - - - - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 145 - - - - - $class - - CF$UID - 142 - - IDEQuickLookPageNumber - - CF$UID - 141 - - documentURL - - CF$UID - 146 - - timestamp - - CF$UID - 147 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_debug/libtest.dylib - 364649085.813344 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 149 - - - CF$UID - 151 - - - NS.objects - - - CF$UID - 153 - - - CF$UID - 156 - - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 150 - - - x-xcode-log://8F205468-1A1B-4527-8236-65EF2FC96289 - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 152 - - - x-xcode-log://37C7873C-8039-41F4-9D56-D2A086650F4D - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 154 - - - NS.objects - - - CF$UID - 155 - - - - SelectedDocumentLocations - - $class - - CF$UID - 57 - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 154 - - - NS.objects - - - CF$UID - 155 - - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 158 - - - CF$UID - 159 - - - NS.objects - - - CF$UID - 160 - - - CF$UID - 161 - - - - IDEDeviceLocation - IDEDeviceArchitecture - dvtdevice-local-computer:localhost - x86_64 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 163 - - - NS.objects - - - CF$UID - 164 - - - - IDENameString - testexe - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 166 - - - CF$UID - 167 - - - CF$UID - 168 - - - NS.objects - - - CF$UID - 169 - - - CF$UID - 196 - - - CF$UID - 54 - - - - IDEActivityReportCompletionSummaryStringSegments - IDEActivityReportOptions - IDEActivityReportTitle - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 170 - - - CF$UID - 177 - - - CF$UID - 181 - - - CF$UID - 186 - - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 171 - - - CF$UID - 172 - - - CF$UID - 173 - - - NS.objects - - - CF$UID - 174 - - - CF$UID - 175 - - - CF$UID - 176 - - - - IDEActivityReportStringSegmentPriority - IDEActivityReportStringSegmentBackSeparator - IDEActivityReportStringSegmentStringValue - 2 - - Build - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 171 - - - CF$UID - 172 - - - CF$UID - 173 - - - NS.objects - - - CF$UID - 178 - - - CF$UID - 179 - - - CF$UID - 180 - - - - 4 - : - testexe - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 171 - - - CF$UID - 172 - - - CF$UID - 173 - - - NS.objects - - - CF$UID - 182 - - - CF$UID - 183 - - - CF$UID - 184 - - - - 1 - │ - - $class - - CF$UID - 185 - - NS.data - - YnBsaXN0MDDUAQIDBAUGOzxYJHZlcnNpb25YJG9iamVjdHNZJGFy - Y2hpdmVyVCR0b3ASAAGGoK0HCA8QGhscJCUrMTQ3VSRudWxs0wkK - CwwNDlxOU0F0dHJpYnV0ZXNWJGNsYXNzWE5TU3RyaW5ngAOADIAC - VkZhaWxlZNMKERITFBdXTlMua2V5c1pOUy5vYmplY3RzgAuiFRaA - BIAFohgZgAaACVZOU0ZvbnRXTlNDb2xvctQKHR4fICEiI1ZOU05h - bWVWTlNTaXplWE5TZkZsYWdzgAiAByNAJgAAAAAAABENEF8QEUx1 - Y2lkYUdyYW5kZS1Cb2xk0iYnKClaJGNsYXNzbmFtZVgkY2xhc3Nl - c1ZOU0ZvbnSiKCpYTlNPYmplY3TTCiwtLi8wXE5TQ29sb3JTcGFj - ZVVOU1JHQoAKEAFGMSAwIDAA0iYnMjNXTlNDb2xvcqIyKtImJzU2 - XE5TRGljdGlvbmFyeaI1KtImJzg5XxASTlNBdHRyaWJ1dGVkU3Ry - aW5nojoqXxASTlNBdHRyaWJ1dGVkU3RyaW5nXxAPTlNLZXllZEFy - Y2hpdmVy0T0+VHJvb3SAAQAIABEAGgAjAC0AMgA3AEUASwBSAF8A - ZgBvAHEAcwB1AHwAgwCLAJYAmACbAJ0AnwCiAKQApgCtALUAvgDF - AMwA1QDXANkA4gDlAPkA/gEJARIBGQEcASUBLAE5AT8BQQFDAUoB - TwFXAVoBXwFsAW8BdAGJAYwBoQGzAbYBuwAAAAAAAAIBAAAAAAAA - AD8AAAAAAAAAAAAAAAAAAAG9 - - - - $classes - - NSMutableData - NSData - NSObject - - $classname - NSMutableData - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 171 - - - CF$UID - 187 - - - CF$UID - 188 - - - CF$UID - 173 - - - CF$UID - 189 - - - CF$UID - 190 - - - NS.objects - - - CF$UID - 191 - - - CF$UID - 192 - - - CF$UID - 193 - - - CF$UID - 195 - - - CF$UID - 192 - - - CF$UID - 192 - - - - IDEActivityReportStringSegmentType - IDEActivityReportStringSegmentDate - IDEActivityReportStringSegmentDateStyle - IDEActivityReportStringSegmentTimeStyle - 3 - 1 - - $class - - CF$UID - 194 - - NS.time - 364649297.31927902 - - - $classes - - NSDate - NSObject - - $classname - NSDate - - Today at 12:28 - 234 - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 3 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 151 - - - CF$UID - 149 - - - CF$UID - 199 - - - CF$UID - 200 - - - CF$UID - 201 - - - CF$UID - 203 - - - CF$UID - 204 - - - CF$UID - 206 - - - CF$UID - 208 - - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 47 - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 146 - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 202 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/buildsys/vs2008/testexe/testexe.cpp - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 139 - - - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 205 - - - file://localhost/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/jni.h - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 207 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/JNI.h - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 209 - - - file://localhost/Users/ochafik/github/nativelibs4java2/libraries/BridJ/src/main/cpp/bridj/RawNativeForwardCallback.h - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 211 - - - CF$UID - 212 - - - CF$UID - 213 - - - CF$UID - 214 - - - CF$UID - 215 - - - CF$UID - 216 - - - CF$UID - 217 - - - CF$UID - 218 - - - NS.objects - - - CF$UID - 219 - - - CF$UID - 220 - - - CF$UID - 102 - - - CF$UID - 3 - - - CF$UID - 216 - - - CF$UID - 221 - - - CF$UID - 15 - - - CF$UID - 102 - - - - IDEWindowFrame - IDEOrderedWorkspaceTabControllers - IDEWindowInFullscreenMode - IDEWorkspaceWindowControllerUniqueIdentifier - IDEActiveWorkspaceTabController - IDEWorkspaceTabController_0B89BC78-4018-40A8-B291-8BBB5B04D47E - IDEWindowToolbarIsVisible - IDEWindowTabBarIsVisible - {{163, 8}, {1400, 952}} - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 216 - - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 222 - - - CF$UID - 223 - - - CF$UID - 224 - - - CF$UID - 225 - - - CF$UID - 226 - - - CF$UID - 227 - - - CF$UID - 228 - - - CF$UID - 229 - - - NS.objects - - - CF$UID - 230 - - - CF$UID - 15 - - - CF$UID - 141 - - - CF$UID - 231 - - - CF$UID - 237 - - - CF$UID - 292 - - - CF$UID - 102 - - - CF$UID - 301 - - - - IDETabLabel - IDEShowNavigator - AssistantEditorsLayout - IDEWorkspaceTabControllerUtilityAreaSplitView - IDENavigatorArea - IDEWorkspaceTabControllerDesignAreaSplitView - IDEShowUtilities - IDEEditorArea - Build testexe - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 232 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 233 - - - CF$UID - 235 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 37 - - - CF$UID - 234 - - - - 652 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 37 - - - CF$UID - 236 - - - - 224 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 238 - - - CF$UID - 239 - - - CF$UID - 240 - - - CF$UID - 241 - - - CF$UID - 242 - - - NS.objects - - - CF$UID - 243 - - - CF$UID - 261 - - - CF$UID - 241 - - - CF$UID - 266 - - - CF$UID - 276 - - - - Xcode.IDEKit.Navigator.Structure - Xcode.IDEKit.Navigator.Debug - SelectedNavigator - Xcode.IDEKit.Navigator.Logs - Xcode.IDEKit.Navigator.Issues - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 244 - - - CF$UID - 245 - - - CF$UID - 246 - - - CF$UID - 247 - - - CF$UID - 248 - - - CF$UID - 249 - - - CF$UID - 250 - - - NS.objects - - - CF$UID - 251 - - - CF$UID - 102 - - - CF$UID - 252 - - - CF$UID - 102 - - - CF$UID - 102 - - - CF$UID - 254 - - - CF$UID - 257 - - - - IDEVisibleRect - IDEUnsavedDocumentFilteringEnabled - IDENavigatorExpandedItemsBeforeFilteringSet - IDERecentDocumentFilteringEnabled - IDESCMStatusFilteringEnabled - IDESelectedObjects - IDEExpandedItemsSet - {{0, 0}, {259, 832}} - - $class - - CF$UID - 253 - - NS.objects - - - - $classes - - NSSet - NSObject - - $classname - NSSet - - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 255 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 256 - - - - testexe - - $class - - CF$UID - 253 - - NS.objects - - - CF$UID - 258 - - - CF$UID - 259 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 256 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 256 - - - CF$UID - 260 - - - - Products - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 262 - - - CF$UID - 263 - - - CF$UID - 264 - - - NS.objects - - - CF$UID - 265 - - - CF$UID - 141 - - - CF$UID - 102 - - - - IDEStackCompressionValue - IDEThreadOrQueueMode - IDEShowOnlyInterestingContent - 2 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 267 - - - CF$UID - 268 - - - CF$UID - 269 - - - CF$UID - 270 - - - NS.objects - - - CF$UID - 271 - - - CF$UID - 272 - - - CF$UID - 102 - - - CF$UID - 275 - - - - IDELogNavigatorExpandedItemsStateKey - IDELogNavigatorSelectedObjectsStateKey - IDELogNavigatorRecentFilterStateKey - IDELogNavigatorVisibleRectStateKey - - $class - - CF$UID - 42 - - NS.objects - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 273 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 274 - - - - Build testexe : 12:28:17 - {{0, 0}, {259, 832}} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 277 - - - CF$UID - 278 - - - CF$UID - 279 - - - CF$UID - 280 - - - CF$UID - 281 - - - CF$UID - 282 - - - CF$UID - 283 - - - CF$UID - 284 - - - CF$UID - 285 - - - NS.objects - - - CF$UID - 102 - - - CF$UID - 286 - - - CF$UID - 287 - - - CF$UID - 288 - - - CF$UID - 289 - - - CF$UID - 102 - - - CF$UID - 290 - - - CF$UID - 102 - - - CF$UID - 291 - - - - IDEErrorFilteringEnabled - IDEVisibleRect - IDECollapsedFiles - IDEExpandedIssues - IDESelectedNavigables - IDEShowsByType - IDECollapsedTypes - IDERecentFilteringEnabled - IDECollapsedGroups - {{0, 0}, {259, 810}} - - $class - - CF$UID - 73 - - NS.objects - - - - $class - - CF$UID - 73 - - NS.objects - - - - $class - - CF$UID - 42 - - NS.objects - - - - $class - - CF$UID - 73 - - NS.objects - - - - $class - - CF$UID - 73 - - NS.objects - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 293 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 294 - - - CF$UID - 296 - - - CF$UID - 298 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 226 - - - CF$UID - 295 - - - - 260 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 229 - - - CF$UID - 297 - - - - 1140 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 299 - - - CF$UID - 300 - - - - IDEUtilitiesArea - 260 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 302 - - - CF$UID - 303 - - - CF$UID - 304 - - - CF$UID - 305 - - - CF$UID - 306 - - - CF$UID - 307 - - - CF$UID - 308 - - - CF$UID - 309 - - - NS.objects - - - CF$UID - 310 - - - CF$UID - 327 - - - CF$UID - 358 - - - CF$UID - 15 - - - CF$UID - 141 - - - CF$UID - 383 - - - CF$UID - 391 - - - CF$UID - 15 - - - - layoutTree - IDEEditorMode_Standard - IDEEDitorArea_DebugArea - IDEShowEditor - EditorMode - DebuggerSplitView - DefaultPersistentRepresentations - ShowDebuggerArea - - $class - - CF$UID - 326 - - geniusEditorContextNode - - CF$UID - 0 - - primaryEditorContextNode - - CF$UID - 311 - - rootLayoutTreeNode - - CF$UID - 323 - - - - $class - - CF$UID - 325 - - children - - CF$UID - 0 - - contentType - 1 - documentArchivableRepresentation - - CF$UID - 312 - - orientation - 0 - parent - - CF$UID - 323 - - - - $class - - CF$UID - 322 - - DocumentLocation - - CF$UID - 319 - - DomainIdentifier - - CF$UID - 313 - - IdentifierPath - - CF$UID - 314 - - IndexOfDocumentIdentifier - - CF$UID - 318 - - - Xcode.IDENavigableItem.WorkspaceLogsDomain - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 315 - - - - - $class - - CF$UID - 317 - - Identifier - - CF$UID - 316 - - - Build testexe : 12:28:17 - - $classes - - IDEArchivableStringIndexPair - NSObject - - $classname - IDEArchivableStringIndexPair - - 9223372036854775807 - - $class - - CF$UID - 321 - - documentURL - - CF$UID - 320 - - timestamp - - CF$UID - 0 - - - x-xcode-log://37C7873C-8039-41F4-9D56-D2A086650F4D - - $classes - - DVTDocumentLocation - NSObject - - $classname - DVTDocumentLocation - - - $classes - - IDENavigableItemArchivableRepresentation - NSObject - - $classname - IDENavigableItemArchivableRepresentation - - - $class - - CF$UID - 325 - - children - - CF$UID - 324 - - contentType - 0 - documentArchivableRepresentation - - CF$UID - 0 - - orientation - 0 - parent - - CF$UID - 0 - - - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 311 - - - - - $classes - - IDEWorkspaceTabControllerLayoutTreeNode - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTreeNode - - - $classes - - IDEWorkspaceTabControllerLayoutTree - NSObject - - $classname - IDEWorkspaceTabControllerLayoutTree - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 328 - - - NS.objects - - - CF$UID - 329 - - - - EditorLayout_PersistentRepresentation - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 330 - - - NS.objects - - - CF$UID - 331 - - - - Main - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 332 - - - CF$UID - 333 - - - CF$UID - 334 - - - NS.objects - - - CF$UID - 335 - - - CF$UID - 141 - - - CF$UID - 356 - - - - EditorLayout_StateSavingStateDictionaries - EditorLayout_Selected - EditorLayout_Geometry - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 336 - - - - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 337 - - - CF$UID - 338 - - - CF$UID - 339 - - - CF$UID - 340 - - - CF$UID - 341 - - - CF$UID - 342 - - - CF$UID - 343 - - - NS.objects - - - CF$UID - 344 - - - CF$UID - 345 - - - CF$UID - 352 - - - CF$UID - 353 - - - CF$UID - 353 - - - CF$UID - 20 - - - CF$UID - 354 - - - - FileDataType - ArchivableRepresentation - EditorState - NavigableItemName - DocumentNavigableItemName - DocumentExtensionIdentifier - DocumentURL - com.apple.dt.IDE.BuildLogContentType - - $class - - CF$UID - 322 - - DocumentLocation - - CF$UID - 350 - - DomainIdentifier - - CF$UID - 313 - - IdentifierPath - - CF$UID - 346 - - IndexOfDocumentIdentifier - - CF$UID - 349 - - - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 347 - - - - - $class - - CF$UID - 317 - - Identifier - - CF$UID - 348 - - - Build testexe : 12:28:17 - 9223372036854775807 - - $class - - CF$UID - 321 - - documentURL - - CF$UID - 351 - - timestamp - - CF$UID - 0 - - - x-xcode-log://37C7873C-8039-41F4-9D56-D2A086650F4D - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 154 - - - NS.objects - - - CF$UID - 155 - - - - Build testexe : 12:28:17 - - $class - - CF$UID - 25 - - NS.base - - CF$UID - 0 - - NS.relative - - CF$UID - 355 - - - x-xcode-log://37C7873C-8039-41F4-9D56-D2A086650F4D - - $class - - CF$UID - 57 - - NS.objects - - - CF$UID - 357 - - - - {{0, 0}, {1140, 739}} - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 359 - - - CF$UID - 360 - - - CF$UID - 361 - - - CF$UID - 362 - - - CF$UID - 363 - - - CF$UID - 364 - - - NS.objects - - - CF$UID - 192 - - - CF$UID - 365 - - - CF$UID - 367 - - - CF$UID - 192 - - - CF$UID - 369 - - - CF$UID - 377 - - - - LayoutFocusMode - console - variables - LayoutMode - IDEDebugArea_SplitView - IDEDebuggerAreaSplitView - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 366 - - - NS.objects - - - CF$UID - 141 - - - - ConsoleFilterMode - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 368 - - - NS.objects - - - CF$UID - 192 - - - - VariablesViewSelectedScope - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 370 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 371 - - - CF$UID - 374 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 372 - - - CF$UID - 373 - - - - VariablesView - 572 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 375 - - - CF$UID - 376 - - - - ConsoleArea - 567 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 378 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 379 - - - CF$UID - 381 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 372 - - - CF$UID - 380 - - - - 572 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 375 - - - CF$UID - 382 - - - - 567 - - $class - - CF$UID - 43 - - NS.keys - - - CF$UID - 32 - - - NS.objects - - - CF$UID - 384 - - - - - $class - - CF$UID - 42 - - NS.objects - - - CF$UID - 385 - - - CF$UID - 388 - - - - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 386 - - - CF$UID - 387 - - - - IDEEditor - 761 - - $class - - CF$UID - 39 - - NS.keys - - - CF$UID - 35 - - - CF$UID - 36 - - - NS.objects - - - CF$UID - 389 - - - CF$UID - 390 - - - - IDEDebuggerArea - 115 - - $class - - CF$UID - 43 - - NS.keys - - NS.objects - - - - $top - - State - - CF$UID - 1 - - - $version - 100000 - - diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist deleted file mode 100644 index fa5a96e87..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/testexe.xcscheme b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/testexe.xcscheme deleted file mode 100644 index 587ade58b..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/testexe.xcscheme +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist b/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 094f94cc5..000000000 --- a/libraries/BridJ/src/test/cpp/test/testexe.xcodeproj/xcuserdata/ochafik.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - testexe.xcscheme - - orderHint - 1 - - - SuppressBuildableAutocreation - - 90E6FC2715BC0C3400A88421 - - primary - - - - - diff --git a/libraries/BridJ/src/test/java/org/bridj/AndroidTest.java b/libraries/BridJ/src/test/java/org/bridj/AndroidTest.java deleted file mode 100644 index c45c5cb2d..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/AndroidTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -public class AndroidTest { - - @Test - public void testPackageNameExtraction() { - String expected = "com.example.hellojni"; - for (String url : new String[] { - "jar:file:/mnt/asec/com.example.hellojni-1/pkg.apk!/lib/armeabi/libhello-jni.so", - "jar:file:/data/app/com.example.hellojni-1.apk!/lib/armeabi/libhello-jni.so" - - }) - assertEquals("URL not recognized : " + url, expected, AndroidSupport.getAndroidPackageNameFromResourceURL(url)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/AnnotationsTest.java b/libraries/BridJ/src/test/java/org/bridj/AnnotationsTest.java deleted file mode 100644 index 6eb0dfdb6..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/AnnotationsTest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; -import org.bridj.util.AnnotationUtils; -import org.bridj.ann.Ptr; -import org.bridj.ann.Field; -import org.junit.Test; -import static org.junit.Assert.*; -/** - * - * @author ochafik - */ -public class AnnotationsTest { - public static class MyPtrStruct extends StructObject { - @Field(0) - @MyPtr - public long value; - } - - @Test - public void testMyPtr() throws NoSuchFieldException { - assertTrue(AnnotationUtils.isAnnotationPresent(Ptr.class, MyPtrStruct.class.getField("value"))); - assertEquals(Pointer.SIZE, BridJ.sizeOf(MyPtrStruct.class)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/BridJTest.java b/libraries/BridJ/src/test/java/org/bridj/BridJTest.java deleted file mode 100644 index fc73542f2..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/BridJTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bridj; - - -import org.bridj.demangling.Demangler; -import java.util.Collection; - -import org.junit.Test; - - -import static org.junit.Assert.*; - -public class BridJTest { - - @Test - public void testLongToIntCast() { - for (long value : new long[] { 1, -1, -2, 100 }) { - assertEquals((int)value, SizeT.safeIntCast(value)); - } - } - @Test - public void loadPthread() throws Exception { - if (!Platform.isUnix()) - return; - - assertNotNull(BridJ.getNativeLibrary("pthread")); - } - @Test - public void symbolsTest() throws Exception { - NativeLibrary lib = BridJ.getNativeLibrary("test"); - Collection symbols = lib.getSymbols(); - - assertTrue("Not enough symbols : found only " + symbols.size(), symbols.size() > 20); - boolean found = false; - for (Demangler.Symbol symbol : symbols) { - if (symbol.getName().contains("Ctest")) { - found = true; - break; - } - } - assertTrue("Failed to find any Ctest-related symbol !", found); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/COMTest.java b/libraries/BridJ/src/test/java/org/bridj/COMTest.java deleted file mode 100644 index 1fbc2b6be..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/COMTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bridj; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.junit.Test; - -import org.bridj.ann.*; -import static org.junit.Assert.*; -import org.bridj.cpp.com.COMRuntime; -import org.bridj.cpp.com.IUnknown; -import org.bridj.cpp.com.CLSID; -import org.bridj.cpp.com.IID; -import org.bridj.cpp.com.shell.IShellWindows; - -public class COMTest { - - static boolean hasCOM = Platform.isWindows();// || !Platform.is64Bits(); - - - @Test - public void shellFolder() { - if (!hasCOM) - return; - try { - IShellWindows win = COMRuntime.newInstance(IShellWindows.class); - assertNotNull(win); - IUnknown iu = win.QueryInterface(IUnknown.class); - assertNotNull(iu); - win = iu.QueryInterface(IShellWindows.class); - assertNotNull(win); - win.Release(); - - } catch (ClassNotFoundException ex) { - Logger.getLogger(COMTest.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException(ex); - } - } - - static class SomeUnknown extends IUnknown { - //public SomeUnknown() {} - @Override - public int QueryInterface(Pointer riid, Pointer> ppvObject) { - return 0; - } - int refs; - @Override - public synchronized int AddRef() { return ++refs; } - - @Override - public synchronized int Release() { return --refs; } - } - - @Test - public void testSomeUnknownInstantiation() { - new SomeUnknown(); - } - - - @CLSID("62BE5D10-60EB-11d0-BD3B-00A0C911CE86") - @IID("29840822-5B84-11D0-BD3B-00A0C911CE86") - public static class ICreateDevEnum extends IUnknown { - @Virtual(0) - public native int CreateClassEnumerator(Pointer clsidDeviceClass, Pointer> enumerator, int flags); - } - - @Test - public void testICreateDevEnum() throws Exception { - if (!hasCOM) - return; - - //Not needed, as it's called by COMRuntime.newInstance : COMRuntime.initialize(); - ICreateDevEnum devEnumCreator = COMRuntime.newInstance(ICreateDevEnum.class); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/CPPTemplateTest.java b/libraries/BridJ/src/test/java/org/bridj/CPPTemplateTest.java deleted file mode 100644 index 549513036..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/CPPTemplateTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bridj; - -import org.bridj.cpp.CPPRuntime.CPPTypeInfo; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Constructor; -import org.bridj.ann.Template; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.cpp.*; -import org.bridj.cpp.std.*; -import static org.bridj.Pointer.*; - -import java.lang.reflect.Type; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html -@Library("test") -@Runtime(CPPRuntime.class) -public class CPPTemplateTest { - static { - BridJ.register(); - } - - @Template({ Integer.class, Class.class }) - public static class InvisibleSourcesTemplate extends CPPObject { - public final int n; - @Constructor(0) - public InvisibleSourcesTemplate(int n, Type t, int arg) { - super(null, 0, n, t, arg); - this.n = n; - } - public native Pointer createSome(); - public native void deleteSome(Pointer pValue); - } - @Template({ Class.class }) - public static class Temp1 extends CPPObject { } - - @Template({ Class.class, Class.class }) - public static class Temp2 extends CPPObject { } - - @Template({ Class.class, Integer.class }) - public static class TempV extends CPPObject { } - - @Test - public void invisibleSourcesTemplateIntegerTest() { - invisibleSourcesTemplateTest(Integer.class); - } - void invisibleSourcesTemplateTest(Class t) { - InvisibleSourcesTemplate ii = new InvisibleSourcesTemplate(10, t, 4); - Pointer p = ii.createSome(); - T v = p.as(t).get(); - System.out.println("Template created value : " + v); - ii.deleteSome(p); - } - - //public static native - ///* - @Test - public void testSTLVector() throws Exception { - NativeLibrary lib = BridJ.getNativeLibrary("test"); - Pointer ptr = lib.getSymbolPointer("newIntVector").getPointer(); - Pointer sptr = lib.getSymbolPointer("sizeofIntVector").getPointer(); - int sizeofIntVector = (Integer)sptr.asDynamicFunction(null, int.class).apply(); - - Type intVectorType = CPPType.getCPPType(vector.class, int.class); - - assertEquals("bad vector size !", sizeofIntVector, BridJ.sizeOf(intVectorType)); - CPPTypeInfo> typeInfo = (CPPTypeInfo)CPPRuntime.getInstance().getCPPTypeInfo(intVectorType); - vector intVector = new vector(Integer.class); - //vector intVector = typeInfo.createReturnInstance(); - - //Pointer intVector = allocateBytes(sizeofIntVector); - Pointer intVectorPtr = pointerTo(intVector); - DynamicFunction f = ptr.asDynamicFunction(null, void.class, Pointer.class, int.class); - - int size = 10; - f.apply(intVectorPtr, size); - - //long start = intVectorPtr.getSizeTAtOffset(0); - //long end = intVector.getSizeTAtOffset(SizeT.SIZE); - //long endOfStorage = intVector.getSizeTAtOffset(SizeT.SIZE * 2); - assertEquals("Bad size", size, intVector.size()); - - for (int i = 0; i < size; i++) { - int v = intVector.get(i); - - assertEquals(i, v); - } - //System.out.println("size = " + (end - start)); - //System.out.println("capacity = " + (endOfStorage - start)); - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/CPPTest.java b/libraries/BridJ/src/test/java/org/bridj/CPPTest.java deleted file mode 100644 index a6586e18f..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/CPPTest.java +++ /dev/null @@ -1,236 +0,0 @@ -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Constructor; -import org.bridj.ann.Convention; -import org.bridj.ann.Ptr; -import org.bridj.cpp.CPPObject; - - -import org.bridj.BridJ; -import org.bridj.Pointer; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Name; -import org.bridj.ann.Runtime; -import org.bridj.ann.Virtual; -import org.bridj.cpp.CPPRuntime; - -import org.junit.After; -import static org.bridj.Pointer.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html -@Library("test") -@Runtime(CPPRuntime.class) -public class CPPTest { - static { - BridJ.register(); - } - ///* - @Test - public void testSize() { - assertEquals("Invalid size for class Ctest", sizeOfCtest(), BridJ.sizeOf(Ctest.class)); - assertEquals("Invalid size for class Ctest2", sizeOfCtest2(), BridJ.sizeOf(Ctest2.class)); - assertTrue("sizeOfCtest() = " + sizeOfCtest(), sizeOfCtest() >= 12 && sizeOfCtest() <= 20); - assertTrue("sizeOfCtest2() = " + sizeOfCtest2(), sizeOfCtest2() >= 16 && sizeOfCtest() <= 30); - } - - @Test - public void test_Ctest_constructors() { - Ctest ct = new Ctest(); - Pointer p = pointerTo(ct); - assertEquals(-123456, ct.firstField()); - assertEquals(-33, new Ctest(-33).firstField()); - } - @Test - public void test_Ctest_testAdd() { - testAdd(new Ctest(), 1, 2, 3, 3); -// testAdd(Ctest.createTest().get(), 1, 2, 3); - } - @Test - public void test_Ctest_testAddStdCall() { - Ctest instance = new Ctest(); - testAdd(instance, 1, 2, 3, 3); -// testAdd(Ctest.createTest().get(), 1, 2, 3); - } - @Test - public void test_Ctest2_testAdd() { - testAdd(new Ctest2(), 1, 2, 5, 3); - } - - @Test - public void testDestruction() throws InterruptedException { - Pointer pState = allocateInt(); - Ctest2 t = new Ctest2(); - t.setState(pState); - int destructedState = 10; - t.setDestructedState(destructedState); - t = null; - GC(); - assertEquals(destructedState, pState.getInt()); - } - //*/ - ///* - void testAdd(Ctest instance, int a, int b, int res, int baseRes) { - //long peer = Pointer.getAddress(test, Ctest.class); - - //TestCPP.print(instance.getClass().getSimpleName(), pointerTo(instance).getPeer(), 10, 2); - //TestCPP.print(instance.getClass().getSimpleName() + "'s vtable", pointerTo(instance).getSizeT(), 10, 2); - - int c = instance.testVirtualAdd(a, b); - assertEquals(res, c); - - c = Pointer.pointerTo(instance).getNativeObject(Ctest.class).testAdd(a, b); - assertEquals(baseRes, c); - - if (Platform.isWindows()) { - c = instance.testVirtualAddStdCall(null, a, b); - assertEquals("testVirtualAddStdCall", baseRes, c); - - c = instance.testVirtualAddStdCall(Pointer.allocateInt(), a, b); - assertEquals("testVirtualAddStdCall", 0, c); - - c = instance.testAddStdCall(null, a, b); - assertEquals("testAddStdCall", baseRes, c); - - c = instance.testAddStdCall(Pointer.allocateInt(), a, b); - assertEquals("testAddStdCall", 0, c); - } - } - //*/ - public static native int testIndirectVirtualAdd(Pointer pTest, int a, int b); - - @Test - public void testJavaVirtualOverride() { - Ctest test = new Ctest(); - assertEquals(3, testIndirectVirtualAdd(pointerTo(test), 1, 2)); - - test = new Ctest(10) { - @Override - public int testVirtualAdd(int a, int b) { - return a * 10 + b * 100;//super.testVirtualAdd(a, b) * 2; - } - }; - /* - List virtualMethods = new ArrayList(); - CPPRuntime.getInstance().listVirtualMethods(test.getClass(), virtualMethods); - System.out.println("virtualMethods = " + virtualMethods); - //*/ - int a = 1, b = 2; - int ind = testIndirectVirtualAdd(pointerTo(test), a, b); - assertEquals(a * 10 + b * 100, ind); - } - - @Ptr public static native long sizeOfCtest(); - @Ptr public static native long sizeOfCtest2(); - - //@Library("test") - public static class Ctest extends CPPObject { - @Constructor(0) - public Ctest() { - super((Void)null, 0); - } - @Constructor(1) - public Ctest(int firstField) { - super((Void)null, 1, firstField); - } - public Ctest(Pointer pointer) { - super(pointer); - } - public Ctest(Void voidArg, int constructorId, Object... args) { - super(voidArg, constructorId, args); - } - - @Field(0) - public int firstField() { - return this.io.getIntField(this, 0); - } - @Field(0) - public Ctest firstField(int firstField) { - this.io.setIntField(this, 0, firstField); - return this; - } - public final int firstField_$eq(int firstField) { - firstField(firstField); - return firstField; - } - @Field(1) - public int secondField() { - return this.io.getIntField(this, 1); - } - @Field(1) - public Ctest secondField(int secondField) { - this.io.setIntField(this, 1, secondField); - return this; - } - public final int secondField_$eq(int secondField) { - secondField(secondField); - return secondField; - } - @Name("~Ctest") - public native void CtestDestructor(); - @Virtual(0) - public native int testVirtualAdd(int a, int b); - public native int testAdd(int a, int b); - @Virtual(1) - @Convention(Convention.Style.StdCall) - public native int testVirtualAddStdCall(Pointer ptr, int a, int b); - @Convention(Convention.Style.StdCall) - public native int testAddStdCall(Pointer ptr, int a, int b); - public native static void static_void(); - }; - /// native declaration : line 18 - public static class Ctest2 extends Ctest { - @Constructor(0) - public Ctest2() { - super((Void)null, 0); - } - public Ctest2(Pointer pointer) { - super(pointer); - } - - /// C type : int* - @Field(0) - public Pointer fState() { - return this.io.getPointerField(this, 0); - } - /// C type : int* - @Field(0) - public Ctest2 fState(Pointer fState) { - this.io.setPointerField(this, 0, fState); - return this; - } - /// C type : int* - public final Pointer fState_$eq(Pointer fState) { - fState(fState); - return fState; - } - @Field(1) - public int fDestructedState() { - return this.io.getIntField(this, 1); - } - @Field(1) - public Ctest2 fDestructedState(int fDestructedState) { - this.io.setIntField(this, 1, fDestructedState); - return this; - } - public final int fDestructedState_$eq(int fDestructedState) { - fDestructedState(fDestructedState); - return fDestructedState; - } - public native void setState(Pointer pState); - public native void setDestructedState(int destructedState); - @Virtual(0) - public native int testVirtualAdd(int a, int b); - public native int testAdd(int a, int b); - }; - - @After - public void GC() throws InterruptedException { - System.gc(); - Thread.sleep(200); - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/CPPTest2.java b/libraries/BridJ/src/test/java/org/bridj/CPPTest2.java deleted file mode 100644 index 2d8b3d862..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/CPPTest2.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bridj; -import java.io.File; -import org.bridj.ann.Library; -import org.bridj.ann.Virtual; -import org.bridj.cpp.CPPObject; - -import org.bridj.*; -import static org.bridj.Pointer.*; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Ignore; - -@Library("test") -public class CPPTest2 { - - public static class Module extends CPPObject { - @Virtual - public native int add(int a, int b); - } - - public static class IModule extends CPPObject { - public IModule() { - super(); - } - @Virtual(2) - public native int add(int a, int b); - @Virtual(3) - public native int subtract(int a, int b); - } - - public static class AModule extends IModule { - public AModule() { - super(); - } - //@Name("AModule") - //public native int AModule$2(); - @Virtual(2) - public native int add(int a, int b); - @Virtual(3) - public native int subtract(int a, int b); - } - - @Test - public void test() { - - IModule m = new AModule(), i = pointerTo(m).as(IModule.class).get(); - - assertEquals("AModule.add failed", 3, m.add(1, 2)); - assertEquals("AModule.subtract failed", -1, m.subtract(1, 2)); - - assertEquals("IModule.add failed", 3, i.add(1, 2)); - assertEquals("IModule.subtract failed", -1, i.subtract(1, 2)); - - assertEquals("Module.add failed", 3, new Module().add(1, 2)); - - - } - - @Library("test") - public abstract class IVirtual extends CPPObject { - public IVirtual() { - super(); - } - @Virtual(2) - public native int add(int a, int b); - } - public static native int testIVirtualAdd(Pointer pVirtual, int a, int b); - - @Ignore - @Test - public void testPureVirtual() { - BridJ.register(getClass()); - - IVirtual v = new IVirtual() { - @Override - public int add(int a, int b) { - return a * 10 + b * 100; - } - }; - assertEquals(210, testIVirtualAdd(pointerTo(v), 1, 2)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/CallbackTest.java b/libraries/BridJ/src/test/java/org/bridj/CallbackTest.java deleted file mode 100644 index 255165f02..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/CallbackTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bridj; -import static org.bridj.Pointer.*; -import org.junit.Test; -import org.bridj.ann.Runtime; -import static org.junit.Assert.*; - -import org.bridj.ann.Library; - -@Library("test") -@Runtime(CRuntime.class) -public class CallbackTest { - static { - BridJ.register(); - } - - @Test - public void deleteTest() { - MyCallback cb = new MyCallback() { - @Override - public int doSomething(int a, int b) { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - - pointerTo(cb).release(); - } - @Test - public void testJavaTargetIntCallbacks() { - assertEquals(3, forwardCall(new MyCallback() { - @Override - public int doSomething(int a, int b) { - return a + b; - } - }.toPointer(), 1, 2)); - - assertEquals(21, forwardCall(new MyCallback() { - @Override - public int doSomething(int a, int b) { - return a + b * 10; - } - }.toPointer(), 1, 2)); - } - - @Test - public void testNativeTargetIntCallbacks() { - MyCallback adder = getAdder().getNativeObject(MyCallback.class); - assertEquals(3, adder.doSomething(1, 2)); - } - - static native int forwardCall(Pointer cb, int a, int b); - static native Pointer getAdder(); - - public static abstract class MyCallback extends Callback { - public abstract int doSomething(int a, int b); - } - - - - - @Test - public void testJavaTargetPtrCallbacks() { - assertEquals(3, forwardPtrCall(new MyPtrCallback() { - @Override - public Pointer doSomething(Pointer a, Pointer b) { - return pointerToAddress(a.getPeer() + b.getPeer()); - } - }.toPointer(), pointerToAddress(1), pointerToAddress(2)).getPeer()); - - Pointer pa = pointerToInt(1), pb = pointerToInt(2); - - assertEquals(4, forwardPtrCall(new MyPtrCallback() { - @Override - public Pointer doSomething(Pointer a, Pointer b) { - return pointerToInt(a.get() + b.get() + 1); - //return pointerToInt(a.getInt() + b.getInt() + 1); - } - }.toPointer(), pa, pb).getInt()); // .get()); - } - - @Test - public void testNativeTargetPtrCallbacks() { - MyPtrCallback adder = getPtrAdder().getNativeObject(MyPtrCallback.class); - assertEquals(3, adder.doSomething((Pointer)pointerToAddress(1), (Pointer)pointerToAddress(2)).getPeer()); - } - static native Pointer forwardPtrCall(Pointer cb, Pointer a, Pointer b); - static native Pointer getPtrAdder(); - - public static abstract class MyPtrCallback extends Callback { - public abstract Pointer doSomething(Pointer a, Pointer b); - } - - -} diff --git a/libraries/BridJ/src/test/java/org/bridj/ComparisonTest.java b/libraries/BridJ/src/test/java/org/bridj/ComparisonTest.java deleted file mode 100644 index 678aaadce..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/ComparisonTest.java +++ /dev/null @@ -1,675 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; -import static org.bridj.Pointer.*; - -import org.bridj.ann.*; -import org.bridj.cpp.CPPRuntime; -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.Test; -/** - * mvn -o compile test-compile && MAVEN_OPTS="-Xmx2g -Xrunhprof:cpu=samples,doe=y,depth=15" mvn -o -DforkMode=never surefire:test -DenableAssertions=false -Dtest=ComparisonTest && jProfBeautifier - -set MAVEN_OPTS=-Xmx1g -Xrunhprof:cpu=samples,doe=y,depth=15 -mvn -o compile test-compile && mvn -o -DforkMode=never surefire:test -DenableAssertions=false -Dtest=ComparisonTest - - * @author Olivier Chafik - */ -@org.bridj.ann.Runtime(CPPRuntime.class) -public class ComparisonTest { - - @Library("test") - public static class TestLib { - public TestLib() { - BridJ.register(getClass()); - } - //@Mangling({"?sinInt@@YANH@Z", "_Z6sinInti"}) - public native double sinInt(int d); - - //@Mangling({"?voidTest@@YAXXZ", "_Z8voidTestv"}) - public native void voidTest(); - - static class Struct1 { - String ws; - String s; - - } - static class Struct2 extends StructObject { - Struct1 s1; - @Array(10) Pointer s; - } - } - /** - * @param args the command line arguments - */ - @Test - public void perfTest() { - //if (true) return; - //com.sun.jna.Native.setProtected(true); - TestLib test = null; - try { - System.out.println(ComparisonTest.class.getResource("Main.class")); - int nWarmUp = 1600; - int nCalls = 100000; - int nTests = 10; - int arg = 10; - double res = 0; - - boolean warmup = true; - test = new TestLib(); - - if (true) { - Method[] mes = TestLib.class.getDeclaredMethods(); - Method me = mes[0]; - //Test.class.getMethod("sinInt", Integer.TYPE) - //long address = DynCall.getSymbolAddress(me); - //JNI.registerClass(Test.class); - - /* - mes = PerfTest.class.getDeclaredMethods(); - me = mes[0]; - //Test.class.getMethod("sinInt", Integer.TYPE) - address = DynCall.getSymbolAddress(me); - JNI.registerClass(PerfTest.class); - */ - test.voidTest(); - //res = test.sinInt(arg); - double tot = 0; - if (warmup) { - for (int i = 0; i < nWarmUp; i++) - tot += test.sinInt(arg); - for (int i = 0; i < nWarmUp; i++) - tot += Math.sin(arg); - } - - double totalSlower = 0; - for (int iTest = 0; iTest < nTests; iTest++) { - long startNat = System.nanoTime(); - for (int i = 0; i < nCalls; i++) - tot += test.sinInt(arg); - long timeNat = System.nanoTime() - startNat; - - long startPrim = System.nanoTime(); - for (int i = 0; i < nCalls; i++) - tot += Math.sin(arg); - long timePrim = System.nanoTime() - startPrim; - - //System.out.println("timeNat = " + timeNat); - //System.out.println("timePrim = " + timePrim); - double slower = (timeNat / (double)timePrim); - totalSlower += slower; - } - System.out.println("#"); - System.out.println("# Dyncall+JNI's sinus is " + (totalSlower / nTests) + " times slower than java sinus function"); - System.out.println("#"); - - } - - PerfLib.DynCallTest dct = new PerfLib.DynCallTest(); - if (true) { - //JNI.registerClass(PerfTest.class); - //PerfTest.DynCall.testAddDyncall(1, 2); - int tot = 0, seed = System.getenv().size(); - if (warmup) { - for (int i = 0; i < nWarmUp; i++) - tot = PerfLib.testAddJNI(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = dct.testAddDyncall(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = PerfLib.JNATest.testAddJNA(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = PerfLib.JNAInterfaceTest.INSTANCE.testAddJNA(tot, seed); - } - - double totalJNI = 0, totalDynCall = 0, totalJNA = 0, totalJNAInterface = 0; - - long startJNI = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = PerfLib.testAddJNI(tot, seed); - } - long timeJNI = System.nanoTime() - startJNI; - totalJNI += timeJNI; - - long startDyncall = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = dct.testAddDyncall(tot, seed); - } - long timeDyncall = System.nanoTime() - startDyncall; - totalDynCall += timeDyncall; - - long startJNA = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = PerfLib.JNATest.testAddJNA(tot, seed); - } - long timeJNA = System.nanoTime() - startJNA; - totalJNA += timeJNA; - - long startJNAInterface = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = PerfLib.JNAInterfaceTest.INSTANCE.testAddJNA(tot, seed); - } - long timeJNAInterface = System.nanoTime() - startJNAInterface; - totalJNAInterface += timeJNAInterface; - - - - //System.out.println("timeNat = " + timeNat); - //System.out.println("timePrim = " + timePrim); - System.out.println("#"); - System.out.println("# Dyncall's simple int add is " + (totalDynCall / totalJNI) + " times slower than pure JNI in average"); - System.out.println("# JNA's simple int add is " + (totalJNA / totalJNI) + " times slower than pure JNI in average"); - - double bridJFaster = totalJNA / (double)totalDynCall; - double bridJFasterInterf = totalJNAInterface / (double)totalDynCall; - System.out.println("# => Dyncall is " + bridJFaster + " times faster than JNA in direct mode"); - System.out.println("# => Dyncall is " + bridJFasterInterf + " times faster than JNA in interface mode"); - System.out.println("#"); - - if (Math.abs(bridJFaster - 1) > 1e10) { - assertBridJFaster(bridJFaster, 0.8); - assertBridJFaster(bridJFasterInterf, 5.0); - } - - } - - if (true) { - //JNI.registerClass(PerfTest.class); - //PerfTest.DynCall.testAddDyncall(1, 2); - int tot = 0, seed = System.getenv().size(); - if (warmup) { - for (int i = 0; i < nWarmUp; i++) - tot += (int)PerfLib.testASinB(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = dct.testASinB(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = PerfLib.JNATest.testASinB(tot, seed); - for (int i = 0; i < nWarmUp; i++) - tot = PerfLib.JNAInterfaceTest.INSTANCE.testASinB(tot, seed); - } - - double totalJNI = 0, totalDynCall = 0, totalJNA = 0, totalJNAInterface = 0; - long startJNI = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot += (int)PerfLib.testASinB(tot, seed); - } - long timeJNI = System.nanoTime() - startJNI; - totalJNI += timeJNI; - - long startDyncall = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = dct.testASinB(tot, seed); - } - long timeDyncall = System.nanoTime() - startDyncall; - totalDynCall += timeDyncall; - - long startJNA = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = PerfLib.JNATest.testASinB(tot, seed); - } - long timeJNA = System.nanoTime() - startJNA; - totalJNA += timeJNA; - - - long startJNAInterface = System.nanoTime(); - for (int iTest = 0; iTest < nTests; iTest++) { - for (int i = 0; i < nCalls; i++) - tot = PerfLib.JNAInterfaceTest.INSTANCE.testASinB(tot, seed); - } - long timeJNAInterface = System.nanoTime() - startJNAInterface; - totalJNAInterface += timeJNAInterface; - - System.out.println("#"); - System.out.println("# Dyncall's 'a * sin(b)' add is " + (totalDynCall / (double)totalJNI) + " times slower than pure JNI in average"); - System.out.println("# JNA's 'a * sin(b)' add is " + (totalJNA / (double)totalJNI) + " times slower than pure JNI in average"); - double bridJFaster = totalJNA / (double)totalDynCall; - double bridJFasterInterf = totalJNAInterface / (double)totalDynCall; - System.out.println("# => Dyncall is " + bridJFaster + " times faster than JNA in direct mode"); - System.out.println("# => Dyncall is " + bridJFasterInterf + " times faster than JNA in interface mode"); - System.out.println("#"); - - if (Math.abs(bridJFaster - 1) > 1e10) { - assertBridJFaster(bridJFaster, 0.8); - assertBridJFaster(bridJFasterInterf, 5.0); - } - } - System.out.println("res = " + res + ", sin(" + arg + ") = " + Math.sin(arg)); - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - if (test != null) - test.voidTest(); - } - System.out.println(Platform.SIZE_T_SIZE); - try { - //System.in.read(); - } catch (Exception ex) { - Logger.getLogger(ComparisonTest.class.getName()).log(Level.SEVERE, null, ex); - } - } - - - - @Test - public void compareStructCreations() throws InterruptedException { - //if (true) return; - - long n = 100000; - long warmup = 2000; - for (int i = 0; i < warmup; i++) - new StructTest.MyStruct(); - - for (int i = 0; i < warmup; i++) - new StructTest.MyJNAStruct(); - - for (int i = 0; i < warmup; i++) - new StructTest.MyNIOStruct(); - - for (int i = 0; i < warmup; i++) - new StructTest.MyOptimalStruct(); - - for (int i = 0; i < warmup; i++) - new StructTest.MyJavolutionStruct(); - - long timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution; - - doGC(); - //System.err.println("# Testings NIO structs..."); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyNIOStruct(); - - System.gc(); - timeNIO = System.nanoTime() - start; - } - doGC(); - //System.err.println("# Testings JNA structs..."); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyJNAStruct(); - - System.gc(); - timeJNA = System.nanoTime() - start; - } - doGC(); - //System.err.println("# Testings Optimal structs..."); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyOptimalStruct(); - - System.gc(); - timeOptimal = System.nanoTime() - start; - } - doGC(); - //System.err.println("# Testings BridJ structs..."); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyStruct(); - - System.gc(); - timeBridJ = System.nanoTime() - start; - } - doGC(); - //System.err.println("# Testings Javolution structs..."); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyJavolutionStruct().getByteBuffer(); - - System.gc(); - timeJavolution = System.nanoTime() - start; - } - double bridJFaster = printResults("Creation of struct", "Creation of BridJ's structs", "create", n, timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution); - - if (Math.abs(bridJFaster - 1) < 1e10) - return; - - assertBridJFaster(bridJFaster, 20); - } - - @Test - public void compareStructCasts() throws InterruptedException { - //if (true) return; - - long n = 100000; - long warmup = 2000; - Pointer pBridJ = allocateBytes(100); - com.sun.jna.Memory pJNA = new com.sun.jna.Memory(100); - ByteBuffer pNIO = ByteBuffer.allocateDirect(100); - - for (int i = 0; i < warmup; i++) - new StructTest.MyStruct(pBridJ); - - for (int i = 0; i < warmup; i++) - new StructTest.MyNIOStruct(pNIO); - - for (int i = 0; i < warmup; i++) - new StructTest.MyJNAStruct(pJNA); - - for (int i = 0; i < warmup; i++) - new StructTest.MyOptimalStruct(pNIO); - - for (int i = 0; i < warmup; i++) - new StructTest.MyJavolutionStruct().setByteBuffer(pNIO, 0); - - long timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution; - - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyNIOStruct(pNIO); - - System.gc(); - timeNIO = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyJNAStruct(pJNA); - - System.gc(); - timeJNA = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyOptimalStruct(pNIO); - - System.gc(); - timeOptimal = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyJavolutionStruct().setByteBuffer(pNIO, 0); - - System.gc(); - timeJavolution = System.nanoTime() - start; - } - //*/ - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyStruct(pBridJ); - - System.gc(); - timeBridJ = System.nanoTime() - start; - } - double bridJFaster = printResults("Cast to struct", "Cast to BridJ's structs", "cast", n, timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution); - - assertBridJFaster(bridJFaster, 30); // */ - } - - ByteBuffer next(ByteBuffer b, long skip) { - for (int i = 0; i < skip; i++) - b.get(); - return b.slice(); - } - @Test - public void compareStructArrayCasts() throws InterruptedException { - //if (true) return; - - long n = 100000; - long warmup = 2000; - long structSize = 10; - int arraySize = 5; - Pointer pBridJ = allocateBytes(100).as(StructTest.MyStruct.class).validElements(arraySize); - com.sun.jna.Memory pJNA = new com.sun.jna.Memory(100); - ByteBuffer pNIO = ByteBuffer.allocateDirect(100); - - for (int i = 0; i < warmup; i++) { - StructTest.MyStruct[] a = pBridJ.toArray(new StructTest.MyStruct[arraySize]); - } - - for (int i = 0; i < warmup; i++) { - StructTest.MyNIOStruct[] a = new StructTest.MyNIOStruct[arraySize]; - ByteBuffer b = pNIO.duplicate(); - for (int o = 0; o < arraySize; o++) { - a[o] = new StructTest.MyNIOStruct(b); - b = next(b, structSize); - } - } - - for (int i = 0; i < warmup; i++) { - com.sun.jna.Structure[] a = new StructTest.MyJNAStruct(pJNA).toArray(new StructTest.MyJNAStruct[arraySize]); - } - /* - for (int i = 0; i < warmup; i++) - new StructTest.MyOptimalStruct(pNIO); - */ - for (int i = 0; i < warmup; i++) { - StructTest.MyJavolutionStruct[] a = new StructTest.MyJavolutionStruct[arraySize]; - for (int o = 0; o < arraySize; o++) { - (a[o] = new StructTest.MyJavolutionStruct()).setByteBuffer(pNIO, (int)(o * structSize)); - } - } - - long timeJNA, timeOptimal = -1, timeBridJ, timeNIO, timeJavolution; - - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - StructTest.MyNIOStruct[] a = new StructTest.MyNIOStruct[arraySize]; - ByteBuffer b = pNIO.duplicate(); - for (int o = 0; o < arraySize; o++) { - a[o] = new StructTest.MyNIOStruct(b); - b = next(b, structSize); - } - } - - System.gc(); - timeNIO = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - com.sun.jna.Structure[] a = new StructTest.MyJNAStruct(pJNA).toArray(new StructTest.MyJNAStruct[arraySize]); - } - - System.gc(); - timeJNA = System.nanoTime() - start; - } - /*doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) - new StructTest.MyOptimalStruct(pNIO); - - timeOptimal = System.nanoTime() - start; - }*/ - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - StructTest.MyStruct[] a = pBridJ.toArray(new StructTest.MyStruct[arraySize]); - } - - System.gc(); - timeBridJ = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - StructTest.MyJavolutionStruct[] a = new StructTest.MyJavolutionStruct[arraySize]; - for (int o = 0; o < arraySize; o++) { - (a[o] = new StructTest.MyJavolutionStruct()).setByteBuffer(pNIO, (int)(o * structSize)); - } - } - - System.gc(); - timeJavolution = System.nanoTime() - start; - } - double bridJFaster = printResults("Cast to struct array", "Cast to BridJ's struct array", "cast", n, timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution); - - assertBridJFaster(bridJFaster, 30); // */ - } - - @Test - public void compareFieldsAccess() throws InterruptedException { - //if (true) return; - - long n = 1000000; - long warmup = 2000; - Pointer pBridJ = allocateBytes(100); - com.sun.jna.Memory pJNA = new com.sun.jna.Memory(100); - ByteBuffer pNIO = ByteBuffer.allocateDirect(100); - - StructTest.MyStruct bridJ = new StructTest.MyStruct(); - StructTest.MyNIOStruct nio = new StructTest.MyNIOStruct(); - StructTest.MyJNAStruct jna = new StructTest.MyJNAStruct(); - StructTest.MyOptimalStruct optim = new StructTest.MyOptimalStruct(); - StructTest.MyJavolutionStruct javo = new StructTest.MyJavolutionStruct(); - - for (int i = 0; i < warmup; i++) { - bridJ.a(bridJ.a() + 1); - bridJ.b(bridJ.a() + bridJ.b()); - } - - for (int i = 0; i < warmup; i++) { - jna.a = jna.a + 1; - jna.b = jna.a + jna.b; - //jna.writeField("b"); - //jna.writeField("b"); - jna.write(); - } - - for (int i = 0; i < warmup; i++) { - nio.a(nio.a() + 1); - nio.b(nio.a() + nio.b()); - } - - for (int i = 0; i < warmup; i++) { - optim.a(optim.a() + 1); - optim.b(optim.a() + optim.b()); - } - - for (int i = 0; i < warmup; i++) { - javo.a.set(javo.a.get() + 1); - javo.b.set(javo.a.get() + javo.b.get()); - } - - long timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution; - - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - nio.a(nio.a() + 1); - nio.b(nio.a() + nio.b()); - } - - System.gc(); - timeNIO = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - optim.a(optim.a() + 1); - optim.b(optim.a() + optim.b()); - } - - System.gc(); - timeOptimal = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - javo.a.set(javo.a.get() + 1); - javo.b.set(javo.a.get() + javo.b.get()); - } - - System.gc(); - timeJavolution = System.nanoTime() - start; - } - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - jna.a = jna.a + 1; - jna.b = jna.a + jna.b; - //jna.writeField("b"); - //jna.writeField("b"); - jna.write(); - } - - System.gc(); - timeJNA = System.nanoTime() - start; - } // */ - doGC(); - { - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - bridJ.a(bridJ.a() + 1); - bridJ.b(bridJ.a() + bridJ.b()); - } - - System.gc(); - timeBridJ = System.nanoTime() - start; - } - double bridJFaster = printResults("Fields read/write", "Read/write of BridJ's struct fields", "read/write", n, timeJNA, timeOptimal, timeBridJ, timeNIO, timeJavolution); - - assertBridJFaster(bridJFaster, 1.5); // */ - } - static void assertBridJFaster(double factor, double minExpectedFactor) { - if (factor < 0) - return; - assertTrue("BridJ is not as fast as expected (" + factor + "x faster, expected > " + minExpectedFactor + "x faster)", factor >= minExpectedFactor); - } - static double printResults(String title, String longOp, String op, long n, long timeJNA, long timeOptimal, long timeBridJ, long timeNIO, long timeJavolution) { - System.err.println("#"); - System.err.println("# " + title + " :"); - if (timeOptimal >= 0) - System.err.println("# Optimal took " + (timeOptimal / 1000000d) + " millis to " + op + " " + n + " simple structs : " + microPerStruct(timeOptimal, n)); - if (timeBridJ >= 0) - System.err.println("# BridJ took " + (timeBridJ / 1000000d) + " millis to " + op + " " + n + " simple structs : " + microPerStruct(timeBridJ, n)); - if (timeJavolution >= 0) - System.err.println("# Javolution took " + (timeJavolution / 1000000d) + " millis to " + op + " " + n + " simple structs : " + microPerStruct(timeJavolution, n)); - if (timeNIO >= 0) - System.err.println("# NIO took " + (timeNIO / 1000000d) + " millis to " + op + " " + n + " simple structs : " + microPerStruct(timeNIO, n)); - if (timeJNA >= 0) - System.err.println("# JNA took " + (timeJNA / 1000000d) + " millis to " + op + " " + n + " simple structs : " + microPerStruct(timeJNA, n)); - - double bridJFaster = timeJNA / (double)timeBridJ; - System.err.println("# " + longOp + " is " + bridJFaster + " times faster than JNA's "); - System.err.println("#"); - return bridJFaster; - } - static String microPerStruct(long nanoTime, long n) { - return (nanoTime / 1000d / (double)n) + " microsecond per struct"; - } - static void doGC() throws InterruptedException { - System.gc(); - Thread.sleep(200); - System.gc(); - Thread.sleep(100); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/DemanglingTest.java b/libraries/BridJ/src/test/java/org/bridj/DemanglingTest.java deleted file mode 100644 index f7beba463..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/DemanglingTest.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; -import org.bridj.FunctionTest.ETest; -import static org.bridj.util.DefaultParameterizedType.*; -import org.bridj.demangling.Demangler; -import org.bridj.demangling.Demangler.TypeRef; -import org.bridj.demangling.Demangler.Ident; -import org.bridj.demangling.Demangler.IdentLike; -import org.bridj.demangling.Demangler.DemanglingException; -import org.bridj.demangling.Demangler.MemberRef; -import org.bridj.demangling.GCC4Demangler; -import org.bridj.demangling.VC9Demangler; -import org.bridj.cpp.CPPType; -import org.bridj.demangling.Demangler.SpecialName; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Type; -import java.lang.annotation.Annotation; -import org.junit.Test; - -import static org.junit.Assert.*; -public class DemanglingTest { - - @Test - public void gcc() { - demangle( - null, - "__Z17testInPlaceSquarePdj", // REMARK (REMI): c++filt does not accept double underscore as a prefix, I don't know if the ones in this file are intended... in the end, it should not really hurt that our demangler is too permissive - null, - ident("testInPlaceSquare"), - void.class, Pointer.class, int.class - ); - } - static Type clongType = CLong.class;//CPPType.getCPPType(new Object[] { CLong.class }); - @Test - public void testLongLongBackReference() { - demangle( - "?test_add9_long@@YA_J_J00000000@Z", - "_Z14test_add9_longlllllllll", - null, - ident("test_add9_long"), - long.class, long.class, long.class, long.class, long.class, long.class, long.class, long.class, long.class, long.class - //clongType, clongType, clongType, clongType, clongType, clongType, clongType, clongType, clongType, clongType - ); - } - public static class C {} - @Test - public void testStaticMethod() { - demangle( - "?m@C@@SAPAV1@XZ", - null, - C.class, - ident("m"), - paramType(Pointer.class, C.class) - ); - } - @Test - public void testCLongsBackReference() { - demangle( - "?testAddCLongs@@YAJJJ@Z", - null, - null, - ident("testAddCLongs"), - CLong.class, CLong.class, CLong.class - ); - } - @Test - public void testJLongsBackReference() { - demangle( - "?testAddJLongs@@YA_J_J0@Z", - null, - null, - ident("testAddJLongs"), - long.class, long.class, long.class - ); - } - - - - static Type etestEnumType = paramType(ValuedEnum.class, ETest.class); - @Test - public void testEnumArgAndRet() { - demangle( - "?testEnum@@YA?AW4ETest@@W41@@Z", - null, - null, - ident("testEnum"), - etestEnumType, etestEnumType - ); - } - @Test - public void testEnumArg() { - demangle( - "?testEnumArgSecond@@YAHW4ETest@@@Z", - null, - null, - ident("testEnumArgSecond"), - int.class, etestEnumType - ); - } - @Test - public void testEnumRet() { - demangle( - "?testEnumRetSecond@@YA?AW4ETest@@XZ", - null, - null, - ident("testEnumRetSecond"), - etestEnumType - ); - } - @Test - public void testEnumArgs() { - demangle( - "?testEnumArgs@@YAHW4ETest@@0@Z", - null, - null, - ident("testEnumArgs"), - int.class, etestEnumType, etestEnumType - ); - } - // - // - - @Test - public void testSimple() { - demangle( - null, - "_Z17test_incr_int_outiPi", - null, - ident("test_incr_int_out"), - null, int.class, paramType(Pointer.class, int.class) - ); - } - - - @Test - public void testPtrsBackRef() { - demangle( - "?f@@YAPADPADPAF1@Z", - null, - "byte* f(byte*, short*, short*)" - ); - } - - @Test - public void simpleCppFun() { - demangle( - null, - "__Z11sizeOfCtestv", - "null sizeOfCtest()" - ); - } - @Test - public void testPrimsBackRef() { - demangle( - "?f@@YADDFF@Z", - null, - "byte f(byte, short, short)" - ); - } - @Test - public void testPrimPtrs() { - demangle( - "?f@@YAPADPADPAFPAHPAJPA_JPAMPAN@Z", - null, - "byte* f(byte*, short*, int*, CLong*, long*, float*, double*)" - ); - } - @Test - public void testPrims() { - demangle( - "?ff@@YAFDFHJ_JMN@Z", - null, - "short ff(byte, short, int, CLong, long, float, double)" - ); - } - @Test - public void parameterlessFunction() { - demangle( - null, // TODO - "_Z14test_no_paramsv", - null, - ident("test_no_params"), - null - ); - } - @Test - public void simpleConstructor() { - demangle( - "??0Ctest@@QEAA@XZ", - "_ZN5CtestC1Ev", - CPPTest.Ctest.class, - SpecialName.Constructor, - null - ); - } - @Test - public void methods() { - demangle( - null, - "_ZN5Ctest7testAddEii", - CPPTest.Ctest.class, - ident("testAdd"), - int.class, int.class, int.class - ); - - } - - @Test - public void template1() { - demangle( - null, - "__ZN5Temp1IdE4tempEd", - CPPType.getCPPType(new Object[] { CPPTemplateTest.Temp1.class, Double.class }), - ident("temp"), - void.class, - double.class - ); - } - - @Test - public void template2() { - demangle( - null, - "__ZN5Temp2IisE4tempEis", - CPPType.getCPPType(new Object[] { CPPTemplateTest.Temp2.class, int.class, short.class }), - ident("temp"), - void.class, - int.class, - short.class - ); - } - - @Test - public void templateHardConstructor1() { - demangle( - null, - "_ZN24InvisibleSourcesTemplateILi10ESsEC1Ei", - CPPType.getCPPType(new Object[] { CPPTemplateTest.InvisibleSourcesTemplate.class, 10, int.class }), - SpecialName.Constructor, - void.class, - int.class - ); - } - @Test - public void templateHardConstructor2() { - demangle( - null, - "_ZN24InvisibleSourcesTemplateILi10EiEC2Ei", - CPPType.getCPPType(new Object[] { CPPTemplateTest.InvisibleSourcesTemplate.class, 10, int.class }), - SpecialName.SpecialConstructor, - void.class, - int.class - ); - } - - @Test - public void simpleFunctions() { - demangle("?sinInt@@YANH@Z", "_Z6sinInti", null, - ident("sinInt"), - double.class, int.class); - demangle("?forwardCall@@YAHP6AHHH@ZHH@Z", "_Z11forwardCallPvii", null, ident("forwardCall"), int.class, Pointer.class, int.class, int.class); - // NB: the forwardCall test for gcc is written with a "void*" as first parameter (I could not get the pointer type from the VC6 mangled name - } - - @Test - public void complexPointerTypeParameters() { - // TODO VC versions - // NB: with gcc, we have no info about the return type (don't know about VC6) - demangle(null, "_Z14pointerAliasesPPvS_PS0_PPi", null, ident("pointerAliases"), null, Pointer.class, Pointer.class, Pointer.class, Pointer.class); - demangle(null, "_Z14pointerAliasesPPvS_PS0_PPi", null, ident("pointerAliases"), null, "**Void", "*Void", "***Void", "**Integer"); - } - - @Test - public void gccMemoryShortcuts() { - // does VC do something similar? - demangle(null, "_Z15shortcutsSimplePPPPccS_S0_S1_S2_PS2_", "null shortcutsSimple(byte****, byte, byte*, byte**, byte***, byte****, byte*****)"); - } - - @Test - public void gccBuiltinShortcuts() { - // does VC do something similar? - //demangle(null, "_ZN1a1bI1cI1d1eEE1f", ""); - demangle(null, "_Z25shortcutsBuiltinStdPrefixSt9exception", "null shortcutsBuiltinStdPrefix(std.exception)"); - String str = "std.basic_string, std.allocator>"; //std::basic_string, std::allocator > (from c++filt) - demangle(null, "_Z22shortcutsBuiltinStringSs", "null shortcutsBuiltinString(" + str + ")"); - String iostream = "std.basic_iostream>"; //std::basic_iostream > - String istream = iostream.replaceAll("iostream", "istream"); - String ostream = iostream.replaceAll("iostream", "ostream"); - demangle(null, "_Z7streamsSiSoSd", "null streams(" + istream + ", " + ostream + ", " + iostream + ")"); - } - - @Test - public void gccTrickyMemoryAndBuiltinShortcutsWithTemplates() { - demangle(null, "_Z3blaPN7Helping4HandE", "null bla(Helping.Hand*)"); // validate the output syntax for pointers to namespaced types - String vectorOfXYZ = "std.vector>"; - String str = "std.basic_string, std.allocator>"; - demangle(null, "_ZN3bla5inputEPSt6vectorISsSaISsEEPS0_IPN7Helping4HandESaIS6_EE", - // bla::input(std::vector, std::allocator >, std::allocator, std::allocator > > >*, std::vector >*) - // bla::input(vectorof(string)*, vectorof(Helping::Hand*)*) - "null bla.input(" + vectorOfXYZ.replaceAll("XYZ", str) + "*, " + vectorOfXYZ.replaceAll("XYZ", "Helping.Hand*") + "*)"); - } - - static IdentLike ident(String name) { - return new Ident(name); - } - private void demangle(String vc9, String gcc4, Type enclosingType, IdentLike memberName, Type returnType, Object... paramTypes) { - try { - if (vc9 != null) - checkSymbol(vc9, new VC9Demangler(null, vc9).parseSymbol(), enclosingType, memberName, returnType, paramTypes, null, null); - if (gcc4 != null) - checkSymbol(gcc4, new GCC4Demangler(null, gcc4).parseSymbol(), enclosingType, memberName, returnType, paramTypes,null, null); - } catch (DemanglingException ex) { - Logger.getLogger(DemanglingTest.class.getName()).log(Level.SEVERE, null, ex); - throw new AssertionError(ex.toString()); - } - } - - private void demangle(String vc9, String gcc4, String toString) { - try { - if (vc9 != null) - assertEquals(toString, new VC9Demangler(null, vc9).parseSymbol().toString()); - if (gcc4 != null) - assertEquals(toString, new GCC4Demangler(null, gcc4).parseSymbol().toString()); - } catch (DemanglingException ex) { - Logger.getLogger(DemanglingTest.class.getName()).log(Level.SEVERE, null, ex); - throw new AssertionError(ex.toString()); - } - } - - private void checkSymbol(String str, MemberRef symbol, Type enclosingType, IdentLike memberName, Type returnType, Object[] paramTypes, Annotation[][] paramAnns, AnnotatedElement element) { - if (symbol == null) - assertTrue("Symbol not successfully parsed \"" + str + "\"", false); - if (memberName != null) - assertEquals("Bad name", memberName, symbol.getMemberName()); - if (enclosingType != null) { - assertNotNull("Null enclosing type : " + symbol, symbol.getEnclosingType()); - assertTrue("Bad enclosing type (got " + symbol.getEnclosingType() + ", expected " + (enclosingType instanceof Class ? ((Class)enclosingType).getName() : enclosingType.toString()) + ")", symbol.getEnclosingType().matches(enclosingType, Demangler.annotations(enclosingType))); - } - if (returnType != null && symbol.getValueType() != null) - assertTrue("Bad return type : expected " + returnType + ", got " + symbol.getValueType() + " (got class " + symbol.getValueType().getClass().getName() + ")", symbol.getValueType().matches(returnType, Demangler.annotations(element))); - - int nArgs = symbol.paramTypes.length; - assertEquals("Bad number of parameters", paramTypes.length, nArgs); - - for (int iArg = 0; iArg < nArgs; iArg++) { - if (paramTypes[iArg] instanceof Type) { - Type expecting = (Type)paramTypes[iArg]; - TypeRef demangled = symbol.paramTypes[iArg]; - assertTrue("Bad type for " + (iArg + 1) + "th param : (symbol = " + symbol + ", expecting " + expecting + " and demangled " + demangled + " (" + demangled.getClass().getName() + ")", - demangled.matches(expecting, paramAnns == null ? null : Demangler.annotations(paramAnns[iArg]))); - - } else if (paramTypes[iArg] instanceof String) { - String targetType = (String) paramTypes[iArg]; - TypeRef currentType = symbol.paramTypes[iArg]; - int count = 0; - while (targetType.startsWith("*")) { - assertEquals("For " + (iArg + 1) + "th param, after " + count + " dereferencing, wrong non-pointer type", Demangler.PointerTypeRef.class, currentType.getClass()); - targetType = targetType.substring(1); - currentType = ((Demangler.PointerTypeRef) currentType).pointedType; - count++; - } - Class targetPointedType = null; - try { - if (targetType.contains(".")) { - throw new RuntimeException("this code has never been used before, comment this exception and check it"); - //targetPointedType = Class.forName(targetType); - } else { - targetPointedType = (Class) Class.forName("java.lang." + targetType).getDeclaredField("TYPE").get(null); - } - } catch (Exception e) { - throw new RuntimeException("Check your test for target type " + targetType, e); - } - assertTrue("For " + (iArg + 1) + "th parameter, after " + count + " dereferencing, wrong final pointed type: expected " + targetType + " got " + currentType.getQualifiedName(new StringBuilder(), true), currentType.matches(targetPointedType, null)); - } else { - assertTrue("Problem in the expression of the test code", false); - } - } - } - -} \ No newline at end of file diff --git a/libraries/BridJ/src/test/java/org/bridj/DependencyTest.java b/libraries/BridJ/src/test/java/org/bridj/DependencyTest.java deleted file mode 100644 index 6090bada5..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/DependencyTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bridj; -import org.bridj.ann.*; -import org.junit.*; -import static org.junit.Assert.*; - -@Library(value = "dependsOnTest", dependencies = { "test" }) -public class DependencyTest { - public DependencyTest() { - BridJ.register(); - } - public static native int addThatDependsOnTest(int a, int b); - - @Test - public void testAdd() { - assertEquals(4, addThatDependsOnTest(3, 1)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/DummyTest.java b/libraries/BridJ/src/test/java/org/bridj/DummyTest.java deleted file mode 100644 index 1b08b945e..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/DummyTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bridj; -import org.junit.Test; - -import org.bridj.ann.*; - -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -public class DummyTest { - - @Test - public void dummy() { - BridJ.register(); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/DynamicCallbackTest.java b/libraries/BridJ/src/test/java/org/bridj/DynamicCallbackTest.java deleted file mode 100644 index a78b30463..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/DynamicCallbackTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import java.io.IOException; -import java.io.FileNotFoundException; -import org.junit.Test; -import static org.junit.Assert.*; - - -/** - * - * @author ochafik - */ -public class DynamicCallbackTest { - - public DynamicCallbackTest() { - } - - - @Test - public void testAddDynamicFunction() throws IOException { - NativeLibrary lib = BridJ.getNativeLibrary("test"); - DynamicFunction i = lib.getSymbolPointer("testAddDyncall").asDynamicFunction(null, int.class, int.class, int.class); - int res = (Integer)i.apply(1, 2); - assertEquals(3, res); - } - - @Test - public void testDynamicFunctionCallback() throws FileNotFoundException { - Pointer dc = Pointer.allocateDynamicCallback( - new DynamicCallback() { - - public Integer apply(Object... args) { - int a = (Integer)args[0]; - int b = (Integer)args[1]; - return a + b; - } - - }, null, int.class, int.class, int.class - ); - DynamicFunction df = dc.asUntyped().asDynamicFunction(null, int.class, int.class, int.class); - int ret = df.apply(1, 2); - assertEquals(3, ret); - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/test/java/org/bridj/ExceptionsTest.java b/libraries/BridJ/src/test/java/org/bridj/ExceptionsTest.java deleted file mode 100644 index c526029ee..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/ExceptionsTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bridj; - -import org.junit.Test; - -import org.bridj.ann.Library; -import static org.bridj.Pointer.*; -import static org.junit.Assert.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html - -@Library("test") -public class ExceptionsTest { - static { - BridJ.register(); - } - - public static native void crashIllegalAccess() throws RuntimeException; - public static native void throwMyExceptionByValue(Pointer message) throws RuntimeException; - public static native void throwNewMyException(Pointer message) throws RuntimeException; - public static native void throwInt(int value) throws RuntimeException; - - void throwExpectedIfNotSupported() { - if (!BridJ.protectedMode) { - System.out.println("Please run this test with protected mode enabled :\n\tBRIDJ_PROTECTED=1 mvn test -o -Dtest=" + getClass().getSimpleName()); - SignalError.throwNew(0, 0, 0); - } - } - - @Test(expected=NativeError.class) - public void testCrashIllegalAccess() { - throwExpectedIfNotSupported(); - - try { - crashIllegalAccess(); - } catch (NativeError ex) { - System.out.println(ex); - throw ex; - } - } - - - @Test(expected=NativeError.class) - public void testThrowCPPException() { - throwExpectedIfNotSupported(); - - throwMyExceptionByValue(pointerToCString("Whatever")); - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/FunctionTest.java b/libraries/BridJ/src/test/java/org/bridj/FunctionTest.java deleted file mode 100644 index a9d4e6be7..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/FunctionTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import org.bridj.ann.Name; -import org.bridj.ann.Library; -//import com.sun.jna.Native; -import java.util.Collections; -import java.util.Iterator; -import org.junit.*; -import static org.junit.Assert.*; - -/** - * - * @author Olivier - */ -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -public class FunctionTest { - - @Before - public void register() { - BridJ.register(getClass()); - } - @After - public void unregister() { - // BridJ.releaseAll(); - System.gc(); - try { - Thread.sleep(200); - } catch (Exception ex) {} - System.gc(); - } - public native int testAddDyncall(int a, int b); - - @Name("testAddDyncall") - public native int fooBar(int a, int b); - - public enum ETest implements IntValuedEnum { - eFirst(0), - eSecond(1), - eThird(2); - - ETest(int value) { - this.value = value; - } - final int value; - public long value() { - return value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - } - public static native ValuedEnum testEnum(ValuedEnum e); - @Name("testEnum") - public static native IntValuedEnum testIntEnum(IntValuedEnum e); - - @Test - public void add() { - int res = testAddDyncall(10, 4); - assertEquals(14, res); - } - - @Test - public void renamedAdd() { - int res = fooBar(10, 4); - assertEquals(14, res); - } - - @Test - public void testEnumCalls() { - for (ETest e : ETest.values()) { - ValuedEnum r = testEnum(e); - assertEquals(e.value(), r.value()); - - r = testIntEnum(e); - assertEquals(e.value(), r.value()); - //assertEquals(e, r); - } - } - @Test - public void enu() { - for (ETest v : ETest.values()) - { - FlagSet e = FlagSet.fromValues(v); - assertNotNull(e); - assertEquals(v.value(), e.value()); - ETest[] values = e.getEnumClassValues(); - assertEquals(1, values.length); - assertEquals(v, values[0]); - } - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/JAWTTest.java b/libraries/BridJ/src/test/java/org/bridj/JAWTTest.java deleted file mode 100644 index fe5d4eefa..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/JAWTTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bridj; - - - -import org.junit.Test; -import java.awt.*; -import org.bridj.jawt.*; - -import static org.junit.Assert.*; - -public class JAWTTest { - - @Test - public void testWindowPeer() throws Exception { - assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class)); - assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class)); - //assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class)); - //assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class)); - - - Frame f = new Frame(); - f.pack(); - - f.setVisible(true); - long p = JAWTUtils.getNativePeerHandle(f); - assertTrue(p != 0); - f.setVisible(false); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/LibCTest.java b/libraries/BridJ/src/test/java/org/bridj/LibCTest.java deleted file mode 100644 index f969bffcb..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/LibCTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bridj; - -import java.io.IOException; -import java.io.FileNotFoundException; -import org.bridj.ann.*; // annotations such as Library... - -import static org.bridj.Pointer.*; -import org.junit.*; -import static org.junit.Assert.*; - -@Library("c") -@org.bridj.ann.Runtime(CRuntime.class) -public class LibCTest { - static { - if ("1".equals(System.getenv("JNA"))) - com.sun.jna.Native.register("c"); - else - BridJ.register(); - } - public static native void sprintf(Pointer dest, Pointer format, Object... values); - - @Library("m") - public static native double fabs(double x); - public static native int abs(int x); - public static native int getpid(); - - public static native @org.bridj.ann.CLong long strtol(Pointer str, Pointer> endptr, int base) throws LastError; - - @Optional // only on Windows - @Library("test") - public static native void setLastWindowsError() throws LastError; - - @Test - public void testFabs() { - assertEquals(10.0, fabs(-10.0), 0.000001); - } - @Test(expected=LastError.class) - public void testLastWindowsError() { - if (!Platform.isWindows()) - throw new LastError(0, ""); - - setLastWindowsError(); - } - @Test - public void testErrno() throws IOException { - if (!Platform.isUnix()) - return; - - assertNotNull(BridJ.getNativeLibrary("c").getSymbolPointer("errno")); - } - - public void testNoLastError() { - long v = strtol(pointerToCString("1010"), null, 10); - assertEquals(1010, v); - } - - @Test(expected = LastError.class) - public void testLastError() { - strtol(pointerToCString("18446744073709551616"), null, 10); - } - - @Test - public void testAbs() { - assertEquals(10, abs(-10)); - } -} - - diff --git a/libraries/BridJ/src/test/java/org/bridj/MiscBugsTest.java b/libraries/BridJ/src/test/java/org/bridj/MiscBugsTest.java deleted file mode 100644 index a2e8a6c21..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/MiscBugsTest.java +++ /dev/null @@ -1,248 +0,0 @@ -package org.bridj; -import java.nio.CharBuffer; -import org.bridj.ann.*; -import org.junit.Test; - -import static org.bridj.Pointer.*; -import static org.junit.Assert.*; - -public class MiscBugsTest { - - static { - BridJ.register(); - } - - @Library("test") - @Optional - public static native void whatever(SizeT v); - - @Library("test") - public static native Pointer getSomeWString(); - - /** - * Issue 295 : wchar_t broken on MacOS X - * https://github.com/ochafik/nativelibs4java/issues/295 - */ - @Test - public void testWideCharReadout() { - assertEquals("1234567890", getSomeWString().getWideCString()); - } - - /** - * Issue 68 : simple SizeT calls are broken - * http://code.google.com/p/nativelibs4java/issues/detail?id=68 - */ - @Test(expected = UnsatisfiedLinkError.class) - public void testSizeTArgs() { - whatever(new SizeT(1)); - } - - /** - * Issue 37 : BridJ: org.bridj.Pointer#iterator for native-allocated pointers is empty - * http://code.google.com/p/nativelibs4java/issues/detail?id=37 - */ - @Test - public void emptyIteratorFromUnmanagedPointer() { - Pointer ptr = allocateBytes(10); - assertTrue(!ptr.asList().isEmpty()); - assertTrue(ptr.iterator().next() != null); - - Pointer unmanaged = pointerToAddress(ptr.getPeer()).as(Byte.class); - assertTrue(!unmanaged.asList().isEmpty()); - assertTrue(unmanaged.iterator().next() != null); - } - - /** - * Issue 47: Pointer#pointerToAddress(long, Class, Releaser) does not use releaser argument - * http://code.google.com/p/nativelibs4java/issues/detail?id=37 - */ - @Test - public void usePointerReleaser() { - final boolean[] released = new boolean[1]; - Pointer p = allocateInt(); - long address = p.getPeer(); - - { - Pointer pp = pointerToAddress(address); - assertEquals(address, pp.getPeer()); - } - - { - Pointer pp = pointerToAddress(address, 123); - assertEquals(address, pp.getPeer()); - assertEquals(123, pp.getValidBytes()); - } - - Releaser releaser = new Releaser() { - //@Override - public void release(Pointer p) { - released[0] = true; - } - }; - - { - released[0] = false; - Pointer pp = pointerToAddress(address, Integer.class, releaser); - assertEquals(address, pp.getPeer()); - assertEquals(Integer.class, pp.getTargetType()); - pp.release(); - assertEquals(true, released[0]); - } - - { - Pointer pp = pointerToAddress(address, PointerIO.getIntInstance()); - assertEquals(address, pp.getPeer()); - assertEquals(Integer.class, pp.getTargetType()); - } - - { - released[0] = false; - Pointer pp = pointerToAddress(address, PointerIO.getIntInstance(), releaser); - assertEquals(address, pp.getPeer()); - assertEquals(Integer.class, pp.getTargetType()); - pp.release(); - assertEquals(true, released[0]); - } - - { - released[0] = false; - Pointer pp = pointerToAddress(address, releaser); - assertEquals(address, pp.getPeer()); - pp.release(); - assertEquals(true, released[0]); - } - - { - released[0] = false; - Pointer pp = pointerToAddress(address, 123, releaser); - assertEquals(address, pp.getPeer()); - assertEquals(123, pp.getValidBytes()); - pp.release(); - assertEquals(true, released[0]); - } - - { - Pointer pp = pointerToAddress(address, Integer.class); - assertEquals(address, pp.getPeer()); - assertEquals(Integer.class, pp.getTargetType()); - } - - { - Pointer pp = pointerToAddress(address, 123, PointerIO.getIntInstance()); - assertEquals(address, pp.getPeer()); - assertEquals(123, pp.getValidBytes()); - assertEquals(Integer.class, pp.getTargetType()); - } - - } - - public class VIDEOHDR extends StructObject - { - // fields - /** - * Pointer to locked data buffer. - */ - @Field(0) - public Pointer lpData; - /** - * Length of data buffer. - */ - @Field(1) - public int dwBufferLength; - /** - * Bytes actually used. - */ - @Field(2) - public int dwBytesUsed; - /** - * Milliseconds from start of stream. - */ - @Field(3) - public int dwTimeCaptured; - /** - * User-defined data. - */ - @Field(4) - public int dwUser; - /** - * The flags are defined as follows: - *
VHDR_DONE - Done bit - *
VHDR_PREPARED - Set if this header has been prepared - *
VHDR_INQUEUE - Reserved for driver - *
VHDR_KEYFRAME - Key Frame - */ - @Field(5) - public int dwFlags; - /** - * Reserved for driver. - */ - @Field(6) - @Array(4) - public Pointer> dwReserved; - - /** - * Constructor. - */ - public VIDEOHDR() - { - } - - /** - * Constructor. - * - * @param ptr - */ - public VIDEOHDR(Pointer ptr) - { - super(ptr); - } - } - /** - * https://github.com/ochafik/nativelibs4java/issues/56#issuecomment-2075496 - */ - @Test - public void javaFieldsStructArrayFieldsVsSignedIntegrals() { - new VIDEOHDR(); - } - - static class v4l2_fmtdesc extends StructObject { - @Field(0) - public int index; - @Field(1) - public int type; - @Field(2) - public int flags; - @Field(3) - @Array(32) - public Pointer description; - @Field(4) - public int pixelformat; - @Field(5) - @Array(4) - public Pointer reserved; - } - @Union - static class fmt extends StructObject { - @Field(0) - public v4l2_fmtdesc pix; - - @Field(1) - @Array(200) - public Pointer raw_data; - } - static class v4l2_format extends StructObject { - @Field(0) - public int type; - @Field(1) - public fmt fmt; - } - /** - * https://github.com/ochafik/nativelibs4java/issues/200 - */ - @Test - public void testUnionRegression() { - new v4l2_fmtdesc(); - new fmt(); - new v4l2_format(); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/MyLibrary.java b/libraries/BridJ/src/test/java/org/bridj/MyLibrary.java deleted file mode 100644 index 1e09ccaed..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/MyLibrary.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bridj; - -import org.bridj.*; -import static org.bridj.Pointer.*; -import org.bridj.ann.*; - -/** - * - * @author Olivier - */ -public class MyLibrary { - public MyLibrary() { - BridJ.register(getClass()); - } - public static class MyCallback { - - } - public static class MyTypedPtr extends TypedPointer { - public MyTypedPtr(Pointer ptr) { - super(ptr.getPeer()); - } - @Deprecated - public MyTypedPtr(long peer) { - super(peer); - } - } - protected native @Ptr long someFunction_native(@Ptr long arg1); - public MyCallback someFunction(MyTypedPtr arg1) { - return null;//Callback.wrapCallback(someFunction_native(Pointer.getPeer(arg1)), MyCallback.class); - } - - protected native int someFunction_native(@Ptr long stringArray, @Ptr long errOut); - public int someFunction(String[] arg1, Pointer errOut) { - return someFunction_native(pointerToCStrings(arg1).getPeer(), errOut.getPeer()); - } - - protected native int someFunction2_native(@Ptr long size, @Ptr long sizeOut); - public int someFunction2(long size, Pointer sizeOut) { - return someFunction2_native(size, Pointer.getPeer(sizeOut)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/MyPtr.java b/libraries/BridJ/src/test/java/org/bridj/MyPtr.java deleted file mode 100644 index 0b6d6770d..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/MyPtr.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.bridj.ann.Ptr; - -/** - * For annotations that can be forwarded to other annotations. - * E.g. @Ptr can be forwarded to @MyPtr if the MyPtr annotation class is annotated with @Ptr - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) -@Ptr // forwarded to this ! -public @interface MyPtr { - -} \ No newline at end of file diff --git a/libraries/BridJ/src/test/java/org/bridj/NASATest.java b/libraries/BridJ/src/test/java/org/bridj/NASATest.java deleted file mode 100644 index 0034fa4df..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/NASATest.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.ann.Struct; -import static org.bridj.Pointer.*; -import static org.bridj.BridJ.*; - -@Library("test") -public class NASATest { - static { - BridJ.register(); - } - public static class stuff extends StructObject { - public stuff() { - super(); - } - /// C type : char[100] - @Array({100}) - @Field(0) - public Pointer part1() { - return this.io.getPointerField(this, 0); - } - /// C type : char[100] - @Array({100}) - @Field(1) - public Pointer part2() { - return this.io.getPointerField(this, 1); - } - /// C type : char[100] - @Array({100}) - @Field(2) - public Pointer part3() { - return this.io.getPointerField(this, 2); - } - public stuff(Pointer pointer) { - super(pointer); - } - }; - public static class container extends StructObject { - public container() { - super(); - } - /// C type : char[100] - @Array({100}) - @Field(0) - public Pointer type() { - return this.io.getPointerField(this, 0); - } - /// C type : char[100] - @Array({100}) - @Field(1) - public Pointer date() { - return this.io.getPointerField(this, 1); - } - /// C type : char[100] - @Array({100}) - @Field(2) - public Pointer time() { - return this.io.getPointerField(this, 2); - } - /// C type : stuff - @Field(3) - public stuff stuff1() { - return this.io.getNativeObjectField(this, 3); - } - /// C type : stuff - @Field(3) - public container stuff1(stuff stuff1) { - this.io.setNativeObjectField(this, 3, stuff1); - return this; - } - /// C type : stuff - public final stuff stuff1_$eq(stuff stuff1) { - stuff1(stuff1); - return stuff1; - } - /// C type : stuff - @Field(4) - public stuff stuff2() { - return this.io.getNativeObjectField(this, 4); - } - /// C type : stuff - @Field(4) - public container stuff2(stuff stuff2) { - this.io.setNativeObjectField(this, 4, stuff2); - return this; - } - /// C type : stuff - public final stuff stuff2_$eq(stuff stuff2) { - stuff2(stuff2); - return stuff2; - } - public container(Pointer pointer) { - super(pointer); - } - }; - public static class message extends StructObject { - public message() { - super(); - } - /// C type : char[512] - @Array({512}) - @Field(0) - public Pointer text() { - return this.io.getPointerField(this, 0); - } - /// C type : container[1] - @Array({1}) - @Field(1) - public Pointer container() { - return this.io.getPointerField(this, 1); - } - public message(Pointer pointer) { - super(pointer); - } - }; - - public static native void Connect(Pointer msg); - - @Test - public void test() { - message msg = new message(); - - msg.text().setCString("this is a test string from java"); - - Pointer Pmsg = Pointer.pointerTo(msg); - Connect(Pmsg); - - int i = 0; - for (container object : msg.container()) - { - System.out.println("Object " + i++); - System.out.println("Type = " + object.type().getCString()); - } - - System.out.println("return message = " + msg.text().getCString()); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/NativeLibraryTest.java b/libraries/BridJ/src/test/java/org/bridj/NativeLibraryTest.java deleted file mode 100644 index 6e4bd0f35..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/NativeLibraryTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.objc.*; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import java.io.*; - -@Library("Foundation") -@Runtime(ObjectiveCRuntime.class) -public class NativeLibraryTest { - - static File tempDir() throws IOException { - File f = File.createTempFile("bridj", "natlibtest"); - f.delete(); - f.mkdir(); - f.deleteOnExit(); - return f; - } - static void touch(File dir, String name) throws IOException { - File f = new File(dir, name); - f.deleteOnExit(); - new FileOutputStream(f).close(); - } - - @Test - public void testVersionedLibrary() throws IOException { - File d = new File("."); - String[] files = new String[] { - "libc.so.0.1", - "libc.so.1", - "libc.so.13.0", - "libc.so.2.1", - "libc.so.1.0.0" - }; - - assertEquals("libc.so.13.0", BridJ.findFileWithGreaterVersion(d, files, "libc.so").getName()); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/ObjectiveCTest.java b/libraries/BridJ/src/test/java/org/bridj/ObjectiveCTest.java deleted file mode 100644 index 78b43c782..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/ObjectiveCTest.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.bridj; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.Before; -import org.junit.After; -import static org.junit.Assert.*; - -import org.bridj.objc.*; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import org.bridj.ann.Ptr; -import static org.bridj.Pointer.*; -import static org.bridj.objc.FoundationLibrary.*; -import java.util.*; -import static org.bridj.ObjectiveCTest.TestLib.*; - -@Library("Foundation") -@Runtime(ObjectiveCRuntime.class) -public class ObjectiveCTest { - static boolean mac = Platform.isMacOSX() && (System.getenv("BRIDJ_NO_OBJC") == null); - static { - if (mac) - try { - BridJ.register(); - } catch (Throwable th) { - if (mac) - throw new RuntimeException(th); - } - } - - protected Pointer pool; - - @Before - public void init() { - if (!mac) return; - pool = NSAutoreleasePool.new_(); - assertNotNull(pool); - } - - @After - public void cleanup() { - if (!mac) return; - pool.get().drain(); - } - //* - @Test - public void testNSNumber() { - if (!mac) return; - - long n = 13; - Pointer pnn = NSNumber.numberWithLong(n); - //System.out.println("pnn = " + pnn); - NSNumber nn = pnn.get(); - //System.out.println("nn = " + nn); - assertEquals(n + "", nn.toString()); - assertEquals(n, nn.shortValue()); - assertEquals(n, nn.intValue()); - assertEquals(n, nn.longValue()); - assertEquals(n, nn.floatValue(), 0); - assertEquals(n, nn.doubleValue(), 0); - } - - @Library("Foundation") - public static class NSWorkspace extends NSObject - { - public static native Pointer sharedWorkspace(); - - public native Pointer runningApplications(); - } - @Test - public void testNSWorkspace() { - if (!mac) return; - - BridJ.register(NSWorkspace.class); - Pointer pWorkspace = NSWorkspace.sharedWorkspace(); - assertNotNull(pWorkspace); - - NSWorkspace workspace = pWorkspace.get(); - assertNotNull(workspace); - } - - @Test - public void testNSString() { - if (!mac) return; - for (String s : new String[] { "", "1", "ha\nha\u1234" }) { - assertEquals(s, pointerToNSString(s).get().toString()); - - NSString ns = new NSString(s); - assertEquals(s, ns.toString()); - assertEquals(s.length(), ns.length()); - } - } - - @Test - public void testSEL() { - if (!mac) return; - for (String s : new String[] { "", "1", "ha:ha" }) { - SEL sel = SEL.valueOf(s); - assertEquals(s, sel.getName()); - } - } - - @Test - public void testNSDictionary() { - if (!mac) return; - Map map = new HashMap(), map2; - for (String s : new String[] { "", "1", "ha\nha\u1234" }) - map.put(s, NSString.valueOf(s + s)); - - NSDictionary dic = NSDictionary.valueOf(map); - assertEquals(map.size(), dic.count()); - - map2 = dic.toMap(); - assertEquals(map.size(), map2.size()); - - //assertEquals(map, map2); - for (Map.Entry e : map.entrySet()) { - String key = e.getKey(); - NSObject expected = e.getValue(); - NSObject got = map2.get(key); - assertEquals(expected, got); - //assertEquals(expected.toString(), got.toString()); - } - } - - public static class NSNonExistentTestClass extends NSObject { - public native int add2(int a, Pointer p); - public native float incf(float v); - public native double add8(byte a, short b, int c, char d, long e, double f, Pointer p); - } - static void test_NSNonExistentTestClass_add(ObjCObject proxy) { - if (!mac) return; - NSNonExistentTestClass p = pointerTo(proxy).as(NSNonExistentTestClass.class).get(); - Pointer ptr = pointerToInt(64); - assertEquals(1 + ptr.get(), p.add2(1, ptr)); - assertEquals(127, p.add8((byte)1, (short)2, (int)4, (char)8, (long)16, (double)32, ptr), 0); - } - String DESCRIPTION = "WHATEVER !!!"; - @Test - public void testProxy() { - if (!mac) return; - ObjCProxy proxy = new ObjCProxy() { - public Pointer description() { - return pointerToNSString(DESCRIPTION); - } - public int add2(int a, Pointer p) { - return a + p.get(); - } - public float incf(float v) { - return v + 1; - } - public double add8(long a, int b, short c, byte d, char e, double f, Pointer p) { - return a + b + c + d + e + f + p.get(); - } - }; - test_NSNonExistentTestClass_add(proxy); - test_NSNonExistentTestClass_add(new ObjCProxy(proxy)); - } - - @Ignore - @Test - public void testProxyFloat() { - if (!mac) return; - Object proxy = new Object() { - public float incf(float v) { - return v + 1; - } - }; - NSNonExistentTestClass p = pointerTo(new ObjCProxy(proxy)).as(NSNonExistentTestClass.class).get(); - System.out.println(p.description().get()); - assertEquals(11, p.incf(10), 0); - } - //*/ - public static class NSEvent extends NSObject { - //@Selector("addGlobalMonitorForEventsMatchingMask:handler:") - public static native Pointer addGlobalMonitorForEventsMatchingMask_handler(long mask, Pointer handler); - } - - public abstract static class NSEventGlobalCallback extends ObjCBlock { - public abstract void callback(Pointer event); - } - - @Ignore - @Test - public void testGlobalNSEventHook() throws Exception { - if (!mac) return; - BridJ.register(NSEvent.class); - - final boolean called[] = new boolean[1]; - NSEventGlobalCallback handler = new NSEventGlobalCallback() { - @Override - public void callback(Pointer event) { - System.out.println("Event: " + event); - called[0] = true; - } - }; - - //System.out.println("handler: " + handler); - - Pointer hook = NSEvent.addGlobalMonitorForEventsMatchingMask_handler(-1L/*1 << 1*/, pointerTo(handler)); - - //System.out.println("hook: " + hook); - - Thread.sleep(10000); - - assertTrue(called[0]); - } - //* - @Library("test") - public static class TestLib { - public static interface Delg extends ObjCDelegate { - int add_to(int a, int b); - } - public static class DelgImpl extends NSObject implements Delg { - public native int add_to(int a, int b); - } - public static class DelgHolder extends NSObject { - public native void setDelegate(Pointer delegate); - public native int outerAdd_to(int a, int b); - } - public static abstract class FwdBlock extends ObjCBlock { - public abstract int apply(int a, int b); - } - public static native int forwardBlockCallIntIntInt(Pointer block, int a, int b); - } - - static void testDelegate(Delg delegate) { - DelgHolder holder = new DelgHolder(); - holder.setDelegate(pointerTo(delegate)); - - int a = 10, b = 20, expected = a + b; - int res = holder.outerAdd_to(a, b); - //System.out.println(Delg.class.getName() + ".add[through delegate](" + a + ", " + b + ") = " + res); - assertEquals(expected, res); - } - - @Test - public void testNativeDelegate() { - if (!mac) return; - testDelegate(new DelgImpl()); - } - static class MyDelg extends ObjCProxy implements Delg { - @Override - public int add_to(int a, int b) { - return a + b; - } - } - @Test - public void testJavaDelegate() { - if (!mac) return; - testDelegate(new MyDelg()); - } - - @Test - public void testBlock() { - if (!mac) return; - FwdBlock block = new FwdBlock() { - @Override - public int apply(int a, int b) { - return a + b; - } - }; - int a = 10, b = 20, expected = a + b; - int res = forwardBlockCallIntIntInt(pointerTo(block), a, b); - assertEquals(expected, res); - } - //*/ -} diff --git a/libraries/BridJ/src/test/java/org/bridj/PerfLib.java b/libraries/BridJ/src/test/java/org/bridj/PerfLib.java deleted file mode 100644 index edc348d22..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/PerfLib.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import org.bridj.ann.Library; -//import com.sun.jna.Native; - -/** - * - * @author Olivier - */ -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -public class PerfLib { - static java.io.File libraryFile = BridJ.getNativeLibraryFile(BridJ.getNativeLibraryName(PerfLib.class)); - static { - System.load(libraryFile.toString()); - } - public static class DynCallTest { - static { - BridJ.register(); - } - public native int testAddDyncall(int a, int b); - public native int testASinB(int a, int b); - } - - public static class JNATest implements com.sun.jna.Library { - static { - try { - com.sun.jna.Native.register(libraryFile.toString()); - } catch (Exception ex) { - throw new RuntimeException("Failed to initialize test JNA library", ex); - } - } - public static native int testAddJNA(int a, int b); - public static native int testASinB(int a, int b); - } - public interface JNAInterfaceTest extends com.sun.jna.Library { - public static final JNAInterfaceTest INSTANCE = (JNAInterfaceTest)com.sun.jna.Native.loadLibrary(libraryFile.toString(), JNAInterfaceTest.class); - int testAddJNA(int a, int b); - int testASinB(int a, int b); - } - public static native int testAddJNI(int a, int b); - public static native double testASinB(int a, int b); -} diff --git a/libraries/BridJ/src/test/java/org/bridj/PlatformTest.java b/libraries/BridJ/src/test/java/org/bridj/PlatformTest.java deleted file mode 100644 index bb835635a..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/PlatformTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bridj; -import static org.bridj.Platform.*; -import org.junit.*; -import static org.junit.Assert.*; -import java.io.*; - -public class PlatformTest { - @Test - public void testSizes() { - int clong = isWindows() || !is64Bits() ? 4 : 8; - int sizet = is64Bits() ? 8 : 4, ptr = sizet; - int wchar = isUnix() ? 4 : 2; - - assertEquals(clong, Platform.CLONG_SIZE); - assertEquals(sizet, Platform.SIZE_T_SIZE); - assertTrue(Platform.TIME_T_SIZE > 0); - assertEquals(wchar, Platform.WCHAR_T_SIZE); - assertEquals(ptr, Platform.POINTER_SIZE); - - assertEquals(ptr, Pointer.SIZE); - assertEquals(sizet, SizeT.SIZE); - assertTrue(TimeT.SIZE > 0); - assertEquals(clong, CLong.SIZE); - - } - @Test - public void testMachine() throws Exception { - if (!isUnix()) - return; - - Process p = Runtime.getRuntime().exec(new String[] { "uname", "-m" }); - BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); - - String m = r.readLine().trim(); - assertTrue(m.length() > 0); - - if (m.matches("i\\d86")) - m = "i386"; - else if (m.matches("i86pc")) - m = "x86"; - - assertEquals(m, Platform.getMachine()); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/Struct2Test.java b/libraries/BridJ/src/test/java/org/bridj/Struct2Test.java deleted file mode 100644 index 9d35bd975..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/Struct2Test.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bridj; - -import com.sun.jna.Memory; -import java.nio.ByteBuffer; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.ann.Struct; -import org.bridj.cpp.com.*; -import static org.bridj.Pointer.*; -import static org.bridj.BridJ.*; -import java.util.List; - -import javolution.io.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html - -public class Struct2Test { - public static class OrphanStruct extends StructObject { - @Field(0) - public int a; - - @Field(1) - public int b; - } - @Test - public void testOrphanStruct() { - new OrphanStruct(); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/Struct3Test.java b/libraries/BridJ/src/test/java/org/bridj/Struct3Test.java deleted file mode 100644 index a0d0276e0..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/Struct3Test.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.ann.Optional; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html - -@Library("test") -public class Struct3Test { - static { - BridJ.register(); - } - - @Optional - public static native @Ptr long sizeOf_message(); - @Optional - public static native @Ptr long sizeOf_container(); - @Optional - public static native @Ptr long sizeOf_stuff(); - - public static class stuff extends StructObject { - public stuff() { - super(); - } - /// C type : char[100] - @Array({100}) - @Field(0) - public Pointer part1() { - return this.io.getPointerField(this, 0); - } - /// C type : char[100] - @Array({100}) - @Field(1) - public Pointer part2() { - return this.io.getPointerField(this, 1); - } - /// C type : char[100] - @Array({100}) - @Field(2) - public Pointer part3() { - return this.io.getPointerField(this, 2); - } - public stuff(Pointer pointer) { - super(pointer); - } - }; - public static class container extends StructObject { - public container() { - super(); - } - /// C type : char[100] - @Array({100}) - @Field(0) - public Pointer type() { - return this.io.getPointerField(this, 0); - } - /// C type : char[100] - @Array({100}) - @Field(1) - public Pointer date() { - return this.io.getPointerField(this, 1); - } - /// C type : char[100] - @Array({100}) - @Field(2) - public Pointer time() { - return this.io.getPointerField(this, 2); - } - /// C type : stuff - @Field(3) - public stuff stuff1() { - return this.io.getNativeObjectField(this, 3); - } - /// C type : stuff - @Field(3) - public container stuff1(stuff stuff1) { - this.io.setNativeObjectField(this, 3, stuff1); - return this; - } - /// C type : stuff - @Field(4) - public stuff stuff2() { - return this.io.getNativeObjectField(this, 4); - } - /// C type : stuff - @Field(4) - public container stuff2(stuff stuff2) { - this.io.setNativeObjectField(this, 4, stuff2); - return this; - } - public container(Pointer pointer) { - super(pointer); - } - }; - public static class message extends StructObject { - public message() { - super(); - } - /// C type : char[512] - @Array({512}) - @Field(0) - public Pointer text() { - return this.io.getPointerField(this, 0); - } - /// C type : container[1] - @Array({1}) - @Field(1) - public Pointer container() { - return this.io.getPointerField(this, 1); - } - public message(Pointer pointer) { - super(pointer); - } - }; - - @Test - public void testSizeOfMessage() { - assertEquals(sizeOf_stuff(), BridJ.sizeOf(stuff.class)); - assertEquals(sizeOf_container(), BridJ.sizeOf(container.class)); - assertEquals(sizeOf_message(), BridJ.sizeOf(message.class)); - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/StructByValueTest.java b/libraries/BridJ/src/test/java/org/bridj/StructByValueTest.java deleted file mode 100644 index 7fd36a818..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/StructByValueTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package org.bridj; - -import java.util.logging.Level; -import org.junit.Ignore; -import org.bridj.ann.Library; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; -import org.bridj.ann.Array; - - -import static org.bridj.dyncall.DyncallLibrary.*; - -@Ignore -@Library("test") -public class StructByValueTest { - static { - if (!BridJ.Switch.StructsByValue.enabled) - BridJ.warning("Structs by value are not enabled (see " + BridJ.Switch.StructsByValue.getFullDescription() + ")"); - else - BridJ.register(); - } - public static class SimpleStruct extends StructObject { - @Field(0) - public int a; - - @Field(1) - @Array(2) - public Pointer b; - - @Field(2) - public short c; - - @Field(3) - @Array(3) - public Pointer d; - - @Field(4) - public float e; - } - - public static class S_int extends StructObject { - @Field(0) - public int a; - } - public static class S_int2 extends StructObject { - @Field(0) - public int a; - @Field(1) - public int b; - } - public static class S_jlong4 extends StructObject { - @Field(0) - public long a; - @Field(1) - public long b; - @Field(2) - public long c; - @Field(3) - public long d; - } - public static class S_jlong10 extends StructObject { - @Field(0) - @Array(10) - public Pointer a; - } - - public static native int incr(S_int s); - public static native long sum(S_int2 s); - public static native long sum(S_jlong4 s); - public static native long sum(S_jlong10 s); - -// @Test -// public void testSimpleStruct() { -// Pointer s = dcNewStruct(5, DEFAULT_ALIGNMENT); -// try { -// dcStructField(s, DC_SIGCHAR_INT, DEFAULT_ALIGNMENT, 1); -// dcStructField(s, DC_SIGCHAR_LONGLONG, DEFAULT_ALIGNMENT, 2); -// dcStructField(s, DC_SIGCHAR_SHORT, DEFAULT_ALIGNMENT, 1); -// dcStructField(s, DC_SIGCHAR_CHAR, DEFAULT_ALIGNMENT, 3); -// dcStructField(s, DC_SIGCHAR_FLOAT, DEFAULT_ALIGNMENT, 1); -// dcCloseStruct(s); -// -// long size = dcStructSize(s); -// assertEquals(BridJ.sizeOf(SimpleStruct.class), size); -// } finally { -// dcFreeStruct(s); -// } -// } - - - @Test - public void testStructSizes() { - if (!BridJ.Switch.StructsByValue.enabled) - return; - - StructIO io = StructIO.getInstance(SimpleStruct.class); - Pointer struct = DyncallStructs.buildDCstruct(io); - assertNotNull(struct); - } - - //@Ignore - @Test - public void testIncrInt() { - if (!BridJ.Switch.StructsByValue.enabled) - return; - - int value = 12345; - S_int s = new S_int(); - s.a = value; - BridJ.writeToNative(s); - assertEquals(value + 1, incr(s)); - } - - - @Ignore - @Test - public void testIncrLong4() { - if (!BridJ.Switch.StructsByValue.enabled) - return; - - long value = 12345; - S_jlong4 s = new S_jlong4(); - s.a = 10; - s.b = 100; - s.c = 1000; - s.d = 10000; - BridJ.writeToNative(s); - assertEquals(s.a + s.b + s.c + s.d, sum(s)); - } - - @Test - public void testIncrLong10() { - if (!BridJ.Switch.StructsByValue.enabled) - return; - - long tot = 0; - S_jlong10 s = new S_jlong10(); - for (int i = 0; i < 10; i++) { - long v = i + 1; - tot += v; - s.a.set(i, v); - } - BridJ.writeToNative(s); - assertEquals(tot, sum(s)); - } -} \ No newline at end of file diff --git a/libraries/BridJ/src/test/java/org/bridj/StructTest.java b/libraries/BridJ/src/test/java/org/bridj/StructTest.java deleted file mode 100644 index 02419e7a5..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/StructTest.java +++ /dev/null @@ -1,840 +0,0 @@ -package org.bridj; - -import com.sun.jna.Memory; -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.Iterator; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Array; -import org.bridj.ann.Ptr; -import org.bridj.ann.Struct; -import org.bridj.ann.Optional; -import org.bridj.cpp.com.*; -import static org.bridj.Pointer.*; -import static org.bridj.BridJ.*; -import java.util.List; - -import javolution.io.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html - -@Library("test") -public class StructTest { - static { - BridJ.register(); - } - - @Optional - public static native @Ptr long sizeOfVARIANT(); - @Optional - public static native @Ptr long sizeOfDECIMAL(); - @Optional - public static native @Ptr long sizeOfCAPDRIVERCAPS(); - - - @Test - public void guidSize() { - long s = BridJ.sizeOf(GUID.class); - assertEquals(16, s); - } - - @Test - public void variantSize() { - if (!Platform.isWindows()) - return; - - long s = BridJ.sizeOf(VARIANT.class); - assertEquals(sizeOfVARIANT(), s); - } - - @Test - public void decimalSize() { - long s = BridJ.sizeOf(DECIMAL.class); - if (Platform.isWindows()) - assertEquals(sizeOfDECIMAL(), s); - else - assertEquals(16, s); - } - - @Test - public void testSizeOfCAPDRIVERCAPS() { - long s = BridJ.sizeOf(CAPDRIVERCAPS.class); - if (Platform.isUnix()) { - if (Platform.is64Bits()) - assertEquals(64, s); - else - assertEquals(44, s); - } else if (Platform.isWindows()) - assertEquals(sizeOfCAPDRIVERCAPS(), s); - } - - public class CAPDRIVERCAPS extends StructObject { - public CAPDRIVERCAPS() { - super(); - } - public CAPDRIVERCAPS(Pointer pointer) { - super(pointer); - } - /// C type : UINT - @Field(0) - public int wDeviceIndex() { - return this.io.getIntField(this, 0); - } - /// C type : UINT - @Field(0) - public CAPDRIVERCAPS wDeviceIndex(int wDeviceIndex) { - this.io.setIntField(this, 0, wDeviceIndex); - return this; - } - /// C type : UINT - public final int wDeviceIndex_$eq(int wDeviceIndex) { - wDeviceIndex(wDeviceIndex); - return wDeviceIndex; - } - @Field(1) - public int fHasOverlay() { - return this.io.getIntField(this, 1); - } - @Field(1) - public CAPDRIVERCAPS fHasOverlay(int fHasOverlay) { - this.io.setIntField(this, 1, fHasOverlay); - return this; - } - public final int fHasOverlay_$eq(int fHasOverlay) { - fHasOverlay(fHasOverlay); - return fHasOverlay; - } - @Field(2) - public int fHasDlgVideoSource() { - return this.io.getIntField(this, 2); - } - @Field(2) - public CAPDRIVERCAPS fHasDlgVideoSource(int fHasDlgVideoSource) { - this.io.setIntField(this, 2, fHasDlgVideoSource); - return this; - } - public final int fHasDlgVideoSource_$eq(int fHasDlgVideoSource) { - fHasDlgVideoSource(fHasDlgVideoSource); - return fHasDlgVideoSource; - } - @Field(3) - public int fHasDlgVideoFormat() { - return this.io.getIntField(this, 3); - } - @Field(3) - public CAPDRIVERCAPS fHasDlgVideoFormat(int fHasDlgVideoFormat) { - this.io.setIntField(this, 3, fHasDlgVideoFormat); - return this; - } - public final int fHasDlgVideoFormat_$eq(int fHasDlgVideoFormat) { - fHasDlgVideoFormat(fHasDlgVideoFormat); - return fHasDlgVideoFormat; - } - @Field(4) - public int fHasDlgVideoDisplay() { - return this.io.getIntField(this, 4); - } - @Field(4) - public CAPDRIVERCAPS fHasDlgVideoDisplay(int fHasDlgVideoDisplay) { - this.io.setIntField(this, 4, fHasDlgVideoDisplay); - return this; - } - public final int fHasDlgVideoDisplay_$eq(int fHasDlgVideoDisplay) { - fHasDlgVideoDisplay(fHasDlgVideoDisplay); - return fHasDlgVideoDisplay; - } - @Field(5) - public int fCaptureInitialized() { - return this.io.getIntField(this, 5); - } - @Field(5) - public CAPDRIVERCAPS fCaptureInitialized(int fCaptureInitialized) { - this.io.setIntField(this, 5, fCaptureInitialized); - return this; - } - public final int fCaptureInitialized_$eq(int fCaptureInitialized) { - fCaptureInitialized(fCaptureInitialized); - return fCaptureInitialized; - } - @Field(6) - public int fDriverSuppliesPalettes() { - return this.io.getIntField(this, 6); - } - @Field(6) - public CAPDRIVERCAPS fDriverSuppliesPalettes(int fDriverSuppliesPalettes) { - this.io.setIntField(this, 6, fDriverSuppliesPalettes); - return this; - } - public final int fDriverSuppliesPalettes_$eq(int fDriverSuppliesPalettes) { - fDriverSuppliesPalettes(fDriverSuppliesPalettes); - return fDriverSuppliesPalettes; - } - /// C type : HANDLE - @Field(7) - public Pointer hVideoIn() { - return this.io.getPointerField(this, 7); - } - /// C type : HANDLE - @Field(7) - public CAPDRIVERCAPS hVideoIn(Pointer hVideoIn) { - this.io.setPointerField(this, 7, hVideoIn); - return this; - } - /// C type : HANDLE - public final Pointer hVideoIn_$eq(Pointer hVideoIn) { - hVideoIn(hVideoIn); - return hVideoIn; - } - /// C type : HANDLE - @Field(8) - public Pointer hVideoOut() { - return this.io.getPointerField(this, 8); - } - /// C type : HANDLE - @Field(8) - public CAPDRIVERCAPS hVideoOut(Pointer hVideoOut) { - this.io.setPointerField(this, 8, hVideoOut); - return this; - } - /// C type : HANDLE - public final Pointer hVideoOut_$eq(Pointer hVideoOut) { - hVideoOut(hVideoOut); - return hVideoOut; - } - /// C type : HANDLE - @Field(9) - public Pointer hVideoExtIn() { - return this.io.getPointerField(this, 9); - } - /// C type : HANDLE - @Field(9) - public CAPDRIVERCAPS hVideoExtIn(Pointer hVideoExtIn) { - this.io.setPointerField(this, 9, hVideoExtIn); - return this; - } - /// C type : HANDLE - public final Pointer hVideoExtIn_$eq(Pointer hVideoExtIn) { - hVideoExtIn(hVideoExtIn); - return hVideoExtIn; - } - /// C type : HANDLE - @Field(10) - public Pointer hVideoExtOut() { - return this.io.getPointerField(this, 10); - } - /// C type : HANDLE - @Field(10) - public CAPDRIVERCAPS hVideoExtOut(Pointer hVideoExtOut) { - this.io.setPointerField(this, 10, hVideoExtOut); - return this; - } - /// C type : HANDLE - public final Pointer hVideoExtOut_$eq(Pointer hVideoExtOut) { - hVideoExtOut(hVideoExtOut); - return hVideoExtOut; - } - } - public class Simple extends StructObject { - public Simple() { - super(); - } - public Simple(Pointer pointer) { - super(pointer); - } - @Field(0) - public boolean a() { - return this.io.getBooleanField(this, 0); - } - @Field(0) - public Simple a(boolean a) { - this.io.setBooleanField(this, 0, a); - return this; - } - public final boolean a_$eq(boolean a) { - a(a); - return a; - } - @Field(1) - public boolean b() { - return this.io.getBooleanField(this, 1); - } - @Field(1) - public Simple b(boolean b) { - this.io.setBooleanField(this, 1, b); - return this; - } - public final boolean b_$eq(boolean b) { - b(b); - return b; - } - /// C type : void* - @Field(2) - public Pointer i() { - return this.io.getPointerField(this, 2); - } - /// C type : void* - @Field(2) - public Simple i(Pointer i) { - this.io.setPointerField(this, 2, i); - return this; - } - /// C type : void* - public final Pointer i_$eq(Pointer i) { - i(i); - return i; - } - } - - @Test - public void testSizeOfSimple() { - if (Platform.is64Bits()) - assertEquals(16, BridJ.sizeOf(Simple.class)); - else - assertEquals(8, BridJ.sizeOf(Simple.class)); - } - - public static class MyStruct extends StructObject { - public MyStruct(Pointer p) { super(p); } - public MyStruct() { super(); } - @Field(0) - public int a() { - return io.getIntField(this, 0); - } - public MyStruct a(int a) { - io.setIntField(this, 0, a); - return this; - } - - @Field(1) - public double b() { - return io.getDoubleField(this, 1); - } - public MyStruct b(double b) { - io.setDoubleField(this, 1, b); - return this; - } - } - - public static class TestStruct extends MyStruct { - public TestStruct(Pointer p) { super(p); } - public TestStruct() { super(); } - - @Array(10) - @Field(2) - public Pointer values() { - return io.getPointerField(this, 2); - } - - @Field(3) - public MyStruct sub() { - return io.getNativeObjectField(this, 3); - } - } - - - public static class TestStructWithFields extends StructObject { - public TestStructWithFields(Pointer p) { super(p); } - public TestStructWithFields() { super(); } - @Field(0) - public int a; - - @Field(1) - public double b; - - @Array(10) - @Field(2) - public Pointer values; - - @Field(3) - public MyStruct sub; - } - - @Test - public void testJavaFieldStructs() { - assertEquals(BridJ.sizeOf(TestStruct.class), BridJ.sizeOf(TestStructWithFields.class)); - - TestStruct s = new TestStruct(); - - s.a(10); - s.b(20); - - TestStructWithFields fs = new TestStructWithFields(pointerTo(s)); - - assertEquals(s.a(), 10); // no modification of original struct - assertEquals(s.b(), 20, 0); - assertEquals(s.a(), fs.a); // read fields upon creation - assertEquals(s.b(), fs.b, 0); - - assertEquals(pointerTo(s.sub()), pointerTo(fs.sub)); - - assertEquals(s.values(), fs.values); - - fs.a = 100; - fs.b = 200; - BridJ.writeToNative(fs); - assertEquals(s.a(), fs.a); // did write succeed ? - assertEquals(s.b(), fs.b, 0); - s.a(1000); - s.b(2000); - BridJ.readFromNative(fs); - assertEquals(s.a(), fs.a); // did read succeed ? - assertEquals(s.b(), fs.b, 0); - } - - @Test - public void testEquality() { - MyStruct x = new MyStruct(), y = new MyStruct(), z = new MyStruct(); - long len = sizeOf(MyStruct.class); - int a = 10; - double b = 12.0; - pointerTo(x).clearBytesAtOffset(0, len, (byte)0xff); - for (MyStruct s : new MyStruct[] { x, y }) - s.a(a).b(b); - - assertFalse(pointerTo(x).compareBytes(pointerTo(y), len) == 0); - assertEquals(x, y); - assertFalse(x.equals(z)); - } - - public static class MyJNAStruct extends com.sun.jna.Structure { - public MyJNAStruct(com.sun.jna.Pointer p) { - super(p); - } - public MyJNAStruct() { - super(); - } - public int a; - public double b; - } - public static class MyNIOStruct { - final ByteBuffer p; - public MyNIOStruct(ByteBuffer p) { - this.p = p; - } - public MyNIOStruct() { - this(ByteBuffer.allocateDirect(12)); - } - public int a() { - return p.getInt(0); - } - public void a(int a) { - p.putInt(0, a); - } - - public double b() { - return p.getDouble(4); - } - public void b(double b) { - p.putDouble(4, b); - } - } - public static class MyOptimalStruct { - //protected final com.sun.jna.Pointer pointer; - ByteBuffer pointer; - private static final long aOffset, bOffset; - static { - StructIO io = StructIO.getInstance(MyOptimalStruct.class, MyOptimalStruct.class); - io.build(); - aOffset = io.fields[0].byteOffset; - bOffset = io.fields[1].byteOffset; - } - public MyOptimalStruct(ByteBuffer p) {//com.sun.jna.Pointer p) { - this.pointer = p; - } - public MyOptimalStruct() { - //this(new Memory(16)); - //this(allocateBytes(16)); - this(ByteBuffer.allocateDirect(16)); - } - @Field(0) - public int a() { - return pointer.getInt((int)aOffset); - } - public void a(int a) { - pointer.putInt((int)aOffset, a); - } - - @Field(1) - public double b() { - return pointer.getDouble((int)bOffset); - } - public void b(double b) { - pointer.putDouble((int)bOffset, b); - } - } - - public static class MyJavolutionStruct extends javolution.io.Struct { - public final Signed32 a = new Signed32(); - public final Float64 b = new Float64(); - } - - @Test - public void trivial() { - MyStruct s = new MyStruct(); - s.a(10); - s.b(100.0); - int a = s.a(); - double b = s.b(); - assertEquals(10, a); - assertEquals(100.0, b, 0); - } - - public static class CastStruct extends StructObject { - public CastStruct(Pointer p) { - super(p); - } - @Field(0) - public int a() { - return this.io.getIntField(this, 0); - } - public void a(int a) { - this.io.setIntField(this, 0, a); - } - //public native CastStruct a(int a); - - } - - @Test - public void testCast() { - Pointer m = Pointer.allocateBytes(100); - CastStruct s = new CastStruct(m); - s.a(10); - //assertTrue(s == s.a(10)); - int a = s.a(); - assertEquals(10, a); - } - - public static class ArrStruct extends StructObject { - - @Field(0) - public int a() { - return this.io.getIntField(this, 0); - } - public ArrStruct a(int a) { - this.io.setIntField(this, 0, a); - return this; - } - - } - @Test - public void arrayCast() { - Pointer formats = allocateArray(ArrStruct.class, 10); - assertEquals(10, formats.getValidElements()); - for (ArrStruct s : formats) { - assertNotNull(s); - assertEquals(0, s.a()); - assertTrue(s == s.a(10)); - } - } - - - public static class ThisStruct extends StructObject { - - @Field(0) - public int a() { - return io.getIntField(this, 0); - } - public ThisStruct a(int a) { - io.setIntField(this, 0, a); - return this; - } - @Field(1) - public SubStruct sub() { - return io.getNativeObjectField(this, 1); - } - - } - public static class SubStruct extends StructObject { - - @Field(0) - public int a() { - return io.getIntField(this, 0); - } - public SubStruct a(int a) { - io.setIntField(this, 0, a); - return this; - } - - } - - @Test - public void testThisStruct() { - ThisStruct s = new ThisStruct(); - ThisStruct o = s.a(10); - assertTrue(s == o); - int a = s.a(); - assertEquals(10, a); - } - @Test - public void testThisSubStruct() { - ThisStruct s = new ThisStruct(); - assertEquals(2 * 4, BridJ.sizeOf(ThisStruct.class)); - SubStruct sub = s.sub(); - assertEquals("Invalid sub-struct !", pointerTo(s).offset(4), pointerTo(sub)); - - } - - public static class ThisStructFields extends StructObject { - - @Field(0) - public int a; - - @Field(1) - public SubStructFields sub; - - } - public static class SubStructFields extends StructObject { - - @Field(0) - public int a; - } - - @Test - public void testThisStructFields() { - ThisStructFields s = new ThisStructFields(); - s.a = 10; - BridJ.writeToNative(s); - s = pointerTo(s).get(); - int a = s.a; - assertEquals(10, a); - } - @Test - public void testThisSubStructFields() { - ThisStructFields s = new ThisStructFields(); - assertEquals(2 * 4, BridJ.sizeOf(ThisStructFields.class)); - SubStructFields sub = s.sub; - assertEquals("Invalid sub-struct !", pointerTo(s).offset(4), pointerTo(sub)); - sub.a = 100; - BridJ.writeToNative(s); - - s = pointerTo(s).get(); - assertEquals(100, s.sub.a); - } - - public static class StructWithArrays extends StructObject { - @Array(10) - @Field(0) - public Pointer ints() { - return io.getPointerField(this, 0); - } - } - @Test - public void testStructWithArrays() { - StructWithArrays s = new StructWithArrays(); - Pointer pInts = s.ints(); - assertEquals("Invalid array field pointer type", Integer.class, pInts.getTargetType()); - assertEquals("Invalid sub array", pointerTo(s).getPeer(), pInts.getPeer()); - } - - public static class CLongSize extends StructObject { - @Field(0) - @org.bridj.ann.CLong - public long v; - } - - @Test - public void testCLongSize() { - assertEquals(CLong.SIZE, BridJ.sizeOf(CLongSize.class)); - } - public static class SizeTSize extends StructObject { - @Field(0) - @Ptr - public long v; - } - - @Test - public void testSizeTSize() { - assertEquals(SizeT.SIZE, BridJ.sizeOf(SizeTSize.class)); - } - - public static class NoLoop extends StructObject { - @Field(0) - public int value; - - @Field(1) - public Pointer next; - } - - @Test - public void testNoLoop() { - long s = BridJ.sizeOf(NoLoop.class); - assertEquals(2 * Pointer.SIZE, s); - //System.out.println("sizeof = " + s); - NoLoop l = new NoLoop(); - Pointer p = pointerTo(l); - //System.out.println("NoLoop = " + p); - //System.out.println("valid bytes = " + p.getValidBytes() + ", sizeof = " + s); - l = p.get(); - } - - /// see vfw.h - public static class VIDEOHDR extends StructObject - { - @Field(0) - public Pointer lpData; - @Field(1) - public int dwBufferLength; - @Field(2) - public int dwBytesUsed; - @Field(3) - public int dwTimeCaptured; - @Field(4) - public Pointer dwUser; - @Field(5) - public int dwFlags; - @Field(6) @Array(4) - public Pointer> dwReserved; - } - @Test - public void testSizeOfVIDEOHDR() { - if (!Platform.isWindows()) - return; - - long s = BridJ.sizeOf(VIDEOHDR.class); - long expected = Platform.is64Bits() ? 72 : 40; - assertEquals(expected, s); - } - - @Struct(customizer = TinyStructCustomizer.class) - public static class TinyStruct extends StructObject { - @Field(0) - public long a; - @Field(1) - public long b; - } - public static class ExpectedTinyStruct extends StructObject { - @Field(0) - public byte a; - @Field(1) - public byte b; - } - - public static class TinyStructCustomizer extends StructIO.DefaultCustomizer { - @Override - public void beforeLayout(StructIO io, List aggregatedFields) { - for (StructIO.AggregatedFieldDesc field : aggregatedFields) { - field.byteLength = 1; - field.alignment = 1; - } - } - } - @Test - public void testTinyStructCustomization() { - assertEquals("Invalid customized struct size !", BridJ.sizeOf(ExpectedTinyStruct.class), BridJ.sizeOf(TinyStruct.class)); - ExpectedTinyStruct s = new ExpectedTinyStruct(); - s.a = 10; - s.b = -20; - BridJ.writeToNative(s); - TinyStruct t = pointerTo(s).as(TinyStruct.class).get(); - assertEquals(s.a, t.a); - assertEquals(s.b, t.b); - } - - @Optional - @Ptr - public static native long sizeOfTimeT(); - @Optional - @Ptr - public static native long sizeOfTimeval(); - - @Test - public void testSizeOfTimeval() { - assertEquals(sizeOfTimeval(), BridJ.sizeOf(TimeT.timeval.class)); - } - @Test - public void testTimeval() { - TimeT.timeval tv = new TimeT.timeval(); - Pointer ptv = pointerTo(tv); - tv = ptv.get(); - } - - -// @Library("SmallPt") - public static class S extends StructObject { - @Field(0) - public int a; - @Field(1) - public byte b; - @Field(2) - public byte c; - } - - @Struct(pack = 1) - public static class PackedS extends S { - - } - - @Test - public void testPacked() { - long s = sizeOf(S.class), ps = sizeOf(PackedS.class); - //System.out.println("testPacked " + ps + " vs. " + s); - assertEquals("Invalid packed struct size", 6, ps); - assertTrue("Packed size (" + ps + ") same as size (" + s + ") !", s != ps); - //assertTrue(ps < s); - } - - public static class EnumsStruct extends StructObject { - public enum E implements IntValuedEnum { - A(0), - B(1), - C(2); - E(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - }; - @Array(5) - @Field(0) - public Pointer> p; - } - @Test - public void testEnumsStruct() { - assertEquals(5 * BridJ.sizeOf(IntValuedEnum.class), BridJ.sizeOf(EnumsStruct.class)); - } - - public enum cec_device_type implements IntValuedEnum { - - A, B; - - public long value() { - return ordinal(); - } - - public Iterator iterator() { - return FlagSet.fromValue(value(), cec_device_type.class).iterator(); - } - - } - public static class cec_device_type_list extends StructObject { - public cec_device_type_list() { - super(); - } - /// C type : cec_device_type[5] - @Array({5}) - @Field(0) - public Pointer > types() { - return this.io.getPointerField(this, 0); - } - } - - @Test - public void testEnumsFieldRegression() { - Pointer pDeviceTypeList = Pointer.pointerTo(new cec_device_type_list()); - cec_device_type_list deviceTypeList = pDeviceTypeList.get(); - Pointer> pDeviceTypes = deviceTypeList.types(); - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/TestDylibs.java b/libraries/BridJ/src/test/java/org/bridj/TestDylibs.java deleted file mode 100644 index dc6d4836e..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/TestDylibs.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bridj; - -import java.io.*; - -import org.junit.*; -import static org.junit.Assert.*; - -@Ignore -public class TestDylibs { - @Test - public void test() throws IOException { - if (!Platform.isMacOSX()) - return; - - Process p = Runtime.getRuntime().exec(new String[] { "find", "/usr/lib", "-name", "*.dylib" }); - BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); - - String path; - while ((path = in.readLine()) != null) { - path = path.trim(); - if (path.contains("libSystem")) - continue; - - File f = new File(path); - try { - System.out.println("Loading '" + f + "'"); - NativeLibrary lib = BridJ.getNativeLibrary(f.getName(), f); - assertNotNull(lib); - System.out.println("\t" + lib.getSymbols().size() + " symbols"); - lib.release(); - } catch (Throwable th) { - System.err.println("Failed to load '" + path + "' : " + th); - } - } - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/TypedPointersTest.java b/libraries/BridJ/src/test/java/org/bridj/TypedPointersTest.java deleted file mode 100644 index b94049849..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/TypedPointersTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.bridj; - -import java.io.FileNotFoundException; - -import java.util.Collection; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.*; -import org.bridj.*; - -///http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html -public class TypedPointersTest { - - public static class MyPtr extends TypedPointer { - public MyPtr(long peer) { - super(peer); - } - public MyPtr(Pointer peer) { - super(peer); - } - } - - @Library("test") - public static class MyStruct extends StructObject { - @Field(0) - //public native Pointer a(); - //public native MyStruct a(MyPtr a); - public MyPtr a() { - return io.getTypedPointerField(this, 0); - } - public MyStruct a(MyPtr a) { - io.setPointerField(this, 0, a); - return this; - } - //public native void a(MyPtr a); - } - - @Test - public void testDummyPtrs() { - int nPtrs = 3; - Pointer pptrs = Pointer.allocateTypedPointers(MyPtr.class, nPtrs), pptr = Pointer.allocateTypedPointer(MyPtr.class); - assertEquals(nPtrs, pptrs.getValidElements()); - assertEquals(nPtrs * Pointer.SIZE, pptrs.getValidBytes()); - assertEquals(1, pptr.getValidElements()); - for (Pointer ptrs : new Pointer[] { pptr, pptrs }) {; - ptrs.setSizeT(10); - MyPtr ptr = ptrs.get(); - assertTrue(ptr instanceof MyPtr); - assertEquals(10, ptr.getPeer()); - } - } - - @Test - public void testStructTypedPtrField() { - MyStruct s = new MyStruct(); - assertNull(s.a()); - Pointer ps = Pointer.pointerTo(s); - ps.setSizeT(10); - MyPtr ptr = s.a(); - assertTrue(ptr instanceof MyPtr); - assertEquals(10, ptr.getPeer()); - } - - @Test - public void testStringPointer() { - assertNull(Pointer.pointerToCString(null)); - Pointer p = Pointer.pointerToCString("test"); - assertEquals("test", p.getCString()); - } - - @Test - public void testStringsPointer() { - assertNull(Pointer.pointerToCStrings((String[])null)); - - Pointer> p = Pointer.pointerToCStrings(null, null); - assertNull(p.get(0)); - assertNull(p.get(1)); - - p = Pointer.pointerToCStrings("test1", "test2"); - assertEquals("test1", p.get(0).getCString()); - assertEquals("test2", p.get(1).getCString()); - } - - @Test - public void testEquals() { - Pointer m1 = Pointer.allocateBytes(2), m2 = Pointer.allocateBytes(2); - assertNotNull(m1); - assertNotNull(m2); - assertTrue(!m1.equals(m2)); - - long addr1 = m1.getPeer(), addr2 = m2.getPeer(); - Pointer[] ps1 = new Pointer[] { - m1, - new MyPtr(addr1), - Pointer.pointerToAddress(addr1) - }; - Pointer[] ps2 = new Pointer[] { - m2, - new MyPtr(addr2), - Pointer.pointerToAddress(addr2) - }; - for (Pointer p1 : ps1) { - assertNotNull(p1); - assertEquals(m1, p1); - assertEquals(p1, m1); - } - for (Pointer p2 : ps2) { - assertNotNull(p2); - assertEquals(m2, p2); - assertEquals(p2, m2); - } - - for (Pointer p1 : ps1) { - for (Pointer p2 : ps2) { - assertTrue(!p1.equals(p2)); - } - } - } -} - diff --git a/libraries/BridJ/src/test/java/org/bridj/UnionTest.java b/libraries/BridJ/src/test/java/org/bridj/UnionTest.java deleted file mode 100644 index 688552f28..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/UnionTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package org.bridj; - -import org.junit.Test; -import static org.junit.Assert.*; - -import org.bridj.ann.Field; - -/** - * - * @author ochafik - */ -public class UnionTest { - public static class MyUnionStruct extends StructObject { - public MyUnionStruct(Pointer p) { super(p); } - public MyUnionStruct() { super(); } - - @Field(0) - public int a() { - return io.getIntField(this, 0); - } - public MyUnionStruct a(int a) { - io.setIntField(this, 0, a); - return this; - } - - @Field(value = 1, unionWith = 0) - public double aa() { - return io.getDoubleField(this, 0); - } - public MyUnionStruct aa(double a) { - io.setDoubleField(this, 0, a); - return this; - } - - @Field(2) - public double b() { - return io.getDoubleField(this, 1); - } - public MyUnionStruct b(double b) { - io.setDoubleField(this, 1, b); - return this; - } - - @Field(value = 3, unionWith = 2) - public double bb() { - return io.getDoubleField(this, 1); - } - public MyUnionStruct bb(double b) { - io.setDoubleField(this, 1, b); - return this; - } - } - @Test - public void unionSize() { - assertEquals(16, BridJ.sizeOf(MyUnionStruct.class)); - } - @Test - public void unionValues() { - MyUnionStruct us = new MyUnionStruct(); - us.b(10); - assertEquals(10.0, us.bb(), 0.0); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/ValuedEnumTest.java b/libraries/BridJ/src/test/java/org/bridj/ValuedEnumTest.java deleted file mode 100644 index 551982919..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/ValuedEnumTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj; - -import java.util.Collections; -import java.util.Iterator; -import org.bridj.ann.*; -import org.junit.Test; -import static org.junit.Assert.*; - -@Library("test") -public class ValuedEnumTest { - static { - BridJ.register(); - } - public enum MyEnum implements IntValuedEnum { - One(0), - Two(1), - Three(2); - MyEnum(long value) { - this.value = value; - } - public final long value; - public long value() { - return this.value; - } - public Iterator iterator() { - return Collections.singleton(this).iterator(); - } - public static ValuedEnum fromValue(long value) { - return FlagSet.fromValue(value, values()); - } - }; - public static native ValuedEnum intToMyEnum(int value); - public static native int MyEnumToInt(ValuedEnum value); - - private static final int nTests = 100000; - - @Test - public void testSingleIntToEnum() { - MyEnum expected = MyEnum.Two; - int expectedInt = (int)expected.value(); - ValuedEnum ret = intToMyEnum(expectedInt); - FlagSet f = (FlagSet)ret; - assertEquals(MyEnum.class, f.getEnumClass()); - assertEquals(expectedInt, f.value()); - } - - @Test - public void testIntToEnum() { - MyEnum expected = MyEnum.Two; - int expectedInt = (int)expected.value(); - for (int i = 0; i < nTests; i++) { - ValuedEnum ret = intToMyEnum(expectedInt); - if (expectedInt != ret.value()) - assertEquals(expectedInt, ret.value()); - } - } - - - @Test - public void testEnumToInt() { - MyEnum expected = MyEnum.Two; - int expectedInt = (int)expected.value(); - for (int i = 0; i < nTests; i++) { - int ret = MyEnumToInt(expected); - if (expectedInt != ret) - assertEquals(expectedInt, ret); - } - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/VarArgsTest.java b/libraries/BridJ/src/test/java/org/bridj/VarArgsTest.java deleted file mode 100644 index 2270fee56..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/VarArgsTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bridj; - -import org.bridj.ann.*; // annotations such as Library... - -import static org.bridj.Pointer.*; -import org.junit.*; -import static org.junit.Assert.*; - -import static org.bridj.LibCTest.*; - -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -public class VarArgsTest { - static { - BridJ.register(); - } - public static native void passVarArgs(Pointer out, boolean isInt, Object... args); - - @Test - public void testSPrintf() { - Pointer dest = allocateBytes(100); - String fmtString = "Hello %d !"; - int value = 10; - sprintf(dest, pointerToCString(fmtString), value); - assertEquals(String.format(fmtString, value), dest.getCString()); - } - - @Test - public void testPassBools() { - Pointer out = allocateBytes(8); - for (boolean value : new boolean[] { true, false }) { - passVarArgs(out, true, value); - assertEquals(value, out.getSizeT() != 0); - } - } - int[] intValues = new int[] { 0, 1, -1, 33 }; - @Test - public void testPassInts() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, true, value); - assertEquals(value, out.getSizeT()); - } - } - @Test - public void testPassLongs() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, true, (long)value); - assertEquals(value, out.getSizeT()); - } - } - @Test - public void testPassShorts() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, true, (short)value); - assertEquals(value, out.getSizeT()); - } - } - @Test - public void testPassChars() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, true, (char)value); - assertEquals(value, out.getSizeT()); - } - } - @Test - public void testPassBytes() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, true, (byte)value); - assertEquals(value, out.getSizeT()); - } - } - @Test - public void testPassDouble() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, false, (double)value); - assertEquals(value, out.getDouble(), 0); - } - } - @Test - public void testPassFloats() { - Pointer out = allocateBytes(8); - for (int value : intValues) { - passVarArgs(out, false, (float)value); - assertEquals(value, out.getDouble(), 0); - } - } - -} diff --git a/libraries/BridJ/src/test/java/org/bridj/VersionTest.java b/libraries/BridJ/src/test/java/org/bridj/VersionTest.java deleted file mode 100644 index d42736ead..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/VersionTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bridj; - -import org.junit.*; -import static org.junit.Assert.*; - -public class VersionTest { - @Test - public void testVersion() { - assertTrue(Version.MAVEN_VERSION, - Version.MAVEN_VERSION.matches("\\d+\\.\\d+(\\.\\d+)?(-SNAPSHOT)?")); - - assertTrue(Version.VERSION_SPECIFIC_SUB_PACKAGE, - Version.VERSION_SPECIFIC_SUB_PACKAGE.matches("v\\d+\\_\\d+(_\\d+)?")); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/WindowsTest.java b/libraries/BridJ/src/test/java/org/bridj/WindowsTest.java deleted file mode 100644 index 0a68c8e26..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/WindowsTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bridj; -import org.junit.Test; -import org.junit.BeforeClass; - -import org.bridj.ann.Library; -import org.bridj.ann.Optional; - -@org.bridj.ann.Runtime(CRuntime.class) -public class WindowsTest { - @Library("user32") - @Optional - public static native void SendMessage(Pointer hwnd, int Msg, int wParam, Pointer lParam); - - static final boolean win = Platform.isWindows(); - - @Test - public void testUnicodeWorked() { - if (!win) return; - - SendMessage(null, 0, 0, null); - } - - @BeforeClass - public static void register() { - if (!win) return; - - BridJ.register(); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/ann/PlatformCondition.java b/libraries/BridJ/src/test/java/org/bridj/ann/PlatformCondition.java deleted file mode 100644 index 06db6d438..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/ann/PlatformCondition.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bridj.ann; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * @author Olivier Chafik - */ -@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface PlatformCondition { - public enum Endianness { - Any, LittleEndian, BigEndian - } - Endianness endianness() default Endianness.Any; - - public enum OperatingSystem { - Any, - Windows, - Linux, - Solaris, - MacOSX, - FreeBSD, - Unix - } - OperatingSystem[] os() default OperatingSystem.Any; - - public enum AddressWidth { - Any, - Is64Bits, - Is32Bits - } - AddressWidth addressWidth() default AddressWidth.Any; -} diff --git a/libraries/BridJ/src/test/java/org/bridj/examples/MyCallback.java b/libraries/BridJ/src/test/java/org/bridj/examples/MyCallback.java deleted file mode 100644 index 643c3a00e..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/examples/MyCallback.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bridj.examples; - -import org.bridj.Callback; - -public abstract class MyCallback extends Callback { - public abstract long doSomething(int a, int b); -} diff --git a/libraries/BridJ/src/test/java/org/bridj/examples/MyCallbackImpl.java b/libraries/BridJ/src/test/java/org/bridj/examples/MyCallbackImpl.java deleted file mode 100644 index 4dbe9d9f0..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/examples/MyCallbackImpl.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bridj.examples; - -import org.bridj.Pointer; -import org.bridj.CRuntime; - -@org.bridj.ann.Runtime(CRuntime.class) -public class MyCallbackImpl extends MyCallback { - public native long doSomething(int a, int b); -} diff --git a/libraries/BridJ/src/test/java/org/bridj/examples/MyStruct.java b/libraries/BridJ/src/test/java/org/bridj/examples/MyStruct.java deleted file mode 100644 index 9027172a8..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/examples/MyStruct.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bridj.examples; -import org.bridj.ann.*; -import org.bridj.*; -import java.nio.*; -import java.util.*; - -/** - * - * @author ochafik - */ -public class MyStruct extends StructObject { - @Field(0) - public native int toto(); - - @Field(1) @Bits(1) - public native int isOk(); - - @Field(2) @Array(10) - public native Pointer values(); - public native void values(Pointer buf); - - public native MyStruct toto(int toto); - - public static void main(String[] args) throws CloneNotSupportedException { - MyStruct s = new MyStruct(); - s.toto(10); - s.values(Pointer.pointerToInts(new int[] { 1, 2, 3})); - int[] out = s.values().getIntsAtOffset(0, 3); - System.out.println(Arrays.toString(out)); - - MyStruct ns = (MyStruct) s.clone(); - out = s.values().getIntsAtOffset(0, 3); - System.out.println(Arrays.toString(out)); - - System.out.println(s.toto()); - System.out.println(s); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/examples/MyTemplate.java b/libraries/BridJ/src/test/java/org/bridj/examples/MyTemplate.java deleted file mode 100644 index 2a91e4a69..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/examples/MyTemplate.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bridj.examples; -import org.bridj.ann.*; -import org.bridj.cpp.*; -import org.bridj.*; -import java.lang.reflect.Type; -import java.nio.*; -import java.util.*; - -/** - -mvn package -DskipTests=true -o && java -cp target/bridj-0.4-SNAPSHOT-shaded.jar org.bridj.examples.MyTemplate - -template -class MyTemplate { -public: - MyTemplate(int arg); - T someMethod(); -} - - */ -@Template({ Integer.class, Class.class }) -public class MyTemplate extends CPPObject { - static { - BridJ.register(); - } - - public final int n; - - @Constructor(0) - public MyTemplate(int n, Type t, int arg) { - super(null, 0, n, t, arg); - this.n = n; - } - - public native T someMethod(); - - public static void main(String[] args) throws CloneNotSupportedException { - Type cppt = CPPType.getCPPType(new Object[] { MyTemplate.class, 10, String.class }); - System.out.println("type = " + cppt); - MyTemplate t = new MyTemplate(10, String.class, 4); - System.out.println(t); - MyTemplate nt = (MyTemplate) t.clone(); - System.out.println(nt); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/util/ASMUtilsTest.java b/libraries/BridJ/src/test/java/org/bridj/util/ASMUtilsTest.java deleted file mode 100644 index 984a83efa..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/util/ASMUtilsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import org.bridj.BridJ; -import org.junit.AfterClass; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.BeforeClass; - -/** - * - * @author ochafik - */ -public class ASMUtilsTest { - - public native void someNativeFunction(); - - //public ClassSynchronizerTest() {} - - @Test - public void test() throws IOException, InstantiationException, IllegalAccessException { - Class c = BridJ.subclassWithSynchronizedNativeMethods(ASMUtilsTest.class); - Method[] declaredMethods = c.getDeclaredMethods(); - assertEquals(1, declaredMethods.length); - - Method nativeMethod = declaredMethods[0]; - assertTrue(Modifier.isSynchronized(nativeMethod.getModifiers())); - - c.newInstance(); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/util/BytecodeAnalyzerTest.java b/libraries/BridJ/src/test/java/org/bridj/util/BytecodeAnalyzerTest.java deleted file mode 100644 index 96ad7b02a..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/util/BytecodeAnalyzerTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bridj.util; - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import org.bridj.util.BytecodeAnalyzer; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class BytecodeAnalyzerTest { - public static class MyStruct { - int a, b, c; - - public static class SubStruct { - int sa, sb, sc; - public native void subNative(); - } - public static class SubStructDeriv extends SubStruct { - int sa2, sb2, sc2; - public native void subSubNative(); - } - } - - @Test - public void testFields() throws IOException { - assertEquals(Arrays.asList("a", "b", "c"), BytecodeAnalyzer.getFieldNames(MyStruct.class, Object.class)); - assertEquals(Arrays.asList("sa", "sb", "sc"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStruct.class, Object.class)); - - assertEquals(Arrays.asList("sa2", "sb2", "sc2"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStructDeriv.class, MyStruct.SubStructDeriv.class)); - assertEquals(Arrays.asList("sa", "sb", "sc", "sa2", "sb2", "sc2"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStructDeriv.class, Object.class)); - - List sigs = BytecodeAnalyzer.getNativeMethodSignatures(MyStruct.SubStructDeriv.class); - assertEquals(2, sigs.size()); - assertEquals("subNative", sigs.get(0)[1]); - assertEquals("subSubNative", sigs.get(1)[1]); - } - - @Test - public void testMethods() throws IOException { - assertEquals(Arrays.asList(""), BytecodeAnalyzer.getMethodNames(MyStruct.class, Object.class)); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/util/JNIUtilsTest.java b/libraries/BridJ/src/test/java/org/bridj/util/JNIUtilsTest.java deleted file mode 100644 index b363f1fb1..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/util/JNIUtilsTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bridj.util; - -import java.io.IOException; -import org.bridj.demangling.Demangler; -import java.util.Collection; - -import org.junit.Test; - - -import static org.junit.Assert.*; - - -public class JNIUtilsTest { - @Test - public void testUnderscore() { - assertEquals(5, JNIUtils.findLastNonEscapeUnderscore("o_b_c_m_1m")); - } - - public static native void test_method_1(int i); - - @Test - public void testDecode() throws NoSuchMethodException, IOException { - String className = getClass().getName(); - Object[] nameAndSigArray = new Object[2]; - String enclosingClassName = JNIUtils.decodeMethodNameClassAndSignature("Java_" + className.replaceAll("_", "_1").replace('.', '_') + "_test_1method_11", nameAndSigArray, "", ""); - - assertEquals(className, enclosingClassName.replace('/', '.')); - assertEquals("test_method_1", nameAndSigArray[0]); - assertEquals("(I)V", nameAndSigArray[1]); - } -} diff --git a/libraries/BridJ/src/test/java/org/bridj/util/ProcessUtilsTest.java b/libraries/BridJ/src/test/java/org/bridj/util/ProcessUtilsTest.java deleted file mode 100644 index afb1b06f8..000000000 --- a/libraries/BridJ/src/test/java/org/bridj/util/ProcessUtilsTest.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.bridj.util; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class ProcessUtilsTest { - @Test - public void testPid() { - int pid = ProcessUtils.getCurrentProcessId(); - assertTrue(pid > 0); - } -} diff --git a/libraries/BridJ/src/test/resources/lib/armeabi/test.dylib.nm b/libraries/BridJ/src/test/resources/lib/armeabi/test.dylib.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/lib/armeabi/test.so.nm b/libraries/BridJ/src/test/resources/lib/armeabi/test.so.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libdependsOnTest.dylib b/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libdependsOnTest.dylib deleted file mode 100755 index 25ac0e7e0..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libdependsOnTest.dylib and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libtest.dylib b/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libtest.dylib deleted file mode 100755 index a260cc66c..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/libtest.dylib and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/test.dylib.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/test.dylib.nm deleted file mode 100644 index 29e2caddd..000000000 --- a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/test.dylib.nm +++ /dev/null @@ -1,369 +0,0 @@ - -../../../../test/resources/org/bridj/lib/darwin_universal/libdependsOnTest.dylib: - U __Z11forwardCallPFiiiEii -0000000000000ef0 T __Z20addThatDependsOnTestii - U __Z8getAdderv - U ___gxx_personality_v0 -0000000000000ee4 t __dyld_func_lookup -0000000000000000 t __mh_dylib_header -0000000000000ed0 t dyld_stub_binding_helper - -../../../../test/resources/org/bridj/lib/darwin_universal/libtest.dylib: -0000000000003ec0 t -[DelgHolder delegate] -0000000000003e70 t -[DelgHolder outerAdd:to:] -0000000000003ee0 t -[DelgHolder setDelegate:] -0000000000003f00 t -[DelgImpl add:to:] -0000000000002a90 T _Java_org_bridj_PerfLib_testASinB -0000000000002ae0 T _Java_org_bridj_PerfLib_testAddJNI -00000000000085a0 S _OBJC_CLASS_$_DelgHolder -0000000000008550 S _OBJC_CLASS_$_DelgImpl - U _OBJC_CLASS_$_NSObject -00000000000087d8 S _OBJC_IVAR_$_DelgHolder.delegate -0000000000008578 S _OBJC_METACLASS_$_DelgHolder -0000000000008528 S _OBJC_METACLASS_$_DelgImpl - U _OBJC_METACLASS_$_NSObject -00000000000018e0 t __GLOBAL__I__Z4incr5S_int -0000000000001940 t __GLOBAL__I_newIntVector -0000000000001880 t __GLOBAL__I_ntest - U __Unwind_Resume -0000000000002af0 T __Z10createTestv -0000000000002840 T __Z10newWStringv -00000000000024d0 T __Z10stringCStrPSs -0000000000001c50 T __Z10test_pvoidv -0000000000001e50 T __Z11MyEnumToInt6MyEnum -0000000000001d80 T __Z11forwardCallPFiiiEii -0000000000001db0 T __Z11getPtrAdderv -0000000000001e40 T __Z11intToMyEnumi -0000000000002910 T __Z11passVarArgsPcbz -0000000000001af0 T __Z11sizeOfCtestv -0000000000001bb0 T __Z11testIntEnumi5ETest -00000000000024f0 T __Z11wstringCStrPSbIwSt11char_traitsIwESaIwEE -0000000000003090 T __Z12deleteStringPSs -0000000000001d70 T __Z12getAdder_rawv -0000000000002500 T __Z12resizeStringPSsm -0000000000001b00 T __Z12sizeOfCtest2v -0000000000002430 T __Z12sizeOf_stuffv -00000000000035a0 T __Z12sizeofVectorIdEiv -00000000000035b0 T __Z12sizeofVectorIfEiv -0000000000003580 T __Z12sizeofVectorIiEiv -0000000000003590 T __Z12sizeofVectorIxEiv -0000000000001b90 T __Z12testEnumArgs5ETestS_ -0000000000001ba0 T __Z12testVoidEnumv -0000000000001cf0 T __Z12test_fun_intv -0000000000002d90 T __Z13deleteWStringPSbIwSt11char_traitsIwESaIwEE -0000000000001d50 T __Z13getAdder_longv -00000000000024c0 T __Z13reserveStringPSsm -0000000000002510 T __Z13resizeWStringPSbIwSt11char_traitsIwESaIwEEm -0000000000001e30 T __Z13sizeOfTimevalv -0000000000001a30 T __Z13testAddCLongsll -0000000000001a20 T __Z13testAddJLongsxx -0000000000001ee0 T __Z13test_add2_intii -0000000000001ef0 T __Z13test_add9_intiiiiiiiii -0000000000001cc0 T __Z13test_fun_voidv -0000000000001ec0 T __Z13test_incr_inti -0000000000002800 T __Z14appendToStringPSsPKc -0000000000001dd0 T __Z14forwardPtrCallPFPvS_S_ES_S_ -0000000000001d40 T __Z14getAdder_pvoidv -0000000000001eb0 T __Z14getSomeWStringv -00000000000024e0 T __Z14reserveWStringPSbIwSt11char_traitsIwESaIwEEm -0000000000002420 T __Z14sizeOf_messagev -0000000000001f00 T __Z14test_add20_intiiiiiiiiiiiiiiiiiiii -00000000000020f0 T __Z14test_add2_byteaa -0000000000002250 T __Z14test_add2_chartt -0000000000001f40 T __Z14test_add2_longxx -0000000000002100 T __Z14test_add9_byteaaaaaaaaa -0000000000002260 T __Z14test_add9_charttttttttt -0000000000001f50 T __Z14test_add9_longxxxxxxxxx -00000000000020c0 T __Z14test_incr_bytea -0000000000002220 T __Z14test_incr_chart -0000000000001f10 T __Z14test_incr_longx -0000000000001ca0 T __Z14test_int_floatf -0000000000001d20 T __Z14test_int_shorts -00000000000028b0 T __Z15appendToWStringPSbIwSt11char_traitsIwESaIwEEPKw -0000000000001dc0 T __Z15getPtrAdder_rawv -0000000000001ea0 T __Z15testIVirtualAddP8IVirtualii -0000000000002110 T __Z15test_add20_byteaaaaaaaaaaaaaaaaaaaa -0000000000002270 T __Z15test_add20_chartttttttttttttttttttt -0000000000001f60 T __Z15test_add20_longxxxxxxxxxxxxxxxxxxxx -00000000000023a0 T __Z15test_add2_floatff -0000000000001f90 T __Z15test_add2_shortss -00000000000023b0 T __Z15test_add9_floatfffffffff -0000000000001fa0 T __Z15test_add9_shortsssssssss -0000000000001e20 T __Z15test_incr_clongl -0000000000002380 T __Z15test_incr_floatf -0000000000001f70 T __Z15test_incr_shorts -0000000000001e10 T __Z15test_incr_sizetm -0000000000001e00 T __Z15test_incr_timetl -0000000000001c90 T __Z15test_int_doublev -0000000000002440 T __Z16sizeOf_containerv -00000000000023c0 T __Z16test_add20_floatffffffffffffffffffff -0000000000001fb0 T __Z16test_add20_shortssssssssssssssssssss -00000000000023f0 T __Z16test_add2_doubledd -0000000000002400 T __Z16test_add9_doubleddddddddd -00000000000023d0 T __Z16test_incr_doubled -0000000000001c80 T __Z16test_void_doublev -0000000000001b80 T __Z17testEnumArgSecond5ETest -0000000000001b70 T __Z17testEnumRetSecondv -0000000000002410 T __Z17test_add20_doubledddddddddddddddddddd -0000000000002de0 T __Z17test_add2_int_outiiPi -0000000000002fe0 T __Z17test_add9_int_outiiiiiiiiiPi -0000000000001ce0 T __Z17test_fun_void_intv -0000000000002d00 T __Z17test_incr_int_outiPi -0000000000001df0 T __Z18crashIllegalAccessv -0000000000003040 T __Z18test_add20_int_outiiiiiiiiiiiiiiiiiiiiPi -0000000000002ec0 T __Z18test_add2_byte_outaaPa -0000000000002eb0 T __Z18test_add2_char_outttPt -0000000000002df0 T __Z18test_add2_long_outxxPx -0000000000003000 T __Z18test_add9_byte_outaaaaaaaaaPa -0000000000003010 T __Z18test_add9_char_outtttttttttPt -0000000000002fa0 T __Z18test_add9_long_outxxxxxxxxxPx -0000000000001d00 T __Z18test_fun_int_floatv -0000000000002d30 T __Z18test_incr_byte_outaPa -0000000000002d40 T __Z18test_incr_char_outtPt -0000000000002d10 T __Z18test_incr_long_outxPx -0000000000002120 T __Z19test_add20_byte_outaaaaaaaaaaaaaaaaaaaaPa -0000000000002280 T __Z19test_add20_char_outttttttttttttttttttttPt -0000000000003020 T __Z19test_add20_long_outxxxxxxxxxxxxxxxxxxxxPx -0000000000002e00 T __Z19test_add2_float_outffPf -0000000000002ea0 T __Z19test_add2_short_outssPs -0000000000002f90 T __Z19test_add9_float_outfffffffffPf -0000000000002ff0 T __Z19test_add9_short_outsssssssssPs -0000000000002d50 T __Z19test_incr_float_outfPf -0000000000002d20 T __Z19test_incr_short_outsPs -0000000000002c70 T __Z19throwNewMyExceptionPKc -0000000000003060 T __Z20test_add20_float_outffffffffffffffffffffPf -0000000000001fc0 T __Z20test_add20_short_outssssssssssssssssssssPs -0000000000002e10 T __Z20test_add2_double_outddPd -0000000000002fc0 T __Z20test_add9_double_outdddddddddPd -0000000000002d70 T __Z20test_incr_double_outdPd -0000000000003070 T __Z21test_add20_double_outddddddddddddddddddddPd -0000000000001ed0 T __Z21test_callback_int_intPFiiEi -0000000000001cd0 T __Z21test_fun_void__doubled -0000000000001b20 T __Z22testIndirectVirtualAddP5Ctestii -00000000000020d0 T __Z23test_callback_byte_bytePFaaEa -0000000000002230 T __Z23test_callback_char_charPFttEt -0000000000001f20 T __Z23test_callback_long_longPFxxEx -0000000000002bf0 T __Z23throwMyExceptionByValuePKc -0000000000002390 T __Z25test_callback_float_floatPFffEf -0000000000001f80 T __Z25test_callback_short_shortPFssEs -0000000000001d10 T __Z26test_fun_int_float__doubled -00000000000023e0 T __Z27test_callback_double_doublePFddEd -0000000000002f50 T __Z30test_callback_int_int_asDoublePFiiEi -0000000000002f30 T __Z32test_callback_byte_byte_asDoublePFaaEa -0000000000002f10 T __Z32test_callback_char_char_asDoublePFttEt -0000000000002f70 T __Z32test_callback_long_long_asDoublePFxxEx -0000000000002f00 T __Z34test_callback_float_float_asDoublePFffEf -0000000000002ee0 T __Z34test_callback_short_short_asDoublePFssEs -0000000000002ed0 T __Z36test_callback_double_double_asDoublePFddEd -0000000000001d30 T __Z3addii -0000000000003510 T __Z3sum6S_int2 -0000000000003520 T __Z3sum8S_jlong4 -0000000000003540 T __Z3sum9S_jlong10 -0000000000001840 t __Z41__static_initialization_and_destruction_0ii -00000000000018a0 t __Z41__static_initialization_and_destruction_0ii -0000000000001900 t __Z41__static_initialization_and_destruction_0ii -0000000000003500 T __Z4incr5S_int -0000000000003570 T __Z4totov -0000000000001da0 T __Z7addPtrsPvS_ -0000000000001d60 T __Z8getAdderv -0000000000001b60 T __Z8testEnum5ETest -0000000000001c70 T __Z8test_intv -0000000000002880 T __Z8throwInti -0000000000002860 T __Z9newStringv -00000000000035c0 T __Z9newVectorIdESt6vectorIT_SaIS1_EEi -0000000000003670 T __Z9newVectorIfESt6vectorIT_SaIS1_EEi -0000000000003720 T __Z9newVectorIiESt6vectorIT_SaIS1_EEi -00000000000037c0 T __Z9newVectorIxESt6vectorIT_SaIS1_EEi -0000000000001c60 T __Z9test_pintv -0000000000001cb0 T __Z9test_voidv -0000000000008ab8 b __ZGVZN6Ctest28toStringEvE1s -0000000000003440 T __ZN11MyExceptionD0Ev -00000000000034a0 T __ZN11MyExceptionD1Ev -0000000000003250 T __ZN24InvisibleSourcesTemplateILi10ESsE10createSomeEv -0000000000003120 T __ZN24InvisibleSourcesTemplateILi10ESsE10deleteSomeEPSs -0000000000003290 T __ZN24InvisibleSourcesTemplateILi10ESsEC1Ei -00000000000032f0 T __ZN24InvisibleSourcesTemplateILi10ESsEC2Ei -0000000000003390 T __ZN24InvisibleSourcesTemplateILi10EiE10createSomeEv -0000000000003350 T __ZN24InvisibleSourcesTemplateILi10EiE10deleteSomeEPi -0000000000003190 T __ZN24InvisibleSourcesTemplateILi10EiEC1Ei -00000000000031f0 T __ZN24InvisibleSourcesTemplateILi10EiEC2Ei -0000000000002b50 T __ZN5Ctest11getInstanceEv -0000000000001bc0 T __ZN5Ctest11static_voidEv -0000000000001b40 T __ZN5Ctest14testAddStdCallEPvii -0000000000001b10 T __ZN5Ctest14testVirtualAddEii -0000000000001b50 T __ZN5Ctest21testVirtualAddStdCallEPvii -00000000000028f0 T __ZN5Ctest6getIntEv -0000000000002900 T __ZN5Ctest7getEnumEv -0000000000001b30 T __ZN5Ctest7testAddEii -0000000000001ab0 T __ZN5CtestC1Ei -0000000000001a70 T __ZN5CtestC1Ev -0000000000001a90 T __ZN5CtestC2Ei -0000000000001a50 T __ZN5CtestC2Ev -0000000000001ae0 T __ZN5CtestD1Ev -0000000000001ad0 T __ZN5CtestD2Ev -0000000000002460 T __ZN5Temp1IdE4tempEd -0000000000002700 T __ZN5Temp1IdED0Ev -0000000000002720 T __ZN5Temp1IdED1Ev -0000000000002740 T __ZN5Temp1IdED2Ev -0000000000002450 T __ZN5Temp1IiE4tempEi -0000000000002760 T __ZN5Temp1IiED0Ev -0000000000002780 T __ZN5Temp1IiED1Ev -00000000000027a0 T __ZN5Temp1IiED2Ev -0000000000002490 T __ZN5Temp2IddE4tempEdd -00000000000025e0 T __ZN5Temp2IddED0Ev -0000000000002600 T __ZN5Temp2IddED1Ev -0000000000002620 T __ZN5Temp2IddED2Ev -0000000000002470 T __ZN5Temp2IiiE4tempEii -00000000000026a0 T __ZN5Temp2IiiED0Ev -00000000000026c0 T __ZN5Temp2IiiED1Ev -00000000000026e0 T __ZN5Temp2IiiED2Ev -0000000000002480 T __ZN5Temp2IisE4tempEis -0000000000002640 T __ZN5Temp2IisED0Ev -0000000000002660 T __ZN5Temp2IisED1Ev -0000000000002680 T __ZN5Temp2IisED2Ev -00000000000024b0 T __ZN5TempVIdLi33EE4tempEd -0000000000002520 T __ZN5TempVIdLi33EED0Ev -0000000000002540 T __ZN5TempVIdLi33EED1Ev -0000000000002560 T __ZN5TempVIdLi33EED2Ev -00000000000024a0 T __ZN5TempVIiLi66EE4tempEi -0000000000002580 T __ZN5TempVIiLi66EED0Ev -00000000000025a0 T __ZN5TempVIiLi66EED1Ev -00000000000025c0 T __ZN5TempVIiLi66EED2Ev -0000000000001c30 T __ZN6Ctest214testVirtualAddEii -0000000000002b20 T __ZN6Ctest216getCtestInstanceEv -0000000000001c20 T __ZN6Ctest218setDestructedStateEi -0000000000001c40 T __ZN6Ctest27testAddEii -0000000000001c10 T __ZN6Ctest28setStateEPi -00000000000029d0 T __ZN6Ctest28toStringEv -0000000000002bc0 T __ZN6Ctest2C1Ev -0000000000002b90 T __ZN6Ctest2C2Ev -0000000000001bf0 T __ZN6Ctest2D1Ev -0000000000001bd0 T __ZN6Ctest2D2Ev -0000000000001e60 T __ZN6Module3addEii -0000000000003400 T __ZN6ModuleD0Ev -0000000000003420 T __ZN6ModuleD1Ev -0000000000001e80 T __ZN7AModule3addEii -0000000000001e90 T __ZN7AModule8subtractEii -0000000000002b80 T __ZN7AModuleC1Ev -0000000000001e70 T __ZN7AModuleC2Ev -00000000000027c0 T __ZN7AModuleD0Ev -00000000000027e0 T __ZN7AModuleD1Ev -00000000000027f0 T __ZN7AModuleD2Ev -00000000000033c0 T __ZN7IModuleD0Ev -00000000000033e0 T __ZN7IModuleD1Ev -0000000000003430 T __ZNK11MyException4whatEv - U __ZNSbIwSt11char_traitsIwESaIwEE4_Rep10_M_destroyERKS1_ - U __ZNSbIwSt11char_traitsIwESaIwEE4_Rep20_S_empty_rep_storageE - U __ZNSbIwSt11char_traitsIwESaIwEE6appendEPKwm - U __ZNSbIwSt11char_traitsIwESaIwEE6resizeEmw - U __ZNSbIwSt11char_traitsIwESaIwEE7reserveEm - U __ZNSolsEi - U __ZNSs4_Rep10_M_destroyERKSaIcE - U __ZNSs4_Rep20_S_empty_rep_storageE - U __ZNSs6appendEPKcm - U __ZNSs6resizeEmc - U __ZNSs7reserveEm - U __ZNSsC1EPKcRKSaIcE -0000000000003870 T __ZNSt6vectorIdSaIdEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPdS1_EERKd -00000000000039f0 T __ZNSt6vectorIfSaIfEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPfS1_EERKf -0000000000003b70 T __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi -0000000000003cf0 T __ZNSt6vectorIxSaIxEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPxS1_EERKx - U __ZNSt8ios_base4InitC1Ev - U __ZNSt8ios_base4InitD1Ev - U __ZNSt9exceptionD2Ev - U __ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l - U __ZSt17__throw_bad_allocv - U __ZSt20__throw_length_errorPKc - U __ZSt4cout -0000000000008ac8 b __ZStL8__ioinit -0000000000008ac9 b __ZStL8__ioinit -0000000000008ab0 b __ZStL8__ioinit -00000000000084e0 S __ZTI11MyException -0000000000008360 S __ZTI5Ctest -00000000000082f0 S __ZTI5Temp1IdE -0000000000008300 S __ZTI5Temp1IiE -00000000000082c0 S __ZTI5Temp2IddE -00000000000082e0 S __ZTI5Temp2IiiE -00000000000082d0 S __ZTI5Temp2IisE -00000000000082a0 S __ZTI5TempVIdLi33EE -00000000000082b0 S __ZTI5TempVIiLi66EE -0000000000008340 S __ZTI6Ctest2 -0000000000008330 S __ZTI6Module -0000000000008310 S __ZTI7AModule -0000000000008460 S __ZTI7IModule -00000000000084c0 S __ZTIP11MyException - U __ZTISt9exception - U __ZTIi -000000000000409c S __ZTS11MyException -00000000000041aa S __ZTS5Ctest -000000000000417d S __ZTS5Temp1IdE -0000000000004187 S __ZTS5Temp1IiE -000000000000415c S __ZTS5Temp2IddE -0000000000004172 S __ZTS5Temp2IiiE -0000000000004167 S __ZTS5Temp2IisE -000000000000413e S __ZTS5TempVIdLi33EE -000000000000414d S __ZTS5TempVIiLi66EE -00000000000041a2 S __ZTS6Ctest2 -000000000000419a S __ZTS6Module -0000000000004191 S __ZTS7AModule -0000000000004084 S __ZTS7IModule -000000000000408d S __ZTSP11MyException -0000000000008500 S __ZTV11MyException -0000000000008280 S __ZTV5Ctest -0000000000008420 S __ZTV5Temp1IdE -0000000000008440 S __ZTV5Temp1IiE -00000000000083c0 S __ZTV5Temp2IddE -0000000000008400 S __ZTV5Temp2IiiE -00000000000083e0 S __ZTV5Temp2IisE -0000000000008380 S __ZTV5TempVIdLi33EE -00000000000083a0 S __ZTV5TempVIiLi66EE -0000000000008260 S __ZTV6Ctest2 -0000000000008220 S __ZTV6Module -00000000000081e0 S __ZTV7AModule -0000000000008480 S __ZTV7IModule - U __ZTVN10__cxxabiv117__class_type_infoE - U __ZTVN10__cxxabiv119__pointer_type_infoE - U __ZTVN10__cxxabiv120__si_class_type_infoE - U __ZTVSt9exception -0000000000008ac0 b __ZZN6Ctest28toStringEvE1s - U __ZdlPv - U __Znam - U __Znwm - U ___cxa_allocate_exception - U ___cxa_atexit - U ___cxa_free_exception - U ___cxa_guard_abort - U ___cxa_guard_acquire - U ___cxa_guard_release - U ___cxa_pure_virtual - U ___cxa_throw - U ___gxx_personality_v0 -0000000000003f40 t ___tcf_0 -00000000000030e0 t ___tcf_0 -0000000000003f60 t ___tcf_0 -0000000000003f20 t ___tcf_1 -0000000000001968 t __dyld_func_lookup -0000000000000000 t __mh_dylib_header - U __objc_empty_cache - U __objc_empty_vtable -0000000000003f10 T _forwardBlockCallIntIntInt - U _memmove -0000000000008a08 D _newIntVector -0000000000008aa8 D _ntest - U _objc_msgSend_fixup -0000000000001a40 T _otherFunc - U _sin -0000000000001980 T _sinInt -0000000000008a10 D _sizeofIntVector - U _strlen -0000000000002a60 T _testASinB -0000000000002ad0 T _testAddDyncall -0000000000002ac0 T _testAddJNA -00000000000019f0 T _testInPlaceSquare -0000000000001990 T _testSum -0000000000002e30 T _testSumInt -00000000000019c0 T _testSumi -0000000000002e70 T _testSumll -0000000000001970 T _voidTest - U _wcslen -0000000000001954 t dyld_stub_binding_helper diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/test.so.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/darwin_universal/test.so.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_arm32_arm/test.so b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_arm32_arm/test.so deleted file mode 100755 index a5120493d..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_arm32_arm/test.so and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.dylib.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.dylib.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so deleted file mode 100755 index 3567900b9..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so.nm deleted file mode 100644 index c9da28487..000000000 --- a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x64/test.so.nm +++ /dev/null @@ -1,340 +0,0 @@ -000000000020b210 d DW.ref.__gxx_personality_v0 -00000000000061b0 T Java_org_bridj_PerfLib_testASinB -0000000000006120 T Java_org_bridj_PerfLib_testAddJNI -000000000020ad48 a _DYNAMIC -000000000020afe8 a _GLOBAL_OFFSET_TABLE_ -0000000000007490 t _GLOBAL__I_structs.cpp -00000000000074d0 t _GLOBAL__I_templates.cpp -0000000000006ee0 t _GLOBAL__I_test.cpp - w _Jv_RegisterClasses - U _Unwind_Resume@@GCC_3.0 -0000000000006480 T _Z10createTestv -00000000000067b0 T _Z10newWStringv -00000000000067a0 T _Z10stringCStrPSs -0000000000006550 T _Z10test_pvoidv -0000000000006a10 T _Z11MyEnumToInt6MyEnum -0000000000006670 T _Z11forwardCallPFiiiEii -0000000000006680 T _Z11getPtrAdderv -0000000000006a00 T _Z11intToMyEnumi -0000000000005f20 T _Z11passVarArgsPcbz -00000000000063c0 T _Z11sizeOfCtestv -0000000000006460 T _Z11testIntEnumi5ETest -00000000000068a0 T _Z11wstringCStrPSbIwSt11char_traitsIwESaIwEE -0000000000006740 T _Z12deleteStringPSs -0000000000006660 T _Z12getAdder_rawv -0000000000006730 T _Z12resizeStringPSsm -00000000000063d0 T _Z12sizeOfCtest2v -0000000000006ec0 T _Z12sizeOf_stuffv -0000000000007520 W _Z12sizeofVectorIdEiv -0000000000007530 W _Z12sizeofVectorIfEiv -0000000000007500 W _Z12sizeofVectorIiEiv -0000000000007510 W _Z12sizeofVectorIxEiv -0000000000006440 T _Z12testEnumArgs5ETestS_ -0000000000006450 T _Z12testVoidEnumv -00000000000065f0 T _Z12test_fun_intv -0000000000006840 T _Z13deleteWStringPSbIwSt11char_traitsIwESaIwEE -0000000000006640 T _Z13getAdder_longv -0000000000006720 T _Z13reserveStringPSsm -0000000000006830 T _Z13resizeWStringPSbIwSt11char_traitsIwESaIwEEm -00000000000069f0 T _Z13sizeOfTimevalv -0000000000006100 T _Z13testAddCLongsll -00000000000060f0 T _Z13testAddJLongsll -0000000000006aa0 T _Z13test_add9_intiiiiiiiii -00000000000065c0 T _Z13test_fun_voidv -0000000000006a50 T _Z13test_incr_inti -00000000000066e0 T _Z14appendToStringPSsPKc -00000000000066a0 T _Z14forwardPtrCallPFPvS_S_ES_S_ -0000000000006630 T _Z14getAdder_pvoidv -0000000000006a40 T _Z14getSomeWStringv -0000000000006820 T _Z14reserveWStringPSbIwSt11char_traitsIwESaIwEEm -0000000000006eb0 T _Z14sizeOf_messagev -0000000000006ca0 T _Z14test_add9_byteaaaaaaaaa -0000000000006d60 T _Z14test_add9_charttttttttt -0000000000006b30 T _Z14test_add9_longlllllllll -0000000000006c40 T _Z14test_incr_bytea -0000000000006d00 T _Z14test_incr_chart -0000000000006ae0 T _Z14test_incr_longl -00000000000065a0 T _Z14test_int_floatf -0000000000006620 T _Z14test_int_shorts -00000000000067e0 T _Z15appendToWStringPSbIwSt11char_traitsIwESaIwEEPKw -0000000000006690 T _Z15getPtrAdder_rawv -0000000000006a30 T _Z15testIVirtualAddP8IVirtualii -0000000000006e10 T _Z15test_add9_floatfffffffff -0000000000006be0 T _Z15test_add9_shortsssssssss -00000000000069e0 T _Z15test_incr_clongl -0000000000006dc0 T _Z15test_incr_floatf -0000000000006b80 T _Z15test_incr_shorts -00000000000069d0 T _Z15test_incr_sizetm -00000000000069c0 T _Z15test_incr_timetl -0000000000006590 T _Z15test_int_doublev -0000000000006ed0 T _Z16sizeOf_containerv -0000000000006e80 T _Z16test_add9_doubleddddddddd -0000000000006e40 T _Z16test_incr_doubled -0000000000006580 T _Z16test_void_doublev -0000000000006430 T _Z17testEnumArgSecond5ETest -0000000000006420 T _Z17testEnumRetSecondv -0000000000006ab0 T _Z17test_add9_int_outiiiiiiiiiPi -00000000000065e0 T _Z17test_fun_void_intv -0000000000006a60 T _Z17test_incr_int_outiPi -00000000000068b0 T _Z18crashIllegalAccessv -0000000000006cb0 T _Z18test_add9_byte_outaaaaaaaaaPa -0000000000006d70 T _Z18test_add9_char_outtttttttttPt -0000000000006b40 T _Z18test_add9_long_outlllllllllPl -0000000000006600 T _Z18test_fun_int_floatv -0000000000006c50 T _Z18test_incr_byte_outaPa -0000000000006d10 T _Z18test_incr_char_outtPt -0000000000006af0 T _Z18test_incr_long_outlPl -0000000000006e20 T _Z19test_add9_float_outfffffffffPf -0000000000006bf0 T _Z19test_add9_short_outsssssssssPs -0000000000006dd0 T _Z19test_incr_float_outfPf -0000000000006b90 T _Z19test_incr_short_outsPs -0000000000006930 T _Z19throwNewMyExceptionPKc -0000000000006e90 T _Z20test_add9_double_outdddddddddPd -0000000000006e50 T _Z20test_incr_double_outdPd -0000000000006a70 T _Z21test_callback_int_intPFiiEi -00000000000065d0 T _Z21test_fun_void__doubled -00000000000063e0 T _Z22testIndirectVirtualAddP5Ctestii -0000000000006c70 T _Z23test_callback_byte_bytePFaaEa -0000000000006d30 T _Z23test_callback_char_charPFttEt -0000000000006b00 T _Z23test_callback_long_longPFllEl -00000000000068c0 T _Z23throwMyExceptionByValuePKc -0000000000006de0 T _Z25test_callback_float_floatPFffEf -0000000000006bb0 T _Z25test_callback_short_shortPFssEs -0000000000006610 T _Z26test_fun_int_float__doubled -0000000000006e60 T _Z27test_callback_double_doublePFddEd -0000000000006a80 T _Z30test_callback_int_int_asDoublePFiiEi -0000000000006c80 T _Z32test_callback_byte_byte_asDoublePFaaEa -0000000000006d40 T _Z32test_callback_char_char_asDoublePFttEt -0000000000006b10 T _Z32test_callback_long_long_asDoublePFllEl -0000000000006df0 T _Z34test_callback_float_float_asDoublePFffEf -0000000000006bc0 T _Z34test_callback_short_short_asDoublePFssEs -0000000000006e70 T _Z36test_callback_double_double_asDoublePFddEd -0000000000005e80 T _Z3addii -0000000000007410 T _Z3sum6S_int2 -0000000000007420 T _Z3sum8S_jlong4 -0000000000007440 T _Z3sum9S_jlong10 -0000000000007400 T _Z4incr5S_int -00000000000074c0 T _Z4totov -0000000000005e90 T _Z7addPtrsPvS_ -0000000000006650 T _Z8getAdderv -0000000000006410 T _Z8testEnum5ETest -0000000000006570 T _Z8test_intv -00000000000069a0 T _Z8throwInti -00000000000066b0 T _Z9newStringv -0000000000007c10 W _Z9newVectorIdESt6vectorIT_SaIS1_EEi -0000000000007e60 W _Z9newVectorIfESt6vectorIT_SaIS1_EEi -0000000000007770 W _Z9newVectorIiESt6vectorIT_SaIS1_EEi -00000000000079c0 W _Z9newVectorIxESt6vectorIT_SaIS1_EEi -0000000000006560 T _Z9test_pintv -00000000000065b0 T _Z9test_voidv -000000000020b250 b _ZGVZN6Ctest28toStringEvE1s -0000000000007140 W _ZN11MyExceptionD0Ev -00000000000070d0 W _ZN11MyExceptionD1Ev -00000000000070d0 W _ZN11MyExceptionD2Ev -00000000000072e0 W _ZN24InvisibleSourcesTemplateILi10ESsE10createSomeEv -0000000000007320 W _ZN24InvisibleSourcesTemplateILi10ESsE10deleteSomeEPSs -0000000000007280 W _ZN24InvisibleSourcesTemplateILi10ESsEC1Ei -0000000000007280 W _ZN24InvisibleSourcesTemplateILi10ESsEC2Ei -0000000000007210 W _ZN24InvisibleSourcesTemplateILi10EiE10createSomeEv -0000000000007250 W _ZN24InvisibleSourcesTemplateILi10EiE10deleteSomeEPi -00000000000071b0 W _ZN24InvisibleSourcesTemplateILi10EiEC1Ei -00000000000071b0 W _ZN24InvisibleSourcesTemplateILi10EiEC2Ei -0000000000006280 T _ZN5Ctest11getInstanceEv -0000000000006470 T _ZN5Ctest11static_voidEv -0000000000006400 T _ZN5Ctest14testAddStdCallEPvii -0000000000005e50 T _ZN5Ctest14testVirtualAddEii -0000000000005e60 T _ZN5Ctest21testVirtualAddStdCallEPvii -00000000000062d0 T _ZN5Ctest6getIntEv -00000000000062c0 T _ZN5Ctest7getEnumEv -00000000000063f0 T _ZN5Ctest7testAddEii -0000000000006250 T _ZN5CtestC1Ei -0000000000006230 T _ZN5CtestC1Ev -0000000000006250 T _ZN5CtestC2Ei -0000000000006230 T _ZN5CtestC2Ev -0000000000006270 T _ZN5CtestD1Ev -0000000000006270 T _ZN5CtestD2Ev -00000000000073a0 W _ZN5Temp1IdE4tempEd -0000000000007070 W _ZN5Temp1IdED0Ev -0000000000006f50 W _ZN5Temp1IdED1Ev -0000000000006f50 W _ZN5Temp1IdED2Ev -0000000000007390 W _ZN5Temp1IiE4tempEi -0000000000007090 W _ZN5Temp1IiED0Ev -0000000000006f40 W _ZN5Temp1IiED1Ev -0000000000006f40 W _ZN5Temp1IiED2Ev -00000000000073d0 W _ZN5Temp2IddE4tempEdd -0000000000007010 W _ZN5Temp2IddED0Ev -0000000000006f80 W _ZN5Temp2IddED1Ev -0000000000006f80 W _ZN5Temp2IddED2Ev -00000000000073b0 W _ZN5Temp2IiiE4tempEii -0000000000007050 W _ZN5Temp2IiiED0Ev -0000000000006f60 W _ZN5Temp2IiiED1Ev -0000000000006f60 W _ZN5Temp2IiiED2Ev -00000000000073c0 W _ZN5Temp2IisE4tempEis -0000000000007030 W _ZN5Temp2IisED0Ev -0000000000006f70 W _ZN5Temp2IisED1Ev -0000000000006f70 W _ZN5Temp2IisED2Ev -00000000000073f0 W _ZN5TempVIdLi33EE4tempEd -0000000000006fd0 W _ZN5TempVIdLi33EED0Ev -0000000000006fa0 W _ZN5TempVIdLi33EED1Ev -0000000000006fa0 W _ZN5TempVIdLi33EED2Ev -00000000000073e0 W _ZN5TempVIiLi66EE4tempEi -0000000000006ff0 W _ZN5TempVIiLi66EED0Ev -0000000000006f90 W _ZN5TempVIiLi66EED1Ev -0000000000006f90 W _ZN5TempVIiLi66EED2Ev -0000000000005e70 T _ZN6Ctest214testVirtualAddEii -0000000000006380 T _ZN6Ctest216getCtestInstanceEv -0000000000006530 T _ZN6Ctest218setDestructedStateEi -0000000000006540 T _ZN6Ctest27testAddEii -0000000000006520 T _ZN6Ctest28setStateEPi -00000000000062e0 T _ZN6Ctest28toStringEv -00000000000064c0 T _ZN6Ctest2C1Ev -00000000000064c0 T _ZN6Ctest2C2Ev -00000000000064f0 T _ZN6Ctest2D1Ev -00000000000064f0 T _ZN6Ctest2D2Ev -0000000000005ea0 T _ZN6Module3addEii -0000000000006fb0 W _ZN6ModuleD0Ev -0000000000006f10 W _ZN6ModuleD1Ev -0000000000006f10 W _ZN6ModuleD2Ev -0000000000005ec0 T _ZN7AModule3addEii -0000000000005ed0 T _ZN7AModule8subtractEii -0000000000006a20 T _ZN7AModuleC1Ev -0000000000006a20 T _ZN7AModuleC2Ev -0000000000005ee0 T _ZN7AModuleD0Ev -0000000000005eb0 T _ZN7AModuleD1Ev -0000000000005eb0 T _ZN7AModuleD2Ev -00000000000070b0 W _ZN7IModuleD0Ev -0000000000006f20 W _ZN7IModuleD1Ev -0000000000006f20 W _ZN7IModuleD2Ev -0000000000006f30 W _ZNK11MyException4whatEv - U _ZNSbIwSt11char_traitsIwESaIwEE4_Rep10_M_destroyERKS1_@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE4_Rep20_S_empty_rep_storageE@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE6appendEPKwm@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE6resizeEmw@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE7reserveEm@@GLIBCXX_3.4 - U _ZNSolsEi@@GLIBCXX_3.4 - U _ZNSs4_Rep10_M_destroyERKSaIcE@@GLIBCXX_3.4 - U _ZNSs4_Rep20_S_empty_rep_storageE@@GLIBCXX_3.4 - U _ZNSs6appendEPKcm@@GLIBCXX_3.4 - U _ZNSs6resizeEmc@@GLIBCXX_3.4 - U _ZNSs7reserveEm@@GLIBCXX_3.4 - U _ZNSsC1EPKcRKSaIcE@@GLIBCXX_3.4 - U _ZNSsD1Ev@@GLIBCXX_3.4 -0000000000007a60 W _ZNSt6vectorIdSaIdEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPdS1_EERKd -0000000000007580 W _ZNSt6vectorIdSaIdEED1Ev -0000000000007580 W _ZNSt6vectorIdSaIdEED2Ev -0000000000007cb0 W _ZNSt6vectorIfSaIfEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPfS1_EERKf -00000000000075a0 W _ZNSt6vectorIfSaIfEED1Ev -00000000000075a0 W _ZNSt6vectorIfSaIfEED2Ev -00000000000075c0 W _ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi -0000000000007540 W _ZNSt6vectorIiSaIiEED1Ev -0000000000007540 W _ZNSt6vectorIiSaIiEED2Ev -0000000000007810 W _ZNSt6vectorIxSaIxEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPxS1_EERKx -0000000000007560 W _ZNSt6vectorIxSaIxEED1Ev -0000000000007560 W _ZNSt6vectorIxSaIxEED2Ev - U _ZNSt8ios_base4InitC1Ev@@GLIBCXX_3.4 - U _ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4 - U _ZNSt9exceptionD2Ev@@GLIBCXX_3.4 - U _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l@@GLIBCXX_3.4.9 - U _ZSt4cout@@GLIBCXX_3.4 -000000000020b244 b _ZStL8__ioinit -000000000020b260 b _ZStL8__ioinit -000000000020b264 b _ZStL8__ioinit -000000000020ad00 V _ZTI11MyException -000000000020ac80 V _ZTI5Ctest -000000000020ac10 V _ZTI5Temp1IdE -000000000020ac20 V _ZTI5Temp1IiE -000000000020abe0 V _ZTI5Temp2IddE -000000000020ac00 V _ZTI5Temp2IiiE -000000000020abf0 V _ZTI5Temp2IisE -000000000020abc0 V _ZTI5TempVIdLi33EE -000000000020abd0 V _ZTI5TempVIiLi66EE -000000000020ac60 V _ZTI6Ctest2 -000000000020ac50 V _ZTI6Module -000000000020ac30 V _ZTI7AModule -000000000020ac90 V _ZTI7IModule -000000000020ace0 V _ZTIP11MyException - U _ZTISt9exception@@GLIBCXX_3.4 - U _ZTIi@@CXXABI_1.3 -0000000000008063 V _ZTS11MyException -0000000000008044 V _ZTS5Ctest -0000000000008017 V _ZTS5Temp1IdE -0000000000008021 V _ZTS5Temp1IiE -0000000000007ff6 V _ZTS5Temp2IddE -000000000000800c V _ZTS5Temp2IiiE -0000000000008001 V _ZTS5Temp2IisE -0000000000007fd8 V _ZTS5TempVIdLi33EE -0000000000007fe7 V _ZTS5TempVIiLi66EE -000000000000803c V _ZTS6Ctest2 -0000000000008034 V _ZTS6Module -000000000000802b V _ZTS7AModule -000000000000804b V _ZTS7IModule -0000000000008054 V _ZTSP11MyException -000000000020ad20 V _ZTV11MyException -000000000020aba0 V _ZTV5Ctest -000000000020ab40 V _ZTV5Temp1IdE -000000000020ab60 V _ZTV5Temp1IiE -000000000020aae0 V _ZTV5Temp2IddE -000000000020ab20 V _ZTV5Temp2IiiE -000000000020ab00 V _ZTV5Temp2IisE -000000000020aaa0 V _ZTV5TempVIdLi33EE -000000000020aac0 V _ZTV5TempVIiLi66EE -000000000020ab80 V _ZTV6Ctest2 -000000000020aa60 V _ZTV6Module -000000000020aa20 V _ZTV7AModule -000000000020aca0 V _ZTV7IModule - U _ZTVN10__cxxabiv117__class_type_infoE@@CXXABI_1.3 - U _ZTVN10__cxxabiv119__pointer_type_infoE@@CXXABI_1.3 - U _ZTVN10__cxxabiv120__si_class_type_infoE@@CXXABI_1.3 -000000000020b258 b _ZZN6Ctest28toStringEvE1s - U _ZdlPv@@GLIBCXX_3.4 - U _Znam@@GLIBCXX_3.4 - U _Znwm@@GLIBCXX_3.4 -000000000020aa00 d __CTOR_END__ -000000000020a9e0 d __CTOR_LIST__ -000000000020aa10 d __DTOR_END__ -000000000020aa08 d __DTOR_LIST__ -0000000000009c70 r __FRAME_END__ -000000000020aa18 d __JCR_END__ -000000000020aa18 d __JCR_LIST__ -000000000020b228 A __bss_start - U __cxa_allocate_exception@@CXXABI_1.3 - U __cxa_atexit@@GLIBC_2.2.5 - w __cxa_finalize@@GLIBC_2.2.5 - U __cxa_free_exception@@CXXABI_1.3 - U __cxa_guard_abort@@CXXABI_1.3 - U __cxa_guard_acquire@@CXXABI_1.3 - U __cxa_guard_release@@CXXABI_1.3 - U __cxa_pure_virtual@@CXXABI_1.3 - U __cxa_throw@@CXXABI_1.3 -0000000000007f00 t __do_global_ctors_aux -0000000000005da0 t __do_global_dtors_aux -000000000020b208 d __dso_handle - w __gmon_start__ - U __gxx_personality_v0@@CXXABI_1.3 -000000000020b228 A _edata -000000000020b268 A _end -0000000000007f38 T _fini -0000000000005948 T _init -0000000000005d80 t call_gmon_start -000000000020b230 b completed.6557 -000000000020b238 b dtor_idx.6559 -0000000000005e20 t frame_dummy - U memmove@@GLIBC_2.2.5 -000000000020b218 D newIntVector -000000000020b240 B ntest -0000000000006110 T otherFunc - w pthread_cancel - U sin -0000000000005f10 T sinInt -000000000020b220 D sizeofIntVector - U strlen@@GLIBC_2.2.5 -00000000000061f0 T testASinB -0000000000006150 T testAddDyncall -0000000000006180 T testAddJNA -0000000000006040 T testInPlaceSquare -0000000000005fa0 T testSum -0000000000006020 T testSumInt -0000000000005fd0 T testSumi -0000000000006000 T testSumll -0000000000005f00 T voidTest - U wcslen@@GLIBC_2.2.5 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so deleted file mode 100755 index c575cad50..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so.nm deleted file mode 100644 index 702a36332..000000000 --- a/libraries/BridJ/src/test/resources/org/bridj/lib/linux_x86/test.so.nm +++ /dev/null @@ -1,305 +0,0 @@ -000043c0 T Java_org_bridj_PerfLib_testASinB -00004390 T Java_org_bridj_PerfLib_testAddJNI -00008f10 a _DYNAMIC -00008ff4 a _GLOBAL_OFFSET_TABLE_ -000054b0 t _GLOBAL__I__Z4incr5S_int -000054f0 t _GLOBAL__I_newIntVector -00004f70 t _GLOBAL__I_ntest - w _Jv_RegisterClasses - U _Unwind_Resume@@GCC_3.0 -000045c0 T _Z10createTestv -000048f0 T _Z10newWStringv -000048e0 T _Z10stringCStrPSs -00004670 T _Z10test_pvoidv -00004b70 T _Z11MyEnumToInt6MyEnum -00004790 T _Z11forwardCallPFiiiEii -000047b0 T _Z11getPtrAdderv -00004b60 T _Z11intToMyEnumi -000041f0 T _Z11passVarArgsPcbz -000044e0 T _Z11sizeOfCtestv -000045a0 T _Z11testIntEnumi5ETest -000049e0 T _Z11wstringCStrPSbIwSt11char_traitsIwESaIwEE -00004880 T _Z12deleteStringPSs -00004780 T _Z12getAdder_rawv -00004850 T _Z12resizeStringPSsj -000044f0 T _Z12sizeOfCtest2v -00005540 W _Z12sizeofVectorIdEiv -00005550 W _Z12sizeofVectorIfEiv -00005520 W _Z12sizeofVectorIiEiv -00005530 W _Z12sizeofVectorIxEiv -00004570 T _Z12testEnumArgs5ETestS_ -00004590 T _Z12testVoidEnumv -00004710 T _Z12test_fun_intv -00004980 T _Z13deleteWStringPSbIwSt11char_traitsIwESaIwEE -00004760 T _Z13getAdder_longv -00004840 T _Z13reserveStringPSsj -00004950 T _Z13resizeWStringPSbIwSt11char_traitsIwESaIwEEj -00004b50 T _Z13sizeOfTimevalv -00004370 T _Z13testAddCLongsll -00004350 T _Z13testAddJLongsxx -00004be0 T _Z13test_add9_intiiiiiiiii -000046e0 T _Z13test_fun_voidv -00004b80 T _Z13test_incr_inti -00004810 T _Z14appendToStringPSsPKc -000047d0 T _Z14forwardPtrCallPFPvS_S_ES_S_ -00004750 T _Z14getAdder_pvoidv -00004940 T _Z14reserveWStringPSbIwSt11char_traitsIwESaIwEEj -00004dc0 T _Z14test_add9_byteaaaaaaaaa -00004e50 T _Z14test_add9_charttttttttt -00004c90 T _Z14test_add9_longxxxxxxxxx -00004d50 T _Z14test_incr_bytea -00004de0 T _Z14test_incr_chart -00004c00 T _Z14test_incr_longx -000046c0 T _Z14test_int_floatf -00004740 T _Z14test_int_shorts -00004910 T _Z15appendToWStringPSbIwSt11char_traitsIwESaIwEEPKw -000047c0 T _Z15getPtrAdder_rawv -00004ed0 T _Z15test_add9_floatfffffffff -00004d30 T _Z15test_add9_shortsssssssss -00004b40 T _Z15test_incr_clongl -00004e70 T _Z15test_incr_floatf -00004cc0 T _Z15test_incr_shorts -00004b30 T _Z15test_incr_sizetj -00004b20 T _Z15test_incr_timetl -000046b0 T _Z15test_int_doublev -00004f50 T _Z16test_add9_doubleddddddddd -00004ef0 T _Z16test_incr_doubled -000046a0 T _Z16test_void_doublev -00004560 T _Z17testEnumArgSecond5ETest -00004550 T _Z17testEnumRetSecondv -00004bf0 T _Z17test_add9_int_outiiiiiiiiiPi -00004700 T _Z17test_fun_void_intv -00004b90 T _Z17test_incr_int_outiPi -000049f0 T _Z18crashIllegalAccessv -00004dd0 T _Z18test_add9_byte_outaaaaaaaaaPa -00004e60 T _Z18test_add9_char_outtttttttttPt -00004ca0 T _Z18test_add9_long_outxxxxxxxxxPx -00004720 T _Z18test_fun_int_floatv -00004d60 T _Z18test_incr_byte_outaPa -00004df0 T _Z18test_incr_char_outtPt -00004c20 T _Z18test_incr_long_outxPx -00004ee0 T _Z19test_add9_float_outfffffffffPf -00004d40 T _Z19test_add9_short_outsssssssssPs -00004e80 T _Z19test_incr_float_outfPf -00004cd0 T _Z19test_incr_short_outsPs -00004a70 T _Z19throwNewMyExceptionPKc -00004f60 T _Z20test_add9_double_outdddddddddPd -00004f00 T _Z20test_incr_double_outdPd -00004ba0 T _Z21test_callback_int_intPFiiEi -000046f0 T _Z21test_fun_void__doubled -00004500 T _Z22testIndirectVirtualAddP5Ctestii -00004d80 T _Z23test_callback_byte_bytePFaaEa -00004e10 T _Z23test_callback_char_charPFttEt -00004c40 T _Z23test_callback_long_longPFxxEx -00004a00 T _Z23throwMyExceptionByValuePKc -00004e90 T _Z25test_callback_float_floatPFffEf -00004cf0 T _Z25test_callback_short_shortPFssEs -00004730 T _Z26test_fun_int_float__doubled -00004f10 T _Z27test_callback_double_doublePFddEd -00004bc0 T _Z30test_callback_int_int_asDoublePFiiEi -00004da0 T _Z32test_callback_byte_byte_asDoublePFaaEa -00004e30 T _Z32test_callback_char_char_asDoublePFttEt -00004c60 T _Z32test_callback_long_long_asDoublePFxxEx -00004eb0 T _Z34test_callback_float_float_asDoublePFffEf -00004d10 T _Z34test_callback_short_short_asDoublePFssEs -00004f30 T _Z36test_callback_double_double_asDoublePFddEd -000041b0 T _Z3addii -00005430 T _Z3sum6S_int2 -00005440 T _Z3sum8S_jlong4 -00005460 T _Z3sum9S_jlong10 -00005420 T _Z4incr5S_int -000054e0 T _Z4totov -000041c0 T _Z7addPtrsPvS_ -00004770 T _Z8getAdderv -00004540 T _Z8testEnum5ETest -00004690 T _Z8test_intv -00004af0 T _Z8throwInti -000047f0 T _Z9newStringv -00005bc0 W _Z9newVectorIdESt6vectorIT_SaIS1_EEi -00005de0 W _Z9newVectorIfESt6vectorIT_SaIS1_EEi -00005760 W _Z9newVectorIiESt6vectorIT_SaIS1_EEi -00005990 W _Z9newVectorIxESt6vectorIT_SaIS1_EEi -00004680 T _Z9test_pintv -000046d0 T _Z9test_voidv -00009028 b _ZGVZN6Ctest28toStringEvE1s -00005160 W _ZN11MyExceptionD0Ev -00005100 W _ZN11MyExceptionD1Ev -00005100 W _ZN11MyExceptionD2Ev -000052f0 W _ZN24InvisibleSourcesTemplateILi10ESsE10createSomeEv -00005330 W _ZN24InvisibleSourcesTemplateILi10ESsE10deleteSomeEPSs -000052a0 W _ZN24InvisibleSourcesTemplateILi10ESsEC1Ei -000052a0 W _ZN24InvisibleSourcesTemplateILi10ESsEC2Ei -00005220 W _ZN24InvisibleSourcesTemplateILi10EiE10createSomeEv -00005260 W _ZN24InvisibleSourcesTemplateILi10EiE10deleteSomeEPi -000051d0 W _ZN24InvisibleSourcesTemplateILi10EiEC1Ei -000051d0 W _ZN24InvisibleSourcesTemplateILi10EiEC2Ei -000045b0 T _ZN5Ctest11static_voidEv -00004520 T _ZN5Ctest14testAddStdCallEPvii -00004170 T _ZN5Ctest14testVirtualAddEii -00004180 T _ZN5Ctest21testVirtualAddStdCallEPvii -00004510 T _ZN5Ctest7testAddEii -00004420 T _ZN5CtestC1Ei -00004400 T _ZN5CtestC1Ev -00004420 T _ZN5CtestC2Ei -00004400 T _ZN5CtestC2Ev -00004440 T _ZN5CtestD1Ev -00004440 T _ZN5CtestD2Ev -000053c0 W _ZN5Temp1IdE4tempEd -000050c0 W _ZN5Temp1IdED0Ev -00004fc0 W _ZN5Temp1IdED1Ev -00004fc0 W _ZN5Temp1IdED2Ev -000053b0 W _ZN5Temp1IiE4tempEi -000050e0 W _ZN5Temp1IiED0Ev -00004fb0 W _ZN5Temp1IiED1Ev -00004fb0 W _ZN5Temp1IiED2Ev -000053f0 W _ZN5Temp2IddE4tempEdd -00005060 W _ZN5Temp2IddED0Ev -00004ff0 W _ZN5Temp2IddED1Ev -00004ff0 W _ZN5Temp2IddED2Ev -000053d0 W _ZN5Temp2IiiE4tempEii -000050a0 W _ZN5Temp2IiiED0Ev -00004fd0 W _ZN5Temp2IiiED1Ev -00004fd0 W _ZN5Temp2IiiED2Ev -000053e0 W _ZN5Temp2IisE4tempEis -00005080 W _ZN5Temp2IisED0Ev -00004fe0 W _ZN5Temp2IisED1Ev -00004fe0 W _ZN5Temp2IisED2Ev -00005410 W _ZN5TempVIdLi33EE4tempEd -00005020 W _ZN5TempVIdLi33EED0Ev -00005010 W _ZN5TempVIdLi33EED1Ev -00005010 W _ZN5TempVIdLi33EED2Ev -00005400 W _ZN5TempVIiLi66EE4tempEi -00005040 W _ZN5TempVIiLi66EED0Ev -00005000 W _ZN5TempVIiLi66EED1Ev -00005000 W _ZN5TempVIiLi66EED2Ev -000041a0 T _ZN6Ctest214testVirtualAddEii -00004650 T _ZN6Ctest218setDestructedStateEi -00004660 T _ZN6Ctest27testAddEii -00004640 T _ZN6Ctest28setStateEPi -00004450 T _ZN6Ctest28toStringEv -000045f0 T _ZN6Ctest2C1Ev -000045f0 T _ZN6Ctest2C2Ev -00004620 T _ZN6Ctest2D1Ev -00004620 T _ZN6Ctest2D2Ev -00004fa0 W _ZNK11MyException4whatEv - U _ZNSbIwSt11char_traitsIwESaIwEE4_Rep10_M_destroyERKS1_@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE4_Rep20_S_empty_rep_storageE@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE6appendEPKwj@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE6resizeEjw@@GLIBCXX_3.4 - U _ZNSbIwSt11char_traitsIwESaIwEE7reserveEj@@GLIBCXX_3.4 - U _ZNSolsEi@@GLIBCXX_3.4 - U _ZNSs4_Rep10_M_destroyERKSaIcE@@GLIBCXX_3.4 - U _ZNSs4_Rep20_S_empty_rep_storageE@@GLIBCXX_3.4 - U _ZNSs6appendEPKcj@@GLIBCXX_3.4 - U _ZNSs6resizeEjc@@GLIBCXX_3.4 - U _ZNSs7reserveEj@@GLIBCXX_3.4 - U _ZNSsC1EPKcRKSaIcE@@GLIBCXX_3.4 - U _ZNSsD1Ev@@GLIBCXX_3.4 -00005a30 W _ZNSt6vectorIdSaIdEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPdS1_EERKd -000055a0 W _ZNSt6vectorIdSaIdEED1Ev -000055a0 W _ZNSt6vectorIdSaIdEED2Ev -00005c60 W _ZNSt6vectorIfSaIfEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPfS1_EERKf -000055c0 W _ZNSt6vectorIfSaIfEED1Ev -000055c0 W _ZNSt6vectorIfSaIfEED2Ev -000055e0 W _ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi -00005560 W _ZNSt6vectorIiSaIiEED1Ev -00005560 W _ZNSt6vectorIiSaIiEED2Ev -000057f0 W _ZNSt6vectorIxSaIxEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPxS1_EERKx -00005580 W _ZNSt6vectorIxSaIxEED1Ev -00005580 W _ZNSt6vectorIxSaIxEED2Ev - U _ZNSt8ios_base4InitC1Ev@@GLIBCXX_3.4 - U _ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4 - U _ZNSt9exceptionD2Ev@@GLIBCXX_3.4 - U _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_i@@GLIBCXX_3.4.9 - U _ZSt4cout@@GLIBCXX_3.4 -00009024 b _ZStL8__ioinit -00009034 b _ZStL8__ioinit -00009038 b _ZStL8__ioinit -00006088 V _ZTI11MyException -00006070 V _ZTI5Ctest -00006038 V _ZTI5Temp1IdE -0000604c V _ZTI5Temp1IiE -00005ffc V _ZTI5Temp2IddE -00006024 V _ZTI5Temp2IiiE -00006010 V _ZTI5Temp2IisE -00005fd0 V _ZTI5TempVIdLi33EE -00005fe8 V _ZTI5TempVIiLi66EE -0000605c V _ZTI6Ctest2 -00006078 V _ZTIP11MyException - U _ZTISt9exception@@GLIBCXX_3.4 - U _ZTIi@@CXXABI_1.3 -000060bb V _ZTS11MyException -00006068 V _ZTS5Ctest -0000602c V _ZTS5Temp1IdE -00006040 V _ZTS5Temp1IiE -00005ff0 V _ZTS5Temp2IddE -00006018 V _ZTS5Temp2IiiE -00006004 V _ZTS5Temp2IisE -00005fc0 V _ZTS5TempVIdLi33EE -00005fd8 V _ZTS5TempVIiLi66EE -00006054 V _ZTS6Ctest2 -000060ac V _ZTSP11MyException -00006098 V _ZTV11MyException -00005fb0 V _ZTV5Ctest -00005f80 V _ZTV5Temp1IdE -00005f90 V _ZTV5Temp1IiE -00005f50 V _ZTV5Temp2IddE -00005f70 V _ZTV5Temp2IiiE -00005f60 V _ZTV5Temp2IisE -00005f30 V _ZTV5TempVIdLi33EE -00005f40 V _ZTV5TempVIiLi66EE -00005fa0 V _ZTV6Ctest2 - U _ZTVN10__cxxabiv117__class_type_infoE@@CXXABI_1.3 - U _ZTVN10__cxxabiv119__pointer_type_infoE@@CXXABI_1.3 - U _ZTVN10__cxxabiv120__si_class_type_infoE@@CXXABI_1.3 -00009030 b _ZZN6Ctest28toStringEvE1s - U _ZdlPv@@GLIBCXX_3.4 - U _Znwj@@GLIBCXX_3.4 -00008f00 d __CTOR_END__ -00008ef0 d __CTOR_LIST__ -00008f08 d __DTOR_END__ -00008f04 d __DTOR_LIST__ -00007f00 r __FRAME_END__ -00008f0c d __JCR_END__ -00008f0c d __JCR_LIST__ -00009014 A __bss_start - U __cxa_allocate_exception@@CXXABI_1.3 - U __cxa_atexit@@GLIBC_2.1.3 - w __cxa_finalize@@GLIBC_2.1.3 - U __cxa_free_exception@@CXXABI_1.3 - U __cxa_guard_abort@@CXXABI_1.3 - U __cxa_guard_acquire@@CXXABI_1.3 - U __cxa_guard_release@@CXXABI_1.3 - U __cxa_throw@@CXXABI_1.3 -00005e80 t __do_global_ctors_aux -000040b0 t __do_global_dtors_aux -00009008 d __dso_handle - w __gmon_start__ - U __gxx_personality_v0@@CXXABI_1.3 -00004167 t __i686.get_pc_thunk.bx -00009014 A _edata -0000903c A _end -00005eb8 T _fini -00004044 T _init -00009018 b completed.6155 -0000901c b dtor_idx.6157 -00004130 t frame_dummy - U memmove@@GLIBC_2.0 -0000900c D newIntVector -00009020 B ntest -00004380 T otherFunc - w pthread_cancel - U sin -000041e0 T sinInt -00009010 D sizeofIntVector - U strlen@@GLIBC_2.0 -000043e0 T testASinB -000043a0 T testAddDyncall -000043b0 T testAddJNA -00004320 T testInPlaceSquare -00004220 T testSum -000042e0 T testSumInt -00004250 T testSumi -00004280 T testSumll -000041d0 T voidTest - U wcslen@@GLIBC_2.0 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.dylib.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.dylib.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.so b/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.so deleted file mode 100755 index 6eee8ae81..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.so and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.so.nm b/libraries/BridJ/src/test/resources/org/bridj/lib/sunos_x86/test.so.nm deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/win32/test.dll b/libraries/BridJ/src/test/resources/org/bridj/lib/win32/test.dll deleted file mode 100644 index 0b4e6be1b..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/win32/test.dll and /dev/null differ diff --git a/libraries/BridJ/src/test/resources/org/bridj/lib/win64/test.dll b/libraries/BridJ/src/test/resources/org/bridj/lib/win64/test.dll deleted file mode 100644 index 83be2f01d..000000000 Binary files a/libraries/BridJ/src/test/resources/org/bridj/lib/win64/test.dll and /dev/null differ diff --git a/libraries/BridJ/src/test/velocity/org/bridj/CallTest.cpp b/libraries/BridJ/src/test/velocity/org/bridj/CallTest.cpp deleted file mode 100644 index ccbb65eb4..000000000 --- a/libraries/BridJ/src/test/velocity/org/bridj/CallTest.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#pragma warning(disable: 4244) - -#foreach ($prim in $primitivesNoBool) - -TEST_API j${prim.Name} test_incr_${prim.Name}(j${prim.Name} value) { - return (j${prim.Name})(value + 1); -} - -TEST_API void test_incr_${prim.Name}_out(j${prim.Name} value, j${prim.Name}* pOut) { - *pOut = test_incr_${prim.Name}(value); -} -TEST_API j${prim.Name} test_callback_${prim.Name}_${prim.Name}(j${prim.Name} (*cb)(j${prim.Name}), j${prim.Name} value) { - j${prim.Name} ret = cb(value); - return ret; -} - -TEST_API jdouble test_callback_${prim.Name}_${prim.Name}_asDouble(j${prim.Name} (*cb)(j${prim.Name}), j${prim.Name} value) { - return (jdouble)test_callback_${prim.Name}_${prim.Name}(cb, value); -} - -#foreach ($n in [2, 9, 20]) - -TEST_API j${prim.Name} test_add${n}_${prim.Name}(#foreach ($i in [1..$n])#if($i > 1), #end j${prim.Name} arg$i#end) { - j${prim.Name} tot = (j${prim.Name})0; - j${prim.Name} fact = (j${prim.Name})2; -#foreach ($i in [1..$n]) - j${prim.Name} v$i = (j${prim.Name})(fact * ($i + 1)); - fact *= (j${prim.Name})2; - tot += v$i; -#end - return tot; -} -TEST_API void test_add${n}_${prim.Name}_out(#foreach ($i in [1..$n])#if($i > 1), #end j${prim.Name} arg$i#end, j${prim.Name}* pOut) { - *pOut = test_add${n}_${prim.Name}(#foreach ($i in [1..$n])#if($i > 1), #end arg$i#end); -} - -#end - -#end - - diff --git a/libraries/BridJ/src/test/velocity/org/bridj/CallTest.java b/libraries/BridJ/src/test/velocity/org/bridj/CallTest.java deleted file mode 100644 index 476b4feb2..000000000 --- a/libraries/BridJ/src/test/velocity/org/bridj/CallTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.bridj; -import static org.bridj.Pointer.*; -import org.bridj.ann.*; -//import static org.bridj.Functional.*; -import java.util.*; -import org.junit.*; -import static org.junit.Assert.*; - -@Library("test") -@org.bridj.ann.Runtime(CRuntime.class) -public class CallTest { - - public CallTest() { - BridJ.register(CallTest.class); - } - - /// Returns value + 1 - public static native TimeT test_incr_timet(TimeT value); - public static native SizeT test_incr_sizet(SizeT value); - public static native CLong test_incr_clong(CLong value); - - @Test - public void testTimeTSize() { - assertTrue(TimeT.SIZE == 4 || TimeT.SIZE == 8); - } - @Test - public void testIncrementTimeT() { - assertEquals(11, test_incr_timet(new TimeT(10)).longValue()); - } - @Test - public void testIncrementSizeT() { - assertEquals(11, test_incr_sizet(new SizeT(10)).longValue()); - } - @Test - public void testIncrementCLong() { - assertEquals(11, test_incr_clong(new CLong(10)).longValue()); - } - -#foreach ($prim in $primitivesNoBool) - - /// Returns value + 1 - public static native ${prim.Name} test_incr_${prim.Name}(${prim.Name} value); - - /// Returns value + 1 in pointed value - public static native void test_incr_${prim.Name}_out(${prim.Name} value, Pointer<${prim.WrapperName}> out); - - @Test - public void testIncrement${prim.CapName}() { - Pointer<${prim.WrapperName}> out = allocate${prim.CapName}(); - for (${prim.Name} value : new ${prim.Name}[] { (${prim.Name})0, (${prim.Name})1, (${prim.Name})-1 }) { - ${prim.Name} ret = test_incr_${prim.Name}(value); - ${prim.Name} incr = (${prim.Name})(value + 1); - assertEquals(incr, ret#if($prim.Name == "float" || $prim.Name == "double"), 0#end); - - test_incr_${prim.Name}_out(value, out); - ret = out.get(); - assertEquals(incr, ret#if($prim.Name == "float" || $prim.Name == "double"), 0#end); - } - } - - public static abstract class MyCallback_${prim.Name} extends Callback { - public abstract ${prim.Name} apply(${prim.Name} value); - } - ///* - /// Returns cb.apply(value) - //public static native ${prim.Name} test_callback_${prim.Name}_${prim.Name}(Func1<${prim.WrapperName}, ${prim.WrapperName}> cb, ${prim.Name} value); - public static native ${prim.Name} test_callback_${prim.Name}_${prim.Name}(Pointer cb, ${prim.Name} value); - - @Test - public void testCallback_${prim.Name}() { - MyCallback_${prim.Name} cb = new MyCallback_${prim.Name}() { - public ${prim.Name} apply(${prim.Name} value) { - return (${prim.Name})(value + 1); - } - }; - /* - Func1<${prim.WrapperName}, ${prim.WrapperName}> cb = new Func1<${prim.WrapperName}, ${prim.WrapperName}>() { - public ${prim.Name} apply(${prim.Name} value) { - return (${prim.Name})(value + 1); - } - };*/ - for (${prim.Name} value : new ${prim.Name}[] { (${prim.Name})0, (${prim.Name})1, (${prim.Name})-1 }) { - ${prim.Name} ret = test_callback_${prim.Name}_${prim.Name}(cb.toPointer(), value); - ${prim.Name} incr = (${prim.Name})(value + 1); - assertEquals(incr, ret#if($prim.Name == "float" || $prim.Name == "double"), 0#end); - } - } - //*/ - - -#foreach ($n in [2, 9, 20]) - public static native ${prim.Name} test_add${n}_${prim.Name}(#foreach ($i in [1..$n])#if($i > 1), #end${prim.Name} arg$i#end); - public static native void test_add${n}_${prim.Name}_out(#foreach ($i in [1..$n])#if($i > 1), #end${prim.Name} arg$i#end, Pointer<${prim.WrapperName}> out); - - @Test - public void testAdd${n}${prim.CapName}() { - Pointer<${prim.WrapperName}> out = allocate${prim.CapName}(); - - ${prim.Name} expectedTot = (${prim.Name})0; - ${prim.Name} fact = (${prim.Name})2; -#foreach ($i in [1..$n]) - ${prim.Name} arg$i = (${prim.Name})(fact * ($i + 1)); - fact *= (${prim.Name})2; - expectedTot += arg$i; -#end - ${prim.Name} tot = test_add${n}_${prim.Name}(#foreach ($i in [1..$n])#if($i > 1),#end arg$i#end); - assertEquals(expectedTot, tot#if($prim.Name == "float" || $prim.Name == "double"), 0#end); - - test_add${n}_${prim.Name}_out(#foreach ($i in [1..$n])#if($i > 1),#end arg$i#end, out); - tot = out.get(); - assertEquals(expectedTot, tot#if($prim.Name == "float" || $prim.Name == "double"), 0#end); - } -#end - - -#end -} diff --git a/libraries/BridJ/src/test/velocity/org/bridj/PointerTest.java b/libraries/BridJ/src/test/velocity/org/bridj/PointerTest.java deleted file mode 100644 index 5bb27e4e9..000000000 --- a/libraries/BridJ/src/test/velocity/org/bridj/PointerTest.java +++ /dev/null @@ -1,998 +0,0 @@ -package org.bridj; -import org.bridj.cpp.*; -import org.junit.Test; - -import java.nio.charset.Charset; -import java.nio.*; -import java.util.Iterator; -import java.util.Arrays; -import static java.util.Arrays.asList; -import org.bridj.ann.Ptr; -import org.bridj.ann.Library; -import org.bridj.ann.Runtime; -import static org.junit.Assert.*; -import static org.bridj.Pointer.*; - -#set($v1 = "(1 << 32 | 1)") -#set($v2 = "(2 << 32 | 2)") -#set($v3 = "(3 << 32 | 3)") - -@Library("test") -@Runtime(CPPRuntime.class) -public class PointerTest { - static { - BridJ.register(); - } - int n = 3; - static final ByteOrder[] orders = new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }; - - @Test - public void testValidity() { - Pointer p = allocateShorts(10), p2 = p.next(2), p2w = p2.withoutValidityInformation(); - Pointer p2u = p2.asUntyped(); - - assertEquals(p.getPeer() + 4, p2.getPeer()); - assertEquals(p2.getPeer(), p2u.getPeer()); - assertEquals(p2.getPeer(), p2w.getPeer()); - - assertEquals(p.getValidStart(), p2.getValidStart()); - assertEquals(p.getValidEnd(), p2.getValidEnd()); - - assertEquals(p.getValidStart(), p2u.getValidStart()); - assertEquals(p.getValidEnd(), p2u.getValidEnd()); - - assertEquals(p.getIO(), p2w.getIO()); - } - - @Test - public void testRelease() { - final boolean called[] = new boolean[1]; - Pointer p = allocateInts(3).withReleaser(new Releaser() { - public void release(Pointer p) { - called[0] = true; - } - }); - Pointer p2 = p.offset(1); - p2.release(); - assertTrue(called[0]); - Pointer.release(p, p2); - } - @Test - public void testStaticGet() { - assertNull(Pointer.get(null)); - assertNotNull(Pointer.get(allocateInt())); - } - @Test - public void testMisc() { - Pointer p = allocateInt(); - assertFalse(p.equals(null)); - assertFalse(p.equals("toto")); - assertSame(p, p.validBytes(p.getValidBytes())); - assertSame(p, p.offset(0)); - assertEquals(p.getPeer(), p.offset(0, PointerIO.getDoubleInstance()).getPeer()); - } - @Test(expected = IllegalArgumentException.class) - public void testNegSize() { - allocateInts(-1); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void testInvalidValidBytes() { - allocateBytes(1).validBytes(2); - } - @Test(expected = IndexOutOfBoundsException.class) - public void testInvalidOffset() { - allocateBytes(1).offset(2); - } - @Test - public void testPointerPointerPointer() { - Pointer p = allocateInt(); - Pointer> pp = allocatePointer(Integer.class); - Pointer>> ppp = allocatePointerPointer(Integer.class); - p.set(10); - pp.set(p); - ppp.set(pp); - assertEquals(10, (int)(Integer)ppp.get().get().get()); - } - - @Test - public void testNext() { - int n = 3; - Pointer ints = allocateInts(n), p = ints; - - for (int i = 0; i < n; i++) { - p.set(i); - p = p.next(); - } - assertEquals(asList(0, 1, 2), ints.asList()); - } - @Test - public void testClone() { - Pointer p = pointerToInts(1, 2, 3, 4); - Pointer c = p.clone(); - assertTrue(p.getPeer() != c.getPeer()); - for (int i = 0; i < 4; i++) - assertEquals(i + 1, (int)c.get(i)); - - assertEquals(0, p.compareBytes(c, p.getValidBytes())); - } - @Test - public void testIdentities() { - Pointer p = allocateInt(); - assertTrue(p == (Pointer)p.offset(0)); - assertTrue(p == (Pointer)p.next(0)); - assertTrue(p == (Pointer)p.as(p.getIO())); - assertTrue(p == (Pointer)p.as(p.getIO().getTargetType())); - assertTrue(p == (Pointer)p.order(p.order())); - } - - @Test - public void testFind() { - Pointer p = pointerToInts(1, 2, 3, 4); - assertEquals(null, p.find(null)); - assertEquals(null, p.find(pointerToInts(1, 4))); - assertEquals(p, p.find(p)); - assertEquals(p.next(2), p.find(pointerToInts(3, 4))); - } - @Test - public void testFindLast() { - Pointer p = pointerToInts(1, 2, 3, 4, 1, 2); - assertEquals(null, p.findLast(null)); - assertEquals(null, p.findLast(pointerToInts(1, 4))); - assertEquals(p, p.findLast(p)); - assertEquals(p.next(4), p.findLast(pointerToInts(1, 2))); - } - @Test - public void testList() { - NativeList list = allocateList(int.class, 10); - assertEquals(asList(), list); - list.add(10); - list.add(20); - assertEquals(asList(10, 20), list); - list.remove(0); - assertEquals(asList(20), list); - list.clear(); - assertEquals(asList(), list); - - } - - @Test - public void testDebugBulkPut() { - long s = BridJ.sizeOf(int.class); - Pointer a = pointerToInts(-1, 2, -3); - Pointer b = allocateInts(4); - - b.getByteBufferAtOffset(1 * s, 3 * s).put(a.getByteBuffer()); - - assertEquals(Arrays.asList(0, -1, 2, -3), b.asList()); - } - - @Test - public void testDebugFloatEndian() { - float value = 10.0f; - for (ByteOrder order : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) { - ByteBuffer b = ByteBuffer.allocateDirect(20).order(order); - b.asFloatBuffer().put(0, value); - Pointer p = allocateFloat().order(order); - p.setFloat(value); - - //System.out.println("Order = " + order); - //System.out.println(Integer.toHexString(b.asIntBuffer().get())); - //System.out.println(Integer.toHexString(p.getInt())); - assertEquals(value, b.asFloatBuffer().get(0), 0); - assertEquals(value, p.getFloat(), 0); - - assertEquals(value, pointerToBuffer(b).getFloat(), 0); - assertEquals(value, p.getFloatBuffer().get(), 0); - } - } - - @Test - public void assumptionsOnDoubleBuffers() { - double v = 13579000030.5336163; - ByteBuffer b = ByteBuffer.allocateDirect(8); - DoubleBuffer d1 = b.order(ByteOrder.BIG_ENDIAN).asDoubleBuffer(); - DoubleBuffer d2 = b.order(ByteOrder.BIG_ENDIAN).asDoubleBuffer(); - DoubleBuffer d3 = b.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); - - d1.put(0, v); - - LongBuffer l1 = b.order(ByteOrder.BIG_ENDIAN).asLongBuffer(); - LongBuffer l3 = b.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); - - //System.out.println("ORDER 1 = " + Long.toHexString(l1.get(0))); - //System.out.println("ORDER 2 = " + Long.toHexString(l3.get(0))); - - assertTrue(d1.get(0) == d2.get(0)); - assertTrue(d1.get(0) != d3.get(0)); - } - @Test - public void assumptionsOnDoublePointers() { - double v = 13579000030.5336163; - Pointer b = allocateDouble(); - Pointer d1 = b.order(ByteOrder.BIG_ENDIAN); - Pointer d2 = b.order(ByteOrder.BIG_ENDIAN); - Pointer d3 = b.order(ByteOrder.LITTLE_ENDIAN); - - d1.set(v); - - Pointer l1 = b.order(ByteOrder.BIG_ENDIAN).as(Long.class); - Pointer l3 = b.order(ByteOrder.LITTLE_ENDIAN).as(Long.class); - - //System.out.println("Ptr ORDER 1 = " + Long.toHexString(l1.get(0))); - //System.out.println("Ptr ORDER 2 = " + Long.toHexString(l3.get(0))); - - assertEquals("d1 = " + d1.get(0) + ", d2 = " + d2.get(0), d1.get(0), d2.get(0), 0.0); - assertTrue("d1 = " + d1.get(0) + ", d3 = " + d3.get(0), d1.get(0) != d3.get(0)); - } - @Test - public void manualTestDoubleEndian() { - - Pointer b = allocateDouble(); - for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) { - b.order(bo).setDouble(10.0); - assertEquals(10.0, b.order(bo).getDoubles(1)[0], 0); - assertEquals(10.0, b.order(bo).getDoubleBuffer().get(0), 0); - } - } - @Test(expected=UnsupportedOperationException.class) - public void noRef() { - allocateBytes(10).getReference(); - } - @Test(expected=UnsupportedOperationException.class) - public void noRemoveIt() { - Iterator it = allocateBytes(10).iterator(); - assertTrue(it.hasNext()); - it.next(); - it.remove(); - } - @Test(expected=RuntimeException.class) - public void untypedGet() { - allocateBytes(10).asUntyped().get(0); - } - - @Test - public void findByte() { - Pointer p = pointerToBytes((byte)1, (byte)2, (byte)3, (byte)4); - assertNotNull(p.findByte(0, (byte)2, 4)); - assertNull(p.findByte(0, (byte)5, 4)); - assertNull(p.findByte(0, (byte)2, 1)); - } - - @Test - public void testAligned() { - Pointer p = allocateInts(2); - assertTrue(p.isAligned()); - assertTrue(!p.offset(1).isAligned()); - assertTrue(!p.offset(2).isAligned()); - assertTrue(p.offset(2).isAligned(2)); - assertTrue(!p.offset(3).isAligned()); - assertTrue(p.offset(4).isAligned()); - } - @Test - public void testExplicitAlignment() { - for (int alignment = 2; alignment < 20; alignment++) { - Pointer p = allocateAlignedArray(int.class, 3, alignment); - assertEquals(0, p.getPeer() % alignment); - p.release(); - } - } - - - - @Test - public void iterate() { - int i = 0; - for (int v : pointerToInts(0, 1, 2, 3, 4)) { - assertEquals(i, v); - i++; - } - } - - @Test - public void basicTest() { - Pointer p = allocateBytes(10); - assertTrue(p == p.offset(0)); - assertEquals(p, p); - - assertTrue(!p.equals(p.offset(1))); - assertEquals(p, p.offset(1).offset(-1)); - - assertEquals(new Long(p.getPeer()).hashCode(), p.hashCode()); - - assertEquals(1, p.compareTo(null)); - assertEquals(-1, p.compareTo(p.offset(1))); - assertEquals(0, p.compareTo(p.offset(1).offset(-1))); - assertEquals(1, p.offset(1).compareTo(p.offset(1).offset(-1))); - - assertTrue(!allocateBytes(10).equals(allocateBytes(10))); - } - - @Test - public void refTest() { - Pointer> pp = allocatePointers(10); - Pointer pa = allocateBytes(5); - pp.set(2, pa); - Pointer p = pp.get(2); - assertEquals(p, pa); - Pointer ref = p.getReference(); - assertNotNull(ref); - assertEquals(pp.offset(2 * Pointer.SIZE), ref); - } - - void testAlignment(int alignment) { - for (long byteSize : new long[] { 1, 2, 3, 4, 5, 10, 130 }) { - Pointer p = allocateAlignedBytes(PointerIO.getIntInstance(), byteSize, alignment, null); - assertTrue(p.isAligned(alignment)); - if (alignment > 1) - assertTrue((((int)p.getPeer()) % alignment) == 0); - assertEquals(byteSize, p.getValidBytes()); - } - } - -#foreach ($align in [0, 1, 2, 4, 8, 16, 32, 64]) - @Test - public void testAlignment${align}() { - testAlignment($align); - } -#end - @Test - public void testDefaultAlignment() { - testAlignment(-1); - } - -#macro (testString $string $eltWrapper) - @Test - public void test${string}String() { - String s = "Hello, World !"; - Pointer<$eltWrapper> p = pointerTo${string}String(s); - assertEquals(s, p.get${string}String()); - } -#end -#testString("C", "Byte") -#testString("WideC", "Character") - - @Test - public void testStrings() { - String s = "Hello, World !"; - String s2 = "Hello you !"; - Charset charset = null; - for (int offset : new int[] { 0, 1, 4, 10 }) { - for (Pointer.StringType type : Pointer.StringType.values()) { - if (!type.canCreate) - continue; - - Pointer p = pointerToString(s, type, charset); - assertEquals("Failed alloc / set of string type " + type, s, p.getString(type)); - - p.setString(s2, type); - assertEquals("Failed set / get of string type " + type, s2, p.getString(type)); - } - } - } - - /* - public static native Pointer newString(); - public static native Pointer newWString(); - - public static native void deleteWString(Pointer s); - public static native void appendToWString(Pointer s, Pointer a); - public static native void resizeWString(Pointer s, @Ptr long newSize); - public static native void reserveWString(Pointer s, @Ptr long newCapacity); - public static native Pointer wstringCStr(Pointer s); - - public static native void deleteString(Pointer s); - public static native void appendToString(Pointer s, Pointer a); - public static native void resizeString(Pointer s, @Ptr long newSize); - public static native void reserveString(Pointer s, @Ptr long newCapacity); - public static native Pointer stringCStr(Pointer s); - - @Test - public void stlTestTest() { - //if (true) return; - String s1 = "Test !"; - String s2 = "Test, yeah man ! Test, yeah man 2 ! Test, yeah man 3 !"; - Pointer p = newString(); - System.err.println("Created new string : " + p); - appendToString(p, pointerToCString(s1)); - assertEquals(s1, stringCStr(p).getCString()); - System.out.println("Created string just fine !"); - - resizeString(p, 0); - appendToString(p, pointerToCString(s2)); - assertEquals(s2, stringCStr(p).getCString()); - } - */ - -#foreach ($prim in $bridJPrimitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - - @Test - public void testAllocateArrayPrim_${prim.Name}() { - for (int type = 0; type < 4; type++) { - Pointer ptr = null; - switch (type) { - case 0: - ptr = Pointer.allocate${prim.CapName}(); - break; - case 1: - ptr = Pointer.allocate${prim.CapName}s(2); - break; - case 2: - ptr = Pointer.allocateArray(${prim.Name}.class, 2); - break; - case 3: - ptr = Pointer.allocateArray(${prim.WrapperName}.class, 2); - break; - }; - assertTrue("approach " + type + " failed", ptr.getIO() == (PointerIO)PointerIO.get${prim.CapName}Instance()); - assertTrue("approach " + type + " failed", ptr.getIO() == (PointerIO)PointerIO.getInstance(${prim.Name}.class)); - } - } -#end - - Pointer someUntypedPtr() { - Pointer p = allocateInt(); - return pointerToAddress(p.getPeer()); - } - @Test(expected=RuntimeException.class) - public void testUntypedSize() { - someUntypedPtr().getTargetSize(); - } - @Test(expected=RuntimeException.class) - public void testUntypedNext() { - someUntypedPtr().next(); - } - @Test(expected=RuntimeException.class) - public void testUntypedGetArray() { - someUntypedPtr().getArray(); - } - @Test(expected=RuntimeException.class) - public void testUntypedGetBuffer() { - someUntypedPtr().getBuffer(); - } - - @Test - public void testPointerToNulls() { - assertEquals(0, getPeer(null)); - assertEquals(null, allocateBytes(null, 0, null)); - assertEquals(null, allocateArray(int.class, 0)); - assertEquals(null, pointerToAddress(0)); - assertEquals(null, pointerToArray(null)); - assertEquals(null, pointerToBuffer(null)); - -#foreach ($prim in $bridJPrimitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - { - assertTrue(pointerTo${prim.CapName}s((${prim.Name}[])null) == null); -#if ($prim.Name == "SizeT" || $prim.Name == "CLong") - assertTrue(pointerTo${prim.CapName}s((int[])null) == null); - assertTrue(pointerTo${prim.CapName}s((long[])null) == null); -#end - } -#end -#foreach ($prim in $primitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - { - // TODO implement 2D and 3D arrays for CLong, SizeT ! - assertTrue(pointerTo${prim.CapName}s((${prim.Name}[][])null) == null); - assertTrue(pointerTo${prim.CapName}s((${prim.Name}[][][])null) == null); - } -#end -#foreach ($prim in $primitivesNoBool) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - { - assertTrue(pointerTo${prim.CapName}s((${prim.BufferName})null) == null); - } -#end - } - - @Test - public void testSignedIntegrals() { - long value = 124; - for (int sizeof : new int[] { 1, 2, 4, 8 }) { - Pointer p = allocateBytes(sizeof); - p.setSignedIntegralAtOffset(0, value, sizeof); - assertEquals(value, p.getSignedIntegralAtOffset(0, sizeof)); - } - } - - @Test(expected = RuntimeException.class) - public void testUpdateDifferentDirectBuffer() { - ByteBuffer b = ByteBuffer.allocateDirect(4); - Pointer p = pointerToBytes(b); - p.updateBuffer(ByteBuffer.allocateDirect(4)); - } - @Test(expected = RuntimeException.class) - public void testUpdateDirectBufferOnNonBufferBoundPointer() { - allocateInt().updateBuffer(ByteBuffer.allocateDirect(4)); - } - -#foreach ($prim in $bridJPrimitives) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - -#if ($prim.Name == "double" || $prim.Name == "float") -#set ($precisionArg = ", (" + $prim.Name + ")0.00001") -#else -#set ($precisionArg = "") -#end - -#if ($prim.Name != "SizeT" && $prim.Name != "CLong" && $prim.Name != "Pointer" && $prim.Name != "boolean" && $prim.Name != "char") - - - @Test - public void testCopy${prim.CapName}s() { - $prim.Name - zero = ${prim.value("0")}, - one = ${prim.value("1")}, - two = ${prim.value("2")}, - three = ${prim.value("3")}; - - Pointer<${prim.WrapperName}> src = pointerTo${prim.CapName}s(one, two, three); - Pointer<${prim.WrapperName}> dest = allocate${prim.CapName}s(4); - - dest.clearValidBytes(); - src.copyTo(dest, 1); - assertEquals(one, (${prim.Name})dest.get(0)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(1)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(2)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(3)$precisionArg); - - dest.clearValidBytes(); - src.copyTo(dest, 2); - assertEquals(one, (${prim.Name})dest.get(0)$precisionArg); - assertEquals(two, (${prim.Name})dest.get(1)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(2)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(3)$precisionArg); - - dest.clearValidBytes(); - src.copyTo(dest); - assertEquals(one, (${prim.Name})dest.get(0)$precisionArg); - assertEquals(two, (${prim.Name})dest.get(1)$precisionArg); - assertEquals(three, (${prim.Name})dest.get(2)$precisionArg); - assertEquals(zero, (${prim.Name})dest.get(3)$precisionArg); - } - - @Test - public void test${prim.BufferName}Update() { - // Non-direct buffer - ${prim.BufferName} b = ${prim.BufferName}.allocate(1); - Pointer< ${prim.WrapperName}> p = pointerTo${prim.CapName}s(b); - for (${prim.Name} value : new ${prim.Name}[] { ${prim.value($v1)}, ${prim.value($v2)}, ${prim.value($v3)} }) { - p.set(value); - assertEquals(value, (${prim.Name})p.get()$precisionArg); - p.updateBuffer(b); - assertEquals(value, b.get(0)$precisionArg); - } - } - - @Test(expected = IllegalArgumentException.class) - public void testIllegal${prim.BufferName}() { - allocate${prim.CapName}().set${prim.CapName}sAtOffset(0, (${prim.BufferName})null, 0, 0); - } - @Test - public void setBufferSet${prim.CapName}s() { - for (${prim.Name} value : new ${prim.Name}[] { ${prim.value("-1")}, ${prim.value("-2")}, ${prim.value("0")}, ${prim.value($v1)} }) { - //for (${prim.Name} value : new ${prim.Name}[] { ${prim.value($v1)}, ${prim.value($v2)}, ${prim.value($v3)} }) { - Pointer<${prim.WrapperName}> p = allocateBytes(${primSize}).as(${prim.WrapperName}.class); - ByteBuffer bb = ByteBuffer.allocateDirect(${primSize}).order(ByteOrder.nativeOrder()); - assertEquals(bb.order(), p.order()); - bb = bb.order(ByteOrder.LITTLE_ENDIAN); - ${prim.BufferName} b; - #if ($prim.Name == "byte") - b = bb; - #else - b = bb.as${prim.BufferName}(); - #end - b.put(0, value); - p.set${prim.CapName}s(b); - ${prim.BufferName} b2 = p.get${prim.BufferName}(); - ${prim.Name} gotBuf = b2.get(0), gotPtr = p.get(); - assertEquals(value, gotBuf$precisionArg); - assertEquals(value, gotPtr$precisionArg); - } - } - -#end - -#if ($prim.Name == "SizeT" || $prim.Name == "CLong") -#set ($rawType = "long") -#set ($rawCapName = "Long") -#else -#set ($rawType = $prim.Name) -#set ($rawCapName = $prim.CapName) -#end - - static ${prim.Name}[] createExpected${prim.CapName}s(int n) { - ${prim.Name}[] expected = new ${prim.Name}[n]; - expected[0] = ${prim.value($v1)}; - expected[1] = ${prim.value($v2)}; - expected[2] = ${prim.value($v3)}; - //for (int i = 0; i < n; i++) - // expected[i] = (${prim.Name})(i + 1); - return expected; - } - - @Test - public void test${prim.CapName}sIterator() { - ${prim.Name}[] expected = createExpected${prim.CapName}s(n); - Pointer<${prim.typeRef}> p = Pointer.pointerTo${prim.CapName}s(expected); - long peer = p.getPeer(); - - Iterator<${prim.typeRef}> it = p.iterator(); - for (int i = 0; i < n; i++) { - assertTrue(it.hasNext()); - ${prim.typeRef} obVal = it.next(); - assertNotNull(obVal); - ${prim.Name} val = obVal; - assertEquals("at position i = " + i, (Object)expected[i], (Object)val); - } - assertTrue(!it.hasNext()); - } - - - @Test - public void testPointerTo_${prim.Name}_Values() { - // Test pointerToInts(int...) - Pointer<${prim.typeRef}> p = Pointer.pointerTo${prim.CapName}s(${prim.value($v1)}, ${prim.value($v2)}, ${prim.value($v3)}); - assertEquals(${prim.value($v1)}, (${prim.Name})p.get(0)$precisionArg); - assertEquals(${prim.value($v2)}, (${prim.Name})p.get(1)$precisionArg); - assertEquals(${prim.value($v3)}, (${prim.Name})p.get(2)$precisionArg); - - p = Pointer.pointerTo${prim.CapName}s(${prim.rawValue($v1)}, ${prim.rawValue($v2)}, ${prim.rawValue($v3)}); - assertEquals(${prim.rawValue($v1)}, p.get${prim.CapName}AtOffset(0 * ${primSize})$precisionArg); - assertEquals(${prim.rawValue($v2)}, p.get${prim.CapName}AtOffset(1 * ${primSize})$precisionArg); - assertEquals(${prim.rawValue($v3)}, p.get${prim.CapName}AtOffset(2 * ${primSize})$precisionArg); - assertEquals(${prim.rawValue($v1)}, p.get${prim.CapName}AtIndex(0)$precisionArg); - assertEquals(${prim.rawValue($v2)}, p.get${prim.CapName}AtIndex(1)$precisionArg); - assertEquals(${prim.rawValue($v3)}, p.get${prim.CapName}AtIndex(2)$precisionArg); - - $rawType[] arr = p.get${prim.CapName}s(); - assertEquals(${prim.rawValue($v1)}, arr[0]$precisionArg); - assertEquals(${prim.rawValue($v2)}, arr[1]$precisionArg); - assertEquals(${prim.rawValue($v3)}, arr[2]$precisionArg); - - } - @Test - public void testPointerTo_${prim.Name}_Value() { - Pointer<${prim.typeRef}> p = Pointer.pointerTo${prim.CapName}(${prim.value($v1)}); - assertEquals(${prim.value($v1)}, (${prim.Name})p.get(0)$precisionArg); - - p = Pointer.pointerTo${prim.CapName}(${prim.rawValue($v1)}); - assertEquals(${prim.rawValue($v1)}, p.get${prim.CapName}()$precisionArg); - } - - - @Test - public void testGet${prim.CapName}s() { - - for (int type = 0; type <= 5; type++) { - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}s(n); - $rawType[] expected = createExpected${rawCapName}s(n); - $rawType[] values = null; - - switch (type) { - case 0: - p.set${prim.CapName}s(expected); - values = p.get${prim.CapName}s(); - break; - case 1: - p.set${prim.CapName}sAtOffset(0, expected); - values = p.get${prim.CapName}s(); - break; - case 2: - p.set${prim.CapName}sAtOffset(0, expected, 0, expected.length); - values = p.get${prim.CapName}sAtOffset(0, expected.length); - break; - case 3: - values = new $rawType[n]; - for (int i = 0; i < n; i++) { -#if ($prim.Name == "SizeT" || $prim.Name == "CLong") - p.set(i, new ${prim.Name}(expected[i])); - values[i] = p.get(i).longValue(); -#else - p.set(i, expected[i]); - values[i] = p.get(i); -#end - } - break; - case 4: - values = new $rawType[n]; - for (int i = 0; i < n; i++) { - p.set${prim.CapName}AtOffset(i * ${primSize}, expected[i]); - values[i] = p.get${prim.CapName}AtOffset(i * ${primSize}); - } - break; - case 5: - values = new $rawType[n]; - for (int i = 0; i < n; i++) { - p.set${prim.CapName}AtIndex(i, expected[i]); - values[i] = p.get${prim.CapName}AtIndex(i); - } - break; - } - assertNotNull(values); - assertEquals("approach " + type + " failed", expected.length, values.length); - for (int i = 0; i < n; i++) { - assertEquals("approach " + type + " failed", expected[i], values[i]$precisionArg); - } - } - } - - #foreach ($order in [ "LITTLE_ENDIAN", "BIG_ENDIAN"]) - @Test - public void simpleSetGet${prim.CapName}s_$order() { - Pointer<${prim.typeRef}> p = allocate${prim.CapName}s(3).order(ByteOrder.$order); - - p.set(2, ${prim.value($v3)}); - assertEquals(${prim.value($v3)}, (${prim.Name})p.get(2)$precisionArg); - - p.set${prim.CapName}(${prim.value($v1)}); - assertEquals(${prim.rawValue($v1)}, ($rawType)p.get${prim.CapName}()$precisionArg); - - p.set${prim.CapName}AtOffset(${primSize}, ${prim.value("-2")}); - assertEquals(${prim.rawValue("-2")}, ($rawType)p.get${prim.CapName}AtOffset(${primSize})$precisionArg); - - p.set${prim.CapName}sAtOffset(${primSize}, new ${prim.Name}[] { ${prim.value("5")}, ${prim.value("6")} }); - assertEquals(${prim.value("5")}, (${prim.Name})p.get(1)$precisionArg); - assertEquals(${prim.value("6")}, (${prim.Name})p.get(2)$precisionArg); - $rawType[] a = p.get${prim.CapName}sAtOffset(${primSize}, 2); - assertEquals(2, a.length); - assertEquals(${prim.rawValue("5")}, a[0]$precisionArg); - assertEquals(${prim.rawValue("6")}, a[1]$precisionArg); - } - #end - - @Test - public void testPointerToArray_${prim.Name}() { - ${prim.Name}[] original = new ${prim.Name}[] { ${prim.value($v1)}, ${prim.value($v2)}, ${prim.value($v3)} }; - Pointer<${prim.typeRef}> p = pointerToArray(original); - assertEquals(3, p.getValidElements()); - assertEquals(${prim.value($v1)}, (${prim.Name})p.get(0)$precisionArg); - assertEquals(${prim.value($v2)}, (${prim.Name})p.get(1)$precisionArg); - assertEquals(${prim.value($v3)}, (${prim.Name})p.get(2)$precisionArg); - - ${prim.Name}[] values = (${prim.Name}[])p.getArray(); - assertEquals(original.length, values.length); - for (int i = 0; i < original.length; i++) - assertEquals(original[i], values[i]$precisionArg); - } - -#end - -#foreach ($prim in $primitivesNoBool) -#if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end - -#if ($prim.Name == "double" || $prim.Name == "float") -#set ($precisionArg = ", 0") -#else -#set ($precisionArg = "") -#end - - @Test - public void testAllocateBounds_${prim.Name}_ok() { - assertEquals(${prim.value("0")}, (${prim.Name})Pointer.allocate${prim.CapName}().get(0)$precisionArg); - assertEquals(${prim.value("0")}, (${prim.Name})Pointer.allocate${prim.CapName}s(1).get(0)$precisionArg); - assertEquals(${prim.value("0")}, (${prim.Name})Pointer.allocate${prim.CapName}s(2).offset(${primSize}).get(-1)$precisionArg); - - //TODO slide, slideBytes - } - - //@Test(expected=UnsupportedOperationException.class) - public void testPointerTo_${prim.Name}_IndirectBuffer() { - ${prim.BufferName} b = ${prim.BufferName}.wrap(new ${prim.Name}[3]); - b.put(0, ${prim.value($v1)}); - b.put(1, ${prim.value($v2)}); - b.put(2, ${prim.value($v3)}); - - Pointer<${prim.typeRef}> p; - - for (boolean generic : new boolean[] { false, true }) { - if (generic) - p = (Pointer<${prim.typeRef}>)Pointer.pointerToBuffer(b); - else - p = Pointer.pointerTo${prim.CapName}s(b); - - assertEquals(3 * ${primSize}, p.getValidBytes()); - assertEquals(${prim.value($v1)}, (${prim.Name})p.get(0)$precisionArg); - assertEquals(${prim.value($v2)}, (${prim.Name})p.get(1)$precisionArg); - assertEquals(${prim.value($v3)}, (${prim.Name})p.get(2)$precisionArg); - } - - p = (Pointer<${prim.typeRef}>)Pointer.pointerToBuffer(b); - - p.set(1, ${prim.value("22")}); - p.updateBuffer(b); - assertEquals(${prim.value("22")}, (${prim.Name})b.get(1)$precisionArg); - } - - #if ($prim.Name != "char") - - @Test - public void testGet${prim.BufferName}s() { - for (int type = 0; type < 6; type++) { - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}s(n); - ${prim.Name}[] expected = createExpected${prim.CapName}s(n); - ${prim.BufferName} buf = ${prim.BufferName}.wrap(expected); - ${prim.BufferName} values = null; - - switch (type) { - case 0: - p.setValues(buf); - values = (${prim.BufferName})p.getBuffer(); - break; - case 1: - p.setValuesAtOffset(0, buf); - values = (${prim.BufferName})p.getBuffer(); - break; - case 2: - p.setValuesAtOffset(0, buf, 0, n); - values = (${prim.BufferName})p.getBufferAtOffset(0, n); - break; - case 3: - p.set${prim.CapName}s(buf); - values = p.get${prim.BufferName}(); - break; - case 4: - p.set${prim.CapName}sAtOffset(0, buf); - values = p.get${prim.BufferName}(); - break; - case 5: - p.set${prim.CapName}sAtOffset(0, buf, 0, n); - values = p.get${prim.BufferName}AtOffset(0, n); - break; - } - assertEquals("approach " + type + " failed", n, values.capacity()); - - for (int i = 0; i < n; i++) { - assertEquals("approach " + type + " failed", expected[i], values.get(i)$precisionArg); - } - } - } - - @Test - public void testPointerTo_${prim.Name}_DirectBuffer() { - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}s(3); - assertEquals(3 * ${primSize}, p.getValidBytes()); - p.set(0, ${prim.value($v1)}); - p.set(1, ${prim.value($v2)}); - p.set(2, ${prim.value($v3)}); - ${prim.BufferName} b = p.get${prim.BufferName}(); - assertEquals(3, b.capacity()); - - for (boolean generic : new boolean[] { false, true }) { - if (generic) - p = (Pointer<${prim.typeRef}>)Pointer.pointerToBuffer(b); - else - p = Pointer.pointerTo${prim.CapName}s(b); - - assertEquals(3 * ${primSize}, p.getValidBytes()); - assertEquals(${prim.value($v1)}, (${prim.Name})p.get(0)$precisionArg); - assertEquals(${prim.value($v2)}, (${prim.Name})p.get(1)$precisionArg); - assertEquals(${prim.value($v3)}, (${prim.Name})p.get(2)$precisionArg); - } - } - #end - - public void testPointerTo_${prim.Name}_Values2D(${prim.Name}[][] values, Pointer> p, int dim1, int dim2) { - for (int i = 0; i < dim1; i++) - for (int j = 0; j < dim2; j++) - assertEquals(values[i][j], (${prim.Name})p.get(i).get(j)$precisionArg); - } - @Test - public void testPointerTo_${prim.Name}_Values2D() { - ${prim.Name}[][] values = new ${prim.Name}[][] { - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}} - }; - Pointer> p = Pointer.pointerTo${prim.CapName}s(values); - int dim1 = values.length; - int dim2 = values[0].length; - testPointerTo_${prim.Name}_Values2D(values, p, dim1, dim2); - - Pointer> p2 = allocate${prim.CapName}s(dim1, dim2); - p.copyTo(p2); - testPointerTo_${prim.Name}_Values2D(values, p2, dim1, dim2); - } - - @Test - public void testPointerTo_${prim.Name}_Values3D() { - ${prim.Name}[][][] values = new ${prim.Name}[][][] { - { - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}} - }, - { - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}}, - {${prim.value($v1)}, ${prim.value($v2)}} - } - }; - Pointer>> ppp = Pointer.pointerTo${prim.CapName}s(values); - int dim1 = values.length; - int dim2 = values[0].length; - int dim3 = values[0][0].length; - - int subSize = dim2 * dim3 * ${primSize}; - for (int i = 0; i < dim1; i++) { - for (int j = 0; j < dim2; j++) { - for (int k = 0; k < dim3; k++) { - Object o = values[i][j][k]; - //System.out.println(o); - - Pointer> pp = ppp.get(i); - assertEquals(i * subSize, pp.getPeer() - ppp.getPeer()); - - Pointer<${prim.typeRef}> p = pp.get(j); - ${prim.Name} value = p.get(k); - ${prim.Name} expected = values[i][j][k]; - - //System.out.println("ppp.get(i) = " + pp); - //System.out.println("ppp.get(i).get(j) = " + p); - //System.out.println("ppp.get(i).get(j).get(k) = " + value); - assertEquals("expected " + expected + ", got " + value + " (i = " + i + ", j = " + j + ", k = " + k + ")", expected, value$precisionArg); - } - } - } - } - - @Test - public void testAllocateRemaining_${prim.Name}_ok() { - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}s(2); - assertEquals(2, p.getValidElements()); - assertEquals(2 * ${primSize}, p.getValidBytes()); - - Pointer<${prim.typeRef}> n = p.next(); - Pointer<${prim.typeRef}> o = p.offset(${primSize}); - assertEquals(n, o); - - assertEquals(1, n.getValidElements()); - assertEquals(${primSize}, n.getValidBytes()); - assertEquals(1, o.getValidElements()); - assertEquals(${primSize}, o.getValidBytes()); - - //TODO slide, slideBytes - } - - @Test(expected=IndexOutOfBoundsException.class) - public void testAllocateBounds_${prim.Name}_failAfter() { - Pointer.allocate${prim.CapName}().get(1); - } - @Test(expected=IndexOutOfBoundsException.class) - public void testAllocateBounds_${prim.Name}_failBefore() throws IndexOutOfBoundsException { - Pointer.allocate${prim.CapName}().get(-1); - } - - - @Test - public void test${prim.CapName}Order() { - for (ByteOrder order : orders) { - boolean isOrdered = order.equals(ByteOrder.nativeOrder()); - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}().order(order); - assertEquals(order, p.order()); - assertEquals(isOrdered, p.isOrdered()); - } - } - #if (($prim.Name == "short") || ($prim.Name == "int") || ($prim.Name == "long") || ($prim.Name == "double") || ($prim.Name == "float")) - - #foreach ($order in [ "LITTLE_ENDIAN", "BIG_ENDIAN"]) - - @Test - public void test${prim.CapName}_Endianness_$order() { - for (${prim.Name} value : new ${prim.Name}[] { ${prim.value($v1)}, ${prim.value("-1")}, ${prim.value("-2")}, ${prim.value("0")} }) { - Pointer<${prim.typeRef}> p = Pointer.allocate${prim.CapName}().order(ByteOrder.$order); - p.set(value); - assertEquals(ByteOrder.$order, p.order()); - assertEquals(ByteOrder.$order, p.get${prim.BufferName}AtOffset(0, 1).order()); - assertEquals((${prim.Name})p.get${prim.BufferName}AtOffset(0, 1).get(), p.getByteBufferAtOffset(0, ${primSize}).order(ByteOrder.$order).as${prim.BufferName}().get()$precisionArg); // always true (?) : NIO consistency - - assertEquals(value, (${prim.Name})p.get${prim.BufferName}AtOffset(0, 1).get()$precisionArg); // check that the NIO buffer was created with the correct order by default - assertEquals(value, p.getByteBufferAtOffset(0, ${primSize}).order(ByteOrder.$order).as${prim.BufferName}().get()$precisionArg); - } - } - #end - #end -#end -} diff --git a/libraries/DirectX/pom.xml b/libraries/DirectX/pom.xml index a60349703..3b98d82ff 100644 --- a/libraries/DirectX/pom.xml +++ b/libraries/DirectX/pom.xml @@ -5,14 +5,14 @@ directx4java DirectX4Java http://code.google.com/p/nativelibs4java/wiki/DirectX - 0.2-SNAPSHOT + 0.2 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/FFMpeg/pom.xml b/libraries/FFMpeg/pom.xml index b6346080f..0fad57135 100644 --- a/libraries/FFMpeg/pom.xml +++ b/libraries/FFMpeg/pom.xml @@ -5,14 +5,14 @@ ffmpeg4java FFMpeg4Java http://code.google.com/p/nativelibs4java/wiki/FFMpeg - 0.2-SNAPSHOT + 0.2 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/IdleTime/pom.xml b/libraries/IdleTime/pom.xml index 5b777bb97..d07b07dba 100644 --- a/libraries/IdleTime/pom.xml +++ b/libraries/IdleTime/pom.xml @@ -6,14 +6,14 @@ http://code.google.com/p/nativelibs4java/wiki/Runtime com.nativelibs4java idletime - 0.7-SNAPSHOT + 0.7 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/InteropIntegration/VersionSpecificBridJ/pom.xml b/libraries/InteropIntegration/VersionSpecificBridJ/pom.xml index ee2211a7f..faf29db52 100644 --- a/libraries/InteropIntegration/VersionSpecificBridJ/pom.xml +++ b/libraries/InteropIntegration/VersionSpecificBridJ/pom.xml @@ -4,21 +4,21 @@ com.nativelibs4java bridj-version-specific-tests BridJ Version-Specific Tests - 0.6.2-SNAPSHOT + 0.7.0 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - ../.. + 1.9 + ../../.. com.nativelibs4java bridj - 0.6.2-SNAPSHOT + 0.7.0 version-specific-packages diff --git a/libraries/InteropIntegration/pom.xml b/libraries/InteropIntegration/pom.xml index fe53d32ef..b82893afa 100644 --- a/libraries/InteropIntegration/pom.xml +++ b/libraries/InteropIntegration/pom.xml @@ -5,13 +5,13 @@ interop-integration-root pom Interop Integration Root - 0.6.2-SNAPSHOT + 0.7 com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/JarShrinker/pom.xml b/libraries/JarShrinker/pom.xml index d89248098..be06e1aa6 100644 --- a/libraries/JarShrinker/pom.xml +++ b/libraries/JarShrinker/pom.xml @@ -6,7 +6,7 @@ jarshrinker JarShrinker http://code.google.com/p/nativelibs4java/wiki/Runtime - 0.7-SNAPSHOT + 0.7 jar @@ -17,8 +17,8 @@ com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/Mono/Mono4Java/pom.xml b/libraries/Mono/Mono4Java/pom.xml index d1f8a7d04..eaaab2d6b 100644 --- a/libraries/Mono/Mono4Java/pom.xml +++ b/libraries/Mono/Mono4Java/pom.xml @@ -6,13 +6,13 @@ mono4java Mono4Java http://code.google.com/p/nativelibs4java/wiki/Mono - 0.2-SNAPSHOT + 0.2 jar com.nativelibs4java mono4java-parent - 0.2-SNAPSHOT + 0.2 .. diff --git a/libraries/Mono/pom.xml b/libraries/Mono/pom.xml index 68c0858cf..11311b85d 100644 --- a/libraries/Mono/pom.xml +++ b/libraries/Mono/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.nativelibs4java mono4java-parent - 0.2-SNAPSHOT + 0.2 pom Mono4Java Common Configuration 2009 @@ -12,8 +12,8 @@ com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. diff --git a/libraries/OpenCL-JNA/.gitignore b/libraries/OpenCL-JNA/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL-JNA/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9c0c21ef3..000000000 --- a/libraries/OpenCL-JNA/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:24 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL-JNA/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL-JNA/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 09e51cf49..000000000 --- a/libraries/OpenCL-JNA/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Sat Jan 30 11:48:04 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL-JNA/CHANGELOG b/libraries/OpenCL-JNA/CHANGELOG deleted file mode 100644 index a54e56c70..000000000 --- a/libraries/OpenCL-JNA/CHANGELOG +++ /dev/null @@ -1,157 +0,0 @@ -For future changes, please see CHANGELOG of JavaCL / BridJ version. - -Version 1.0.0-RC1 (r2130, 20110621) - -- BridJ version now becomes the default : the JNA version is still maintained and available with all Maven artifact ids suffixed with "-jna" (BridJ-based JavaCL's main artifact is now "javacl", while the JNA-based version is "javacl-jna") -- added simple Fourier-analysis classes (package com.nativelibs4java.opencl.util.fft), with double and float variants, usable with primitive arrays or OpenCL buffers : - - naive Discrete Fourier Transform (DFT) - - Fast Fourier Transform (FFT) for power-of-two arrays / buffers (performs better than Apache Commons on a CPU) -- added some compiler options to CLProgram : - - setFastRelaxedMath() (triggers all the others !) - - setFiniteMathOnly() - - setUnsafeMathOptimizations() - - setMadEnable() - - setNoSignedZero() -- added CLContext.createBuffer(Usage, Buffer) -- added CLBuffer.copyTo(CLQueue, CLMem destination, CLEvent...) and CLBuffer.emptyClone(Usage) -- added NIOUtils.indirectBuffer(size, bufferClass) -- added CLContext.toString -- deprecated CLXXXBuffer in favor of CLBuffer (CLIntBuffer becomes CLBuffer, etc...) -- changed CLContext.createBuffer(Usage, length, class) to createBuffer(Usage, class, length) to match the JavaCL/BridJ API (and provoke migration issues : people should now use a primitive class rather than an NIO buffer class !!! -- complete rewrite of CLBuffer genericity to unify with the BridJ port : CLBuffer is now CLBuffer, and CLBuffer.read/write/map are no longer strongly typed (it is implicitely typed with Buffer subclasses for compatibility with existing code). The BridJ port will be favoured, and its read/write/map methods use typed Pointer. -- complete rewrite of UJMP Matrix implementation, using principles borrowed from ScalaCL -- fixed issue #66 (create temp files in ~/.javacl subdirectories instead of /tmp) -- fixed OpenGL sharing on MacOS X -- fixed CLProgram.getBinaries() in some cases -- fixed CLBuffer.read on indirect buffers -- fixed NPE that happens with null varargs CLEvent[] array -- fixed length = 1 case in reduction utility -- fixed ATI detection ("ATI Stream" now replaced by "AMD Accelerated Parallel Processing", cf. Csaba's comment in issue #39) -- fixed issue #55 : applied Kazo Csaba's patch to fix the bounds of CLBuffer.map's returned buffer -- fixed inheritance of CLBuildException (now derives from CLException) - -Version 1.0-beta-6 (r1637, 20100204) - -- Fixed support of ATI Stream 2.3 (CPU) -- New interactive image kernel demo : lets you edit and test image kernels in a snap (bundled with a few samples) -- Experimental BridJ port with same functionality as JNA-powered version, but smaller and faster (JAR weighs 750 kB instead of 1.8 MB, overhead per-function call about 10x smaller) -- Added automatic and transparent program binaries caching : - - Disabled by default on ATI Stream. - - Can force on/off with : - - property -Djavacl.cacheBinaries=true/false - - environment variable JAVACL_CACHE_BINARIES=1/0 - - methods CLContext.setCacheBinaries and CLProgram.setCached -- JavaCL.createBestContext now takes an ordered list of CLPlatform.DeviceFeature enums that help prioritize the features considered as "best" (list can be empty or contain any of CPU, GPU, DoubleSupport, MaxComputeUnits, NativeEndianness, ImageSupport, MostImageFormats...). These features are preferences, not requirements : with createBestContext(GPU, MaxComputeUnits) you might end up getting a CPU-based context if there's no GPU available, but you'll have the most powerful GPU (in terms of compute units) if there are two of them. -- Kernels can now include files that are in the classpath (+ added CLProgram.addInclude that accepts directories and base URLs) -- Added LibCL : growing collection of OpenCL functions that can be included from any JavaCL kernel -- CLKernel.enqueueNDRange has a new overload without localWorkSizes argument (it's then adjusted to a good value by the OpenCL implementation). -- ScalaCLv2 was rewritten to fit nicely into Scala's collections framework. -- Added CLContext.createProgram(Map) to create from saved binaries (contribution from Kazo Csaba, issue #30) -- Added CLProgram.addBuildOption(String) -- Fixed CLBuffer.copyTo -- Demos now use the latest jogamp JOGL binaries (see the updated build instructions : http://code.google.com/p/javacl/wiki/Build) - -Version 1.0-beta-5 (r1067, 20100717) - -- Now using a nice configuration dialog when launching ParticlesDemo : has -optional OpenCL settings with "Fastest", "Normal" and "Safest" presets + -detailed platform and device choice (with optional OpenGL sharing choice). -- Added optional context properties map argument to JavaCL.createContext (can be nulled -out) -- Fixed issue #18: CLImage.write calls enqueueImageRead ! -- Documented workaround for Linux crashes (issue #20) : http://code.google.com/p/javacl/wiki/TroubleShootingJavaCLOnLinux -- Fixed issue #21: NIOUtils.put() doesn't accept ByteBuffer -- Fixed issue #25: CLEvent.waitFor bug causes segfault -- OpenCL 1.1 support : - - CLContext.createUserEvent() - - CLUserEvent.setStatus(int), setCompleted() - - CLEvent.setCallback(status, callbac), setCompletionCallback(callback) - - CLBuffer.createSubBuffer(usage, offset, length) - - CLContext.getDeviceCount() - - CLDevice.getOpenCLVersion() - - CLDevice.isHostUnifiedMemory() - - CLDevice.getNativeVectorWidthXXX() methods - - CLMem.setDestructorCallback(callback) - - CLKernel.getPreferredWorkGroupSizeMultiple() - - CLKernel.enqueueNDRange overload with potentially non-null globalOffsets - - CLImageFormat.ChannelOrder.Rx, RGx, RGBx -- Faster enums -- Check for cl_amd_fp64 in CLDevice.isDoubleSupported() -- Fixed CLProgram.getBinaries() -- Fixed issue #22 (maven pom issue) - -Version 1.0-beta-4 (r760, 20100121) - -- Changed semantics of offset & length arguments in typed CLxxxBuffer.read / write / map methods : now expressed in elements, not in bytes (e.g. 4 bytes per element for CLIntBuffer) -- Added OpenGL interoperability methods to CLContext and CLQueue (can create a CLByteBuffer from an OpenGL buffer object, a CLImage2D/3D from an OpenGL 2D/3D texture or a renderbuffer). -- Added OpenGL-compatible context creation methods to JavaCL & CLPlatform classes -- Added basic reduction support in ReductionUtils (cumulative additions, multiplications, min, max...) -- Created javacl-demos package, with Particles, Hardware Report and Mandelbrot demos... -- Finished migration from NativeLong to NativeSize (changes only the low-level bindings) -- Added profiling methods to CLEvent (+ facility CLDevice.createProfilingQueue()) -- Better JavaDoc for low-level bindings (links to Khronos online manual pages) -- Added deferred program allocation : CLProgram.addSource(String), CLProgram.allocate() (called automatically)... -- Added very simple OpenCL backend for UJMP (Universal Java Matrix Package), which does matrix multiplications in OpenCL. -- Created a kernel wrapper autogenerator (Maven plugin based on JNAerator) : translates all constants on the Java side and presents kernels as methods with the correct Java argument types. It assumes OpenCL kernels (*.c, *.cl) are in src/main/opencl -- Added wrappers around clGetKernelWorkGroupInfo -- Fixed respect of endianness of devices that have different endianness than platform -- Fixed issue #10: "getMaxWorkItemSizes() fails on win7 64 GTX260" - -Version 1.0-beta-3 (r , 20091030) - -- Fixed Issue #8 : NativeLong's can not represent size_t on windows x64 system (all user code that uses the low-level bindings needs to be updated : NativeLong -> NativeSize) -- Added CLContext/CLDevice.isDoubleSupported, isHalfSupported, isByteAddressableStoreSupported -- Added If function to ScalaCL (operates on statements or on expressions) -- Added CLAbstractEntity.release() -- Fixed Issue #4 : CLContext.createContext(CLDevice... devices) created context on only one device -- Regenerated the low level bindings with latest JNAerator : now using NativeSize class instead of NativeLong for size_t (fixes Issue #8) -- Fixed Issue #5 : fixed formatting of CLPlatform.toString() -- Fixed Issue #6 : use max X workgroup dimension for better benchmark speed -- Fixed Issue #7 : CLMem class bug in Usage.WriteOnly and Usage.ReadWrite -- Fixed Issue #11 : call clRetainMemObject when sharing a cl_mem between CLBuffer instances. -- Choose 'best' device in benchmark test - -Version 1.0-beta-2 - -- JAR is now self-sufficient (includes JNA + JNAerator's runtime classes) -- Added CLKernel.setLocalArg(argIndex, localArgByteLength) -- Allow localWorkSizes to be null in enqueueNDRange -- Added support for barriers and markers in CLQueue -- Fixed issue #2 : enqueueNDRange does not work for nDim > 1 -- Added CLDevice.getMaxWorkItemSizes() -- CLDevice.toString() now only prints the name -- Moved method createContext from CLContext to CLPlatform -- Added all the CL_DEVICE_PREFERRED_VECTOR_WIDTH_XXX infos to CLDevice as getPreferredVectorWithXXX() -- Changed return type of getExtensions() method of both CLPlatform and CLDevice from String to String[] -- Added com.nativelibs4java.opencl.HardwareReport (with main method) : outputs html report with devices stats -- Rationalized naming of all enums : CL_ENTITY_ATTRIBUTE_SOME_VALUE = CLEntity.Attribute.SomeValue (enum item SomeValue in enum Attribute in class CLEntity) -- Added full support of images : - - CLContext.getSupportedImageFormats + CLImageFormat and associated enums - - CLImage2D, CLImage3D and corresponding creation methods in CLContext + all image info getters -- CLMem is now an abstract base class - - CLBuffer with typed subclasses (CLByteBuffer, CLIntBuffer..) - - To create a CLBuffer : context.createIntBuffer(Input, size) - - Added CLBuffer.copyTo (clEnqueueCopyBuffer) - - Each typed CLBuffer subclass has map, mapLater, read methods that return typed NIO buffers -- Added full typing of OpenCL Exceptions (now possible to selectively catch a CLException.OutOfHostMemory, for instance) -- Added hashCode and equals method to most classes -- Added ability to create out of order queues and change queue properties after creation - -Version 1.0-beta-1 - -- New CLPlatform class (~ OpenCL implementation) which now hosts the list*Devices(...) methods -- Entry point of library is now OpenCL4Java.listPlatforms() -- New CLEvent class, returned by all enqueue* methods (with methods waitFor, invokeUponCompletion...) -- Better separation between blocking and non blocking calls -- New CLSampler class supported as argument of CLKernel -- Many info getters with typesafe enums / enum sets in classes CLDevice, CLPlatform, CLKernel... -- Much more complete JavaDoc : http://nativelibs4java.sourceforge.net/sites/OpenCL4Java/apidocs/ -- Example & benchmark classes became JUnit tests and moved here : http://code.google.com/p/nativelibs4java/source/browse/#svn/trunk/lib... - -While this release is rather OpenCL4Java-focused, ScalaCL also got its bunch of enhancements : -- Added scalar variables IntVar, FloatVar, ShortVar... -- 'local' keyword can be added to variables so they're local to the programs : val x = FloatVar local -- Added many OpenCL math functions -- Added methods ArrayVar.write(Range), ArrayVar.write(Seq) -- Various bugfixes - diff --git a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java b/libraries/OpenCL-JNA/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java deleted file mode 100644 index 33a54c41b..000000000 --- a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.util.NIOUtils.directBuffer; -import java.util.Map; -import static org.junit.Assert.assertEquals; - -import java.nio.IntBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author Kazó Csaba - */ -@SuppressWarnings("unchecked") -public class BinaryKernelTest extends AbstractCommon { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Test - public void simpleTest() throws CLBuildException { - CLProgram program = context.createProgram( - "__kernel void copy(__global int* a, __global int* b) {\n" + - " int i = get_global_id(0);\n" + - " b[i]=a[i];\n" + - "} "); - program.build(); - Map binaries = program.getBinaries(); - program.release(); - - CLProgram binaryProgram = context.createProgram(binaries); - CLKernel kernel=binaryProgram.createKernel("copy"); - - CLIntBuffer a=context.createIntBuffer(CLMem.Usage.Input, 4); - CLIntBuffer b=context.createIntBuffer(CLMem.Usage.Output, 4); - - IntBuffer source = directBuffer(4, context.getByteOrder(), IntBuffer.class); - for (int i=0; i<4; i++) - source.put(i, 3*i+10); - - a.write(queue, source, true); - - kernel.setArgs(a, b); - kernel.enqueueNDRange(queue, new int[]{4}, new int[]{1}).waitFor(); - - IntBuffer target = b.read(queue); - - assertEquals(target.capacity(), source.capacity()); - for (int i=0; i<4; i++) - assertEquals(source.get(i), target.get(i)); - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README b/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README deleted file mode 100644 index b156bfaac..000000000 --- a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README +++ /dev/null @@ -1,8 +0,0 @@ -See http://code.google.com/p/nativelibs4java/issues/detail?id=30 - -kazocsaba's first comment : -<<< -Certainly, I'm happy to contribute the patch under LGPL and BSD. - -Csaba ->>> diff --git a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff b/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff deleted file mode 100644 index 3d25a7389..000000000 --- a/libraries/OpenCL-JNA/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff +++ /dev/null @@ -1,82 +0,0 @@ -Index: OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java -=================================================================== ---- OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java (revision 993) -+++ OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java (working copy) -@@ -64,6 +64,7 @@ - import com.sun.jna.Platform; - import com.sun.jna.Pointer; - import com.sun.jna.ptr.IntByReference; -+import java.util.Map; - - /** - * OpenCL context.
-@@ -189,6 +190,10 @@ - return program; - } - -+ public CLProgram createProgram(Map binaries) { -+ return new CLProgram(this, binaries); -+ } -+ - //cl_queue queue; - @Override - protected void clear() { -Index: OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java -=================================================================== ---- OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java (revision 993) -+++ OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java (working copy) -@@ -47,6 +47,7 @@ - import com.sun.jna.Native; - import com.sun.jna.Pointer; - import com.sun.jna.ptr.IntByReference; -+import com.sun.jna.ptr.PointerByReference; - - /** - * OpenCL program.
-@@ -83,7 +84,30 @@ - this.context = context; - this.devices = devices == null || devices.length == 0 ? context.getDevices() : devices; - } -+ CLProgram(CLContext context, Map binaries) { -+ super(null, true); -+ this.context = context; -+ this.devices = binaries.keySet().toArray(new CLDevice[binaries.size()]); - -+ NativeSize[] lengths = new NativeSize[devices.length]; -+ cl_device_id[] deviceIds = new cl_device_id[devices.length]; -+ String[] binptr=new String[devices.length]; -+ for (int i = 0; i < devices.length; i++) { -+ final byte[] binary = binaries.get(devices[i]); -+ lengths[i] = toNS(binary.length); -+ deviceIds[i] = devices[i].getEntity(); -+ binptr[i]=new String(binary); -+ } -+ -+ IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); -+ cl_program program; -+ int previousAttempts = 0; -+ do { -+ program = CL.clCreateProgramWithBinary(context.getEntity(), devices.length, deviceIds, lengths, binptr, null, errBuff); -+ } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); -+ entity = program; -+ } -+ - List sources = new ArrayList(); - Map programByDevice = new HashMap(); - -Index: OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java -=================================================================== ---- OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java (revision 993) -+++ OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java (working copy) -@@ -595,6 +595,11 @@ - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
- * @see Khronos Documentation for clCreateProgramWithBinary - */ -+ OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSize size_tPtr1[], String[] charPtrPtr1, IntBuffer cl_intPtr1, IntBuffer cl_intPtr2); -+ /** -+ * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
-+ * @see Khronos Documentation for clCreateProgramWithBinary -+ */ - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSizeByReference size_tPtr1, PointerByReference charPtrPtr1, IntByReference cl_intPtr1, IntByReference cl_intPtr2); - /** - * Original signature : cl_int clRetainProgram(cl_program)
diff --git a/libraries/OpenCL-JNA/Core/.classpath b/libraries/OpenCL-JNA/Core/.classpath deleted file mode 100644 index 921941cea..000000000 --- a/libraries/OpenCL-JNA/Core/.classpath +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/.gitignore b/libraries/OpenCL-JNA/Core/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/Core/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/Core/.project b/libraries/OpenCL-JNA/Core/.project deleted file mode 100644 index 8004803d0..000000000 --- a/libraries/OpenCL-JNA/Core/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Core - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL-JNA/Core/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL-JNA/Core/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 45a45b3f0..000000000 --- a/libraries/OpenCL-JNA/Core/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:18 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL-JNA/Core/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL-JNA/Core/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 1a131b4c8..000000000 --- a/libraries/OpenCL-JNA/Core/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:12 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL-JNA/Core/nb-configuration.xml b/libraries/OpenCL-JNA/Core/nb-configuration.xml deleted file mode 100644 index 3486bc9d7..000000000 --- a/libraries/OpenCL-JNA/Core/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - all - - diff --git a/libraries/OpenCL-JNA/Core/nbactions.xml b/libraries/OpenCL-JNA/Core/nbactions.xml deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL-JNA/Core/nbactions.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL-JNA/Core/pom.xml b/libraries/OpenCL-JNA/Core/pom.xml deleted file mode 100644 index 1bdb5e6c2..000000000 --- a/libraries/OpenCL-JNA/Core/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-core-jna - JavaCL Core / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - -JavaCL is an Object-Oriented API that makes the C OpenCL API available to Java in a very natural way. -It hides away the complexity of cross-platform C bindings, has a clean OO design (with generics, Java enums, NIO buffers, fully typed exceptions...), provides high-level features (OpenGL-interop, array reductions) and comes with samples and demos. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - opencl4java-jna - - - - com.nativelibs4java - nativelibs4java-utils - 1.5-SNAPSHOT - compile - - - - - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.4 - - - - - - - - - com.nativelibs4java - maven-velocity-plugin - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractEntity.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractEntity.java deleted file mode 100644 index b7345ec53..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractEntity.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import com.sun.jna.PointerType; - -abstract class CLAbstractEntity { - protected volatile T entity; - private final boolean nullable; - - CLAbstractEntity(T entity) { - this(entity, false); - } - CLAbstractEntity(T entity, boolean nullable) { - if (!nullable && entity == null) { - throw new IllegalArgumentException("Null OpenCL " + getClass().getSimpleName() + " !"); - } - this.nullable = nullable; - this.entity = entity; - } - - /** - * Manual release of the OpenCL resources represented by this object.
- * Note that resources are automatically released by the garbage collector, so in general there's no need to call this method.
- * In an environment with fast allocation/deallocation of large objects, it might be safer to call release() manually, though.
- * Note that release() does not necessarily free the object immediately : OpenCL maintains a reference count for all its objects, and an object released on the Java side might still be pointed to by running kernels or queued operations. - */ - public synchronized void release() { - if (entity == null) { - if (!nullable) - throw new RuntimeException("This " + getClass().getSimpleName() + " has already been released ! Besides, keep in mind that manual release is not necessary, as it will automatically be done by the garbage collector."); - else - return; - } - - doRelease(); - } - - public static > E[] getEntities(A[] objects, E[] out) { - for (int i = 0, len = objects.length; i < len; i++) - out[i] = objects[i].getEntity(); - return out; - } - synchronized T getEntity() { - if (entity == null && !nullable) - throw new RuntimeException("This " + getClass().getSimpleName() + " has been manually released and can't be used anymore !"); - - return entity; - } - - synchronized void doRelease() { - if (entity != null) { - clear(); - entity = null; - } - } - @Override - protected void finalize() throws Throwable { - doRelease(); - } - - protected abstract void clear(); - - /** - * Underyling implementation pointer-based hashCode computation - */ - @Override - public int hashCode() { - return getEntity() == null ? 0 : getEntity().getPointer().hashCode(); - } - - /** - * Underyling implementation pointer-based equality test - */ - @Override - public boolean equals(Object obj) { - if (obj == null || !getClass().isInstance(obj)) - return false; - CLAbstractEntity e = (CLAbstractEntity)obj; - return getEntity().getPointer().equals(e.getEntity().getPointer()); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractUserProgram.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractUserProgram.java deleted file mode 100644 index 3fd1d3e17..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLAbstractUserProgram.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import com.nativelibs4java.util.IOUtils; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.lang.reflect.Array; - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -/** - * - * @author ochafik - */ -public abstract class CLAbstractUserProgram { - - final CLProgram program; - String rawSource; - Map velocityArgs; - //Map kernels; - - volatile boolean addedSources; - - protected Long getSourceChecksum() { - return null; - } - - public CLProgram getProgram() { - return program; - } - - protected void checkArrayLength(Object arr, int length, String argName) { - if (arr == null) - throw new IllegalArgumentException("Argument " + argName + " cannot be null. Expected array of size " + length); - - int len = Array.getLength(arr); - if (len != length) - throw new IllegalArgumentException("Argument " + argName + " must be an array of size " + length + ", but given array of size " + len); - } - protected static String readRawSourceForClass(Class c) throws IOException { - String simpleName = c.getSimpleName(); - - InputStream srcIn = c.getResourceAsStream(simpleName + ".cl"); - try { - if (srcIn == null) - srcIn = c.getResourceAsStream(simpleName + ".c"); - - if (srcIn == null) - throw new FileNotFoundException("OpenCL source code not found : '" + simpleName + "'"); - - return IOUtils.readText(srcIn); - } finally { - if (srcIn != null) - srcIn.close(); - } - } - protected CLAbstractUserProgram(CLProgram program, String rawSource) { - this.program = program; - this.rawSource = rawSource; - } - - protected CLAbstractUserProgram(CLContext context, String rawSource) { - this(context.createProgram(), rawSource); - } - - protected synchronized void addSources() { - if (addedSources) { - return; - } - - String src; - if (velocityArgs != null) { - src = rawSource;//veloTransform(rawSource, velocityArgs); - } else { - src = rawSource; - } - - program.addSource(src); - addedSources = true; - } - - protected void defineMacro(String name, String value) { - if (value == null) { - program.undefineMacro(name); - } else { - program.defineMacro(name, value); - } - } - - protected synchronized CLKernel createKernel(String name) throws CLBuildException { - addSources(); - return program.createKernel(name); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLBuildException.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLBuildException.java deleted file mode 100644 index ef19881e3..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLBuildException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import com.ochafik.util.string.StringUtils; -import java.util.Collection; - -/** - * OpenCL program build exception - * @author ochafik - */ -@SuppressWarnings("serial") -public class CLBuildException extends CLException { - final CLProgram program; - CLBuildException(CLProgram program, String string, Collection errors) { - super(string + "\n" + StringUtils.implode(errors, "\n"), -1); - this.program = program; - } - public CLProgram getProgram() { - return program; - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLByteBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLByteBuffer.java deleted file mode 100644 index b8e7a23a6..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLByteBuffer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object.
- * A buffer object stores a one-dimensional collection of elements.
- * Elements of a buffer object can be a scalar data type (such as an int, float), vector data type, or a user-defined structure.
- * see {@link CLContext#createByteBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createByteBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.Buffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Byte}> - */ -@Deprecated -public class CLByteBuffer extends CLBuffer { - CLByteBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 1, ByteBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLCharBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLCharBuffer.java deleted file mode 100644 index 211e2111d..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLCharBuffer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Character values.
- * see {@link CLContext#createCharBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createCharBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.CharBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Character}> - */ -@Deprecated -public class CLCharBuffer extends CLBuffer { - CLCharBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 2, CharBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDevice.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDevice.java deleted file mode 100644 index 59169610f..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDevice.java +++ /dev/null @@ -1,943 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.sun.jna.*; -import com.sun.jna.ptr.*; -import java.io.IOException; -import java.nio.*; -import static com.nativelibs4java.opencl.JavaCL.*; -import static com.nativelibs4java.util.JNAUtils.*; -import static com.nativelibs4java.util.NIOUtils.*; -import java.util.*; -import static com.nativelibs4java.opencl.CLException.*; -import com.nativelibs4java.util.ValuedEnum; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * OpenCL device (CPU, GPU...).
- * Devices are retrieved from a CLPlatform through - * {@link CLPlatform#listDevices(CLDevice.Type, boolean) }, - * {@link CLPlatform#listAllDevices(boolean) }, - * {@link CLPlatform#listCPUDevices(boolean) }, - * {@link CLPlatform#listGPUDevices(boolean) } - */ -@SuppressWarnings("unused") -public class CLDevice extends CLAbstractEntity { - - private static CLInfoGetter infos = new CLInfoGetter() { - - @Override - protected int getInfo(cl_device_id entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetDeviceInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - volatile CLPlatform platform; - - CLDevice(CLPlatform platform, cl_device_id device) { - super(device); - this.platform = platform; - } - - public synchronized CLPlatform getPlatform() { - if (platform == null) { - Pointer pplat = infos.getPointer(getEntity(), CL_DEVICE_PLATFORM); - platform = new CLPlatform(pplat == null ? null : new cl_platform_id(pplat)); - } - return platform; - } - - @Override - protected void clear() { - } - - public String createSignature() { - return getName() + "|" + getVendor() + "|" + getDriverVersion() + "|" + getProfile(); - } - public static Map> getDevicesBySignature(List devices) { - Map> ret = new HashMap>(); - for (CLDevice device : devices) { - String signature = device.createSignature(); - List list = ret.get(signature); - if (list == null) - ret.put(signature, list = new ArrayList()); - list.add(device); - } - return ret; - } - - - private volatile ByteOrder byteOrder; - public ByteOrder getByteOrder() { - if (byteOrder == null) - byteOrder = isEndianLittle() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - return byteOrder; - } - - /** - * @deprecated Use {@link CLDevice#getByteOrder()} - */ - @Deprecated - public synchronized ByteOrder getKernelsDefaultByteOrder() { - return getByteOrder(); - } - - /** Bit values for CL_DEVICE_EXECUTION_CAPABILITIES */ - public enum ExecutionCapability implements ValuedEnum { - - Kernel(CL_EXEC_KERNEL), - NativeKernel(CL_EXEC_NATIVE_KERNEL); - - ExecutionCapability(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, ExecutionCapability.class); - } - } - - /** - * Describes the execution capabilities of the device.
- * The mandated minimum capability is: Kernel. - */ - @InfoName("CL_DEVICE_EXECUTION_CAPABILITIES") - public EnumSet getExecutionCapabilities() { - return ExecutionCapability.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_EXECUTION_CAPABILITIES)); - } - - /** Bit values for CL_DEVICE_TYPE */ - public enum Type implements ValuedEnum { - - CPU(CL_DEVICE_TYPE_CPU), - GPU(CL_DEVICE_TYPE_GPU), - Accelerator(CL_DEVICE_TYPE_ACCELERATOR), - Default(CL_DEVICE_TYPE_DEFAULT), - All(CL_DEVICE_TYPE_ALL); - - Type(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, Type.class); - } - } - - /** - * The OpenCL device type. - */ - @InfoName("CL_DEVICE_TYPE") - public EnumSet getType() { - return Type.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_TYPE)); - } - - /** - * A unique device vendor identifier.
- * An example of a unique device identifier could be the PCIe ID. - */ - @InfoName("CL_DEVICE_VENDOR_ID") - public int getVendorId() { - return infos.getInt(getEntity(), CL_DEVICE_VENDOR_ID); - } - - /** - * The number of parallel compute cores on the OpenCL device.
- * The minimum value is 1. - */ - @InfoName("CL_DEVICE_MAX_COMPUTE_UNITS") - public int getMaxComputeUnits() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_COMPUTE_UNITS); - } - - /** - * Maximum dimensions that specify the global and local work-item IDs used by the data parallel execution model.
- * (Refer to clEnqueueNDRangeKernel). - *
The minimum value is 3. - */ - @InfoName("CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS") - public int getMaxWorkItemDimensions() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS); - } - - /** - * Maximum number of work-items that can be specified in each dimension of the work-group to clEnqueueNDRangeKernel. - */ - @InfoName("CL_DEVICE_MAX_WORK_ITEM_SIZES") - public long[] getMaxWorkItemSizes() { - long sizes[] = infos.getNativeSizes(getEntity(), CL_DEVICE_MAX_WORK_ITEM_SIZES, getMaxWorkItemDimensions()); - for (int i = 0, n = sizes.length; i < n; i++) { - long size = sizes[i]; - if ((size & 0xffffffff00000000L) == 0xcccccccc00000000L) - sizes[i] = size & 0xffffffffL; - } - return sizes; - } - - /** - * Maximum number of work-items in a work-group executing a kernel using the data parallel execution model. - * (Refer to clEnqueueNDRangeKernel).
- * The minimum value is 1. - */ - @InfoName("CL_DEVICE_MAX_WORK_GROUP_SIZE") - public long getMaxWorkGroupSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_WORK_GROUP_SIZE); - } - - /** - * Maximum configured clock frequency of the device in MHz. - */ - @InfoName("CL_DEVICE_MAX_CLOCK_FREQUENCY") - public int getMaxClockFrequency() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_CLOCK_FREQUENCY); - } - - /** - * The default compute device address space size specified as an unsigned integer value in bits. Currently supported values are 32 or 64 bits..
- * Size of size_t type in OpenCL kernels can be obtained with getAddressBits() / 8. - */ - @InfoName("CL_DEVICE_ADDRESS_BITS") - public int getAddressBits() { - return infos.getInt(getEntity(), CL_DEVICE_ADDRESS_BITS); - } - - /** - * Max size of memory object allocation in bytes. The minimum value is max (1/4th of CL_DEVICE_GLOBAL_MEM_SIZE , 128*1024*1024) - */ - @InfoName("CL_DEVICE_MAX_MEM_ALLOC_SIZE") - public long getMaxMemAllocSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_MEM_ALLOC_SIZE); - } - - /** - * Is CL_TRUE if images are supported by the OpenCL device and CL_FALSE otherwise. - */ - @InfoName("CL_DEVICE_IMAGE_SUPPORT") - public boolean hasImageSupport() { - return infos.getBool(getEntity(), CL_DEVICE_IMAGE_SUPPORT); - } - - /** - * Max number of simultaneous image objects that can be read by a kernel.
- * The minimum value is 128 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()). - */ - @InfoName("CL_DEVICE_MAX_READ_IMAGE_ARGS") - public int getMaxReadImageArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_READ_IMAGE_ARGS); - } - - /** - * Max number of simultaneous image objects that can be written to by a kernel.
- * The minimum value is 8 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()). - */ - @InfoName("CL_DEVICE_MAX_WRITE_IMAGE_ARGS") - public int getMaxWriteImageArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_WRITE_IMAGE_ARGS); - } - - @Override - public String toString() { - return getName();// + "{singleFPConfig: " + getSingleFPConfig() + "}"; - } - - /** - * Create an OpenCL execution queue on this device for the specified context. - * @param context context of the queue to create - * @return new OpenCL queue object - */ - @SuppressWarnings("deprecation") - public CLQueue createQueue(CLContext context, QueueProperties... queueProperties) { - IntByReference pErr = new IntByReference(); - long flags = 0; - for (QueueProperties prop : queueProperties) - flags |= prop.value(); - cl_command_queue queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), flags, pErr); - error(pErr.getValue()); - - return new CLQueue(context, queue, this); - } - - @Deprecated - public CLQueue createQueue(EnumSet queueProperties, CLContext context) { - IntByReference pErr = new IntByReference(); - cl_command_queue queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), QueueProperties.getValue(queueProperties), pErr); - error(pErr.getValue()); - - return new CLQueue(context, queue, this); - } - - public CLQueue createOutOfOrderQueue(CLContext context) { - return createQueue(EnumSet.of(QueueProperties.OutOfOrderExecModeEnable), context); - } - - public CLQueue createProfilingQueue(CLContext context) { - return createQueue(EnumSet.of(QueueProperties.ProfilingEnable), context); - } - - /** - * Max width of 2D image in pixels.
- * The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE2D_MAX_WIDTH") - public long getImage2DMaxWidth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_WIDTH); - } - - /** - * Max height of 2D image in pixels.
- * The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE2D_MAX_HEIGHT") - public long getImage2DMaxHeight() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_HEIGHT); - } - - /** - * Max width of 3D image in pixels.
- * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_WIDTH") - public long getImage3DMaxWidth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_WIDTH); - } - - /** - * Max height of 3D image in pixels.
- * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_HEIGHT") - public long getImage3DMaxHeight() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_HEIGHT); - } - - /** - * Max depth of 3D image in pixels.
- * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_DEPTH") - public long getImage3DMaxDepth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_DEPTH); - } - - /** - * Maximum number of samplers that can be used in a kernel.
- * Refer to section 6.11.8 for a detailed description on samplers.
- * The minimum value is 16 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_MAX_SAMPLERS") - public int getMaxSamplers() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_SAMPLERS); - } - - /** - * Max size in bytes of the arguments that can be passed to a kernel.
- * The minimum value is 256. - */ - @InfoName("CL_DEVICE_MAX_PARAMETER_SIZE") - public long getMaxParameterSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_PARAMETER_SIZE); - } - - /** - * Describes the alignment in bits of the base address of any allocated memory object. - */ - @InfoName("CL_DEVICE_MEM_BASE_ADDR_ALIGN") - public int getMemBaseAddrAlign() { - return infos.getInt(getEntity(), CL_DEVICE_MEM_BASE_ADDR_ALIGN); - } - - /** - * The smallest alignment in bytes which can be used for any data type. - */ - @InfoName("CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE") - public int getMinDataTypeAlign() { - return infos.getInt(getEntity(), CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE); - } - - /** Bit values for CL_DEVICE_SINGLE_FP_CONFIG */ - public enum SingleFPConfig implements ValuedEnum { - - /** denorms are supported */ - Denorm(CL_FP_DENORM), - /** INF and quiet NaNs are supported. */ - InfNaN(CL_FP_INF_NAN), - /** round to nearest even rounding mode supported */ - RoundToNearest(CL_FP_ROUND_TO_NEAREST), - /** round to zero rounding mode supported */ - RoundToZero(CL_FP_ROUND_TO_ZERO), - /** round to +ve and -ve infinity rounding modes supported */ - RoundToInf(CL_FP_ROUND_TO_INF), - /** IEEE754-2008 fused multiply-add is supported. */ - FMA(CL_FP_FMA); - - SingleFPConfig(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, SingleFPConfig.class); - } - } - - /** - * Describes single precision floating- point capability of the device.
- * The mandated minimum floating-point capability is: RoundToNearest and InfNaN. - */ - @InfoName("CL_DEVICE_SINGLE_FP_CONFIG") - public EnumSet getSingleFPConfig() { - return SingleFPConfig.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_SINGLE_FP_CONFIG)); - } - - /** Values for CL_DEVICE_GLOBAL_MEM_CACHE_TYPE */ - public enum GlobalMemCacheType implements ValuedEnum { - - None(CL_NONE), - ReadOnlyCache(CL_READ_ONLY_CACHE), - ReadWriteCache(CL_READ_WRITE_CACHE); - - GlobalMemCacheType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static GlobalMemCacheType getEnum(long v) { - return EnumValues.getEnum(v, GlobalMemCacheType.class); - } - } - - /** - * Type of global memory cache supported. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_TYPE") - public GlobalMemCacheType getGlobalMemCacheType() { - return GlobalMemCacheType.getEnum(infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_TYPE)); - } - - /** - * Size of global memory cache line in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE") - public int getGlobalMemCachelineSize() { - return infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE); - } - - /** - * Size of global memory cache in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_SIZE") - public long getGlobalMemCacheSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_SIZE); - } - - /** - * Size of global device memory in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_SIZE") - public long getGlobalMemSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_SIZE); - } - - /** - * Max size in bytes of a constant buffer allocation.
- * The minimum value is 64 KB. - */ - @InfoName("CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE") - public long getMaxConstantBufferSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE); - } - - /** - * Max number of arguments declared with the __constant qualifier in a kernel.
- * The minimum value is 8. - */ - @InfoName("CL_DEVICE_MAX_CONSTANT_ARGS") - public int getMaxConstantArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_CONSTANT_ARGS); - } - - /** Values for CL_DEVICE_LOCAL_MEM_TYPE */ - public enum LocalMemType implements ValuedEnum { - - /** implying dedicated local memory storage such as SRAM */ - Local(CL_LOCAL), - Global(CL_GLOBAL); - - LocalMemType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static LocalMemType getEnum(long v) { - return EnumValues.getEnum(v, LocalMemType.class); - } - } - - /** - * Type of local memory supported.
- */ - @InfoName("CL_DEVICE_LOCAL_MEM_TYPE") - public LocalMemType getLocalMemType() { - return LocalMemType.getEnum(infos.getInt(getEntity(), CL_DEVICE_LOCAL_MEM_TYPE)); - } - - /** - * Size of local memory arena in bytes.
- * The minimum value is 16 KB. - */ - @InfoName("CL_DEVICE_LOCAL_MEM_SIZE") - public long getLocalMemSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_LOCAL_MEM_SIZE); - } - - /** - * Is CL_TRUE if the device implements error correction for the memories, caches, registers etc. in the device.
- * Is CL_FALSE if the device does not implement error correction.
- * This can be a requirement for certain clients of OpenCL. - */ - @InfoName("CL_DEVICE_ERROR_CORRECTION_SUPPORT") - public boolean hasErrorCorrectionSupport() { - return infos.getBool(getEntity(), CL_DEVICE_ERROR_CORRECTION_SUPPORT); - } - - @InfoName("Out of order queues support") - public boolean hasOutOfOrderQueueSupport() { - CLContext context = getPlatform().createContext(null, this); - CLQueue queue = null; - try { - queue = createOutOfOrderQueue(context); - return true; - } catch (CLException.InvalidQueueProperties ex) { - return false; - } finally { - if (queue != null) - queue.release(); - context.release(); - } - } - - /** - * Describes the resolution of device timer.
- * This is measured in nanoseconds.
- * Refer to section 5.9 for details. - */ - @InfoName("CL_DEVICE_PROFILING_TIMER_RESOLUTION") - public long getProfilingTimerResolution() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_PROFILING_TIMER_RESOLUTION); - } - - /** - * Is CL_TRUE if the OpenCL device is a little endian device and CL_FALSE otherwise. - */ - @InfoName("CL_DEVICE_ENDIAN_LITTLE") - public boolean isEndianLittle() { - return infos.getBool(getEntity(), CL_DEVICE_ENDIAN_LITTLE); - } - - /** - * Is CL_TRUE if the device is available and CL_FALSE if the device is not available. - */ - @InfoName("CL_DEVICE_AVAILABLE") - public boolean isAvailable() { - return infos.getBool(getEntity(), CL_DEVICE_AVAILABLE); - } - - /** - * Is CL_FALSE if the implementation does not have a compiler available to compile the program source.
- * Is CL_TRUE if the compiler is available.
- * This can be CL_FALSE for the embededed platform profile only. - */ - @InfoName("CL_DEVICE_COMPILER_AVAILABLE") - public boolean isCompilerAvailable() { - return infos.getBool(getEntity(), CL_DEVICE_COMPILER_AVAILABLE); - } - - /** - Device name string. - */ - @InfoName("CL_DEVICE_NAME") - public String getName() { - return infos.getString(getEntity(), CL_DEVICE_NAME); - } - - /** - * OpenCL C version string.
- * Returns the highest OpenCL C version supported by the compiler for this device.
- * This version string has the following format:
- * OpenCL<space>C<space><major_version.minor_version><space><vendor-specific information>
- * The major_version.minor_version value returned must be 1.1 if CL_DEVICE_VERSION is OpenCL 1.1.
- * The major_version.minor_version value returned can be 1.0 or 1.1 if CL_DEVICE_VERSION is OpenCL 1.0.
- * If OpenCL C 1.1 is returned, this implies that the language feature set defined in section 6 of the OpenCL 1.1 specification is supported by the OpenCL 1.0 device. - * @since OpenCL 1.1 - */ - @InfoName("CL_DEVICE_OPENCL_C_VERSION") - public String getOpenCLVersion() { - try { - return infos.getString(getEntity(), CL_DEVICE_OPENCL_C_VERSION); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return "OpenCL C 1.0"; - } - } - - /** - Vendor name string. - */ - @InfoName("CL_DEVICE_VENDOR") - public String getVendor() { - return infos.getString(getEntity(), CL_DEVICE_VENDOR); - } - - /** - OpenCL software driver version string in the form major_number.minor_number. - */ - @InfoName("CL_DRIVER_VERSION") - public String getDriverVersion() { - return infos.getString(getEntity(), CL_DRIVER_VERSION); - } - - /** - * OpenCL profile string.
- * Returns the profile name supported by the device.
- * The profile name returned can be one of the following strings: - *

    - *
  • FULL_PROFILE if the device supports the OpenCL specification (functionality defined as part of the core specification and does not require any extensions to be supported).
  • - *
  • EMBEDDED_PROFILE if the device supports the OpenCL embedded profile.
  • - *
- */ - @InfoName("CL_DEVICE_PROFILE") - public String getProfile() { - return infos.getString(getEntity(), CL_DEVICE_PROFILE); - } - - /** - * Whether the device and the host have a unified memory subsystem. - * @since OpenCL 1.1 - */ - @InfoName("CL_DEVICE_HOST_UNIFIED_MEMORY") - public boolean isHostUnifiedMemory() { - try { - return infos.getBool(getEntity(), CL_DEVICE_HOST_UNIFIED_MEMORY); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return false; - } - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR") - public int getPreferredVectorWidthChar() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT") - public int getPreferredVectorWidthShort() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT") - public int getPreferredVectorWidthInt() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG") - public int getPreferredVectorWidthLong() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT") - public int getPreferredVectorWidthFloat() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE") - public int getPreferredVectorWidthDouble() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR") - public int getNativeVectorWidthChar() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT") - public int getNativeVectorWidthShort() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_INT") - public int getNativeVectorWidthInt() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_INT); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG") - public int getNativeVectorWidthLong() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT") - public int getNativeVectorWidthFloat() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT); - } - - /** - * Returns the native ISA vector width.
- * The vector width is defined as the number of scalar elements that can be stored in the vector.
- * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE") - public int getNativeVectorWidthDouble() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE); - } - - /** - * OpenCL version string.
- * Returns the OpenCL version supported by the device.
- * This version string has the following format: - * - * OpenCL<space><major_version.min or_version><space><vendor-specific information> - * - * The major_version.minor_version value returned will be 1.0. - */ - @InfoName("CL_DEVICE_VERSION") - public String getVersion() { - return infos.getString(getEntity(), CL_DEVICE_VERSION); - } - - /** - Returns a space separated list of extension names (the extension names themselves do not contain any spaces). The list of extension names returned currently can include one or more of - */ - @InfoName("CL_DEVICE_EXTENSIONS") - public String[] getExtensions() { - if (extensions == null) { - extensions = infos.getString(getEntity(), CL_DEVICE_EXTENSIONS).split("\\s+"); - } - return extensions; - } - private String[] extensions; - - public boolean hasExtension(String name) { - name = name.trim(); - for (String x : getExtensions()) { - if (name.equals(x.trim())) { - return true; - } - } - return false; - } - - /** - * Whether this device support any double-precision number extension (cl_khr_fp64 or cl_amd_fp64) - */ - public boolean isDoubleSupported() { - return isDoubleSupportedKHR() || isDoubleSupportedAMD(); - } - - /** - * Whether this device support the cl_khr_fp64 double-precision number extension - */ - public boolean isDoubleSupportedKHR() { - return hasExtension("cl_khr_fp64"); - } - - /** - * Whether this device supports the cl_amd_fp64 double-precision number extension - */ - public boolean isDoubleSupportedAMD() { - return hasExtension("cl_amd_fp64"); - } - - /** - * If this device supports the extension cl_amd_fp64 but not cl_khr_fp64, replace any OpenCL source code pragma of the style #pragma OPENCL EXTENSION cl_khr_fp64 : enable by #pragma OPENCL EXTENSION cl_amd_fp64 : enable.
- * Also works the other way around (if the KHR extension is available but the source code refers to the AMD extension).
- * This method is called automatically by CLProgram unless the javacl.adjustDoubleExtension property is set to false or the JAVACL_ADJUST_DOUBLE_EXTENSION is set to 0. - */ - public String replaceDoubleExtensionByExtensionActuallyAvailable(String kernelSource) { - boolean hasKHR = isDoubleSupportedKHR(), hasAMD = isDoubleSupportedAMD(); - if (hasAMD && !hasKHR) - kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_khr_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_amd_fp64 : enable"); - else if (!hasAMD && hasKHR) - kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_amd_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_khr_fp64 : enable"); - return kernelSource; - } - - /** - * Whether this device supports the cl_khr_fp16 extension. - */ - public boolean isHalfSupported() { - return hasExtension("cl_khr_fp16"); - } - - /** - * Whether this device supports the cl_khr_byte_addressable_store extension. - */ - public boolean isByteAddressableStoreSupported() { - return hasExtension("cl_khr_byte_addressable_store"); - } - - /** - * Whether this device supports any OpenGL sharing extension (cl_khr_gl_sharing or cl_APPLE_gl_sharing) - */ - public boolean isGLSharingSupported() { - return hasExtension("cl_khr_gl_sharing") || hasExtension("cl_APPLE_gl_sharing"); - } - /** - * Whether this device supports the cl_khr_global_int32_base_atomics extension. - */ - public boolean isGlobalInt32BaseAtomicsSupported() { - return hasExtension("cl_khr_global_int32_base_atomics"); - } - /** - * Whether this device supports the cl_khr_global_int32_extended_atomics extension. - */ - public boolean isGlobalInt32ExtendedAtomicsSupported() { - return hasExtension("cl_khr_global_int32_extended_atomics"); - } - /** - * Whether this device supports the cl_khr_local_int32_base_atomics extension. - */ - public boolean isLocalInt32BaseAtomicsSupported() { - return hasExtension("cl_khr_local_int32_base_atomics"); - } - /** - * Whether this device supports the cl_khr_local_int32_extended_atomics extension. - */ - public boolean isLocalInt32ExtendedAtomicsSupported() { - return hasExtension("cl_khr_local_int32_extended_atomics"); - } - - /** Bit values for CL_DEVICE_QUEUE_PROPERTIES */ - public enum QueueProperties implements ValuedEnum { - - OutOfOrderExecModeEnable(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), - ProfilingEnable(CL_QUEUE_PROFILING_ENABLE); - - QueueProperties(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, QueueProperties.class); - } - } - - /** - * Describes the command-queue properties supported by the device.
- * These properties are described in table 5.1.
- * The mandated minimum capability is: ProfilingEnable. - */ - @InfoName("CL_DEVICE_QUEUE_PROPERTIES") - public EnumSet getQueueProperties() { - return QueueProperties.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_QUEUE_PROPERTIES)); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDoubleBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDoubleBuffer.java deleted file mode 100644 index 9c472f3f5..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLDoubleBuffer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Double values.
- * see {@link CLContext#createDoubleBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createDoubleBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.DoubleBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Double}> - */ -@Deprecated -public class CLDoubleBuffer extends CLBuffer { - CLDoubleBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 8, DoubleBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLEvent.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLEvent.java deleted file mode 100644 index 3d07056c5..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLEvent.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import java.util.Arrays; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.ValuedEnum; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Callback; -import com.sun.jna.Memory; -import com.sun.jna.Pointer; - -/** - * OpenCL event object.
- * Event objects can be used to refer to a kernel execution command (clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueNativeKernel), or read, write, map and copy commands on memory objects (clEnqueue{Read|Write|Map}{Buffer|Image}, clEnqueueCopy{Buffer|Image}, clEnqueueCopyBufferToImage, or clEnqueueCopyImageToBuffer).
- * An event object can be used to track the execution status of a command.
- * The API calls that enqueue commands to a command-queue create a new event object that is returned in the event argument.
- * In case of an error enqueuing the command in the command-queue the event argument does not return an event object.
- * The execution status of an enqueued command at any given point in time can be CL_QUEUED (command has been enqueued in the command-queue), CL_SUBMITTED (enqueued command has been submitted by the host to the device associated with the command-queue), CL_RUNNING (device is currently executing this command), CL_COMPLETE (command has successfully completed) or the appropriate error code if the command was abnormally terminated (this may be caused by a bad memory access etc.).
- * The error code returned by a terminated command is a negative integer value.
- * A command is considered to be complete if its execution status is CL_COMPLETE or is a negative integer value.
- * If the execution of a command is terminated, the command-queue associated with this terminated command, and the associated context (and all other command-queues in this context) may no longer be available.
- * The behavior of OpenCL API calls that use this context (and command-queues associated with this context) are now considered to be implementation- defined.
- * The user registered callback function specified when context is created can be used to report appropriate error information.
- * - * @author ochafik - */ -public class CLEvent extends CLAbstractEntity { - - private static CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetEventInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - private static CLInfoGetter profilingInfos = new CLInfoGetter() { - @Override - protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetEventProfilingInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - CLEvent(cl_event evt) { - super(evt, false); - } - - CLEvent() { - super(null, true); - } - - public interface EventCallback { - public void callback(CLEvent event, int executionStatus); - } - - /** - * Registers a user callback function for the completion execution status (CL_COMPLETE).
- * @param callback - * @throws UnsupportedOperationException in OpenCL 1.0 - * @since OpenCL 1.1 - */ - public void setCompletionCallback(final EventCallback callback) { - setCallback(CL_COMPLETE, callback); - } - /** - * Registers a user callback function for a specific command execution status.
- * The registered callback function will be called when the execution status of command associated with event changes to the execution status specified by command_exec_status. - * @param commandExecStatus specifies the command execution status for which the callback is registered. The command execution callback values for which a callback can be registered are: CL_COMPLETE. There is no guarantee that the callback functions registered for various execution status values for an event will be called in the exact order that the execution status of a command changes. - * @param callback - * @throws UnsupportedOperationException in OpenCL 1.0 - * @since OpenCL 1.1 - */ - public void setCallback(int commandExecStatus, final EventCallback callback) { - try { - error(CL.clSetEventCallback(getEntity(), commandExecStatus, new clSetEventCallback_arg1_callback() { - public void invoke(OpenCLLibrary.cl_event evt, int executionStatus, Pointer voidPtr1) { - callback.callback(CLEvent.this, executionStatus); - } - }, null)); - } catch (Throwable th) { - // TODO check if supposed to handle OpenCL 1.1 - throw new UnsupportedOperationException("Cannot set event callback (OpenCL 1.1 feature).", th); - } - } - - static boolean noEvents = false; - public static void setNoEvents(boolean noEvents) { - CLEvent.noEvents = noEvents; - } - static CLEvent createEvent(final CLQueue queue, cl_event evt) { - return createEvent(queue, evt, false); - } - static CLEvent createEvent(final CLQueue queue, cl_event evt, boolean isUserEvent) { - if (noEvents && queue != null) { - if (evt != null) - CL.clReleaseEvent(evt); - evt = null; - - if (isUserEvent) - return new CLUserEvent() { - volatile boolean waited = false; - @Override - public synchronized void waitFor() { - if (!waited) { - queue.finish(); - waited = true; - } - } - }; - return new CLEvent() { - volatile boolean waited = false; - @Override - public synchronized void waitFor() { - if (!waited) { - queue.finish(); - waited = true; - } - } - }; - } - if (evt == null) - return null; - - return isUserEvent ? - new CLUserEvent(evt) : - new CLEvent(evt); - } - - static CLEvent createEvent(CLQueue queue, cl_event[] evt1) { - if (evt1 == null) - return null; - return createEvent(queue, evt1[0]); - } - - - /** - * Wait for this event, blocking the caller thread independently of any queue until all of the command associated with this events completes. - */ - public void waitFor() { - if (entity == null) - return; - waitFor(this); - } - - /** - * Wait for events, blocking the caller thread independently of any queue until all of the commands associated with the events completed. - * @param eventsToWaitFor List of events which completion is to be waited for - */ - public static void waitFor(CLEvent... eventsToWaitFor) { - if (eventsToWaitFor.length == 0) - return; - - try { - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - if (evts == null || evts.length == 0) - return; - error(CL.clWaitForEvents(evts.length, evts)); - } catch (Exception ex) { - throw new RuntimeException("Exception while waiting for events " + Arrays.asList(eventsToWaitFor), ex); - } - } - - /** - * Invoke an action in a separate thread only after completion of the command associated with this event.
- * Returns immediately. - * @param action an action to be ran - * @throws IllegalArgumentException if action is null - */ - public void invokeUponCompletion(final Runnable action) { - invokeUponCompletion(action, this); - } - - /** - * Invoke an action in a separate thread only after completion of all of the commands associated with the specified events.
- * Returns immediately. - * @param action an action to be ran - * @param eventsToWaitFor list of events which commands's completion should be waited for before the action is ran - * @throws IllegalArgumentException if action is null - */ - public static void invokeUponCompletion(final Runnable action, final CLEvent... eventsToWaitFor) { - if (action == null) - throw new IllegalArgumentException("Null action !"); - - new Thread() { - public void run() { - waitFor(eventsToWaitFor); - action.run(); - } - }.start(); - } - - static cl_event[] new_event_out(CLEvent[] eventsToWaitFor) { - return noEvents || eventsToWaitFor == null ? null : new cl_event[1]; - } - - static cl_event[] to_cl_event_array(CLEvent... events) { - if (events == null) - return null; - if (noEvents) { - for (CLEvent evt : events) - if (evt != null) - evt.waitFor(); - return null; - } - int n = events.length; - if (n == 0) - return null; - int nonNulls = 0; - for (int i = 0; i < n; i++) - if (events[i] != null && events[i].getEntity() != null) - nonNulls++; - - if (nonNulls == 0) - return null; - - cl_event[] event_wait_list = new cl_event[nonNulls]; - int iDest = 0; - for (int i = 0; i < n; i++) { - CLEvent event = events[i]; - if (event == null || event.getEntity() == null) - continue; - event_wait_list[iDest] = event.getEntity(); - iDest++; - } - return event_wait_list; - } - - @Override - protected void clear() { - error(CL.clReleaseEvent(getEntity())); - } - - /** Values for CL_EVENT_COMMAND_EXECUTION_STATUS */ - public enum CommandExecutionStatus implements ValuedEnum { - /** command has been enqueued in the command-queue */ - Queued(CL_QUEUED), - /** enqueued command has been submitted by the host to the device associated with the command-queue */ - Submitted(CL_SUBMITTED), - /** device is currently executing this command */ - Running(CL_RUNNING), - /** the command has completed */ - Complete(CL_COMPLETE); - - CommandExecutionStatus(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static CommandExecutionStatus getEnum(long v) { return EnumValues.getEnum(v, CommandExecutionStatus.class); } - } - - /** - * Return the execution status of the command identified by event.
- * @throws CLException is the execution status denotes an error - */ - public CommandExecutionStatus getCommandExecutionStatus() { - int v = infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); - CommandExecutionStatus status = CommandExecutionStatus.getEnum(v); - if (status == null) - error(v); - return status; - } - /** - * Return the execution status of the command identified by event.
- * @throws CLException is the execution status denotes an error - */ - @InfoName("CL_EVENT_COMMAND_EXECUTION_STATUS") - public int getCommandExecutionStatusValue() { - return infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); - } - - /** Values for CL_EVENT_COMMAND_TYPE */ - public enum CommandType implements ValuedEnum { - NDRangeKernel(CL_COMMAND_NDRANGE_KERNEL), - Task(CL_COMMAND_TASK), - NativeKernel(CL_COMMAND_NATIVE_KERNEL), - ReadBuffer(CL_COMMAND_READ_BUFFER), - WriteBuffer(CL_COMMAND_WRITE_BUFFER), - CopyBuffer(CL_COMMAND_COPY_BUFFER), - ReadImage(CL_COMMAND_READ_IMAGE), - WriteImage(CL_COMMAND_WRITE_IMAGE), - CopyImage(CL_COMMAND_COPY_IMAGE), - CopyBufferToImage(CL_COMMAND_COPY_BUFFER_TO_IMAGE), - CopyImageToBuffer(CL_COMMAND_COPY_IMAGE_TO_BUFFER), - MapBuffer(CL_COMMAND_MAP_BUFFER), - CommandMapImage(CL_COMMAND_MAP_IMAGE), - UnmapMemObject(CL_COMMAND_UNMAP_MEM_OBJECT), - Marker(CL_COMMAND_MARKER), - AcquireGLObjects(CL_COMMAND_ACQUIRE_GL_OBJECTS), - ReleaseGLObjects(CL_COMMAND_RELEASE_GL_OBJECTS); - - CommandType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static CommandType getEnum(long v) { return EnumValues.getEnum(v, CommandType.class); } - } - - /** - * Return the command associated with event. - */ - @InfoName("CL_EVENT_COMMAND_TYPE") - public CommandType getCommandType() { - return CommandType.getEnum(infos.getInt(getEntity(), CL_EVENT_COMMAND_TYPE)); - } - - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event is enqueued in a command-queue by the host. - */ - @InfoName("CL_CL_PROFILING_COMMAND_QUEUED") - public long getProfilingCommandQueued() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_QUEUED); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event that has been enqueued is submitted by the host to the device associated with the command- queue. - */ - @InfoName("CL_CL_PROFILING_COMMAND_SUBMIT") - public long getProfilingCommandSubmit() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_SUBMIT); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event starts execution on the device. - */ - @InfoName("CL_CL_PROFILING_COMMAND_START") - public long getProfilingCommandStart() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_START); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event has finished execution on the device. - */ - @InfoName("CL_CL_PROFILING_COMMAND_END") - public long getProfilingCommandEnd() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_END); - } - - - @Override - public String toString() { - return "Event {commandType: " + getCommandType() + "}"; - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLException.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLException.java deleted file mode 100644 index f89c484a6..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLException.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.ochafik.util.string.StringUtils; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.*; -import java.lang.reflect.*; -import static com.nativelibs4java.opencl.JavaCL.log; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * OpenCL error - * @author ochafik - */ -@SuppressWarnings("serial") -public class CLException extends RuntimeException { - protected int code; - CLException(String message, int code) { - super(message); - this.code = code; - } - public int getCode() { - return code; - } - - @Retention(RetentionPolicy.RUNTIME) - public @interface ErrorCode { - int value(); - } - - public static class CLTypedException extends CLException { - protected String message; - public CLTypedException() { - super("", 0); - ErrorCode code = getClass().getAnnotation(ErrorCode.class); - this.code = code.value(); - this.message = getClass().getSimpleName(); - } - - @Override - public String getMessage() { - return message + logSuffix; - } - - void setKernelArg(CLKernel kernel, int argIndex) { - message += " (kernel name = " + kernel.getFunctionName() + ", num args = " + kernel.getNumArgs() + ", arg index = " + argIndex; - CLProgram program = kernel.getProgram(); - if (program != null) - message += ", source = <<<\n\t" + program.getSource().replaceAll("\n", "\n\t"); - - message += "\n>>> )"; - } - - } - - @ErrorCode(CL_MISALIGNED_SUB_BUFFER_OFFSET) - public static class MisalignedSubBufferOffset extends CLTypedException {} - @ErrorCode(CL_OUT_OF_RESOURCES) - public static class OutOfResources extends CLTypedException {} - @ErrorCode(CL_COMPILER_NOT_AVAILABLE) - public static class CompilerNotAvailable extends CLTypedException {} - @ErrorCode(CL_INVALID_GLOBAL_WORK_SIZE) - public static class InvalidGlobalWorkSize extends CLTypedException {} - @ErrorCode(CL_MAP_FAILURE) - public static class MapFailure extends CLTypedException {} - @ErrorCode(CL_MEM_OBJECT_ALLOCATION_FAILURE) - public static class MemObjectAllocationFailure extends CLTypedException {} - @ErrorCode(CL_INVALID_EVENT_WAIT_LIST) - public static class InvalidEventWaitList extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_INDEX) - public static class InvalidArgIndex extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_SIZE) - public static class InvalidArgSize extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_VALUE) - public static class InvalidArgValue extends CLTypedException {} - @ErrorCode(CL_INVALID_BINARY) - public static class InvalidBinary extends CLTypedException {} - @ErrorCode(CL_INVALID_EVENT) - public static class InvalidEvent extends CLTypedException {} - @ErrorCode(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR) - public static class InvalidImageFormatDescriptor extends CLTypedException {} - @ErrorCode(CL_INVALID_IMAGE_SIZE) - public static class InvalidImageSize extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_DIMENSION) - public static class InvalidWorkDimension extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_GROUP_SIZE) - public static class InvalidWorkGroupSize extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_ITEM_SIZE) - public static class InvalidWorkItemSize extends CLTypedException {} - @ErrorCode(CL_INVALID_OPERATION) - public static class InvalidOperation extends CLTypedException {} - @ErrorCode(CL_INVALID_BUFFER_SIZE) - public static class InvalidBufferSize extends CLTypedException {} - @ErrorCode(CL_INVALID_GLOBAL_OFFSET) - public static class InvalidGlobalOffset extends CLTypedException {} - @ErrorCode(CL_OUT_OF_HOST_MEMORY) - public static class OutOfHostMemory extends CLTypedException {} - @ErrorCode(CL_INVALID_COMMAND_QUEUE) - public static class InvalidCommandQueue extends CLTypedException {} - @ErrorCode(CL_MEM_COPY_OVERLAP) - public static class MemCopyOverlap extends CLTypedException {} - @ErrorCode(CL_INVALID_CONTEXT) - public static class InvalidContext extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL) - public static class InvalidKernel extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_CONTEXT_APPLE) - public static class InvalidGLContextApple extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR) - public static class InvalidGLShareGroupReference extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_OBJECT) - public static class InvalidGLObject extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_ARGS) - public static class InvalidKernelArgs extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_DEFINITION) - public static class InvalidKernelDefinition extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_NAME) - public static class InvalidKernelName extends CLTypedException {} - @ErrorCode(CL_INVALID_MEM_OBJECT) - public static class InvalidMemObject extends CLTypedException {} - @ErrorCode(CL_INVALID_MIP_LEVEL) - public static class InvalidMipLevel extends CLTypedException {} - @ErrorCode(CL_INVALID_PROGRAM) - public static class InvalidProgram extends CLTypedException {} - @ErrorCode(CL_INVALID_PROGRAM_EXECUTABLE) - public static class InvalidProgramExecutable extends CLTypedException {} - @ErrorCode(CL_INVALID_QUEUE_PROPERTIES) - public static class InvalidQueueProperties extends CLTypedException {} - @ErrorCode(CL_INVALID_VALUE) - public static class InvalidValue extends CLTypedException {} - @ErrorCode(CL_INVALID_SAMPLER) - public static class InvalidSampler extends CLTypedException {} - @ErrorCode(CL_INVALID_DEVICE_TYPE) - public static class InvalidDeviceType extends CLTypedException {} - @ErrorCode(CL_INVALID_BUILD_OPTIONS) - public static class InvalidBuildOptions extends CLTypedException {} - @ErrorCode(CL_BUILD_PROGRAM_FAILURE) - public static class BuildProgramFailure extends CLTypedException {} - - public static String errorString(int err) { - if (err == CL_SUCCESS) - return null; - - List candidates = new ArrayList(); - for (Field f : OpenCLLibrary.class.getDeclaredFields()) { - if (!Modifier.isStatic(f.getModifiers())) { - continue; - } - if (f.getType().equals(Integer.TYPE)) { - try { - int i = (Integer) f.get(null); - if (i == err) { - String name = f.getName(), lname = name.toLowerCase(); - if (lname.contains("invalid") || lname.contains("bad") || lname.contains("illegal") || lname.contains("wrong")) { - candidates.clear(); - candidates.add(name); - break; - } else - candidates.add(name); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return StringUtils.implode(candidates, " or "); - } - - static boolean failedForLackOfMemory(int err, int previousAttempts) { - switch (err) { - case CL_SUCCESS: - return false; - case CL_OUT_OF_HOST_MEMORY: - case CL_OUT_OF_RESOURCES: - case CL_MEM_OBJECT_ALLOCATION_FAILURE: - if (previousAttempts <= 1) { - System.gc(); - if (previousAttempts == 1) { - try { - Thread.sleep(100); - } catch (InterruptedException ex) {} - } - return true; - } - default: - error(err); - assert false; // won't reach - return false; - } - } - static final String logSuffix = System.getenv("CL_LOG_ERRORS") == null ? " (make sure to log all errors with environment variable CL_LOG_ERRORS=stdout)" : ""; - - static Map> typedErrorClassesByCode; - @SuppressWarnings("unchecked") - public static void error(int err) { - if (err == CL_SUCCESS) - return; - //if (err == CL_OUT_OF_RESOURCES) - // return; - - if (typedErrorClassesByCode == null) { - typedErrorClassesByCode = new HashMap>(); - for (Class c : CLException.class.getDeclaredClasses()) { - if (c == CLTypedException.class || !CLTypedException.class.isAssignableFrom(c)) - continue; - typedErrorClassesByCode.put(c.getAnnotation(ErrorCode.class).value(), (Class)c); - } - } - CLException toThrow = null; - Class c = typedErrorClassesByCode.get(err); - if (c != null) { - try { - toThrow = c.newInstance(); - } catch (InstantiationException ex) { - assert log(Level.SEVERE, null, ex); - } catch (IllegalAccessException ex) { - assert log(Level.SEVERE, null, ex); - } - } - if (toThrow == null) - toThrow = new CLException("OpenCL Error : " + errorString(err) + logSuffix, err); - - //assert log(Level.SEVERE, null, toThrow); - - throw toThrow; - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLFloatBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLFloatBuffer.java deleted file mode 100644 index 13371a0ed..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLFloatBuffer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.FloatBuffer; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Float values.
- * see {@link CLContext#createFloatBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createFloatBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.FloatBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Float}> - */ -@Deprecated -public class CLFloatBuffer extends CLBuffer { - CLFloatBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 4, FloatBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage.java deleted file mode 100644 index d49bebcf0..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FALSE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_ELEMENT_SIZE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_FORMAT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_TRUE; -import static com.nativelibs4java.util.JNAUtils.toNS; -import static com.nativelibs4java.util.NIOUtils.directCopy; - -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; - -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.ochafik.util.listenable.Pair; -import com.sun.jna.Native; -import com.sun.jna.Pointer; - - -/** - * OpenCL Image Memory Object.
- * An image object is used to store a two- or three- dimensional texture, frame-buffer or image
- * An image object is used to represent a buffer that can be used as a texture or a frame-buffer. The elements of an image object are selected from a list of predefined image formats. - * @author Oliveir Chafik - */ -public abstract class CLImage extends CLMem { - - CLImageFormat format; - CLImage(CLContext context, cl_mem entity, CLImageFormat format) { - super(context, -1, entity); - this.format = format; - } - - - - /** - * Return image format descriptor specified when image is created with CLContext.create{Input|Output|InputOutput}{2D|3D}. - */ - @InfoName("CL_IMAGE_FORMAT") - public CLImageFormat getFormat() { - if (format == null) { - /// TODO: DOES NOT SEEM TO WORK ON MAC OS X 10.6.1 / CPU - cl_image_format fmt = new cl_image_format(); - fmt.use(infos.getMemory(getEntity(), CL_IMAGE_FORMAT)); - fmt.read(); - format = new CLImageFormat(fmt); - } - return format; - } - - /** - * Return size of each element of the image memory object given by image.
- * An element is made up of n channels. The value of n is given in cl_image_format descriptor. - */ - @InfoName("CL_IMAGE_ELEMENT_SIZE") - public long getElementSize() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_ELEMENT_SIZE); - } - - - protected CLEvent read(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - /*if (!out.isDirect()) { - - }*/ - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueReadImage(queue.getEntity(), getEntity(), - blocking ? CL_TRUE : CL_FALSE, - origin, - region, - toNS(rowPitch), - toNS(slicePitch), - Native.getDirectBufferPointer(out), - evts == null ? 0 : evts.length, evts, - eventOut - )); - return CLEvent.createEvent(queue, eventOut); - } - - protected CLEvent write(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - boolean indirect = !in.isDirect(); - if (indirect) - in = directCopy(in, getContext().getByteOrder()); - - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueWriteImage(queue.getEntity(), getEntity(), - blocking ? CL_TRUE : CL_FALSE, - origin, - region, - toNS(rowPitch), - toNS(slicePitch), - Native.getDirectBufferPointer(in), - evts == null ? 0 : evts.length, evts, - eventOut - )); - CLEvent evt = CLEvent.createEvent(queue, eventOut); - - if (indirect && !blocking) { - final Buffer toHold = in; - evt.invokeUponCompletion(new Runnable() { - public void run() { - // Make sure the GC held a reference to directData until the write was completed ! - toHold.rewind(); - } - }); - } - - return evt; - } - - protected Pair map(CLQueue queue, MapFlags flags, - NativeSize[] offset3, NativeSize[] length3, - Long imageRowPitch, - Long imageSlicePitch, - boolean blocking, CLEvent... eventsToWaitFor) - { - //checkBounds(offset, length); - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - IntBuffer pErr = NIOUtils.directInts(1, ByteOrder.nativeOrder()); - - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - Pointer p = CL.clEnqueueMapImage( - queue.getEntity(), getEntity(), blocking ? CL_TRUE : CL_FALSE, - flags.value(), - offset3, - length3, - imageRowPitch == null ? null : new NativeSizeByReference(toNS(imageRowPitch)), - imageSlicePitch == null ? null : new NativeSizeByReference(toNS(imageSlicePitch)), - evts == null ? 0 : evts.length, evts, - eventOut, - pErr - ); - error(pErr.get()); - return new Pair( - p.getByteBuffer(0, getByteCount()), - CLEvent.createEvent(queue, eventOut) - ); - } - - /** - * see {@link CLImage2D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLImage3D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[]) } - * @param queue - * @param buffer - * @param eventsToWaitFor - * @return Event which completion indicates that the OpenCL was unmapped - */ - public CLEvent unmap(CLQueue queue, ByteBuffer buffer, CLEvent... eventsToWaitFor) { - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueUnmapMemObject(queue.getEntity(), getEntity(), Native.getDirectBufferPointer(buffer), evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(queue, eventOut); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage2D.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage2D.java deleted file mode 100644 index 732c5277c..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage2D.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import com.nativelibs4java.opencl.ImageIOUtils.ImageInfo; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_HEIGHT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_ROW_PITCH; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_WIDTH; -import static com.nativelibs4java.util.JNAUtils.toNS; -import static com.nativelibs4java.util.NIOUtils.directInts; - -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.util.listenable.Pair; - -/** - * OpenCL 2D Image Memory Object
- * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, java.awt.Image, boolean) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, java.nio.Buffer, boolean) } - * see {@link CLContext#createImage2DFromGLRenderBuffer(com.nativelibs4java.opencl.CLMem.Usage, int) } - * see {@link CLContext#createImage2DFromGLTexture2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLContext.GLTextureTarget, int, int) } - * @author Olivier Chafik - */ -public class CLImage2D extends CLImage { - CLImage2D(CLContext context, cl_mem entity, CLImageFormat format) { - super(context, entity, format); - } - - /** - * Return size in bytes of a row of elements of the image object given by image. - */ - @InfoName("CL_IMAGE_ROW_PITCH") - public long getRowPitch() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_ROW_PITCH); - } - - /** - * Return width of the image in pixels - */ - @InfoName("CL_IMAGE_WIDTH") - public long getWidth() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_WIDTH); - } - - /** - * Return height of the image in pixels - */ - @InfoName("CL_IMAGE_HEIGHT") - public long getHeight() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_HEIGHT); - } - - public CLEvent read(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, toNS(minX, minY, 0), toNS(width, height, 1), rowPitch, 0, out, blocking, eventsToWaitFor); - } - public CLEvent write(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, toNS(minX, minY, 0), toNS(width, height, 1), rowPitch, 0, in, blocking, eventsToWaitFor); - } - - public BufferedImage read(CLQueue queue, CLEvent... eventsToWaitFor) { - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - int imageType = info == null ? 0 : info.bufferedImageType; - if (imageType == 0) - throw new UnsupportedOperationException("Cannot convert image of format " + getFormat() + " to a BufferedImage."); - //imageType = BufferedImage.TYPE_INT_ARGB; - - BufferedImage im = new BufferedImage((int)getWidth(), (int)getHeight(), imageType); - read(queue, im, false, eventsToWaitFor); - return im; - } - public void read(CLQueue queue, BufferedImage imageOut, boolean allowDeoptimizingDirectWrite, CLEvent... eventsToWaitFor) { - //if (!getFormat().isIntBased()) - // throw new IllegalArgumentException("Image-read only supports int-based RGBA images"); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - int width = imageOut.getWidth(null), height = imageOut.getHeight(null); - - Buffer dataOut = NIOUtils.directBuffer(width * height * info.channelCount, getContext().getByteOrder(), info.bufferClass); - //Buffer dataOut = info.createBuffer(width, height, true); - //IntBuffer dataOut = directInts(width * height, getContext().getByteOrder()); - read(queue, 0, 0, width, height, 0, dataOut, true, eventsToWaitFor); - info.dataSetter.setData(imageOut, dataOut, allowDeoptimizingDirectWrite); - } - public CLEvent write(CLQueue queue, Image image, CLEvent... eventsToWaitFor) { - return write(queue, image, 0, 0, image.getWidth(null), image.getHeight(null), false, false, eventsToWaitFor); - } - public CLEvent write(CLQueue queue, Image image, boolean allowDeoptimizingDirectRead, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, image, 0, 0, image.getWidth(null), image.getHeight(null), allowDeoptimizingDirectRead, blocking, eventsToWaitFor); - } - public CLEvent write(CLQueue queue, Image image, int destX, int destY, int width, int height, boolean allowDeoptimizingDirectRead, boolean blocking, CLEvent... eventsToWaitFor) { - //int imWidth = image.getWidth(null), height = image.getHeight(null); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - return write(queue, 0, 0, width, height, width * info.pixelByteSize, info.dataGetter.getData(image, null, false, allowDeoptimizingDirectRead, getContext().getByteOrder()), blocking, eventsToWaitFor); - } - public void write(CLQueue queue, BufferedImage imageIn, boolean allowDeoptimizingDirectRead, CLEvent... eventsToWaitFor) { - //if (!getFormat().isIntBased()) - // throw new IllegalArgumentException("Image read only supports int-based RGBA images"); - - int width = imageIn.getWidth(null), height = imageIn.getHeight(null); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - write(queue, 0, 0, width, height, 0, info.dataGetter.getData(imageIn, null, false, allowDeoptimizingDirectRead, getContext().getByteOrder()), true, eventsToWaitFor); - } - public void write(CLQueue queue, BufferedImage im) { - write(queue, im, false); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(0, 0), toNS(getWidth(), getHeight()), getWidth(), null, true, eventsToWaitFor).getFirst(); - } - public ByteBuffer map(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long lengthX, long lengthY, long rowPitch, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(offsetX, offsetY), toNS(lengthX, lengthY), rowPitch, null, true, eventsToWaitFor).getFirst(); - } - public Pair mapLater(CLQueue queue, MapFlags flags, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(0, 0), toNS(getWidth(), getHeight()), getWidth(), null, blocking, eventsToWaitFor); - } - public Pair mapLater(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long lengthX, long lengthY, long rowPitch, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(offsetX, offsetY), toNS(lengthX, lengthY), rowPitch, null, blocking, eventsToWaitFor); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage3D.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage3D.java deleted file mode 100644 index b235f8f46..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImage3D.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_DEPTH; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_SLICE_PITCH; -import static com.nativelibs4java.util.JNAUtils.toNS; - -import java.nio.Buffer; -import java.nio.ByteBuffer; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.ochafik.util.listenable.Pair; - -/** - * OpenCL 3D Image Memory Object
- * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long) } - * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, long, long) } - * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, long, long, java.nio.Buffer, boolean) } - * see {@link CLContext#createImage3DFromGLTexture3D(com.nativelibs4java.opencl.CLMem.Usage, int, int) } - * @author Olivier Chafik - */ -public class CLImage3D extends CLImage2D { - CLImage3D(CLContext context, cl_mem entity, CLImageFormat format) { - super(context, entity, format); - } - - /** - * Return size in bytes of a 2D slice for this 3D image object.
- */ - @InfoName("CL_IMAGE_SLICE_PITCH") - public long getSlicePitch() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_SLICE_PITCH); - } - - /** - * Return depth of the image in pixels. - */ - @InfoName("CL_IMAGE_DEPTH") - public long getDepth() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_DEPTH); - } - - public CLEvent read(CLQueue queue, long minX, long minY, long minZ, long width, long height, long depth, long rowPitch, long slicePitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, toNS(minX, minY, minZ), toNS(width, height, depth), rowPitch, slicePitch, out, blocking, eventsToWaitFor); - } - - public CLEvent write(CLQueue queue, long minX, long minY, long minZ, long width, long height, long depth, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, toNS(minX, minY, minZ), toNS(width, height, depth), rowPitch, slicePitch, in, blocking, eventsToWaitFor); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, 0, 0, 0, getWidth(), getHeight(), getDepth(), getWidth(), getHeight(), true, eventsToWaitFor); - } - public Pair mapLater(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(0, 0, 0), toNS(getWidth(), getHeight(), getDepth()), getWidth(), getHeight(), true, eventsToWaitFor); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long offsetZ, long lengthX, long lengthY, long lengthZ, long rowPitch, long slicePitch, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(offsetX, offsetY, offsetZ), toNS(lengthX, lengthY, lengthZ), rowPitch, slicePitch, true, eventsToWaitFor).getFirst(); - } - public Pair mapLater(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long offsetZ, long lengthX, long lengthY, long lengthZ, long rowPitch, long slicePitch, CLEvent... eventsToWaitFor) { - return map(queue, flags, toNS(offsetX, offsetY, offsetZ), toNS(lengthX, lengthY, lengthZ), rowPitch, slicePitch, true, eventsToWaitFor); - } - -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImageFormat.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImageFormat.java deleted file mode 100644 index 178b120bf..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLImageFormat.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.ValuedEnum; - -/** - * OpenCL Image Format - * see {@link CLContext#getSupportedImageFormats(com.nativelibs4java.opencl.CLMem.Flags, com.nativelibs4java.opencl.CLMem.ObjectType) } - * @author Olivier Chafik - */ -public class CLImageFormat { - - private final ChannelOrder channelOrder; - private final ChannelDataType channelDataType; - - CLImageFormat(cl_image_format fmt) { - this(ChannelOrder.getEnum(fmt.image_channel_order), ChannelDataType.getEnum(fmt.image_channel_data_type)); - } - cl_image_format to_cl_image_format() { - return new cl_image_format((int)channelOrder.value(), (int)channelDataType.value()); - } - public CLImageFormat(ChannelOrder channelOrder, ChannelDataType channelDataType) { - super(); - this.channelDataType = channelDataType; - this.channelOrder = channelOrder; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof CLImageFormat)) - return false; - CLImageFormat f = (CLImageFormat)obj; - if (channelOrder == null) { - if (f.channelOrder != null) - return false; - } else if (!channelOrder.equals(f.channelOrder)) - return false; - - - if (channelDataType == null) { - return f.channelDataType == null; - } else return channelDataType.equals(f.channelDataType); - } - - @Override - public int hashCode() { - int h = super.hashCode(); - if (channelOrder != null) - h ^= channelOrder.hashCode(); - if (channelDataType != null) - h ^= channelDataType.hashCode(); - return h; - } - - public boolean isIntBased() { - if (channelDataType == null || channelOrder == null) - return false; - switch (getChannelOrder()) { - case ARGB: - case BGRA: - case RGBA: - switch (getChannelDataType()) { - case SNormInt8: - case SignedInt8: - case UNormInt8: - case UnsignedInt8: - return true; - } - } - return false; - } - public final ChannelOrder getChannelOrder() { - return channelOrder; - } - public final ChannelDataType getChannelDataType() { - return channelDataType; - } - - @Override - public String toString() { - return "(" + channelOrder + ", " + channelDataType + ")"; - } - - - - public enum ChannelOrder implements ValuedEnum { - - /** - * components of channel data: (r, 0.0, 0.0, 1.0) - */ - R(CL_R), - /** - * components of channel data: (r, 0.0, 0.0, 1.0) - * @since OpenCL 1.1 - */ - Rx(CL_Rx), - /** - * components of channel data: (0.0, 0.0, 0.0, a) - */ - A(CL_A), - /** - * components of channel data: (I, I, I, I)
- * This format can only be used if channel data type = CL_UNORM_INT8, CL_UNORM_INT16, CL_SNORM_INT8, CL_SNORM_INT16, CL_HALF_FLOAT or CL_FLOAT. - */ - INTENSITY(CL_INTENSITY), - /** - * components of channel data: (L, L, L, 1.0)
- * This format can only be used if channel data type = CL_UNORM_INT8, CL_UNORM_INT16, CL_SNORM_INT8, CL_SNORM_INT16, CL_HALF_FLOAT or CL_FLOAT. - */ - LUMINANCE(CL_LUMINANCE), - /** - * components of channel data: (r, g, 0.0, 1.0) - */ - RG(CL_RG), - /** - * components of channel data: (r, g, 0.0, 1.0) - * @since OpenCL 1.1 - */ - RGx(CL_RGx), - /** - * components of channel data: (r, 0.0, 0.0, a) - */ - RA(CL_RA), - /** - * components of channel data: (r, g, b, 1.0)
- * This format can only be used if channel data type = CL_UNORM_SHORT_565, CL_UNORM_SHORT_555 or CL_UNORM_INT101010. - */ - RGB(CL_RGB), - /** - * components of channel data: (r, g, b, 1.0)
- * This format can only be used if channel data type = CL_UNORM_SHORT_565, CL_UNORM_SHORT_555 or CL_UNORM_INT101010. - * @since OpenCL 1.1 - */ - RGBx(CL_RGBx), - /** - * components of channel data: (r, g, b, a) - */ - RGBA(CL_RGBA), - /** - * components of channel data: (r, g, b, a) - */ - ARGB(CL_ARGB), - /** - * components of channel data: (r, g, b, a)
- * This format can only be used if channel data type = CL_UNORM_INT8, CL_SNORM_INT8, CL_SIGNED_INT8 or CL_UNSIGNED_INT8. - */ - BGRA(CL_BGRA); - - - ChannelOrder(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static ChannelOrder getEnum(long v) { return EnumValues.getEnum(v, ChannelOrder.class); } - - } - - /** - * For example, to specify a normalized unsigned 8-bit / channel RGBA image, image_channel_order = CL_RGBA, and image_channel_data_type = CL_UNORM_INT8. The memory layout of this image format is described below: - */ - public enum ChannelDataType implements ValuedEnum { - /** - * Each channel component is a normalized signed 8-bit integer value - */ - SNormInt8(CL_SNORM_INT8, 8), - /** - * Each channel component is a normalized signed 16-bit integer value - */ - SNormInt16(CL_SNORM_INT16, 16), - /** - * Each channel component is a normalized unsigned 8-bit integer value - */ - UNormInt8(CL_UNORM_INT8, 8), - /** - * Each channel component is a normalized unsigned 16- bit integer value - */ - UNormInt16(CL_UNORM_INT16, 16), - /** - * Represents a normalized 5-6-5 3-channel RGB image.
- * The channel order must be CL_RGB or CL_RGBx.
- * CL_UNORM_SHORT_565 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
- * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
- * For CL_UNORM_SHORT_565, R is in bits 15:11, G is in bits 10:5 and B is in bits 4:0. - */ - UNormShort565(CL_UNORM_SHORT_565, 16/* ?? */), - /** - * Represents a normalized x-5-5-5 4-channel xRGB image.
- * The channel order must be CL_RGB or CL_RGBx.
- * CL_UNORM_SHORT_555 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
- * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
- * For CL_UNORM_SHORT_555, bit 15 is undefined, R is in bits 14:10, G in bits 9:5 and B in bits 4:0. - */ - UNormShort555(CL_UNORM_SHORT_555, 15/* ?? */), - /** - * Represents a normalized x-10-10-10 4-channel xRGB image.
- * The channel order must be CL_RGB or CL_RGBx.
- * CL_UNORM_INT_101010 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
- * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
- * For CL_UNORM_INT_101010, bits 31:30 are undefined, R is in bits 29:20, G in bits 19:10 and B in bits 9:0. - */ - UNormInt101010(CL_UNORM_INT_101010, 30/* TODO ?? */), - /** - * Each channel component is an unnormalized signed 8- bit integer value - */ - SignedInt8(CL_SIGNED_INT8, 8), - /** - * Each channel component is an unnormalized signed 16- bit integer value - */ - SignedInt16(CL_SIGNED_INT16, 16), - /** - * Each channel component is an unnormalized signed 32- bit integer value - */ - SignedInt32(CL_SIGNED_INT32, 32), - /** - * Each channel component is an unnormalized unsigned 8-bit integer value - */ - UnsignedInt8(CL_UNSIGNED_INT8, 8), - /** - * Each channel component is an unnormalized unsigned 16-bit integer value - */ - UnsignedInt16(CL_UNSIGNED_INT16, 16), - /** - * Each channel component is an unnormalized unsigned 32-bit integer value - */ - UnsignedInt32(CL_UNSIGNED_INT32, 32), - /** - * Each channel component is a 16-bit half-float value - */ - HalfFloat(CL_HALF_FLOAT, 16), - /** - * Each channel component is a single precision floating- point value - */ - Float(CL_FLOAT, 32); - - ChannelDataType(long value, int bits) { - this.SIZE = bits; - this.value = value; - } - /** - * Size of this ChannelDataType, in bits - */ - public final int SIZE; - long value; - @Override - public long value() { return value; } - public static ChannelDataType getEnum(long v) { return EnumValues.getEnum(v, ChannelDataType.class); } - } - - static CLImageFormat INT_ARGB_FORMAT = new CLImageFormat(ChannelOrder.BGRA, ChannelDataType.UNormInt8); - //static CLImageFormat INT_ARGB_FORMAT = new CLImageFormat(ChannelOrder.RGBA, ChannelDataType.UNormInt8); -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLInfoGetter.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLInfoGetter.java deleted file mode 100644 index 716200881..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLInfoGetter.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.util.JNAUtils.readNS; -import static com.nativelibs4java.util.JNAUtils.toNS; - -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Memory; -import com.sun.jna.Pointer; -import com.sun.jna.PointerType; -import com.sun.jna.ptr.IntByReference; - -/** - * - * @author ochafik - */ -abstract class CLInfoGetter { - - protected abstract int getInfo(T entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut); - - public String getString(T entity, int infoName) { - NativeSizeByReference pLen = new NativeSizeByReference(); - error(getInfo(entity, infoName, toNS(0), null, pLen)); - - int len = pLen.getValue().intValue(); - if (len == 0) { - return ""; - } - Memory buffer = new Memory(len + 1); - error(getInfo(entity, infoName, pLen.getValue(), buffer, null)); - - return buffer.getString(0); - } - - public Pointer getPointer(T entity, int infoName) { - NativeSizeByReference pLen = new NativeSizeByReference(); - Memory mem = new Memory(Pointer.SIZE); - error(getInfo(entity, infoName, toNS(Pointer.SIZE), mem, pLen)); - if (pLen.getValue().intValue() != Pointer.SIZE) { - throw new RuntimeException("Not a pointer : len = " + pLen.getValue()); - } - return mem.getPointer(0); - } - - public Memory getMemory(T entity, int infoName) { - NativeSizeByReference pLen = new NativeSizeByReference(); - error(getInfo(entity, infoName, toNS(0), null, pLen)); - - Memory buffer = new Memory(pLen.getValue().intValue()); - error(getInfo(entity, infoName, pLen.getValue(), buffer, null)); - - return buffer; - } - - public long[] getNativeSizes(T entity, int infoName, int n) { - int nBytes = NativeSize.SIZE * n; - NativeSizeByReference pLen = new NativeSizeByReference(toNS(nBytes)); - Memory mem = new Memory(nBytes); - error(getInfo(entity, infoName, toNS(nBytes), mem, null)); - - if (pLen.getValue().longValue() != nBytes) { - throw new RuntimeException("Not a Size[" + n + "] : len = " + pLen.getValue()); - } - long[] longs = new long[n]; - for (int i = 0; i < n; i++) { - longs[i] = readNS(mem, i * NativeSize.SIZE).longValue(); - } - return longs; - } - - public int getOptionalFeatureInt(T entity, int infoName) { - try { - return getInt(entity, infoName); - } catch (CLException.InvalidValue ex) { - throw new UnsupportedOperationException("Cannot get value " + infoName, ex); - } catch (CLException.InvalidOperation ex) { - throw new UnsupportedOperationException("Cannot get value " + infoName, ex); - } - } - public int getInt(T entity, int infoName) { - return (int)getIntOrLong(entity, infoName); - } - - public boolean getBool(T entity, int infoName) { - NativeSizeByReference pLen = new NativeSizeByReference(); - Memory mem = new Memory(8); - error(getInfo(entity, infoName, toNS(8), mem, pLen)); - - switch ((int)pLen.getValue().longValue()) { - case 1: - return mem.getByte(0) != 0; - case 2: - return mem.getShort(0) != 0; - case 4: - return mem.getInt(0) != 0; - case 8: - return mem.getLong(0) != 0; - default: - throw new RuntimeException("Not a BOOL : len = " + pLen.getValue()); - } - } - - public long getIntOrLong(T entity, int infoName) { - NativeSizeByReference pLen = new NativeSizeByReference(); - Memory mem = new Memory(8); - error(getInfo(entity, infoName, toNS(8), mem, pLen)); - - switch (pLen.getValue().intValue()) { - case 4: - return mem.getInt(0); - case 8: - return mem.getLong(0); - default: - throw new RuntimeException("Not a native long : len = " + pLen.getValue()); - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLIntBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLIntBuffer.java deleted file mode 100644 index 2e84c6dd4..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLIntBuffer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Int values.
- * see {@link CLContext#createIntBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createIntBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.IntBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Integer}> - */ -@Deprecated -public class CLIntBuffer extends CLBuffer { - CLIntBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 4, IntBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLKernel.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLKernel.java deleted file mode 100644 index 9860a4526..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLKernel.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.*; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import static com.nativelibs4java.util.JNAUtils.toNS; - -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.util.HashMap; -import java.util.Map; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Native; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.ByteByReference; -import com.sun.jna.ptr.DoubleByReference; -import com.sun.jna.ptr.FloatByReference; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.LongByReference; -import com.sun.jna.ptr.PointerByReference; -import com.sun.jna.ptr.ShortByReference; - -/** - * OpenCL kernel.
- * A kernel is a function declared in a program.
- * A kernel is identified by the __kernel qualifier applied to any function in a program.
- * A kernel object encapsulates the specific __kernel function declared in a program and the argument values to be used when executing this __kernel function.
- *
- * Kernels can be queued for execution in a CLQueue (see enqueueTask and enqueueNDRange) - * See {@link CLProgram#createKernel(java.lang.String, java.lang.Object[])} and {@link CLProgram#createKernels()} - * @author Olivier Chafik - */ -public class CLKernel extends CLAbstractEntity { - - protected final CLProgram program; - protected String name; - private static CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_kernel entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetKernelInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - private volatile CLInfoGetter kernelInfos; - protected synchronized CLInfoGetter getKernelInfos() { - if (kernelInfos == null) - kernelInfos = new CLInfoGetter() { - - @Override - protected int getInfo(cl_device_id entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetKernelWorkGroupInfo(getEntity(), entity, infoTypeEnum, size, out, sizeOut); - } - }; - return kernelInfos; - } - - CLKernel(CLProgram program, String name, cl_kernel entity) { - super(entity); - this.program = program; - this.name = name; - } - public CLProgram getProgram() { - return program; - } - - public String toString() { - return getFunctionName() + " {args: " + getNumArgs() + "}";//, workGroupSize = " + getWorkGroupSize() + ", localMemSize = " + getLocalMemSize() + "}"; - } - - /** - * Returns the preferred multiple of work- group size for launch.
- * This is a performance hint.
- * Specifying a work- group size that is not a multiple of the value returned by this query as the value of the local work size argument to clEnqueueNDRangeKernel will not fail to enqueue the kernel for execution unless the work-group size specified is larger than the device maximum. - * @since OpenCL 1.1 - */ - public Map getPreferredWorkGroupSizeMultiple() { - try { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE)); - return ret; - } catch (Throwable th) { - // TODO check if supposed to handle OpenCL 1.1 - throw new UnsupportedOperationException("Cannot get CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE (OpenCL 1.1 feature).", th); - } - } - - /** - * This provides a mechanism for the application to query the maximum work-group size that can be used to execute a kernel on a specific device given by device.
- * The OpenCL implementation uses the resource requirements of the kernel (register usage etc.) to determine what this work- group size should be.
- * See CL_KERNEL_WORK_GROUP_SIZE - */ - public Map getWorkGroupSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_WORK_GROUP_SIZE)); - return ret; - } - - /** - * Returns the work-group size specified by the __attribute__((reqd_work_gr oup_size(X, Y, Z))) qualifier.
- * Refer to section 6.7.2.
- * If the work-group size is not specified using the above attribute qualifier (0, 0, 0) is returned.
- * See CL_KERNEL_COMPILE_WORK_GROUP_SIZE - * @return for each CLDevice, array of 3 longs - */ - public Map getCompileWorkGroupSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getNativeSizes(device.getEntity(), CL_KERNEL_COMPILE_WORK_GROUP_SIZE, 3)); - return ret; - } - - /** - * Returns the amount of local memory in bytes being used by a kernel.
- * This includes local memory that may be needed by an implementation to execute the kernel, variables declared inside the kernel with the __local address qualifier and local memory to be allocated for arguments to the kernel declared as pointers with the __local address qualifier and whose size is specified with clSetKernelArg.
- * If the local memory size, for any pointer argument to the kernel declared with the __local address qualifier, is not specified, its size is assumed to be 0.
- * See CL_KERNEL_LOCAL_MEM_SIZE - */ - public Map getLocalMemSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_LOCAL_MEM_SIZE)); - return ret; - } - - public void setArgs(Object... args) { - for (int i = 0; i < args.length; i++) { - setObjectArg(i, args[i]); - } - } - - public static class LocalSize { - long size; - public LocalSize(long size) { - this.size = size; - } - } - private static final NativeSize zeroNS = toNS(0); - public static final Object NULL_POINTER_KERNEL_ARGUMENT = new Object() {}; - public void setObjectArg(int iArg, Object arg) { - - if (arg == null) - throw new IllegalArgumentException("Null arguments are not accepted. Please use CLKernel.NULL_POINTER_KERNEL_ARGUMENT instead."); - - if (arg == NULL_POINTER_KERNEL_ARGUMENT) { - setArg(iArg, (NativeSize)zeroNS); - //} else if (arg instanceof NativeLong) { - // setArg(iArg, (NativeLong) arg); - } else if (arg instanceof NativeSize) { - setArg(iArg, (NativeSize) arg); - } else if (arg instanceof CLMem) { - setArg(iArg, (CLMem) arg); - } else if (arg instanceof CLEvent) { - setArg(iArg, (CLEvent) arg); - } else if (arg instanceof CLSampler) { - setArg(iArg, (CLSampler) arg); - } else if (arg instanceof Integer) { - setArg(iArg, (Integer) arg); - } else if (arg instanceof LocalSize) { - setArg(iArg, (LocalSize)arg); - } else if (arg instanceof Long) { - setArg(iArg, (Long) arg); - } else if (arg instanceof Short) { - setArg(iArg, (Short) arg); - } else if (arg instanceof Byte) { - setArg(iArg, (Byte) arg); - } else if (arg instanceof Float) { - setArg(iArg, (Float) arg); - } else if (arg instanceof Double) { - setArg(iArg, (Double) arg); - } else if (arg instanceof Boolean) { - setArg(iArg, (byte)(Boolean.TRUE.equals(arg) ? 1 : 0)); - } else if (arg instanceof Buffer) { - setArg(iArg, (Buffer) arg); - } else if (arg instanceof int[]) { - setArg(iArg, IntBuffer.wrap((int[])arg)); - } else if (arg instanceof long[]) { - setArg(iArg, LongBuffer.wrap((long[])arg)); - } else if (arg instanceof short[]) { - setArg(iArg, ShortBuffer.wrap((short[])arg)); - } else if (arg instanceof double[]) { - setArg(iArg, DoubleBuffer.wrap((double[])arg)); - } else if (arg instanceof float[]) { - setArg(iArg, FloatBuffer.wrap((float[])arg)); - } else if (arg instanceof byte[]) { - setArg(iArg, ByteBuffer.wrap((byte[])arg)); - } else if (arg instanceof boolean[]) { - boolean[] bools = (boolean[])arg; - byte[] bytes = new byte[bools.length]; - for (int iValue = 0, n = bools.length; iValue < n; iValue++) - bytes[iValue] = (byte)(bools[iValue] ? 1 : 0); - setArg(iArg, ByteBuffer.wrap(bytes)); - } else { - throw new IllegalArgumentException("Cannot handle kernel arguments of type " + arg.getClass().getName() + ". Use CLKernel.get() and OpenCL4Java directly."); - } - } - - public void setArg(int i, LocalSize arg) { - setLocalArg(i, arg.size); - } - public void setLocalArg(int argIndex, long localArgByteLength) { - setKernelArg(argIndex, toNS(localArgByteLength), null); - } - - //public void setArg(int i, NativeLong arg) { - // error(CL.clSetKernelArg(getEntity(), i, toNS(NativeLong.SIZE), new NativeLongByReference(arg).getPointer())); -// error(CL.clSetKernelArg(get(), i, OpenCL4Java.toNL(Native.LONG_SIZE), new IntByReference(128).getPointer())); -// error(CL.clSetKernelArg(get(), i, toNL(Native.LONG_SIZE), new IntByReference(arg.intValue()).getPointer())); - //} - - public void setArg(int i, float[] arg) { - setArg(i, FloatBuffer.wrap(arg)); - } - public void setArg(int i, int[] arg) { - setArg(i, IntBuffer.wrap(arg)); - } - public void setArg(int i, double[] arg) { - setArg(i, DoubleBuffer.wrap(arg)); - } - public void setArg(int i, long[] arg) { - setArg(i, LongBuffer.wrap(arg)); - } - public void setArg(int i, short[] arg) { - setArg(i, ShortBuffer.wrap(arg)); - } - public void setArg(int i, byte[] arg) { - setArg(i, ByteBuffer.wrap(arg)); - } - public void setArg(int i, char[] arg) { - setArg(i, CharBuffer.wrap(arg)); - } - public void setArg(int i, Buffer arg) { - if (!arg.isDirect()) - arg = NIOUtils.directCopy(arg, getProgram().getContext().getByteOrder()); - long size = NIOUtils.getSizeInBytes(arg); - setKernelArg(i, toNS(size), Native.getDirectBufferPointer(arg)); - } - - protected void setKernelArg(int i, NativeSize size, Pointer ptr) { - try { - error(CL.clSetKernelArg(getEntity(), i, size, ptr)); - } catch (CLTypedException ex) { - ex.setKernelArg(this, i); - throw ex; - } - } - - public void setArg(int i, NativeSize arg) { - switch (getProgram().getContext().getAddressBits()) { - case 32: - setKernelArg(i, toNS(4), new IntByReference(arg.intValue()).getPointer()); - break; - case 64: - setKernelArg(i, toNS(8), new LongByReference(arg.longValue()).getPointer()); - break; - default: - setKernelArg(i, toNS(NativeSize.SIZE), new NativeSizeByReference(arg).getPointer()); - break; - } - } - - public void setArg(int i, int arg) { - setKernelArg(i, toNS(4), new IntByReference(arg).getPointer()); - } - - public void setArg(int i, long arg) { - setKernelArg(i, toNS(8), new LongByReference(arg).getPointer()); - } - - public void setArg(int i, short arg) { - setKernelArg(i, toNS(2), new ShortByReference(arg).getPointer()); - } - - public void setArg(int i, byte arg) { - setKernelArg(i, toNS(1), new ByteByReference(arg).getPointer()); - } - - public void setArg(int i, float arg) { - setKernelArg(i, toNS(4), new FloatByReference(arg).getPointer()); - } - - public void setArg(int i, double arg) { - setKernelArg(i, toNS(8), new DoubleByReference(arg).getPointer()); - } - - public void setArg(int index, CLMem mem) { - setKernelArg(index, toNS(Pointer.SIZE), new PointerByReference(mem.getEntity().getPointer()).getPointer()); - } - - public void setArg(int index, CLEvent event) { - setKernelArg(index, toNS(Pointer.SIZE), new PointerByReference(event.getEntity().getPointer()).getPointer()); - } - - public void setArg(int index, CLSampler sampler) { - setKernelArg(index, toNS(Pointer.SIZE), new PointerByReference(sampler.getEntity().getPointer()).getPointer()); - } - - @Override - protected void clear() { - error(CL.clReleaseKernel(getEntity())); - } - - private static final NativeSize[] oneNL = new NativeSize[] {new NativeSize(1)}; - /** - * Enqueues a command to execute a kernel on a device.
- * The kernel is executed using a single work-item. - * @param queue - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueTask(CLQueue queue, CLEvent... eventsToWaitFor) { - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueNDRangeKernel(queue.getEntity(), getEntity(), 1, null, oneNL, oneNL, evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(queue, eventOut); - } - - /** - * Enqueues a command to execute a kernel on a device (see {@link CLKernel#enqueueNDRange(CLQueue, int[], int[], int[], CLEvent[])}) - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param localWorkSizes Each element describes the number of work-items that make up a work-group (also referred to as the size of the work-group) that will execute the kernel specified by kernel. The total number of work-items in a work-group is computed as localWorkSizes[0] * ... * localWorkSizes[localWorkSizes.length - 1]. The total number of work-items in the work-group must be less than or equal to the CL_DEVICE_MAX_WORK_GROUP_SIZE value specified in table 4.3 and the number of work- items specified in localWorkSizes[0], ... localWorkSizes[localWorkSizes.length - 1] must be less than or equal to the corresponding values specified by CLDevice.getMaxWorkItemSizes()[dimensionIndex]. The explicitly specified localWorkSize will be used to determine how to break the global work-items specified by global_work_size into appropriate work-group instances. If localWorkSize is specified, the values specified in globalWorkSize[dimensionIndex] must be evenly divisible by the corresponding values specified in localWorkSize[dimensionIndex]. This parameter can be left null, in which case the OpenCL implementation will choose good values. - * @param queue This kernel will be queued for execution on the device associated with that queue. - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueNDRange(CLQueue queue /*, int[] globalOffsets*/, int[] globalWorkSizes, int[] localWorkSizes, CLEvent... eventsToWaitFor) { - return enqueueNDRange(queue, null, globalWorkSizes, localWorkSizes, eventsToWaitFor); - } - - /** - * Enqueues a command to execute a kernel on a device, using local work sizes chosen by the OpenCL implementation. - * See {@link CLKernel#enqueueNDRange(CLQueue, int[], int[], int[], CLEvent[])} - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param queue This kernel will be queued for execution on the device associated with that queue. - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueNDRange(CLQueue queue /*, int[] globalOffsets*/, int[] globalWorkSizes, CLEvent... eventsToWaitFor) { - return enqueueNDRange(queue, null, globalWorkSizes, null, eventsToWaitFor); - } - - /** - * Enqueues a command to execute a kernel on a device. - * @param globalOffsets Must be null in OpenCL 1.0. Each element describes the offset used to calculate the global ID of a work-item. If globalOffsets is null, the global IDs start at offset (0, 0, ... 0). - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param localWorkSizes Each element describes the number of work-items that make up a work-group (also referred to as the size of the work-group) that will execute the kernel specified by kernel. The total number of work-items in a work-group is computed as localWorkSizes[0] * ... * localWorkSizes[localWorkSizes.length - 1]. The total number of work-items in the work-group must be less than or equal to the CL_DEVICE_MAX_WORK_GROUP_SIZE value specified in table 4.3 and the number of work- items specified in localWorkSizes[0], ... localWorkSizes[localWorkSizes.length - 1] must be less than or equal to the corresponding values specified by CLDevice.getMaxWorkItemSizes()[dimensionIndex]. The explicitly specified localWorkSize will be used to determine how to break the global work-items specified by global_work_size into appropriate work-group instances. If localWorkSize is specified, the values specified in globalWorkSize[dimensionIndex] must be evenly divisible by the corresponding values specified in localWorkSize[dimensionIndex]. This parameter can be left null, in which case the OpenCL implementation will choose good values. - * @param queue This kernel will be queued for execution on the device associated with that queue. - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueNDRange(CLQueue queue, int[] globalOffsets, int[] globalWorkSizes, int[] localWorkSizes, CLEvent... eventsToWaitFor) { - int nDims = globalWorkSizes.length; - if (localWorkSizes != null && localWorkSizes.length != nDims) { - throw new IllegalArgumentException("Global and local sizes must have same dimensions, given " + globalWorkSizes.length + " vs. " + localWorkSizes.length); - } - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueNDRangeKernel(queue.getEntity(), getEntity(), nDims, toNS(globalOffsets), toNS(globalWorkSizes), toNS(localWorkSizes), evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(queue, eventOut); - } - - /** - * Return the number of arguments to kernel. - */ - @InfoName("CL_KERNEL_NUM_ARGS") - public int getNumArgs() { - return infos.getInt(getEntity(), CL_KERNEL_NUM_ARGS); - } - - /** - * Return the kernel function name. - */ - @InfoName("CL_KERNEL_FUNCTION_NAME") - public String getFunctionName() { - if (name == null) - name = infos.getString(getEntity(), CL_KERNEL_FUNCTION_NAME); - return name; - } - - -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLLongBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLLongBuffer.java deleted file mode 100644 index a0c7f4e6c..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLLongBuffer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Long values.
- * see {@link CLContext#createLongBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createLongBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.LongBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Long}> - */ -@Deprecated -public class CLLongBuffer extends CLBuffer { - CLLongBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 8, LongBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLMem.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLMem.java deleted file mode 100644 index 43be6c4b3..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLMem.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import java.util.EnumSet; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.ValuedEnum; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Callback; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.IntByReference; - -/** - * OpenCL memory object.
- * Memory objects are categorized into two types: buffer objects, and image objects.
- * A buffer object stores a one-dimensional collection of elements whereas an image object is used to store a two- or three- dimensional texture, frame-buffer or image.
- * Elements of a buffer object can be a scalar data type (such as an int, float), vector data type, or a user-defined structure. An image object is used to represent a buffer that can be used as a texture or a frame-buffer. The elements of an image object are selected from a list of predefined image formats.
- * The minimum number of elements in a memory object is one.
- * The fundamental differences between a buffer and an image object are: - *
    - *
  • Elements in a buffer are stored in sequential fashion and can be accessed using a pointer by a kernel executing on a device. Elements of an image are stored in a format that is opaque to the user and cannot be directly accessed using a pointer. Built-in functions are provided by the OpenCL C programming language to allow a kernel to read from or write to an image.
  • - *
  • For a buffer object, the data is stored in the same format as it is accessed by the kernel, but in the case of an image object the data format used to store the image elements may not be the same as the data format used inside the kernel. Image elements are always a 4- component vector (each component can be a float or signed/unsigned integer) in a kernel. The built-in function to read from an image converts image element from the format it is stored into a 4-component vector. Similarly, the built-in function to write to an image converts the image element from a 4-component vector to the appropriate image format specified such as 4 8-bit elements, for example.
  • - *
- * - * Kernels take memory objects as input, and output to one or more memory objects. - * @author Olivier Chafik - */ -public abstract class CLMem extends CLAbstractEntity { - - protected final CLContext context; - protected long byteCount = -1; - boolean isGL; - - protected static CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_mem entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetImageInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - CLMem(CLContext context, long byteCount, cl_mem entity) { - super(entity); - this.byteCount = byteCount; - this.context = context; - } - - public CLContext getContext() { - return context; - } - - public interface DestructorCallback { - void callback(CLMem mem); - } - - /** - * Registers a user callback function that will be called when the memory object is deleted and its resources freed.
- * Each call to clSetMemObjectDestructorCallback registers the specified user callback function on a callback stack associated with memobj.
- * The registered user callback functions are called in the reverse order in which they were registered.
- * The user callback functions are called and then the memory object's resources are freed and the memory object is deleted.
- * This provides a mechanism for the application (and libraries) using memobj to be notified when the memory referenced by host_ptr, specified when the memory object is created and used as the storage bits for the memory object, can be reused or freed. - * @since OpenCL 1.1 - * @param callback - */ - public void setDestructorCallback(final DestructorCallback callback) { - error(CL.clSetMemObjectDestructorCallback(getEntity(), new clSetMemObjectDestructorCallback_arg1_callback() { - /// @param cl_mem1 user_data - public void invoke(OpenCLLibrary.cl_mem mem, Pointer userData) { - callback.callback(CLMem.this); - } - }, null)); - } - - public CLEvent acquireGLObject(CLQueue queue, CLEvent... eventsToWaitFor) { - return queue.enqueueAcquireGLObjects(new CLMem[] { this }, eventsToWaitFor); - } - - public CLEvent releaseGLObject(CLQueue queue, CLEvent... eventsToWaitFor) { - return queue.enqueueReleaseGLObjects(new CLMem[] { this }, eventsToWaitFor); - } - - /** - * Get the actual size of the memory object in bytes - * @return actual size of the memory object in bytes - */ - public long getByteCount() { - if (byteCount < 0) { - try { - byteCount = infos.getIntOrLong(getEntity(), CL_MEM_SIZE); - } catch (CLException.InvalidMemObject ex) { - if (isGL) - return -1; // GL objects are not (always?) considered as valid mem objects - else - throw ex; - } - } - return byteCount; - } - - /** - * Memory Object Usage enum - */ - public enum Usage { - Input(CL_MEM_READ_ONLY, Flags.ReadOnly), - Output(CL_MEM_WRITE_ONLY, Flags.WriteOnly), - InputOutput(CL_MEM_READ_WRITE, Flags.ReadWrite); - - private int intFlags; - private Flags flags; - Usage(int intFlags, Flags flags) { - this.intFlags = intFlags; - this.flags = flags; - } - public int getIntFlags() { - return intFlags; - } - public Flags getFlags() { - return flags; - } - } - - public enum Flags implements ValuedEnum { - /** - * This flag specifies that the memory object will be read and written by a kernel. This is the default. - */ - ReadWrite(CL_MEM_READ_WRITE), - /** - * This flags specifies that the memory object will be written but not read by a kernel.
- * Reading from a buffer or image object created with CL_MEM_WRITE_ONLY inside a kernel is undefined. - */ - WriteOnly(CL_MEM_WRITE_ONLY), - /** - * This flag specifies that the memory object is a read-only memory object when used inside a kernel.
- * Writing to a buffer or image object created with CL_MEM_READ_ONLY inside a kernel is undefined. - */ - ReadOnly(CL_MEM_READ_ONLY), - /** - * This flag is valid only if host_ptr is not NULL. If specified, it indicates that the application wants the OpenCL implementation to use memory referenced by host_ptr as the storage bits for the memory object.
- * OpenCL implementations are allowed to cache the buffer contents pointed to by host_ptr in device memory. This cached copy can be used when kernels are executed on a device.
- * The result of OpenCL commands that operate on multiple buffer objects created with the same host_ptr or overlapping host regions is considered to be undefined. - */ - UseHostPtr(CL_MEM_USE_HOST_PTR), - /** - * This flag specifies that the application wants the OpenCL implementation to allocate memory from host accessible memory.
- * CL_MEM_ALLOC_HOST_PTR and CL_MEM_USE_HOST_PTR are mutually exclusive.
- * CL_MEM_COPY_HOST_PTR: This flag is valid only if host_ptr is not NULL. If specified, it indicates that the application wants the OpenCL implementation to allocate memory for the memory object and copy the data from memory referenced by host_ptr.
- * CL_MEM_COPY_HOST_PTR and CL_MEM_USE_HOST_PTR are mutually exclusive.
- * CL_MEM_COPY_HOST_PTR can be used with CL_MEM_ALLOC_HOST_PTR to initialize the contents of the cl_mem object allocated using host-accessible (e.g. PCIe) memory. - */ - AllocHostPtr(CL_MEM_ALLOC_HOST_PTR), - CopyHostPtr(CL_MEM_COPY_HOST_PTR); - - Flags(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static long getValue(EnumSet set) { return EnumValues.getValue(set); } - public static EnumSet getEnumSet(long v) { return EnumValues.getEnumSet(v, Flags.class); } - } - public enum ObjectType implements ValuedEnum { - Buffer(CL_MEM_OBJECT_BUFFER), - Image2D(CL_MEM_OBJECT_IMAGE2D), - Image3D(CL_MEM_OBJECT_IMAGE3D); - - ObjectType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static ObjectType getEnum(long v) { return EnumValues.getEnum(v, ObjectType.class); } - } - - public enum GLObjectType implements ValuedEnum { - Buffer(CL_GL_OBJECT_BUFFER), - RenderBuffer(CL_GL_OBJECT_RENDERBUFFER), - Texture2D(CL_GL_OBJECT_TEXTURE2D), - Texture3D(CL_GL_OBJECT_TEXTURE3D); - - GLObjectType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static GLObjectType getEnum(long v) { return EnumValues.getEnum(v, GLObjectType.class); } - } - - public static class GLObjectInfo { - final GLObjectType type; - final int name; - public GLObjectInfo(GLObjectType type, int name) { - this.type = type; - this.name = name; - } - public GLObjectType getType() { - return type; - } - public int getName() { - return name; - } - } - @SuppressWarnings("deprecation") - public GLObjectInfo getGLObjectInfo() { - IntByReference typeRef = new IntByReference(); - IntByReference nameRef = new IntByReference(); - CL.clGetGLObjectInfo(getEntity(), typeRef, nameRef); - return new GLObjectInfo(GLObjectType.getEnum(typeRef.getValue()), nameRef.getValue()); - } - public enum MapFlags implements ValuedEnum { - Read(CL_MAP_READ), - Write(CL_MAP_WRITE), - ReadWrite(CL_MAP_READ | CL_MAP_WRITE); - - MapFlags(long value) { this.value = value; } - long value; - public long value() { return value; } - public static MapFlags getEnum(long v) { return EnumValues.getEnum(v, MapFlags.class); } - } - - @Override - protected void clear() { - error(CL.clReleaseMemObject(getEntity())); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLPlatform.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLPlatform.java deleted file mode 100644 index 6dbfd9aa2..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLPlatform.java +++ /dev/null @@ -1,524 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - - -import com.nativelibs4java.util.ValuedEnum; -import com.nativelibs4java.opencl.library.OpenGLContextUtils; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.sun.jna.*; -import com.sun.jna.ptr.*; -import java.nio.ByteOrder; -import java.util.*; -import static com.nativelibs4java.opencl.JavaCL.*; -import static com.nativelibs4java.opencl.CLException.*; -import static com.nativelibs4java.util.JNAUtils.*; - -/** - * OpenCL implementation entry point. - * see {@link JavaCL#listPlatforms() } - * @author Olivier Chafik - */ -public class CLPlatform extends CLAbstractEntity { - - CLPlatform(cl_platform_id platform) { - super(platform, true); - } - private static CLInfoGetter infos = new CLInfoGetter() { - - @Override - protected int getInfo(cl_platform_id entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetPlatformInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - @Override - public String toString() { - return toString(new StringBuilder()).toString(); - } - StringBuilder toString(StringBuilder out) { - out. - append(getName()). - append(" {vendor: ").append(getVendor()). - append(", version: ").append(getVersion()). - append(", profile: ").append(getProfile()). - append(", extensions: ").append(Arrays.toString(getExtensions())). - append("}"); - return out; - } - - @Override - protected void clear() { - } - - /** - * Lists all the devices of the platform - * @param onlyAvailable if true, only returns devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listAllDevices(boolean onlyAvailable) { - return listDevices(CLDevice.Type.All, onlyAvailable); - } - - /** - * Lists all the GPU devices of the platform - * @param onlyAvailable if true, only returns GPU devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listGPUDevices(boolean onlyAvailable) { - try { - return listDevices(CLDevice.Type.GPU, onlyAvailable); - } catch (CLException ex) { - if (ex.getCode() == CL_DEVICE_NOT_FOUND) { - return new CLDevice[0]; - } - throw new RuntimeException("Unexpected OpenCL error", ex); - } - } - - /** - * Lists all the CPU devices of the platform - * @param onlyAvailable if true, only returns CPU devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listCPUDevices(boolean onlyAvailable) { - try { - return listDevices(CLDevice.Type.CPU, onlyAvailable); - } catch (CLException ex) { - if (ex.getCode() == CL_DEVICE_NOT_FOUND) { - return new CLDevice[0]; - } - throw new RuntimeException("Unexpected OpenCL error", ex); - } - } - - private CLDevice[] getDevices(cl_device_id[] ids, boolean onlyAvailable) { - int nDevs = ids.length; - CLDevice[] devices; - if (onlyAvailable) { - List list = new ArrayList(nDevs); - for (int i = 0; i < nDevs; i++) { - CLDevice device = new CLDevice(this, ids[i]); - if (device.isAvailable()) { - list.add(device); - } - } - devices = list.toArray(new CLDevice[list.size()]); - } else { - devices = new CLDevice[nDevs]; - for (int i = 0; i < nDevs; i++) { - devices[i] = new CLDevice(this, ids[i]); - } - } - return devices; - } - - static long[] getContextProps(Map contextProperties) { - if (contextProperties == null) - return null; - final long[] properties = new long[contextProperties.size() * 2 + 1]; - int iProp = 0; - for (Map.Entry e : contextProperties.entrySet()) { - //if (!(v instanceof Number)) throw new IllegalArgumentException("Invalid context property value for '" + e.getKey() + ": " + v); - properties[iProp++] = e.getKey().value(); - Object v = e.getValue(); - if (v instanceof Number) - properties[iProp++] = ((Number)v).longValue(); - else if (v instanceof Pointer) - properties[iProp++] = PointerUtils.getAddress((Pointer)v); - else - throw new IllegalArgumentException("Cannot convert value " + v + " to a context property value !"); - } - //properties[iProp] = 0; - return properties; - } - - /** - * Enums used to indicate how to choose the best CLDevice. - */ - public enum DeviceFeature { - /** - * Prefer CPU devices (see {@link CLDevice#getType() }) - */ - CPU { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.CPU) ? 1 : 0; - } - }, - /** - * Prefer GPU devices (see {@link CLDevice#getType() }) - */ - GPU { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.GPU) ? 1 : 0; - } - }, - /** - * Prefer Accelerator devices (see {@link CLDevice#getType() }) - */ - Accelerator { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.Accelerator) ? 1 : 0; - } - }, - /** - * Prefer devices with the most compute units (see {@link CLDevice#getMaxComputeUnits() }) - */ - MaxComputeUnits { - Comparable extractValue(CLDevice device) { - return device.getMaxComputeUnits(); - } - }, - /** - * Prefer devices with the same byte ordering as the hosting platform (see {@link CLDevice#getKernelsDefaultByteOrder() }) - */ - NativeEndianness { - Comparable extractValue(CLDevice device) { - return device.getKernelsDefaultByteOrder() == ByteOrder.nativeOrder() ? 1 : 0; - } - }, - /** - * Prefer devices that support double-precision float computations (see {@link CLDevice#isDoubleSupported() }) - */ - DoubleSupport { - Comparable extractValue(CLDevice device) { - return device.isDoubleSupported() ? 1 : 0; - } - }, - /** - * Prefer devices that support images and with the most supported image formats (see {@link CLDevice#hasImageSupport() }) - */ - ImageSupport { - Comparable extractValue(CLDevice device) { - return device.hasImageSupport() ? 1 : 0; - } - }, - /** - * Prefer devices that support out of order queues (see {@link CLDevice#hasOutOfOrderQueueSupport() }) - */ - OutOfOrderQueueSupport { - Comparable extractValue(CLDevice device) { - return device.hasOutOfOrderQueueSupport() ? 1 : 0; - } - }, - /** - * Prefer devices with the greatest variety of supported image formats (see {@link CLContext#getSupportedImageFormats() }) - */ - MostImageFormats { - Comparable extractValue(CLDevice device) { - if (!device.hasImageSupport()) - return 0; - // TODO: fix that ugly hack ? - CLContext context = JavaCL.createContext(null, device); - try { - return (Integer)context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image2D).length; - } finally { - context.release(); - } - } - }; - - Comparable extractValue(CLDevice device) { - throw new RuntimeException(); - } - } - - public static class DeviceComparator implements Comparator { - - private final List evals; - public DeviceComparator(List evals) { - this.evals = evals; - } - - @Override - public int compare(CLDevice a, CLDevice b) { - for (DeviceFeature eval : evals) { - if (eval == null) - continue; - - Comparable va = eval.extractValue(a), vb = eval.extractValue(b); - int c = va.compareTo(vb); - if (c != 0) - return c; - } - return 0; - } - - } - public static CLDevice getBestDevice(List evals, Collection devices) { - List list = new ArrayList(devices); - Collections.sort(list, new DeviceComparator(evals)); - return !list.isEmpty() ? list.get(list.size() - 1) : null; - } - - public CLDevice getBestDevice() { - return getBestDevice(Arrays.asList(DeviceFeature.MaxComputeUnits), Arrays.asList(listGPUDevices(true))); - } - - /** Bit values for CL_CONTEXT_PROPERTIES */ - public enum ContextProperties implements ValuedEnum { - //D3D10Device(CL_CONTEXT_D3D10_DEVICE_KHR), - GLContext(CL_GL_CONTEXT_KHR), - EGLDisplay(CL_EGL_DISPLAY_KHR), - GLXDisplay(CL_GLX_DISPLAY_KHR), - WGLHDC(CL_WGL_HDC_KHR), - Platform(CL_CONTEXT_PLATFORM), - CGLShareGroupApple(CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE), - CGLShareGroup(CL_CGL_SHAREGROUP_KHR); - - ContextProperties(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, ContextProperties.class); - } - } - - public CLContext createContextFromCurrentGL() { - return createGLCompatibleContext(listAllDevices(true)); - } - - static Map getGLContextProperties(CLPlatform platform) { - Map out = new LinkedHashMap(); - - if (Platform.isMac()) { - NativeSize context = OpenGLContextUtils.INSTANCE.CGLGetCurrentContext(); - NativeSize shareGroup = OpenGLContextUtils.INSTANCE.CGLGetShareGroup(context); - out.put(ContextProperties.CGLShareGroupApple, shareGroup.longValue()); - } else if (Platform.isWindows()) { - NativeSize context = OpenGLContextUtils.INSTANCE.wglGetCurrentContext(); - NativeSize dc = OpenGLContextUtils.INSTANCE.wglGetCurrentDC(); - out.put(ContextProperties.GLContext, context.longValue()); - out.put(ContextProperties.WGLHDC, dc.longValue()); - out.put(ContextProperties.Platform, PointerUtils.getAddress(platform.getEntity().getPointer())); - } else if (Platform.isX11()) { - NativeSize context = OpenGLContextUtils.INSTANCE.glXGetCurrentContext(); - NativeSize dc = OpenGLContextUtils.INSTANCE.glXGetCurrentDisplay(); - out.put(ContextProperties.GLContext, context.longValue()); - out.put(ContextProperties.GLXDisplay, dc.longValue()); - out.put(ContextProperties.Platform, PointerUtils.getAddress(platform.getEntity().getPointer())); - } else - throw new UnsupportedOperationException("Current GL context retrieval not implemented on this platform !"); - - //out.put(ContextProperties.Platform, platform.getEntity().getPointer()); - - return out; - } - @Deprecated - public CLContext createGLCompatibleContext(CLDevice... devices) { - try { - return createContext(getGLContextProperties(this), devices); - } catch (Throwable th) {} - - for (CLDevice device : devices) { - if (!device.isGLSharingSupported()) - continue; - - try { - return createContext(getGLContextProperties(this), device); - } catch (Throwable th) {} - } - throw new UnsupportedOperationException("Failed to create an OpenGL-sharing-enabled OpenCL context out of devices " + Arrays.asList(devices)); - } - - /** - * Creates an OpenCL context formed of the provided devices.
- * It is generally not a good idea to create a context with more than one device, - * because much data is shared between all the devices in the same context. - * @param devices devices that are to form the new context - * @return new OpenCL context - */ - public CLContext createContext(Map contextProperties, CLDevice... devices) { - int nDevs = devices.length; - if (nDevs == 0) { - throw new IllegalArgumentException("Cannot create a context with no associated device !"); - } - cl_device_id[] ids = new cl_device_id[nDevs]; - for (int i = 0; i < nDevs; i++) { - ids[i] = devices[i].getEntity(); - } - - IntByReference errRef = new IntByReference(); - - long[] props = getContextProps(contextProperties); - Memory propsMem = toNSArray(props); - NativeSizeByReference propsRef = new NativeSizeByReference(); - propsRef.setPointer(propsMem); - cl_context context = CL.clCreateContext(propsRef, ids.length, ids, null/*errorCallback.getPointer()*/, null, errRef); - error(errRef.getValue()); - return new CLContext(this, ids, context); - } - /* - public static final clCreateContext_arg1_callback errorCallback = new clCreateContext_arg1_callback() { - public void apply(Pointer errInfo, Pointer private_info, @Ptr long cb, Pointer user_data) { - String log = errInfo.getCString(); - System.out.println("[JavaCL] " + log); - throw new CLException(log); - } - }; - */ - - /** - * List all the devices of the specified types, with only the ones declared as available if onlyAvailable is true. - */ - @SuppressWarnings("deprecation") - public CLDevice[] listDevices(CLDevice.Type type, boolean onlyAvailable) { - IntByReference pCount = new IntByReference(); - error(CL.clGetDeviceIDs(getEntity(), type.value(), 0, (PointerByReference) null, pCount)); - - int nDevs = pCount.getValue(); - if (nDevs == 0) { - return new CLDevice[0]; - } - - cl_device_id[] ids = new cl_device_id[nDevs]; - - error(CL.clGetDeviceIDs(getEntity(), type.value(), nDevs, ids, pCount)); - return getDevices(ids, onlyAvailable); - } - - /* - public CLDevice[] listGLDevices(long openglContextId, boolean onlyAvailable) { - - IntByReference errRef = new IntByReference(); - long[] props = getContextProps(getGLContextProperties()); - Memory propsMem = toNSArray(props); - NativeSizeByReference propsRef = new NativeSizeByReference(); - propsRef.setPointer(propsMem); - - NativeSizeByReference pCount = new NativeSizeByReference(); - error(CL.clGetGLContextInfoKHR(propsRef, CL_DEVICES_FOR_GL_CONTEXT_KHR, toNS(0), (Pointer) null, pCount)); - - int nDevs = pCount.getValue().intValue(); - if (nDevs == 0) - return new CLDevice[0]; - Memory idsMem = new Memory(nDevs * Pointer.SIZE); - error(CL.clGetGLContextInfoKHR(propsRef, CL_DEVICES_FOR_GL_CONTEXT_KHR, toNS(nDevs), idsMem, pCount)); - cl_device_id[] ids = new cl_device_id[nDevs]; - for (int i = 0; i < nDevs; i++) - ids[i] = new cl_device_id(idsMem.getPointer(i * Pointer.SIZE)); - return getDevices(ids, onlyAvailable); - }*/ - - /** - * OpenCL profile string. Returns the profile name supported by the implementation. The profile name returned can be one of the following strings: - *
    - *
  • FULL_PROFILE if the implementation supports the OpenCL specification (functionality defined as part of the core specification and does not require any extensions to be supported).
  • - *
  • EMBEDDED_PROFILE if the implementation supports the OpenCL embedded profile. The embedded profile is defined to be a subset for each version of OpenCL. The embedded profile for OpenCL 1.0 is described in section 10.
  • - *
- */ - @InfoName("CL_PLATFORM_PROFILE") - public String getProfile() { - return infos.getString(getEntity(), CL_PLATFORM_PROFILE); - } - - /** - OpenCL version string. Returns the OpenCL version supported by the implementation. This version string has the following format: - OpenCL - Last Revision Date: 5/16/09 Page 30 - The major_version.minor_version value returned will be 1.0. - */ - @InfoName("CL_PLATFORM_VERSION") - public String getVersion() { - return infos.getString(getEntity(), CL_PLATFORM_VERSION); - } - - /** - * Platform name string. - */ - @InfoName("CL_PLATFORM_NAME") - public String getName() { - return infos.getString(getEntity(), CL_PLATFORM_NAME); - } - - /** - * Platform vendor string. - */ - @InfoName("CL_PLATFORM_VENDOR") - public String getVendor() { - return infos.getString(getEntity(), CL_PLATFORM_VENDOR); - } - - /** - * Returns a list of extension names
- * Extensions defined here must be supported by all devices associated with this platform. - */ - @InfoName("CL_PLATFORM_EXTENSIONS") - public String[] getExtensions() { - if (extensions == null) { - extensions = infos.getString(getEntity(), CL_PLATFORM_EXTENSIONS).split("\\s+"); - } - return extensions; - } - - private String[] extensions; - - boolean hasExtension(String name) { - name = name.trim(); - for (String x : getExtensions()) { - if (name.equals(x.trim())) { - return true; - } - } - return false; - } - - @InfoName("cl_nv_device_attribute_query") - public boolean isNVDeviceAttributeQuerySupported() { - return hasExtension("cl_nv_device_attribute_query"); - } - - @InfoName("cl_nv_compiler_options") - public boolean isNVCompilerOptionsSupported() { - return hasExtension("cl_nv_compiler_options"); - } - - @InfoName("cl_khr_byte_addressable_store") - public boolean isByteAddressableStoreSupported() { - return hasExtension("cl_khr_byte_addressable_store"); - } - - @InfoName("cl_khr_gl_sharing") - public boolean isGLSharingSupported() { - return hasExtension("cl_khr_gl_sharing") || hasExtension("cl_APPLE_gl_sharing"); - } - -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java deleted file mode 100644 index a1f80e967..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java +++ /dev/null @@ -1,783 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import com.ochafik.util.listenable.Pair; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.CLException.errorString; -import static com.nativelibs4java.opencl.CLException.failedForLackOfMemory; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.JavaCL.log; -import java.util.logging.Level; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARIES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARY_SIZES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BUILD_LOG; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_SOURCE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SUCCESS; -import static com.nativelibs4java.util.JNAUtils.readNSArray; -import static com.nativelibs4java.util.JNAUtils.toNS; -import java.io.IOException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.net.MalformedURLException; -import java.net.URLConnection; -import java.net.URL; - -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Arrays; -import java.util.Map; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.io.IOUtils; -import com.ochafik.io.ReadText; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.ochafik.util.string.RegexUtils; -import com.sun.jna.Memory; -import com.sun.jna.Native; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.PointerByReference; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.Process; -import java.net.URL; -import java.util.Collection; -import java.util.regex.Pattern; -import java.util.zip.CRC32; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; -import java.util.zip.GZIPOutputStream; -import java.util.zip.GZIPInputStream; - -/** - * OpenCL program.
- * An OpenCL program consists of a set of kernels that are identified as functions declared with the __kernel qualifier in the program source. OpenCL programs may also contain auxiliary functions and constant data that can be used by __kernel functions. The program executable can be generated online or offline by the OpenCL compiler for the appropriate target device(s).
- * A program object encapsulates the following information: - *
    - *
  • An associated context.
  • - *
  • A program source or binary.
  • - *
  • The latest successfully built program executable
  • - *
  • The list of devices for which the program executable is built
  • - *
  • The build options used and a build log.
  • - *
  • The number of kernel objects currently attached.
  • - *
- * - * A program can be compiled on the fly (costly) but its binaries can be stored and - * loaded back in subsequent executions to avoid recompilation.
- * By default, program binaries are automatically cached on stable platforms (which currently exclude ATI Stream), but the caching can be forced on/off with * {@link CLContext#setCached(boolean) }.
- * To create a program from sources, please use {@link CLContext#createProgram(java.lang.String[]) } - * @author Olivier Chafik - */ -public class CLProgram extends CLAbstractEntity { - - protected final CLContext context; - - private static CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_program entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetProgramInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - CLDevice[] devices; - CLProgram(CLContext context, CLDevice... devices) { - super(null, true); - this.context = context; - this.devices = devices == null || devices.length == 0 ? context.getDevices() : devices; - } - CLProgram(CLContext context, Map binaries, String source) { - super(null, true); - this.context = context; - this.source = source; - - setBinaries(binaries); - } - protected void setBinaries(Map binaries) { - if (this.devices == null) { - this.devices = new CLDevice[binaries.size()]; - int iDevice = 0; - for (CLDevice device : binaries.keySet()) - this.devices[iDevice++] = device; - } - int nDevices = this.devices.length; - NativeSize[] lengths = new NativeSize[nDevices]; - cl_device_id[] deviceIds = new cl_device_id[nDevices]; - Memory binariesArray = new Memory(Pointer.SIZE * nDevices); - Memory[] binariesMems = new Memory[nDevices]; - - for (int iDevice = 0; iDevice < nDevices; iDevice++) - { - CLDevice device = devices[iDevice]; - byte[] binary = binaries.get(device); - - Memory binaryMem = binariesMems[iDevice] = new Memory(binary.length); - binaryMem.write(0, binary, 0, binary.length); - binariesArray.setPointer(iDevice * Pointer.SIZE, binaryMem); - - lengths[iDevice] = toNS(binary.length); - deviceIds[iDevice] = device.getEntity(); - } - PointerByReference binariesPtr = new PointerByReference(); - binariesPtr.setPointer(binariesArray); - - IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); - int previousAttempts = 0; - IntBuffer statuses = NIOUtils.directInts(nDevices, ByteOrder.nativeOrder()); - do { - entity = CL.clCreateProgramWithBinary(context.getEntity(), nDevices, deviceIds, lengths, binariesPtr, statuses, errBuff); - } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); - } - - /** - * Write the compiled binaries of this program (for all devices it was compiled for), so that it can be restored later using {@link CLContext#loadProgram(java.io.InputStream) } - * @param out will be closed - * @throws CLBuildException - * @throws IOException - */ - public void store(OutputStream out) throws CLBuildException, IOException { - writeBinaries(getBinaries(), getSource(), null, out); - } - - private static final void addStoredEntry(ZipOutputStream zout, String name, byte[] data) throws IOException { - ZipEntry ze = new ZipEntry(name); - ze.setMethod(ZipEntry.STORED); - ze.setSize(data.length); - CRC32 crc = new CRC32(); - crc.update(data,0,data.length); - ze.setCrc(crc.getValue()); - zout.putNextEntry(ze); - zout.write(data); - zout.closeEntry(); - } - - private static final String BinariesSignatureZipEntryName = "SIGNATURE", SourceZipEntryName = "SOURCE", textEncoding = "utf-8"; - public static void writeBinaries(Map binaries, String source, String contentSignatureString, OutputStream out) throws IOException { - Map binaryBySignature = new HashMap(); - for (Map.Entry e : binaries.entrySet()) - binaryBySignature.put(e.getKey().createSignature(), e.getValue()); // Maybe multiple devices will have the same signature : too bad, we don't care and just write one binary per signature. - - ZipOutputStream zout = new ZipOutputStream(new GZIPOutputStream(new BufferedOutputStream(out))); - if (contentSignatureString != null) - addStoredEntry(zout, BinariesSignatureZipEntryName, contentSignatureString.getBytes(textEncoding)); - - if (source != null) - addStoredEntry(zout, SourceZipEntryName, source.getBytes(textEncoding)); - - for (Map.Entry e : binaryBySignature.entrySet()) - addStoredEntry(zout, e.getKey(), e.getValue()); - - zout.close(); - } - public static Pair, String> readBinaries(List allowedDevices, String expectedContentSignatureString, InputStream in) throws IOException { - Map ret = new HashMap(); - Map> devicesBySignature = CLDevice.getDevicesBySignature(allowedDevices); - - ZipInputStream zin = new ZipInputStream(new GZIPInputStream(new BufferedInputStream(in))); - ZipEntry ze; - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - String source = null; - - boolean first = true; - byte[] b = new byte[65536]; - while ((ze = zin.getNextEntry()) != null) { - String signature = ze.getName(); - boolean isSignature = signature.equals(BinariesSignatureZipEntryName); - if (first && !isSignature && expectedContentSignatureString != null || - !first && isSignature) - throw new IOException("Expected signature to be the first zip entry, got '" + signature + "' instead !"); - - first = false; - bout.reset(); - int len; - while ((len = zin.read(b)) > 0) - bout.write(b, 0, len); - - byte[] data = bout.toByteArray(); - if (isSignature) { - if (expectedContentSignatureString != null) { - String contentSignatureString = new String(data, textEncoding); - if (!expectedContentSignatureString.equals(contentSignatureString)) - throw new IOException("Content signature does not match expected one :\nExpected '" + expectedContentSignatureString + "',\nGot '" + contentSignatureString + "'"); - } - } else if (signature.equals(SourceZipEntryName)) { - source = new String(data, textEncoding); - } else { - List devices = devicesBySignature.get(signature); - for (CLDevice device : devices) - ret.put(device, data); - } - } - zin.close(); - return new Pair, String>(ret, source); - } - - List sources = new ArrayList(); - Map programByDevice = new HashMap(); - - public CLDevice[] getDevices() { - return devices.clone(); - } - - /// Workaround to avoid crash of ATI Stream 2.0.0 final (beta 3 & 4 worked fine) - public static boolean passMacrosAsSources = true; - - public synchronized void allocate() { - if (entity != null) - throw new IllegalThreadStateException("Program was already allocated !"); - - if (passMacrosAsSources) { - if (macros != null && !macros.isEmpty()) { - StringBuilder b = new StringBuilder(); - for (Map.Entry m : macros.entrySet()) - b.append("#define " + m.getKey() + " " + m.getValue() + "\n"); - this.sources.add(0, b.toString()); - } - } - - if (!"false".equals(System.getProperty("javacl.adjustDoubleExtension")) && !"0".equals(System.getenv("JAVACL_ADJUST_DOUBLE_EXTENSION"))) { - for (int i = 0, len = sources.size(); i < len; i++) { - String source = sources.get(i); - for (CLDevice device : getDevices()) - source = device.replaceDoubleExtensionByExtensionActuallyAvailable(source); - sources.set(i, source); - // TODO keep different sources for each device !!! - } - } - - String[] sources = this.sources.toArray(new String[this.sources.size()]); - NativeSize[] lengths = new NativeSize[sources.length]; - for (int i = 0; i < sources.length; i++) { - lengths[i] = toNS(sources[i].length()); - } - IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); - cl_program program; - int previousAttempts = 0; - do { - program = CL.clCreateProgramWithSource(context.getEntity(), sources.length, sources, lengths, errBuff); - } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); - entity = program; - } - - @Override - protected synchronized cl_program getEntity() { - if (entity == null) - allocate(); - - return entity; - } - - List includes; - - /** - * Add a path (file or URL) to the list of paths searched for included files.
- * OpenCL kernels may contain #include "subpath/file.cl" statements.
- * This automatically adds a "-Ipath" argument to the compilator's command line options.
- * Note that it's not necessary to add include paths for files that are in the classpath. - * @param path A file or URL that points to the root path from which includes can be resolved. - */ - public synchronized void addInclude(String path) { - if (includes == null) - includes = new ArrayList(); - includes.add(path); - resolvedInclusions = null; - } - public synchronized void addSource(String src) { - if (entity != null) - throw new IllegalThreadStateException("Program was already allocated : cannot add sources anymore."); - sources.add(src); - resolvedInclusions = null; - } - - Map resolvedInclusions; - - protected Runnable copyIncludesToTemporaryDirectory() throws IOException { - Map inclusions = resolveInclusions(); - File includesDir = JavaCL.createTempDirectory("includes", "", "includes"); - final List filesToDelete = new ArrayList(); - for (Map.Entry e : inclusions.entrySet()) { - assert log(Level.INFO, "Copying include '" + e.getKey() + "' from '" + e.getValue() + "' to '" + includesDir + "'"); - File f = new File(includesDir, e.getKey().replace('/', File.separatorChar)); - File p = f.getParentFile(); - filesToDelete.add(f); - if (p != null) { - p.mkdirs(); - filesToDelete.add(p); - } - InputStream in = e.getValue().openStream(); - OutputStream out = new FileOutputStream(f); - IOUtils.readWrite(in, out); - in.close(); - out.close(); - f.deleteOnExit(); - } - filesToDelete.add(includesDir); - addInclude(includesDir.toString()); - return new Runnable() { public void run() { - for (File f : filesToDelete) - f.delete(); - }}; - } - public Map resolveInclusions() throws IOException { - if (resolvedInclusions == null) { - resolvedInclusions = new HashMap(); - for (String source : sources) - resolveInclusions(source, resolvedInclusions); - } - return resolvedInclusions; - } - - static Pattern includePattern = Pattern.compile("#\\s*include\\s*\"([^\"]+)\""); - private void resolveInclusions(String source, Map ret) throws IOException { - Collection includedPaths = RegexUtils.find(source, includePattern, 1); - //System.out.println("Included paths = " + includedPaths); - for (String includedPath : includedPaths) { - if (ret.containsKey(includedPath)) - continue; - URL url = getIncludedSourceURL(includedPath); - if (url == null) { - assert log(Level.SEVERE, "Failed to resolve include '" + includedPath + "'"); - } else { - String s = ReadText.readText(url); - ret.put(includedPath, url); - resolveInclusions(s, ret); - } - } - } - - public String getIncludedSourceContent(String path) throws IOException { - URL url = getIncludedSourceURL(path); - if (url == null) - return null; - - String src = ReadText.readText(url); - return src; - } - - public URL getIncludedSourceURL(String path) throws MalformedURLException { - File f = new File(path); - if (f.exists()) - return f.toURI().toURL(); - URL url = getClass().getClassLoader().getResource(path); - if (url != null) - return url; - - if (includes != null) - for (String include : includes) { - f = new File(new File(include), path); - if (f.exists()) - return f.toURI().toURL(); - - url = getClass().getClassLoader().getResource(f.toString()); - if (url != null) - return url; - - try { - url = new URL(include + (include.endsWith("/") ? "" : "/") + path); - url.openStream().close(); - return url; - } catch (IOException ex) { - // Bad URL or impossible to read from the URL - } - - } - - return null; - } - - String source; - /** - * Get the source code of this program - */ - public synchronized String getSource() { - if (source == null) - source = infos.getString(getEntity(), CL_PROGRAM_SOURCE); - - return source; - } - - /** - * Get the binaries of the program (one for each device, in order) - * @return map from each device the program was compiled for to the corresponding binary data - */ - public Map getBinaries() throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - - Memory s = infos.getMemory(getEntity(), CL_PROGRAM_BINARY_SIZES); - int n = (int)s.getSize() / Native.SIZE_T_SIZE; - NativeSize[] sizes = readNSArray(s, n); - //int[] sizes = new int[n]; - //for (int i = 0; i < n; i++) { - // sizes[i] = s.getNativeLong(i * Native.LONG_SIZE).intValue(); - //} - - Memory[] binMems = new Memory[n]; - Memory ptrs = new Memory(n * Native.POINTER_SIZE); - for (int i = 0; i < n; i++) { - ptrs.setPointer(i * Native.POINTER_SIZE, binMems[i] = new Memory(sizes[i].intValue())); - } - error(infos.getInfo(getEntity(), CL_PROGRAM_BINARIES, toNS(ptrs.getSize() * Native.POINTER_SIZE), ptrs, null)); - - Map ret = new HashMap(devices.length); - int iBin = n == devices.length + 1 ? 1 : 0; - for (int i = 0; i < n; i++) { - CLDevice device = devices[i]; - Memory bytes = binMems[iBin + i]; - if (bytes != null) - ret.put(device, bytes.getByteArray(0, sizes[iBin + i].intValue())); - } - return ret; - } - - /** - * Returns the context of this program - */ - public CLContext getContext() { - return context; - } - Map macros; - public CLProgram defineMacro(String name, Object value) { - createMacros(); - macros.put(name, value); - return this; - } - public CLProgram undefineMacro(String name) { - if (macros != null) - macros.remove(name); - return this; - } - - private void createMacros() { - if (macros == null) - macros = new LinkedHashMap(); - } - public void defineMacros(Map macros) { - createMacros(); - this.macros.putAll(macros); - } - List extraBuildOptions; - - /** - * Add the -cl-fast-relaxed-math compile option.
- * Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations. - * This allows optimizations for floating-point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5. - * This option causes the preprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.
- * Also see : Khronos' documentation for clBuildProgram. - */ - public void setFastRelaxedMath() { - addBuildOption("-cl-fast-relaxed-math"); - } - - /** - * Add the -cl-no-signed-zero compile option.
- * Allow optimizations for floating-point arithmetic that ignore the signedness of zero. - * IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -clfinite-math only). - * This option implies that the sign of a zero result isn't significant.
- * Also see : Khronos' documentation for clBuildProgram. - */ - public void setNoSignedZero() { - addBuildOption("-cl-no-signed-zero"); - } - - /** - * Add the -cl-mad-enable compile option.
- * Allow a * b + c to be replaced by a mad. The mad computes a * b + c with reduced accuracy. For example, some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
- * Also see : Khronos' documentation for clBuildProgram. - */ - public void setMadEnable() { - addBuildOption("-cl-mad-enable"); - } - /** - * Add the -cl-finite-math-only compile option.
- * Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or infinites. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5.
- * Also see : Khronos' documentation for clBuildProgram. - */ - public void setFiniteMathOnly() { - addBuildOption("-cl-finite-math-only"); - } - /** - * Add the -cl-unsafe-math-optimizations option.
- * Allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid, (b) may violate IEEE 754 standard and (c) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable options.
- * Also see : Khronos' documentation for clBuildProgram. - */ - public void setUnsafeMathOptimizations() { - addBuildOption("-cl-unsafe-math-optimizations"); - } - - /** - * Please see OpenCL's clBuildProgram documentation for details on supported build options. - */ - public synchronized void addBuildOption(String option) { - if (option.startsWith("-I")) { - addInclude(option.substring(2)); - return; - } - if (extraBuildOptions == null) - extraBuildOptions = new ArrayList(); - - extraBuildOptions.add(option); - } - - protected String getOptionsString() { - StringBuilder b = new StringBuilder("-DJAVACL=1 "); - - if (extraBuildOptions != null) - for (String option : extraBuildOptions) - b.append(option).append(' '); - - // http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clBuildProgram.html - //b.append("-O2 -cl-no-signed-zeros -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math -cl-strict-aliasing "); - - if (!passMacrosAsSources && macros != null && !macros.isEmpty()) - for (Map.Entry m : macros.entrySet()) - b.append("-D" + m.getKey() + "=" + m.getValue() + " "); - - if (includes != null) - for (String path : includes) - if (new File(path).exists()) // path can be an URL as well, in which case it's copied to a local file copyIncludesToTemporaryDirectory() - b.append("-I").append(path).append(' '); - - return b.toString(); - } - - private volatile Boolean cached; - public synchronized void setCached(boolean cached) { - this.cached = cached; - } - public synchronized boolean isCached() { - if (cached == null) - cached = context.getCacheBinaries(); - return cached; - } - - protected String computeCacheSignature() throws IOException { - StringBuilder b = new StringBuilder(16 * 1024); - getContext().getPlatform().toString(b); - b.append('\n'); - for (CLDevice device : getDevices()) - b.append(device).append('\n'); - - b.append(getOptionsString()).append('\n'); - if (macros != null && !macros.isEmpty()) - for (Map.Entry m : macros.entrySet()) - b.append("-D").append(m.getKey()).append('=').append(m.getValue()).append('\n'); - - if (includes != null && !includes.isEmpty()) - for (String path : includes) - b.append("-I").append(path).append('\n'); - - if (sources != null && !sources.isEmpty()) - for (String source : sources) - b.append(source).append('\n'); - - Map inclusions = resolveInclusions(); - if (inclusions != null && !inclusions.isEmpty()) - for (Map.Entry e : inclusions.entrySet()) { - URLConnection con = e.getValue().openConnection(); - InputStream in = con.getInputStream(); - b.append('#').append(e.getKey()).append(con.getLastModified()).append('\n'); - in.close(); - } - - for (String name : propsToIncludeInSignature) - b.append(name).append('=').append(System.getProperty(name)).append('\n'); - - return b.toString(); - } - private final String[] propsToIncludeInSignature = new String[] { - //"java.vm.version", // probably superfluous... - "os.version", - "os.name" - }; - - boolean built; - /** - * Returns the context of this program - */ - public synchronized CLProgram build() throws CLBuildException { - if (built) - throw new IllegalThreadStateException("Program was already built !"); - - String contentSignature = null; - File cacheFile = null; - boolean readBinaries = false; - if (isCached()) { - try { - contentSignature = computeCacheSignature(); - byte[] sha = java.security.MessageDigest.getInstance("MD5").digest(contentSignature.getBytes(textEncoding)); - StringBuilder shab = new StringBuilder(); - for (byte b : sha) - shab.append(Integer.toHexString(b & 0xff)); - String hash = shab.toString(); - cacheFile = new File(JavaCL.userCacheDir, hash); - if (cacheFile.exists()) { - Pair, String> bins = readBinaries(Arrays.asList(getDevices()), contentSignature, new FileInputStream(cacheFile)); - setBinaries(bins.getFirst()); - this.source = bins.getSecond(); - assert log(Level.INFO, "Read binaries cache from '" + cacheFile + "'"); - readBinaries = true; - } - } catch (Exception ex) { - assert log(Level.WARNING, "Failed to load cached program", ex); - entity = null; - } - } - - if (entity == null) - allocate(); - - Runnable deleteTempFiles = null; - if (!readBinaries) - try { - deleteTempFiles = copyIncludesToTemporaryDirectory(); - } catch (IOException ex) { - throw new CLBuildException(this, ex.toString(), Collections.EMPTY_LIST); - } - - int nDevices = devices.length; - cl_device_id[] deviceIds = null; - if (nDevices != 0) { - deviceIds = new cl_device_id[nDevices]; - for (int i = 0; i < nDevices; i++) - deviceIds[i] = devices[i].getEntity(); - } - int err = CL.clBuildProgram(getEntity(), nDevices, deviceIds, readBinaries ? null : getOptionsString(), null, null); - //int err = CL.clBuildProgram(getEntity(), 0, null, getOptionsString(), null, null); - if (err != CL_SUCCESS) {//BUILD_PROGRAM_FAILURE) { - NativeSizeByReference len = new NativeSizeByReference(); - int bufLen = 2048 * 32; //TODO find proper size - Memory buffer = new Memory(bufLen); - - HashSet errs = new HashSet(); - if (deviceIds == null) { - error(CL.clGetProgramBuildInfo(getEntity(), null, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); - String s = buffer.getString(0); - errs.add(s); - } else - for (cl_device_id device : deviceIds) { - error(CL.clGetProgramBuildInfo(getEntity(), device, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); - String s = buffer.getString(0); - errs.add(s); - } - - throw new CLBuildException(this, "Compilation failure : " + errorString(err), errs); - } - built = true; - if (deleteTempFiles != null) - deleteTempFiles.run(); - - if (isCached() && !readBinaries) { - JavaCL.userCacheDir.mkdirs(); - try { - Map binaries = getBinaries(); - if (!binaries.isEmpty()) { - writeBinaries(getBinaries(), getSource(), contentSignature, new FileOutputStream(cacheFile)); - assert log(Level.INFO, "Wrote binaries cache to '" + cacheFile + "'"); - } - } catch (Exception ex) { - new IOException("[JavaCL] Failed to cache program", ex).printStackTrace(); - } - } - - return this; - } - - @Override - protected void clear() { - error(CL.clReleaseProgram(getEntity())); - } - - /** - * Return all the kernels found in the program. - */ - public CLKernel[] createKernels() throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - IntByReference pCount = new IntByReference(); - int previousAttempts = 0; - while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), 0, (cl_kernel[])null, pCount), previousAttempts++)) {} - - int count = pCount.getValue(); - cl_kernel[] kerns = new cl_kernel[count]; - previousAttempts = 0; - while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), count, kerns, pCount), previousAttempts++)) {} - - CLKernel[] kernels = new CLKernel[count]; - for (int i = 0; i < count; i++) - kernels[i] = new CLKernel(this, null, kerns[i]); - - return kernels; - } - - /** - * Find a kernel by its functionName, and optionally bind some arguments to it. - */ - public CLKernel createKernel(String name, Object... args) throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); - cl_kernel kernel; - int previousAttempts = 0; - do { - kernel = CL.clCreateKernel(getEntity(), name, errBuff); - } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); - - CLKernel kn = new CLKernel(this, name, kernel); - kn.setArgs(args); - return kn; - } - - -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLQueue.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLQueue.java deleted file mode 100644 index 1d6eca749..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLQueue.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FALSE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_QUEUE_PROPERTIES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_TRUE; - -import java.util.EnumSet; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.LongByReference; - -/** - * OpenCL command queue.
- * OpenCL objects such as memory, program and kernel objects are created using a context.
- * Operations on these objects are performed using a command-queue.
- * The command-queue can be used to queue a set of operations (referred to as commands) in order.
- * Having multiple command-queues allows applications to queue multiple independent commands without requiring synchronization.
- * Note that this should work as long as these objects are not being shared.
- * Sharing of objects across multiple command-queues will require the application to perform appropriate synchronization.
- *
- * A queue is bound to a single device. - * see {@link CLDevice#createQueue(com.nativelibs4java.opencl.CLContext, com.nativelibs4java.opencl.CLDevice.QueueProperties[]) } - * see {@link CLDevice#createOutOfOrderQueue(com.nativelibs4java.opencl.CLContext) } - * see {@link CLDevice#createProfilingQueue(com.nativelibs4java.opencl.CLContext) } - * see {@link CLContext#createDefaultQueue(com.nativelibs4java.opencl.CLDevice.QueueProperties[]) } - * see {@link CLContext#createDefaultOutOfOrderQueue() } - * see {@link CLContext#createDefaultProfilingQueue() } - * @author Olivier Chafik - * - */ -public class CLQueue extends CLAbstractEntity { - - private CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_command_queue entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetCommandQueueInfo(getEntity(), infoTypeEnum, size, out, sizeOut); - } - }; - - final CLContext context; - final CLDevice device; - - CLQueue(CLContext context, cl_command_queue entity, CLDevice device) { - super(entity); - this.context = context; - this.device = device; - } - - public CLContext getContext() { - return context; - } - public CLDevice getDevice() { - return device; - } - - volatile Boolean outOfOrder; - public synchronized boolean isOutOfOrder() { - if (outOfOrder == null) - outOfOrder = getProperties().contains(CLDevice.QueueProperties.OutOfOrderExecModeEnable); - return outOfOrder; - } - - @InfoName("CL_QUEUE_PROPERTIES") - public EnumSet getProperties() { - return CLDevice.QueueProperties.getEnumSet(infos.getIntOrLong(getEntity(), CL_QUEUE_PROPERTIES)); - } - - @SuppressWarnings("deprecation") - public void setProperty(CLDevice.QueueProperties property, boolean enabled) { - error(CL.clSetCommandQueueProperty(getEntity(), property.value(), enabled ? CL_TRUE : CL_FALSE, (LongByReference)null)); - } - - - @Override - protected void clear() { - error(CL.clReleaseCommandQueue(getEntity())); - } - - /** - * Blocks until all previously queued OpenCL commands in this queue are issued to the associated device and have completed.
- * finish() does not return until all queued commands in this queue have been processed and completed.
- * finish() is also a synchronization point. - */ - public void finish() { - error(CL.clFinish(getEntity())); - } - - /** - * Issues all previously queued OpenCL commands in this queue to the device associated with this queue.
- * flush() only guarantees that all queued commands in this queue get issued to the appropriate device.
- * There is no guarantee that they will be complete after flush() returns. - */ - public void flush() { - error(CL.clFlush(getEntity())); - } - - /** - * Enqueues a wait for a specific event or a list of events to complete before any future commands queued in the this queue are executed. - */ - public void enqueueWaitForEvents(CLEvent... events) { - cl_event[] evts = CLEvent.to_cl_event_array(events); - error(CL.clEnqueueWaitForEvents(getEntity(), evts == null ? 0 : evts.length, evts)); - } - - /** - * Enqueue a barrier operation.
- * The enqueueBarrier() command ensures that all queued commands in command_queue have finished execution before the next batch of commands can begin execution.
- * enqueueBarrier() is a synchronization point. - */ - public void enqueueBarrier() { - error(CL.clEnqueueBarrier(getEntity())); - } - - /** - * Enqueue a marker command to command_queue.
- * The marker command returns an event which can be used by to queue a wait on this marker event i.e. wait for all commands queued before the marker command to complete. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueMarker() { - cl_event[] eventOut = new cl_event[1]; - error(CL.clEnqueueMarker(getEntity(), eventOut)); - return CLEvent.createEvent(this, eventOut); - } - - /** - * Used to acquire OpenCL memory objects that have been created from OpenGL objects.
- * These objects need to be acquired before they can be used by any OpenCL commands queued to a command-queue.
- * The OpenGL objects are acquired by the OpenCL context associated with this queue and can therefore be used by all command-queues associated with the OpenCL context. - * @param objects CL memory objects that correspond to GL objects. - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueAcquireGLObjects(CLMem[] objects, CLEvent... eventsToWaitFor) { - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_mem[] mems = new cl_mem[objects.length]; - for (int i = 0; i < objects.length; i++) - mems[i] = objects[i].getEntity(); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueAcquireGLObjects(getEntity(), mems.length, mems, evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(this, eventOut); - } - - /** - * Used to release OpenCL memory objects that have been created from OpenGL objects.
- * These objects need to be released before they can be used by OpenGL.
- * The OpenGL objects are released by the OpenCL context associated with this queue. - * @param objects CL memory objects that correpond to GL objects. - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueReleaseGLObjects(CLMem[] objects, CLEvent... eventsToWaitFor) { - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_mem[] mems = getEntities(objects, new cl_mem[objects.length]); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueReleaseGLObjects(getEntity(), mems.length, mems, evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(this, eventOut); - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLSampler.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLSampler.java deleted file mode 100644 index 88cc7df6f..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLSampler.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_CLAMP; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_CLAMP_TO_EDGE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_NONE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_REPEAT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FILTER_LINEAR; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FILTER_NEAREST; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_ADDRESSING_MODE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_FILTER_MODE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_NORMALIZED_COORDS; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_sampler; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.ValuedEnum; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Pointer; - -/** - * OpenCL sampler object.
- * A sampler object describes how to sample an image when the image is read in the kernel.
- * The built-in functions to read from an image in a kernel take a sampler as an argument.
- * The sampler arguments to the image read function can be sampler objects created using OpenCL functions and passed as argument values to the kernel or can be samplers declared inside a kernel. - *
- * see {@link CLContext#createSampler(boolean, com.nativelibs4java.opencl.CLSampler.AddressingMode, com.nativelibs4java.opencl.CLSampler.FilterMode) } - * @author Olivier Chafik - */ -public class CLSampler extends CLAbstractEntity { - private static CLInfoGetter infos = new CLInfoGetter() { - @Override - protected int getInfo(cl_sampler entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetSamplerInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - - CLSampler(cl_sampler entity) { - super(entity); - } - - @Override - protected void clear() { - error(CL.clReleaseSampler(getEntity())); - } - - /** - * Values for CL_SAMPLER_ADDRESSING_MODE
- * How out-of-range image coordinates are handled when reading from an image - */ - public enum AddressingMode implements ValuedEnum { - Repeat(CL_ADDRESS_REPEAT), - ClampToEdge(CL_ADDRESS_CLAMP_TO_EDGE), - Clamp(CL_ADDRESS_CLAMP), - None(CL_ADDRESS_NONE); - - AddressingMode(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static AddressingMode getEnum(long v) { return EnumValues.getEnum(v, AddressingMode.class); } - } - - /** - * Return the value specified by addressing_mode argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_ADDRESSING_MODE") - public AddressingMode getAddressingMode() { - return AddressingMode.getEnum(infos.getInt(getEntity(), CL_SAMPLER_ADDRESSING_MODE)); - } - - /** - * Values for CL_SAMPLER_FILTER_MODE
- * Type of filter that must be applied when reading an image - */ - public enum FilterMode implements ValuedEnum { - Nearest(CL_FILTER_NEAREST), - Linear(CL_FILTER_LINEAR); - - FilterMode(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static FilterMode getEnum(int v) { return EnumValues.getEnum(v, FilterMode.class); } - } - /** - * Return the value specified by filter_mode argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_FILTER_MODE") - public FilterMode getFilterMode() { - return FilterMode.getEnum(infos.getInt(getEntity(), CL_SAMPLER_FILTER_MODE)); - } - - /** - * Return the value specified by normalized_coords argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_NORMALIZED_COORDS") - public boolean getNormalizedCoords() { - return infos.getBool(getEntity(), CL_SAMPLER_NORMALIZED_COORDS); - } - - - -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLShortBuffer.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLShortBuffer.java deleted file mode 100644 index 97e1ffd8d..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLShortBuffer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import java.nio.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; - -/** - * OpenCL Memory Buffer Object with Short values.
- * see {@link CLContext#createShortBuffer(com.nativelibs4java.opencl.CLMem.Usage, long) } - * see {@link CLContext#createShortBuffer(com.nativelibs4java.opencl.CLMem.Usage, java.nio.ShortBuffer, boolean) } - * @author Olivier Chafik - * @deprecated Use {@link CLBuffer}<{@link Short}> - */ -@Deprecated -public class CLShortBuffer extends CLBuffer { - CLShortBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer) { - super(context, byteCount, entity, buffer, 2, ShortBuffer.class); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLUserEvent.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLUserEvent.java deleted file mode 100644 index 8533b53a0..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/CLUserEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - - -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; - -public class CLUserEvent extends CLEvent { - CLUserEvent(cl_event evt) { - super(evt); - } - CLUserEvent() { - super(); - } - /** - * Sets the execution status of a this event object. - * NOTE: Enqueued commands that specify user events in the event_wait_list argument of clEnqueue*** commands must ensure that the status of these user events being waited on are set using clSetUserEventStatus before any OpenCL APIs that release OpenCL objects except for event objects are called; otherwise the behavior is undefined. More details in the OpenCL specifications at section 5.9. - * @param executionStatus specifies the new execution status to be set and can be CL_COMPLETE or a negative integer value to indicate an error. A negative integer value causes all enqueued commands that wait on this user event to be terminated. setStatus can only be called once to change the execution status of event. - */ - public void setStatus(int executionStatus) { - error(CL.clSetUserEventStatus(getEntity(), executionStatus)); - } - - /** - * Calls setStatus(CL_COMPLETE) - */ - public void setComplete() { - setStatus(CL_COMPLETE); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/ImageIOUtils.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/ImageIOUtils.java deleted file mode 100644 index 95088199c..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/ImageIOUtils.java +++ /dev/null @@ -1,479 +0,0 @@ -package com.nativelibs4java.opencl; - -import com.nativelibs4java.opencl.CLImageFormat.ChannelOrder; -import com.nativelibs4java.opencl.CLImageFormat.ChannelDataType; -import com.nativelibs4java.util.NIOUtils; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.image.*; -import java.nio.*; -import static com.nativelibs4java.opencl.ImageIOUtils.ImageInfo.*; - -/** - * No apparent correspondance with any OpenCL image type for the following BufferedImage types : - * TYPE_3BYTE_BGR - * TYPE_4BYTE_ABGR (support only argb or bgra : need to see if endian-magic can help...) - * TYPE_4BYTE_ABGR_PRE (no support for pre-multiplied channels) - * TYPE_BYTE_BINARY - * TYPE_BYTE_INDEXED - * TYPE_CUSTOM - * TYPE_INT_ARGB_PRE (no support for pre-multiplied channels) - * TYPE_INT_BGR - * TYPE_INT_RGB (no support for UnsignedInt8 channel data type) - * TYPE_USHORT_555_RGB - * TYPE_USHORT_565_RGB - */ -class ImageIOUtils { - - public static class ImageInfo { - public final int bufferedImageType; - public final CLImageFormat clImageFormat; - //public final int width, height; - public final ImageDataGetter dataGetter; - public final ImageDataSetter dataSetter; - public final Class bufferClass; - public final int channelCount; - public final int pixelByteSize; - public ImageInfo( - int bufferedImageType, - CLImageFormat clImageFormat, - ImageDataGetter dataGetter, - ImageDataSetter dataSetter, - Class bufferClass, - int channelCount, - int pixelByteSize) - { - this.bufferedImageType = bufferedImageType; - this.clImageFormat = clImageFormat; - this.dataGetter = dataGetter; - this.dataSetter = dataSetter; - this.bufferClass = bufferClass; - this.channelCount = channelCount; - this.pixelByteSize = pixelByteSize; - } - - public interface ImageDataGetter { - Buffer getData(I image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder); - } - public interface ImageDataSetter { - void setData(I image, Buffer data, boolean allowDeoptimizingDirectWrite); - } - } - - public static ImageInfo getGenericImageInfo() { - return new ImageInfo( - 0, - CLImageFormat.INT_ARGB_FORMAT, - new ImageDataGetter() { - public Buffer getData(Image image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int[] intData = null; - int width = image.getWidth(null), height = image.getHeight(null); - PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, true); - try { - grabber.grabPixels(); - intData = (int[])grabber.getPixels(); - } catch (InterruptedException ex) { - throw new RuntimeException("Pixel read operation was interrupted", ex); - } - IntBuffer output = IntBuffer.wrap(intData); - if (directBuffer) - return NIOUtils.directCopy(output, byteOrder); - else - return output; - } - }, - new ImageDataSetter() { - public void setData(Image image, Buffer data, boolean allowDeoptimizingDirectWrite) { - if (!(image instanceof BufferedImage)) - throw new UnsupportedOperationException("Image must be a BufferedImage"); - - BufferedImage bufferedImage = (BufferedImage)image; - int width = bufferedImage.getWidth(), height = bufferedImage.getHeight(); - WritableRaster raster = checkWritableRaster(bufferedImage); - - IntBuffer input = checkBuffer(data, IntBuffer.class); - int[] intData = input.array(); - if (intData == null) { - intData = new int[width * height]; - input.get(intData); - } - raster.setPixels(0, 0, width, height, intData); - } - }, - IntBuffer.class, - 1, - 4 - ); - } - - static void checkSinglePixelPackedSampleModel(Raster raster) { - if (raster.getNumDataElements() != 1) - throw new IllegalArgumentException("Raster has " + raster.getNumBands() + " data elements, should have only 1 !"); - - //SampleModel sampleModel = raster.getSampleModel(); - //if (!(sampleModel instanceof SinglePixelPackedSampleModel)) - // throw new IllegalArgumentException("Expected SinglePixelPackedSampleModel, got " + sampleModel.getClass().getName()); - - //return (SinglePixelPackedSampleModel)sampleModel; - } - static DB checkDataBuffer(Raster raster, Class dbType) { - DataBuffer dataBuffer = raster.getDataBuffer(); - if (!dbType.isInstance(dataBuffer)) - throw new IllegalArgumentException("Expected " + dbType.getName() + ", got " + (dataBuffer == null ? null : dataBuffer.getClass().getName())); - - return (DB)dataBuffer; - } - static B checkBuffer(Buffer buffer, Class bType) { - if (!bType.isInstance(buffer)) - throw new IllegalArgumentException("Expected " + bType.getName() + ", got " + (buffer == null ? null : buffer.getClass().getName())); - - return (B)buffer; - } - static WritableRaster checkWritableRaster(BufferedImage image) { - Raster raster = image.getRaster(); - if (!(raster instanceof WritableRaster)) - throw new UnsupportedOperationException("Image data is not writable"); - - return (WritableRaster)raster; - } - public static ImageInfo getShortGrayImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_USHORT_GRAY, - new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.UNormInt16), - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - short[] existingArray = getIndirectArray(optionalExistingOutput, width * height, short[].class); - short[] array; - ShortBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (short[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferShort.class).getData(); - if (optionalExistingOutput instanceof ShortBuffer) { - output = (ShortBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (!output.isDirect()) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = ShortBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); - short[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - short[] outputArray = checkDataBuffer(raster, DataBufferShort.class).getData(); - ShortBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new short[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - ShortBuffer.class, - 1, - 2 - ); - } - - /** - * Image stored in TYPE_USHORT_GRAY BufferedImages but in ChannelOrder.RGBA/BGRA + ChannelDataType.short - */ - public static ImageInfo getARGBShortGrayImageInfo(CLImageFormat format) { - return new ImageInfo( - BufferedImage.TYPE_USHORT_GRAY, - format, - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - int length = width * height; - short[] existingArray = getIndirectArray(optionalExistingOutput, length, short[].class); - short[] array = (short[])raster.getDataElements(0, 0, width, height, existingArray); - - ShortBuffer output = null; - if (optionalExistingOutput instanceof ShortBuffer) { - output = (ShortBuffer)optionalExistingOutput; - if (output.capacity() != length * 4) - output = null; - } - if (output == null) - output = NIOUtils.directShorts(length * 4, byteOrder); - - for (int i = 0; i < length; i++) { - int offset = i * 4; - short value = array[i]; - output.put(offset, value); - output.put(offset + 1, value); - output.put(offset + 2, value); - output.put(offset + 3, (short)0xffff); - } - - return output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); - int length = width * height; - short[] data = new short[length]; - short[] four = new short[4]; - for (int i = 0; i < length; i++) { - int offset = i * 4; - int a = input.get(offset); - int b = input.get(offset + 1); - int c = input.get(offset + 2); - int alpha = input.get(offset + 3); // TODO multiply by ALPHA ??? - data[i] = (short)((a + b + c) / 3); - } - raster.setDataElements(0, 0, width, height, data); - } - }, - ShortBuffer.class, - 4, - 4 * 2 - ); - } - - public static ImageInfo getByteGrayImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_BYTE_GRAY, - new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.SignedInt8), - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - byte[] existingArray = getIndirectArray(optionalExistingOutput, width * height, byte[].class); - byte[] array; - ByteBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (byte[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferByte.class).getData(); - if (optionalExistingOutput instanceof ByteBuffer) { - output = (ByteBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (!output.isDirect()) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = ByteBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ByteBuffer input = checkBuffer(inputBuffer, ByteBuffer.class); - byte[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - byte[] outputArray = checkDataBuffer(raster, DataBufferByte.class).getData(); - ByteBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new byte[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - ByteBuffer.class, - 1, - 1 - ); - } - static A getIndirectArray(Buffer buffer, int length, Class arrayClass) { - if (buffer instanceof IntBuffer && arrayClass == int[].class) - return (A)((IntBuffer)buffer).array(); - if (buffer instanceof ShortBuffer && arrayClass == short[].class) - return (A)((ShortBuffer)buffer).array(); - if (buffer instanceof ByteBuffer && arrayClass == byte[].class) - return (A)((ByteBuffer)buffer).array(); - if (buffer instanceof FloatBuffer && arrayClass == float[].class) - return (A)((FloatBuffer)buffer).array(); - if (buffer instanceof LongBuffer && arrayClass == long[].class) - return (A)((LongBuffer)buffer).array(); - if (buffer instanceof DoubleBuffer && arrayClass == double[].class) - return (A)((DoubleBuffer)buffer).array(); - if (buffer instanceof CharBuffer && arrayClass == char[].class) - return (A)((CharBuffer)buffer).array(); - return null; - } - public static boolean isSubRaster(Raster raster) { - Rectangle bounds = raster.getBounds(); - return raster.getParent() != null || bounds.x != 0 || bounds.y != 0; - } - public static ImageInfo getIntARGBImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_INT_ARGB, - CLImageFormat.INT_ARGB_FORMAT, - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - int[] existingArray = getIndirectArray(optionalExistingOutput, width * height, int[].class); - int[] array; - IntBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (int[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferInt.class).getData(); - if (optionalExistingOutput instanceof IntBuffer) { - output = (IntBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (output.array() != null) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = IntBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - IntBuffer input = checkBuffer(inputBuffer, IntBuffer.class); - int[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - int[] outputArray = checkDataBuffer(raster, DataBufferInt.class).getData(); - IntBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new int[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - IntBuffer.class, - 1, - 4 - ); - } - - public static ImageInfo getImageInfo(Image image) { - if (image instanceof BufferedImage) - return getBufferedImageInfo(((BufferedImage)image).getType()); - return getGenericImageInfo(); - } - public static ImageInfo getBufferedImageInfo(int bufferedImageType) { - switch (bufferedImageType) { - case BufferedImage.TYPE_INT_ARGB: - return getIntARGBImageInfo(); - case BufferedImage.TYPE_BYTE_GRAY: - return getByteGrayImageInfo(); - case BufferedImage.TYPE_USHORT_GRAY: - return getShortGrayImageInfo(); - default: - return (ImageInfo)getGenericImageInfo(); - } - } - public static ImageInfo getBufferedImageInfo(CLImageFormat imageFormat) { - if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) - return null; - - switch (imageFormat.getChannelOrder()) { - case BGRA: - case RGBA: - switch (imageFormat.getChannelDataType()) { - case UNormInt16: - case UnsignedInt16: - case SignedInt16: - return getARGBShortGrayImageInfo(imageFormat); - } - } - return getBufferedImageInfo(getBufferedImageType(imageFormat)); - } - static int getBufferedImageType(CLImageFormat imageFormat) { - if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) - return 0; - - switch (imageFormat.getChannelOrder()) { - case INTENSITY: - case LUMINANCE: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_BYTE_GRAY; - case UnsignedInt16: - case UNormInt16: - case SignedInt16: - return BufferedImage.TYPE_USHORT_GRAY; - default: - return 0; - } - case ARGB: - case BGRA: - case RGBA: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_INT_ARGB; - default: - return 0; - } - case RGB: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_INT_BGR; - default: - return 0; - } - case RGBx: - default: - return 0; - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/InfoName.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/InfoName.java deleted file mode 100644 index 029e6984e..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/InfoName.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Tagging annotation to indicate the name of an OpenCL information in the OpenCL specifications. - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface InfoName { - String value(); -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/JavaCL.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/JavaCL.java deleted file mode 100644 index a42992582..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/JavaCL.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLException.error; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id; -import com.sun.jna.Platform; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.PointerByReference; -import com.sun.jna.Native; - -/** - * Entry point class for the OpenCL4Java Object-oriented wrappers around the OpenCL API.
- * @author Olivier Chafik - */ -public class JavaCL { - - static final boolean verbose = "true".equals(System.getProperty("javacl.verbose")) || "1".equals(System.getenv("JAVACL_VERBOSE")); - static final int minLogLevel = Level.WARNING.intValue(); - static boolean shouldLog(Level level) { - return verbose || level.intValue() >= minLogLevel; - } - static boolean log(Level level, String message, Throwable ex) { - if (!shouldLog(level)) - return true; - Logger.getLogger(JavaCL.class.getName()).log(level, message, ex); - return true; - } - - static boolean log(Level level, String message) { - log(level, message, null); - return true; - } - - private static int getPlatformIDs(OpenCLLibrary lib, int count, cl_platform_id[] out, IntByReference pCount) { - try { - return lib.clIcdGetPlatformIDsKHR(count, out, pCount); - } catch (Throwable th) { - return lib.clGetPlatformIDs(count, out, pCount); - } - } - public interface OpenCLStdCallLibrary extends com.nativelibs4java.opencl.library.OpenCLLibrary, com.sun.jna.win32.StdCallLibrary { - - } - - static final OpenCLLibrary CL; - static { - Class libClass = Platform.isWindows() && !Platform.is64Bit() ? OpenCLStdCallLibrary.class : OpenCLLibrary.class; - OpenCLLibrary lib = (OpenCLLibrary)Native.loadLibrary("OpenCL", libClass); - //if (Platform.isWindows()) - try { - IntByReference pCount = new IntByReference(); - boolean success = false; - try { - success = getPlatformIDs(lib, 0, null, pCount) == OpenCLLibrary.CL_SUCCESS; - } catch (Throwable th) {} - if (!success) { - OpenCLLibrary atiLib = null; - if (Platform.is64Bit()) - atiLib = (OpenCLLibrary)Native.loadLibrary("atiocl64", libClass); - if (atiLib == null) - atiLib = (OpenCLLibrary)Native.loadLibrary("atiocl32", libClass); - if (atiLib == null) - atiLib = (OpenCLLibrary)Native.loadLibrary("atiocl", libClass); - if (atiLib != null) { - int err = getPlatformIDs(atiLib, 0, null, pCount); - if (err == OpenCLLibrary.CL_SUCCESS) { - System.out.println("[JavaCL] Hacking around ATI's weird driver bugs (using atiocl library instead of OpenCL)"); - lib = atiLib; - } - } - } - } catch (Throwable th) {} - - CL = (OpenCLLibrary)Native.synchronizedLibrary(lib); - } - - /** - * List the OpenCL implementations that contain at least one GPU device. - */ - public static CLPlatform[] listGPUPoweredPlatforms() { - CLPlatform[] platforms = listPlatforms(); - List out = new ArrayList(platforms.length); - for (CLPlatform platform : platforms) { - if (platform.listGPUDevices(true).length > 0) - out.add(platform); - } - return out.toArray(new CLPlatform[out.size()]); - } - /** - * Lists all available OpenCL implementations. - */ - public static CLPlatform[] listPlatforms() { - IntByReference pCount = new IntByReference(); - error(getPlatformIDs(CL, 0, null, pCount)); - - int nPlats = pCount.getValue(); - if (nPlats == 0) - return new CLPlatform[0]; - - cl_platform_id[] ids = new cl_platform_id[nPlats]; - - error(getPlatformIDs(CL, nPlats, ids, null)); - CLPlatform[] platforms = new CLPlatform[nPlats]; - - for (int i = 0; i < nPlats; i++) { - platforms[i] = new CLPlatform(ids[i]); - } - return platforms; - } - - /** - * Creates an OpenCL context formed of the provided devices.
- * It is generally not a good idea to create a context with more than one device, - * because much data is shared between all the devices in the same context. - * @param devices devices that are to form the new context - * @return new OpenCL context - */ - public static CLContext createContext(Map contextProperties, CLDevice... devices) { - return devices[0].getPlatform().createContext(contextProperties, devices); - } - - /** - * Allows the implementation to release the resources allocated by the OpenCL compiler.
- * This is a hint from the application and does not guarantee that the compiler will not be used in the future or that the compiler will actually be unloaded by the implementation.
- * Calls to Program.build() after unloadCompiler() will reload the compiler, if necessary, to build the appropriate program executable. - */ - public static void unloadCompiler() { - error(CL.clUnloadCompiler()); - } - - /** - * Returns the "best" OpenCL device (currently, the one that has the largest amount of compute units).
- * For more control on what is to be considered a better device, please use the {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature[]) } variant.
- * This is currently equivalent to getBestDevice(MaxComputeUnits) - */ - public static CLDevice getBestDevice() { - return getBestDevice(CLPlatform.DeviceFeature.MaxComputeUnits); - } - /** - * Returns the "best" OpenCL device based on the comparison of the provided prioritized device feature.
- * The returned device does not necessarily exhibit the features listed in preferredFeatures, but it has the best ordered composition of them.
- * For instance on a system with a GPU and a CPU device, JavaCL.getBestDevice(CPU, MaxComputeUnits) will return the CPU device, but on another system with two GPUs and no CPU device it will return the GPU that has the most compute units. - */ - public static CLDevice getBestDevice(CLPlatform.DeviceFeature... preferredFeatures) { - List devices = new ArrayList(); - for (CLPlatform platform : listPlatforms()) - devices.addAll(Arrays.asList(platform.listAllDevices(true))); - return CLPlatform.getBestDevice(Arrays.asList(preferredFeatures), devices); - } - /** - * Creates an OpenCL context with the "best" device (see {@link JavaCL#getBestDevice() }) - */ - public static CLContext createBestContext() { - return createBestContext(DeviceFeature.MaxComputeUnits); - } - - /** - * Creates an OpenCL context with the "best" device based on the comparison of the provided prioritized device feature (see {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature) }) - */ - public static CLContext createBestContext(CLPlatform.DeviceFeature... preferredFeatures) { - CLDevice device = getBestDevice(preferredFeatures); - return device.getPlatform().createContext(null, device); - } - - /** - * Creates an OpenCL context able to share entities with the current OpenGL context. - * @throws RuntimeException if JavaCL is unable to create an OpenGL-shared OpenCL context. - */ - public static CLContext createContextFromCurrentGL() { - RuntimeException first = null; - for (CLPlatform platform : listPlatforms()) { - try { - CLContext ctx = platform.createContextFromCurrentGL(); - if (ctx != null) - return ctx; - } catch (RuntimeException ex) { - if (first == null) - first = ex; - - } - } - throw new RuntimeException("Failed to create an OpenCL context based on the current OpenGL context", first); - } - - static File userJavaCLDir = new File(new File(System.getProperty("user.home")), ".javacl"); - static File userCacheDir = new File(userJavaCLDir, "cache"); - - static synchronized File createTempFile(String prefix, String suffix, String category) { - File dir = new File(userJavaCLDir, category); - dir.mkdirs(); - try { - return File.createTempFile(prefix, suffix, dir); - } catch (IOException ex) { - throw new RuntimeException("Failed to create a temporary directory for category '" + category + "' in " + userJavaCLDir + ": " + ex.getMessage(), ex); - } - } - static synchronized File createTempDirectory(String prefix, String suffix, String category) { - File file = createTempFile(prefix, suffix, category); - file.delete(); - file.mkdir(); - return file; - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/package-info.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/package-info.java deleted file mode 100644 index c28796f5e..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/opencl/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * Object-oriented wrappers around the OpenCL API, with methods that help creating and managing OpenCL applications.
- * Also see the low-level bindings : {@link com.nativelibs4java.opencl.library.OpenCL4Java} - */ -package com.nativelibs4java.opencl; diff --git a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/util/JNAUtils.java b/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/util/JNAUtils.java deleted file mode 100644 index 6e230836c..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/java/com/nativelibs4java/util/JNAUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.util; - -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.*; -import com.sun.jna.ptr.*; - -/** - * JNA-related util methods - * @author ochafik - */ -public class JNAUtils { - - /** - * Casts an IntByReference to a NativeLongByReference - */ - public static NativeSizeByReference castToNS(IntByReference local) { - NativeSizeByReference nl = new NativeSizeByReference(); - nl.setPointer(local.getPointer()); - return nl; - } - - /** - * Casts a LongByReference to a NativeSizeByReference - */ - public static NativeSizeByReference castToNS(LongByReference local) { - NativeSizeByReference nl = new NativeSizeByReference(); - nl.setPointer(local.getPointer()); - return nl; - } - - public static NativeSize readNS(Pointer p, long offset) { - if (NativeSize.SIZE == 4) - return new NativeSize(p.getInt(offset)); - else if (NativeSize.SIZE == 8) - return new NativeSize(p.getLong(offset)); - else - throw new RuntimeException("sizeof(size_t) must be either 4 or 8"); - } - public static void writeNS(Pointer p, long offset, long value) { - if (NativeSize.SIZE == 4) - p.setInt(offset, (int)value); - else if (NativeSize.SIZE == 8) - p.setLong(offset, value); - else - throw new RuntimeException("sizeof(size_t) must be either 4 or 8"); - } - - public static NativeSize[] readNSArray(Pointer p, int n) { - NativeSize[] sizes = new NativeSize[n]; - for (int i = 0; i < n; i++) - sizes[i] = readNS(p, i * NativeSize.SIZE); - return sizes; - } - - public static void writeNSArray(Pointer p, long... values) { - if (values == null) - return; - for (int i = 0, n = values.length; i < n; i++) - writeNS(p, i * NativeSize.SIZE, values[i]); - } - - /** - * Converts int/long values array to a Memory object containing contiguous size_t values - * @see NativeSize#SIZE - */ - public static Memory toNSArray(long... values) { - if (values == null) - return null; - Memory mem = new Memory(values.length * NativeSize.SIZE); - writeNSArray(mem, values); - return mem; - } - - /** - * Return a new Size with the provided int value - */ - public static NativeSize[] toNS(int[] ints) { - if (ints == null) - return null; - int n = ints.length; - NativeSize[] nls = new NativeSize[n]; - for (int i = 0; i < n; i++) - nls[i] = toNS(ints[i]); - - return nls; - } - - /** - * Return a new NativeSize array with the provided long values - */ - public static NativeSize[] toNS(long... ints) { - if (ints == null) - return null; - int n = ints.length; - NativeSize[] nls = new NativeSize[n]; - for (int i = 0; i < n; i++) - nls[i] = toNS(ints[i]); - - return nls; - } - - /** - * Return a new NativeSize with the provided int value - */ - public static NativeSize toNS(int i) { - return new NativeSize(i); - } - - /** - * Return a new NativeSize with the provided long value - */ - public static NativeSize toNS(long i) { - return new NativeSize(i); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/main/javadoc/overview.html b/libraries/OpenCL-JNA/Core/src/main/javadoc/overview.html deleted file mode 100644 index 03e8f3de8..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/javadoc/overview.html +++ /dev/null @@ -1,75 +0,0 @@ - - - -

-JavaCL is an Object-Oriented API that wraps the OpenCL API.
-It makes it easy to do cross-platform GPGPU with Java. -

- -

-Core classes : -

    -
  • JavaCL: entry point of JavaCL, useful to list platforms, create contexts. -
  • CLContext: all the JavaCL data and programs must be created from a context instance. -
  • CLQueue: OpenCL operations can be executed immediately or queued. A queue instance is however needed even for immediate operations. -
  • CLMem: base class for buffers and 2D and 3D images. -
  • -

    - -

    -JavaCL relies on OpenCL4Java, low-level bindings that closely match the OpenCL C API and use JNA+JNAerator for the native access interop. -

    - -

    -Here's a very simple vector addition JavaCL program : -

    package com.nativelibs4java.opencl.demos.vectoradd;
    -import com.nativelibs4java.opencl.*;
    -import java.nio.*;
    -
    -public class VectorAdd {
    -
    -    public static void main(String[] args) {
    -        try {
    -            FloatBuffer a = FloatBuffer.wrap(new float[] {  1,  2,  3,  4 });
    -            FloatBuffer b = FloatBuffer.wrap(new float[] { 10, 20, 30, 40 });
    -
    -            FloatBuffer sum = add(a, b);
    -            for (int i = 0, n = sum.capacity(); i < n; i++)
    -                System.out.println(sum.get(i));
    -        } catch (Exception ex) {
    -            ex.printStackTrace();
    -        }
    -    }
    -
    -    public static FloatBuffer add(FloatBuffer a, FloatBuffer b) throws CLBuildException {
    -        int n = a.capacity();
    -        
    -        CLContext context = JavaCL.createBestContext();
    -        CLQueue queue = context.createDefaultQueue();
    -        
    -        String source = 
    -            "__kernel void addFloats(__global const float* a, __global const float* b, __global float* output)     " +
    -            "{                                                                                                     " +
    -            "   int i = get_global_id(0);                                                                          " +
    -            "   output[i] = a[i] + b[i];                                                                           " +
    -            "}                                                                                                     ";
    -        
    -        CLKernel kernel = context.createProgram(source).createKernel("addFloats");
    -        CLFloatBuffer aBuf = context.createFloatBuffer(CLMem.Usage.Input, a, true);
    -        CLFloatBuffer bBuf = context.createFloatBuffer(CLMem.Usage.Input, b, true);
    -        CLFloatBuffer outBuf = context.createFloatBuffer(CLMem.Usage.Output, n);
    -        kernel.setArgs(aBuf, bBuf, outBuf);
    -        
    -        kernel.enqueueNDRange(queue, new int[]{n}, new int[] { 1 });
    -        queue.finish();
    -    
    -        return outBuf.read(queue);
    -    }
    -}
    -
    -
    - -

    - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/HardwareReport.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/HardwareReport.jnlp deleted file mode 100644 index cf7d8c23b..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/HardwareReport.jnlp +++ /dev/null @@ -1,30 +0,0 @@ - - - - JavaCL HardwareReport - Olivier Chafik - - JavaCL HardwareReport - JavaCL HardwareReport - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp deleted file mode 100644 index 8a1c2492c..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp +++ /dev/null @@ -1,34 +0,0 @@ - - - - JavaCL Interactive Image Transform Demo - Olivier Chafik - - Image Transform Kernel Editor + Demos for JavaCL (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/JavaCL.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/JavaCL.jnlp deleted file mode 100644 index bfcd3ec88..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/JavaCL.jnlp +++ /dev/null @@ -1,23 +0,0 @@ - - - - JavaCL - Olivier Chafik - - Object-Oriented OpenCL Library for Java - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/MandelbrotDemo.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/MandelbrotDemo.jnlp deleted file mode 100644 index 688533bc6..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/MandelbrotDemo.jnlp +++ /dev/null @@ -1,32 +0,0 @@ - - - - JavaCL Mandelbrot Demos - Olivier Chafik (demo adapted from Bob Boothby's) - - Mandelbrot Demo for JavaCL (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/OpenCL4Java.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/OpenCL4Java.jnlp deleted file mode 100644 index b5419d308..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/OpenCL4Java.jnlp +++ /dev/null @@ -1,25 +0,0 @@ - - - - OpenCL4Java - Olivier Chafik - - OpenCL bindings for Java - OpenCL4Java HardwareReport - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/ParticlesDemo.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/ParticlesDemo.jnlp deleted file mode 100644 index 6a228a6a0..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/ParticlesDemo.jnlp +++ /dev/null @@ -1,35 +0,0 @@ - - - - JavaCL Particles Demos - Olivier Chafik - - Demos for JavaCL (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/jnlp/ScalaCL.jnlp b/libraries/OpenCL-JNA/Core/src/main/jnlp/ScalaCL.jnlp deleted file mode 100644 index 147a21719..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/jnlp/ScalaCL.jnlp +++ /dev/null @@ -1,22 +0,0 @@ - - - - ScalaCL - Olivier Chafik - - OpenCL for Scala: natural DSL and Object-Oriented API - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java b/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java deleted file mode 100644 index fc413e9af..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import static com.nativelibs4java.util.JNAUtils.toNS; -import static com.nativelibs4java.util.NIOUtils.directBytes; -import static com.nativelibs4java.util.NIOUtils.directCopy; - -import java.nio.*; - -import com.nativelibs4java.opencl.library.cl_buffer_region; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.util.listenable.Pair; -import com.sun.jna.Native; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.IntByReference; - -/** - * OpenCL Memory Buffer Object.
    - * A buffer object stores a one-dimensional collection of elements.
    - * Elements of a buffer object can be a scalar data type (such as an int, float), vector data type, or a user-defined structure.
    - * @see CLContext - * @author Olivier Chafik - */ -public class CLBuffer extends CLMem { - /// Buffer to retain a reference to (because it's being copied asynchronously to the underlying OpenCL buffer) - Buffer buffer; - final int elementSize; - final Class typedBufferClass; - final Class elementClass; - CLBuffer(CLContext context, long byteCount, cl_mem entity, Buffer buffer, int elementSize, Class typedBufferClass) { - super(context, byteCount, entity); - this.buffer = buffer; - this.elementSize = elementSize; - this.typedBufferClass = typedBufferClass; - this.elementClass = (Class)NIOUtils.getPrimitiveClass(typedBufferClass); - } - - public Class getBufferClass() { - return typedBufferClass; - } - public Class getElementClass() { - return elementClass; - } - public int getElementSize() { - return elementSize; - } - public long getElementCount() { - return getByteCount() / getElementSize(); - } - public B map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return (B)map(queue, flags, 0, getElementCount(), true, eventsToWaitFor).getFirst(); - } - public B map(CLQueue queue, MapFlags flags, long offset, long length, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return (B)map(queue, flags, offset, length, true, eventsToWaitFor).getFirst(); - } - public Pair mapLater(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, 0, getElementCount(), false, eventsToWaitFor); - } - public Pair mapLater(CLQueue queue, MapFlags flags, long offset, long length, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, offset, length, false, eventsToWaitFor); - } - public B read(CLQueue queue, CLEvent... eventsToWaitFor) { - B out = (B)typedBuffer(directBytes((int)getByteCount(), queue.getDevice().getKernelsDefaultByteOrder())); - read(queue, out, true, eventsToWaitFor); - return out; - } - public B read(CLQueue queue, long offset, long length, CLEvent... eventsToWaitFor) { - B out = (B)typedBuffer(directBytes((int)getByteCount(), queue.getDevice().getKernelsDefaultByteOrder())); - read(queue, offset, length, out, true, eventsToWaitFor); - return out; - } - - protected void checkBounds(long offset, long length) { - if (offset + length * getElementSize() > getByteCount()) - throw new IndexOutOfBoundsException("Trying to map a region of memory object outside allocated range"); - } - - /** - * Can be used to create a new buffer object (referred to as a sub-buffer object) from an existing buffer object. - * @param usage is used to specify allocation and usage information about the image memory object being created and is described in table 5.3 of the OpenCL spec. - * @param offset - * @param length - * @since OpenCL 1.1 - * @return sub-buffer that is a "window" of this buffer starting at the provided offset, with the provided length - */ - public CLBuffer createSubBuffer(Usage usage, long offset, long length) { - try { - int s = getElementSize(); - cl_buffer_region region = new cl_buffer_region(toNS(s * offset), toNS(s * length)); - IntByReference pErr = new IntByReference(); - cl_mem mem = CL.clCreateSubBuffer(getEntity(), usage.getIntFlags(), CL_BUFFER_CREATE_TYPE_REGION, region.getPointer(), pErr); - error(pErr.getValue()); - return mem == null ? null : createBuffer(mem); - } catch (Throwable th) { - // TODO check if supposed to handle OpenCL 1.1 - throw new UnsupportedOperationException("Cannot create sub-buffer (OpenCL 1.1 feature).", th); - } - } - - /** - * enqueues a command to copy a buffer object identified by src_buffer to another buffer object identified by destination. - * @param queue - * @param destination - * @param eventsToWaitFor - * @return event which indicates the copy operation has completed - */ - public CLEvent copyTo(CLQueue queue, CLMem destination, CLEvent... eventsToWaitFor) { - return copyTo(queue, 0, getElementCount(), destination, 0, eventsToWaitFor); - } - - /** - * enqueues a command to copy a buffer object identified by src_buffer to another buffer object identified by destination. - * @param queue - * @param srcOffset - * @param length - * @param destination - * @param destOffset - * @param eventsToWaitFor - * @return event which indicates the copy operation has completed - */ - public CLEvent copyTo(CLQueue queue, long srcOffset, long length, CLMem destination, long destOffset, CLEvent... eventsToWaitFor) { - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - long - byteCount = getByteCount(), - destByteCount = destination.getByteCount(), - eltSize = getElementSize(), - actualSrcOffset = srcOffset * eltSize, - actualDestOffset = destOffset * eltSize, - actualLength = length * eltSize; - - if ( actualSrcOffset < 0 || - actualSrcOffset >= byteCount || - actualSrcOffset + actualLength > byteCount || - actualDestOffset < 0 || - actualDestOffset >= destByteCount || - actualDestOffset + actualLength > destByteCount - ) - throw new IndexOutOfBoundsException("Invalid copy parameters : srcOffset = " + srcOffset + ", destOffset = " + destOffset + ", length = " + length + " (element size = " + eltSize + ", source byte count = " + byteCount + ", destination byte count = " + destByteCount + ")"); - - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueCopyBuffer( - queue.getEntity(), - getEntity(), - destination.getEntity(), - toNS(actualSrcOffset), - toNS(actualDestOffset), - toNS(actualLength), - evts == null ? 0 : evts.length, evts, - eventOut - )); - return CLEvent.createEvent(queue, eventOut); - } - - protected Pair map(CLQueue queue, MapFlags flags, long offset, long length, boolean blocking, CLEvent... eventsToWaitFor) { - checkBounds(offset, length); - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - IntByReference pErr = new IntByReference(); - - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - Pointer p = CL.clEnqueueMapBuffer(queue.getEntity(), getEntity(), blocking ? CL_TRUE : CL_FALSE, - flags.value(), - toNS(offset * getElementSize()), - toNS(length * getElementSize()), - evts == null ? 0 : evts.length, evts, - eventOut, - pErr - ); - error(pErr.getValue()); - return new Pair( - (B)typedBuffer(p.getByteBuffer(0, length * getElementSize()).order(queue.getDevice().getKernelsDefaultByteOrder())), - CLEvent.createEvent(queue, eventOut) - ); - } - - public CLEvent unmap(CLQueue queue, B buffer, CLEvent... eventsToWaitFor) { - typedBufferClass.cast(buffer); - cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueUnmapMemObject(queue.getEntity(), getEntity(), Native.getDirectBufferPointer(buffer), evts == null ? 0 : evts.length, evts, eventOut)); - return CLEvent.createEvent(queue, eventOut); - } - - public CLEvent read(CLQueue queue, B out, boolean blocking, CLEvent... eventsToWaitFor) { - typedBufferClass.cast(out); - long length; - if (isGL) { - length = out.capacity(); - } else { - length = getElementCount(); - long s = out.capacity(); - if (length > s) - length = s; - } - return read(queue, 0, length, out, blocking, eventsToWaitFor); - } - - public CLEvent read(CLQueue queue, long offset, long length, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - typedBufferClass.cast(out); - if (out.isReadOnly()) - throw new IllegalArgumentException("Output buffer for read operation is read-only !"); - Buffer originalOut = null; - if (!out.isDirect()) { - originalOut = out; - out = typedBuffer(directBytes((int)(length * getElementSize()), queue.getDevice().getKernelsDefaultByteOrder())); - blocking = true; - } - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueReadBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : 0, - toNS(offset * getElementSize()), - toNS(length * getElementSize()), - Native.getDirectBufferPointer(out), - evts == null ? 0 : evts.length, evts, - eventOut - )); - if (originalOut != null) - NIOUtils.put(out, originalOut); - return CLEvent.createEvent(queue, eventOut); - } - - public CLEvent write(CLQueue queue, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - typedBufferClass.cast(in); - long length; - if (isGL) { - length = in.capacity(); - } else { - length = getElementCount(); - long s = in.capacity(); - if (length > s) - length = s; - } - return write(queue, 0, length, in, blocking, eventsToWaitFor); - } - - public CLEvent write(CLQueue queue, long offset, long length, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - typedBufferClass.cast(in); - - if (!in.isDirect()) { - blocking = true; - in = typedBuffer(directCopy(in, queue.getDevice().getKernelsDefaultByteOrder())); - } - - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueWriteBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - toNS(offset * getElementSize()), - toNS(length * getElementSize()), - Native.getDirectBufferPointer(in), - evts == null ? 0 : evts.length, evts, - eventOut - )); - return CLEvent.createEvent(queue, eventOut); - } - - public CLEvent writeBytes(CLQueue queue, long offset, long length, ByteBuffer in, boolean blocking, CLEvent... eventsToWaitFor) { - if (!in.isDirect()) { - blocking = true; - in = directCopy(in, queue.getDevice().getKernelsDefaultByteOrder()); - } - - cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor); - cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); - error(CL.clEnqueueWriteBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : 0, - toNS(offset), - toNS(length), - Native.getDirectBufferPointer(in), - evts == null ? 0 : evts.length, evts, - eventOut - )); - return CLEvent.createEvent(queue, eventOut); - } - - public ByteBuffer readBytes(CLQueue queue, long offset, long length, CLEvent... eventsToWaitFor) { - ByteBuffer out = directBytes((int)getByteCount(), queue.getDevice().getKernelsDefaultByteOrder()); - Buffer tout = typedBuffer(out); - read(queue, offset, tout.capacity(), tout, true, eventsToWaitFor); - return out; - } - - private T copyGLMark(T mem) { - mem.isGL = this.isGL; - return mem; - } - - public CLBuffer emptyClone(CLMem.Usage usage) { - return (CLBuffer)getContext().createBuffer(usage, typedBufferClass, getElementCount()); - } - - protected CLBuffer createBuffer(cl_mem mem) { - - //return new CLBuffer(getContext(), -1, mem, null, getElementSize(), typedBufferClass); - - #foreach ($prim in $primitivesNoBool) - - if (typedBufferClass == ${prim.BufferName}.class) - return (CLBuffer)new CL${prim.BufferName}(getContext(), -1, mem, null); - - #end - - throw new RuntimeException("Unable to create an OpenCL buffer for type " + typedBufferClass.getName()); - } - - protected B typedBuffer(ByteBuffer b) { - #foreach ($prim in $primitivesNoBool) - - if (typedBufferClass == ${prim.BufferName}.class) - #if ($prim.Name == "byte") - return (B)b; - #else - return (B)b.as${prim.BufferName}(); - #end - - #end - - throw new RuntimeException("Unable to create a typed buffer for type " + typedBufferClass.getName()); - } - - #foreach ($prim in $primitivesNoBool) - - public CL${prim.BufferName} asCL${prim.BufferName}() { - cl_mem mem = getEntity(); - CL.clRetainMemObject(getEntity()); - return copyGLMark(new CL${prim.BufferName}(context, getByteCount(), mem, buffer)); - } - - #end - -} diff --git a/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java b/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java deleted file mode 100644 index 345a9824e..000000000 --- a/libraries/OpenCL-JNA/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java +++ /dev/null @@ -1,730 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl; -import com.ochafik.util.listenable.Pair; - -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.CLException.failedForLackOfMemory; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import static com.nativelibs4java.util.ImageUtils.getImageIntPixels; -import static com.nativelibs4java.util.JNAUtils.toNS; -import static com.nativelibs4java.util.JNAUtils.toNSArray; -import static com.nativelibs4java.util.NIOUtils.getSizeInBytes; - -import java.awt.Image; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.*; - -import com.nativelibs4java.opencl.CLDevice.QueueProperties; -import com.nativelibs4java.opencl.CLSampler.AddressingMode; -import com.nativelibs4java.opencl.CLSampler.FilterMode; -import com.nativelibs4java.opencl.ImageIOUtils.ImageInfo; -import com.nativelibs4java.opencl.library.OpenGLContextUtils; -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_sampler; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.NIOUtils; -import com.nativelibs4java.util.ValuedEnum; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.Memory; -import com.sun.jna.Native; -import com.sun.jna.Platform; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.IntByReference; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Map; - -/** - * OpenCL context.
    - * An OpenCL context is created with one or more devices.
    - * Contexts are used by the OpenCL runtime for managing objects such as command-queues, memory, program and kernel objects and for executing kernels on one or more devices specified in the context. - * @author Olivier Chafik - */ -public class CLContext extends CLAbstractEntity { - -#macro (docCreateBufferCopy $bufferType $details) - /** - * Create a $bufferType OpenCL buffer $details with the provided initial values.
    - * If copy is true (see CL_MEM_COPY_HOST_PTR), then the buffer will be hosted in OpenCL and will have the best performance, but any change done to the OpenCL buffer won't be propagated to the original data pointer.
    - * If copy is false (see CL_MEM_USE_HOST_PTR), then the provided data pointer will be used for storage of the OpenCL buffer. OpenCL might still cache the data in the OpenCL land, so careful use of {@link CLBuffer#map(CLQueue, MapFlags, CLEvent[])} is then necessary to ensure the data is properly synchronized with the buffer. - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - * @param data Buffer that contains the initial values. It must be direct for the non-copy mode, but indirect buffers should be avoided in all cases for performance reasons. - */ -#end -#macro (docCreateBuffer $bufferType $type $insertParam $exampleOfLength) - /** - * Create a $bufferType OpenCL buffer big enough to hold 'length' values of type $type. - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - $insertParam - * @param elementCount Length of the buffer expressed in elements $exampleOfLength - */ -#end -#macro (docCreateBufferPrim $bufferType $prim) -#docCreateBuffer($bufferType, $prim.Name, "", "(for instance, a $bufferType of length 10 will actually contain 10 * ${prim.Size} bytes, as ${prim.Name}s are ${prim.Size}-bytes-long)") -#end - - volatile Boolean cacheBinaries; - - /** - * Change whether program binaries are automatically cached or not.
    - * By default it is true, it can be set to false with the "javacl.cacheBinaries" Java property or the "JAVACL_CACHE_BINARIES" environment variable (when set to "0").
    - * Each program can be set to be cached or not using {@link CLProgram#setCached(boolean) }.
    - * Caching of binaries might be disabled by default on some platforms (ATI Stream, for instance). - */ - public synchronized void setCacheBinaries(boolean cacheBinaries) { - this.cacheBinaries = cacheBinaries; - } - /** - * Says whether program binaries are automatically cached or not.
    - * By default it is true, it can be set to false with the "javacl.cacheBinaries" Java property, the "JAVACL_CACHE_BINARIES" environment variable (when set to "0") or the {@link JavaCL#setCacheBinaries(boolean) } method.
    - * Each program can be set to be cached or not using {@link CLProgram#setCached(boolean) }.
    - * Caching of binaries might be disabled by default on some platforms (ATI Stream, for instance). - */ - public synchronized boolean getCacheBinaries() { - if (cacheBinaries == null) { - String prop = System.getProperty("javacl.cacheBinaries"), env = System.getenv("JAVACL_CACHE_BINARIES"); - if ("true".equals(prop) || "1".equals(env)) - cacheBinaries = true; - else if ("false".equals(prop) || "0".equals(env)) - cacheBinaries = false; - else { - String plat = getPlatform().getName(); - cacheBinaries = - !"ATI Stream".equals(plat) && - !"AMD Accelerated Parallel Processing".equals(plat) && - true; - } - //System.out.println("CACHE BINARIES = " + cacheBinaries); - } - return cacheBinaries; - } - - private static CLInfoGetter infos = new CLInfoGetter() { - - @Override - protected int getInfo(cl_context entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { - return CL.clGetContextInfo(entity, infoTypeEnum, size, out, sizeOut); - } - }; - CLPlatform platform; - protected cl_device_id[] deviceIds; - - CLContext(CLPlatform platform, cl_device_id[] deviceIds, cl_context context) { - super(context); - this.platform = platform; - this.deviceIds = deviceIds; - - if (getByteOrder() == null) { - JavaCL.log(Level.WARNING, "The devices in this context have mismatching byte orders. This mandates the use of __attribute__((endian(host))) in kernel sources or *very* careful use of buffers to avoid facing endianness issues"); - } - } - - /** - * Creates a user event object.
    - * User events allow applications to enqueue commands that wait on a user event to finish before the command is executed by the device. - * @since OpenCL 1.1 - */ - public CLEvent createUserEvent() { - try { - IntByReference pErr = new IntByReference(); - cl_event evt = CL.clCreateUserEvent(getEntity(), pErr); - error(pErr.getValue()); - return CLEvent.createEvent(null, evt, true); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return null; - } - } - - /** - * Create an OpenCL queue on the first device of this context.
    - * Equivalent to calling getDevices()[0].createQueue(context) - * @return new OpenCL queue - */ - public CLQueue createDefaultQueue(QueueProperties... queueProperties) { - return new CLDevice(platform, deviceIds[0]).createQueue(this, queueProperties); - } - - /** - * Create an out-of-order OpenCL queue on the first device of this context.
    - * Equivalent to calling getDevices()[0].createOutOfOrderQueue(context) - * @return new out-of-order OpenCL queue - */ - public CLQueue createDefaultOutOfOrderQueue() { - return new CLDevice(platform, deviceIds[0]).createOutOfOrderQueue(this); - } - - - public String toString() { - StringBuilder b = new StringBuilder("CLContext(platform = ").append(getPlatform().getName()).append("; devices = "); - boolean first = true; - for (CLDevice d : getDevices()) { - if (first) - first = false; - else - b.append(", "); - b.append(d.getName()); - } - b.append(")"); - return b.toString(); - } - public CLQueue createDefaultOutOfOrderQueueIfPossible() { - try { - return createDefaultOutOfOrderQueue(); - } catch (CLException.InvalidQueueProperties ex) { - return createDefaultQueue(); - } - } - - /** - * Create an profiling-enabled OpenCL queue on the first device of this context.
    - * Equivalent to calling getDevices()[0].createProfilingQueue(context) - * @return new profiling-enabled OpenCL queue - */ - public CLQueue createDefaultProfilingQueue() { - return new CLDevice(platform, deviceIds[0]).createProfilingQueue(this); - } - - @SuppressWarnings("deprecation") - public CLImageFormat[] getSupportedImageFormats(CLBuffer.Flags flags, CLBuffer.ObjectType imageType) { - IntByReference pCount = new IntByReference(); - int memFlags = (int) flags.value(); - int imTyp = (int) imageType.value(); - Memory memCount = new Memory(16); - pCount.setPointer(memCount); - CL.clGetSupportedImageFormats(getEntity(), memFlags, imTyp, 0, null, pCount); - cl_image_format ft = new cl_image_format(); - int sz = ft.size(); - int n = pCount.getValue(); - if (n == 0) { - n = 30; // There HAS to be at least one format. the spec even says even more, but in fact on Mac OS X / CPU there's only one... - } - Memory mem = new Memory(n * sz); - ft.use(mem); - CL.clGetSupportedImageFormats(getEntity(), memFlags, imTyp, n, ft, (IntByReference) null); - List ret = new ArrayList(n); - for (int i = 0; i < n; i++) { - ft.use(mem, i * sz); - ft.read(); - if (ft.image_channel_data_type == 0 && ft.image_channel_order == 0) - break; - - ret.add(new CLImageFormat(ft)); - } - return ret.toArray(new CLImageFormat[ret.size()]); - } - - @SuppressWarnings("deprecation") - public CLSampler createSampler(boolean normalized_coords, AddressingMode addressing_mode, FilterMode filter_mode) { - IntByReference pErr = new IntByReference(); - cl_sampler sampler = CL.clCreateSampler(getEntity(), normalized_coords ? CL_TRUE : CL_FALSE, (int) addressing_mode.value(), (int) filter_mode.value(), pErr); - error(pErr.getValue()); - return new CLSampler(sampler); - } - - public int getDeviceCount() { - return infos.getOptionalFeatureInt(getEntity(), CL.CL_CONTEXT_NUM_DEVICES); - } - - /** - * Lists the devices of this context - * @return array of the devices that form this context - */ - public synchronized CLDevice[] getDevices() { - if (deviceIds == null) { - Memory ptrs = infos.getMemory(getEntity(), CL_CONTEXT_DEVICES); - int n = (int) (ptrs.getSize() / Native.POINTER_SIZE); - deviceIds = new cl_device_id[n]; - for (int i = 0; i < n; i++) { - deviceIds[i] = new cl_device_id(ptrs.getPointer(i * Native.POINTER_SIZE)); - } - } - CLDevice[] devices = new CLDevice[deviceIds.length]; - for (int i = devices.length; i-- != 0;) { - devices[i] = new CLDevice(platform, deviceIds[i]); - } - return devices; - } - - /** - * Create a program with all the C source code content provided as argument. - * @param srcs list of the content of source code for the program - * @return a program that needs to be built - */ - public CLProgram createProgram(String... srcs) { - return createProgram(null, srcs); - } - - public CLProgram createProgram(CLDevice[] devices, String... srcs) { - CLProgram program = new CLProgram(this, devices); - for (String src : srcs) - program.addSource(src); - return program; - } - - /** - * Restore a program previously saved with {@link CLProgram#store(java.io.OutputStream) } - * @param in will be closed - * @return - * @throws IOException - */ - public CLProgram loadProgram(InputStream in) throws IOException { - Pair, String> binaries = CLProgram.readBinaries(Arrays.asList(getDevices()), null, in); - return createProgram(binaries.getFirst(), binaries.getSecond()); - } - - public CLProgram createProgram(Map binaries, String source) { - return new CLProgram(this, binaries, source); - } - - //cl_queue queue; - @Override - protected void clear() { - error(CL.clReleaseContext(getEntity())); - } - - - - @Deprecated - public CLDevice guessCurrentGLDevice() { - long[] props = CLPlatform.getContextProps(CLPlatform.getGLContextProperties(getPlatform())); - Memory propsMem = toNSArray(props); - NativeSizeByReference propsRef = new NativeSizeByReference(); - propsRef.setPointer(propsMem); - - NativeSizeByReference pCount = new NativeSizeByReference(); - Memory mem = new Memory(Pointer.SIZE); - if (Platform.isMac()) - error(CL.clGetGLContextInfoAPPLE(getEntity(), OpenGLContextUtils.INSTANCE.CGLGetCurrentContext(), CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, toNS(Pointer.SIZE), mem, pCount)); - else - error(CL.clGetGLContextInfoKHR(propsRef, CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, toNS(Pointer.SIZE), mem, pCount)); - - if (pCount.getValue().intValue() != Pointer.SIZE) - throw new RuntimeException("Not a device : len = " + pCount.getValue().intValue()); - - Pointer p = mem.getPointer(0); - if (p.equals(Pointer.NULL)) - return null; - return new CLDevice(null, new cl_device_id(p)); - } - - private static T markAsGL(T mem) { - mem.isGL = true; - return mem; - } - - /** - * Makes an OpenGL Vertex Buffer Object (VBO) visible to OpenCL as a buffer object.
    - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * see {@link CLMem#acquireGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLMem#releaseGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * @param openGLBufferObject Identifier of a VBO, as generated by glGenBuffers - */ - @SuppressWarnings("deprecation") - public CLByteBuffer createBufferFromGLBuffer(CLMem.Usage usage, int openGLBufferObject) { - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLBuffer(getEntity(), usage.getIntFlags(), openGLBufferObject, pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - return markAsGL(new CLByteBuffer(this, -1, mem, null)); - } - - /** - * Makes an OpenGL Render Buffer visible to OpenCL as a 2D image.
    - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * see {@link CLMem#acquireGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLMem#releaseGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * @param openGLBufferObject Identifier of an OpenGL render buffer - */ - @SuppressWarnings("deprecation") - public CLImage2D createImage2DFromGLRenderBuffer(CLMem.Usage usage, int openGLRenderBuffer) { - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLRenderbuffer(getEntity(), usage.getIntFlags(), openGLRenderBuffer, pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - return markAsGL(new CLImage2D(this, mem, null)); - } - - /** - * Creates an OpenCL 2D image object from an OpenGL 2D texture object, or a single face of an OpenGL cubemap texture object.
    - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * @param usage - * @param textureTarget Must be one of GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, or GL_TEXTURE_RECTANGLE47. texture_target is used only to define the image type of texture. No reference to a bound GL texture object is made or implied by this parameter. - * @param mipLevel Mipmap level to be used (Implementations may return CL_INVALID_OPERATION for miplevel values > 0) - * @param texture Name of a GL 2D, cubemap or rectangle texture object. The texture object must be a complete texture as per OpenGL rules on texture completeness. The texture format and dimensions defined by OpenGL for the specified miplevel of the texture will be used to create the 2D image object. Only GL texture objects with an internal format that maps to appropriate image channel order and data type specified in tables 5.4 and 5.5 may be used to create a 2D image object. - * @return valid OpenCL image object if the image object is created successfully - * @throws CLException.InvalidMipLevel if miplevel is less than the value of levelbase (for OpenGL implementations) or zero (for OpenGL ES implementations); or greater than the value of q (for both OpenGL and OpenGL ES). levelbase and q are defined for the texture in section 3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and section 3.7.10 of the OpenGL ES 2.0, or if miplevel is greather than zero and the OpenGL implementation does not support creating from non-zero mipmap levels. - * @throws CLException.InvalidGLObject if texture is not a GL texture object whose type matches texture_target, if the specified miplevel of texture is not defined, or if the width or height of the specified miplevel is zero. - * @throws CLException.InvalidImageFormatDescriptor if the OpenGL texture internal format does not map to a supported OpenCL image format. - */ - @SuppressWarnings("deprecation") - public CLImage2D createImage2DFromGLTexture2D(CLMem.Usage usage, GLTextureTarget textureTarget, int texture, int mipLevel) { - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLTexture2D(getEntity(), usage.getIntFlags(), (int)textureTarget.value(), mipLevel, texture, pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - return markAsGL(new CLImage2D(this, mem, null)); - } - - private static final int - GL_TEXTURE_2D = 0x0DE1, - GL_TEXTURE_3D = 0x806F, - GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515, - GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516, - GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517, - GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518, - GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519, - GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A, - GL_TEXTURE_RECTANGLE = 0x84F5; - - public CLPlatform getPlatform() { - return platform; - } - - - public enum GLTextureTarget implements ValuedEnum { - - Texture2D(GL_TEXTURE_2D), - //Texture3D(GL_TEXTURE_3D), - CubeMapPositiveX(GL_TEXTURE_CUBE_MAP_POSITIVE_X), - CubeMapNegativeX(GL_TEXTURE_CUBE_MAP_NEGATIVE_X), - CubeMapPositiveY(GL_TEXTURE_CUBE_MAP_POSITIVE_Y), - CubeMapNegativeY(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y), - CubeMapPositiveZ(GL_TEXTURE_CUBE_MAP_POSITIVE_Z), - CubeMapNegativeZ(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z), - Rectangle(GL_TEXTURE_RECTANGLE); - - GLTextureTarget(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static GLTextureTarget getEnum(int v) { return EnumValues.getEnum(v, GLTextureTarget.class); } - } - - /** - * Creates an OpenCL 3D image object from an OpenGL 3D texture object
    - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * @param usage - * @param mipLevel Mipmap level to be used (Implementations may return CL_INVALID_OPERATION for miplevel values > 0) - * @param texture Name of a GL 3D texture object. The texture object must be a complete texture as per OpenGL rules on texture completeness. The texture format and dimensions defined by OpenGL for the specified miplevel of the texture will be used to create the 3D image object. Only GL texture objects with an internal format that maps to appropriate image channel order and data type specified in tables 5.4 and 5.5 can be used to create the 3D image object. - * @return valid OpenCL image object if the image object is created successfully - * @throws CLException.InvalidMipLevel if miplevel is less than the value of levelbase (for OpenGL implementations) or zero (for OpenGL ES implementations); or greater than the value of q (for both OpenGL and OpenGL ES). levelbase and q are defined for the texture in section 3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and section 3.7.10 of the OpenGL ES 2.0, or if miplevel is greather than zero and the OpenGL implementation does not support creating from non-zero mipmap levels. - * @throws CLException.InvalidGLObject if texture is not a GL texture object whose type matches texture_target, if the specified miplevel of texture is not defined, or if the width or height of the specified miplevel is zero. - * @throws CLException.InvalidImageFormatDescriptor if the OpenGL texture internal format does not map to a supported OpenCL image format. - */ - @SuppressWarnings("deprecation") - public CLImage3D createImage3DFromGLTexture3D(CLMem.Usage usage, int texture, int mipLevel) { - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLTexture3D(getEntity(), usage.getIntFlags(), GL_TEXTURE_3D, mipLevel, texture, pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - return markAsGL(new CLImage3D(this, mem, null)); - } - - /** - * Create an ARGB input 2D image with the content provided - * @param allowUnoptimizingDirectRead Some images expose their internal data for direct read, leading to performance increase during the creation of the OpenCL image. However, direct access to the image data disables some Java2D optimizations for this image, leading to degraded performance in subsequent uses with AWT/Swing. - */ - public CLImage2D createImage2D(CLMem.Usage usage, Image image, boolean allowUnoptimizingDirectRead) { - int width = image.getWidth(null), height = image.getHeight(null); - ImageInfo info = ImageIOUtils.getImageInfo(image); - return createImage2D( - usage, - info.clImageFormat, - width, height, - 0, - info.dataGetter.getData(image, null, true, allowUnoptimizingDirectRead, getByteOrder()), - true); - } - - @SuppressWarnings("deprecation") - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height, long rowPitch, Buffer buffer, boolean copy) { - long memFlags = usage.getIntFlags(); - if (buffer != null) { - memFlags |= copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR; - } - - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateImage2D( - getEntity(), - memFlags, - format.to_cl_image_format(), - toNS(width), - toNS(height), - toNS(rowPitch), - buffer == null ? null : Native.getDirectBufferPointer(buffer), - pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - return new CLImage2D(this, mem, format); - } - - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height, long rowPitch) { - return createImage2D(usage, format, width, height, rowPitch, null, false); - } - - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height) { - return createImage2D(usage, format, width, height, 0, null, false); - } - - @SuppressWarnings("deprecation") - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth, long rowPitch, long slicePitch, Buffer buffer, boolean copy) { - long memFlags = usage.getIntFlags(); - if (buffer != null) { - memFlags |= copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR; - } - - IntByReference pErr = new IntByReference(); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateImage3D( - getEntity(), - memFlags, - format.to_cl_image_format(), - toNS(width), - toNS(height), - toNS(depth), - toNS(rowPitch), - toNS(slicePitch), - buffer == null ? null : Native.getDirectBufferPointer(buffer), - pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - - return new CLImage3D(this, mem, format); - } - - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth, long rowPitch, long slicePitch) { - return createImage3D(usage, format, width, height, depth, rowPitch, slicePitch, null, false); - } - - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth) { - return createImage3D(usage, format, width, height, depth, 0, 0, null, false); - } - -#foreach ($prim in $primitivesNoBool) - -#docCreateBufferCopy("CLBuffer<${prim.WrapperName}>", " (of concrete type {@link com.nativelibs4java.opencl.CL${prim.BufferName}}) ") - public > B create${prim.BufferName}(CLMem.Usage kind, #if ($prim.Name == "byte") Buffer #else ${prim.BufferName} #end data, boolean copy) { - if (!data.isDirect()) { - if (!copy) - throw new IllegalArgumentException("Cannot create an OpenCL buffer object out of a non-direct NIO buffer without copy."); - if (kind == CLMem.Usage.Output) - throw new IllegalArgumentException("Output NIO buffers must be direct."); - data = NIOUtils.directCopy(data, getKernelsDefaultByteOrder()); - } - CLBuffer ret = createBuffer(data, -1, kind.getIntFlags() | (copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR), copy); -#if ($prim.Name == "byte") - return (B)ret; -#else - return (B)ret.asCL${prim.BufferName}(); -#end - } - -#docCreateBufferPrim("CLBuffer<${prim.WrapperName}>", $prim) - public > B create${prim.BufferName}(CLMem.Usage kind, long elementCount) { -#if ($prim.Name == "byte") - return (B)createBuffer(null, elementCount, kind.getIntFlags(), false); -#else - return (B)createByteBuffer(kind, elementCount * ${prim.Size}).asCL${prim.BufferName}(); -#end - } - -#end - - /** - * Create an OpenCL buffer with the provided initial values, in copy mode (see CL_MEM_COPY_HOST_PTR). - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - * @param data Buffer that contains the initial values. Indirect buffers should be avoided for performance reasons. - */ - public CLBuffer createBuffer(CLMem.Usage kind, Buffer data) { - return createBuffer(kind, data, true); - } - -#docCreateBufferCopy("CLBuffer<N>", "") - @SuppressWarnings("unchecked") - public CLBuffer createBuffer(CLMem.Usage kind, Buffer data, boolean copy) { - Class bufferClass = data.getClass(); - #foreach ($prim in $primitivesNoBool) - if (${prim.BufferName}.class.isAssignableFrom(bufferClass)) - return (CLBuffer)create${prim.BufferName}(kind, (${prim.BufferName})data, copy); - #end - - throw new UnsupportedOperationException("Cannot create OpenCL buffers of Java type " + bufferClass.getName()); - } - -#docCreateBuffer("CLBuffer<N>", "T", "* @param elementClass Primitive type of the buffer. For instance a buffer of 'int' values can be created with elementClass being Integer.class or int.class indifferently.", "") - @SuppressWarnings("unchecked") - public CLBuffer createBuffer(CLMem.Usage kind, Class elementClass, long elementCount) { - #foreach ($prim in $primitivesNoBool) - if (${prim.WrapperName}.class.isAssignableFrom(elementClass)) - return (CLBuffer)create${prim.BufferName}(kind, elementCount); - #end - - throw new UnsupportedOperationException("Cannot create OpenCL buffers of Java primitive type " + elementClass.getName()); - } - - @SuppressWarnings("deprecation") - private CLByteBuffer createBuffer(final Buffer buffer, long byteCount, final int CLBufferFlags, final boolean retainBufferReference) { - if (buffer != null) { - byteCount = getSizeInBytes(buffer); - } else if (retainBufferReference) { - throw new IllegalArgumentException("Cannot retain reference to null pointer !"); - } - - if (byteCount <= 0) { - throw new IllegalArgumentException("Buffer size must be greater than zero (asked for size " + byteCount + ")"); - } - - if (buffer != null) { - ByteOrder contextOrder = getByteOrder(); - ByteOrder dataOrder = NIOUtils.getByteOrder(buffer); - if (contextOrder != null && !dataOrder.equals(contextOrder)) - throw new IllegalArgumentException("Byte order of this context is " + contextOrder + ", but was given pointer to data with order " + dataOrder + ". Please create a buffer with correct byte order (XyzBuffer.order(CLContext.getKernelsDefaultByteOrder()))."); - } - - IntByReference pErr = new IntByReference(); - //IntBuffer errBuff = IntBuffer.wrap(new int[1]); - cl_mem mem; - int previousAttempts = 0; - do { - mem = CL.clCreateBuffer( - getEntity(), - CLBufferFlags, - toNS(byteCount), - buffer == null ? null : Native.getDirectBufferPointer(buffer), - pErr); - } while (failedForLackOfMemory(pErr.getValue(), previousAttempts++)); - - return new CLByteBuffer(this, byteCount, mem, buffer); - } - - /** - * @deprecated Use {@link CLContext#getByteOrder()} - */ - @Deprecated - public ByteOrder getKernelsDefaultByteOrder() { - return getByteOrder(); - } - - /** - * Get the endianness common to all devices of this context, or null if the devices have mismatching endiannesses. - */ - public ByteOrder getByteOrder() { - ByteOrder order = null; - for (CLDevice device : getDevices()) { - ByteOrder devOrder = device.getByteOrder(); - if (order != null && devOrder != order) - return null; - order = devOrder; - } - return order; - } - - private volatile int addressBits = -2; - - /** - * Return the number of bits used to represent a pointer on all of the context's devices, or -1 if not all devices use the same number of bits.
    - * Size of size_t type in OpenCL kernels can be obtained with getAddressBits() / 8. - * @return -1 if the address bits of the context's devices do not match, common address bits otherwise - */ - public int getAddressBits() { - if (addressBits == -2) { - synchronized (this) { - if (addressBits == -2) { - for (CLDevice device : getDevices()) { - int bits = device.getAddressBits(); - if (addressBits != -2 && bits != addressBits) { - addressBits = -1; - break; - } - addressBits = bits; - } - } - } - } - return addressBits; - } - - /** - * Whether all the devices in this context support any double-precision numbers (see {@link CLDevice#isDoubleSupported()}). - */ - public boolean isDoubleSupported() { - for (CLDevice device : getDevices()) - if (!device.isDoubleSupported()) - return false; - return true; - } - /** - * Whether all the devices in this context support half-precision numbers (see {@link CLDevice#isHalfSupported()}). - */ - public boolean isHalfSupported() { - for (CLDevice device : getDevices()) - if (!device.isHalfSupported()) - return false; - return true; - } - public boolean isByteAddressableStoreSupported() { - for (CLDevice device : getDevices()) - if (!device.isByteAddressableStoreSupported()) - return false; - return true; - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java deleted file mode 100644 index 328292d01..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import org.junit.Before; -import org.junit.BeforeClass; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author ochafik - */ -public abstract class AbstractCommon { - - CLPlatform platform; - CLContext context; - CLQueue queue; - CLDevice device; - CLImageFormat[] formatsRead2D, formatsRead3D, formatsWrite2D, formatsWrite3D, formatsReadWrite2D, formatsReadWrite3D; - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - static String chosenPlatformName = System.getProperty("javacl.test.platform", System.getenv("JAVACL_TEST_PLATFORM")); - static boolean listedPlatforms; - - @Before - public void setUp() { - CLPlatform chosenPlatform = null; - for (CLPlatform platform : JavaCL.listPlatforms()) { - if (!listedPlatforms) - System.out.println("Platform Detected : \"" + platform.getName() + "\""); - if (chosenPlatformName != null && platform.getName().contains(chosenPlatformName)) { - chosenPlatform = platform; - } - } - listedPlatforms = true; - if (chosenPlatform != null) { - platform = chosenPlatform; - context = platform.createContext(null, platform.getBestDevice()); - } else { - context = JavaCL.createBestContext(); - platform = context.getPlatform(); - } - queue = context.createDefaultQueue(); - device = context.getDevices()[0]; - formatsRead2D = context.getSupportedImageFormats(CLMem.Flags.ReadOnly, CLMem.ObjectType.Image2D); - formatsWrite2D = context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image2D); - formatsRead3D = context.getSupportedImageFormats(CLMem.Flags.ReadOnly, CLMem.ObjectType.Image3D); - formatsWrite3D = context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image3D); - formatsReadWrite2D = context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image2D); - formatsReadWrite3D = context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image3D); - } - - -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java deleted file mode 100644 index fec9d4a35..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.util.NIOUtils.directBuffer; -import java.util.Map; -import static org.junit.Assert.assertEquals; - -import java.nio.IntBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author Kazo Csaba - */ -@SuppressWarnings("unchecked") -public class BinaryKernelTest extends AbstractCommon { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Test - public void simpleTest() throws CLBuildException { - if (!context.getCacheBinaries()) { - System.out.println("Skipping binaries caching test"); - return; - } - CLProgram program = context.createProgram( - "__kernel void copy(__global int* a, __global int* b) {\n" + - " int i = get_global_id(0);\n" + - " b[i]=a[i];\n" + - "} "); - program.build(); - Map binaries = program.getBinaries(); - program.release(); - - CLProgram binaryProgram = context.createProgram(binaries, null); - CLKernel kernel = binaryProgram.createKernel("copy"); - - CLIntBuffer a=context.createIntBuffer(CLMem.Usage.Input, 4); - CLIntBuffer b=context.createIntBuffer(CLMem.Usage.Output, 4); - - IntBuffer source = directBuffer(4, context.getByteOrder(), IntBuffer.class); - for (int i=0; i<4; i++) - source.put(i, 3*i+10); - - a.write(queue, source, true); - - kernel.setArgs(a, b); - kernel.enqueueNDRange(queue, new int[]{4}).waitFor(); - - IntBuffer target = b.read(queue); - - assertEquals(target.capacity(), source.capacity()); - for (int i=0; i<4; i++) - assertEquals(source.get(i), target.get(i)); - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java deleted file mode 100644 index 32cf87673..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.nativelibs4java.opencl; - -import java.nio.LongBuffer; -import java.util.Random; - -import junit.framework.TestCase; - -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; - -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLDevice; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLLongBuffer; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; - -public class BufferReadTest extends TestCase { - - private CLProgram program; - private CLContext context; - private CLQueue q; - private Random r; - @Override - protected void setUp() throws Exception { - super.setUp(); - r = new Random(2011); - initializeCLStuff(); - compileProgram(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if(context != null) - context.release(); - if(q != null) - q.release(); - if(program != null) - program.release(); - context = null; - q = null; - program = null; - } - - public void testBufferRead() throws Exception { - int size = 50; - CLKernel kernel = program.createKernel("testLongRead"); - CLLongBuffer clInBuff = context.createLongBuffer(CLMem.Usage.Input, size); - CLLongBuffer clOutBuff = context.createLongBuffer(CLMem.Usage.Output, size); - long[] longArray = new long[size]; - for(int i = 0; i < longArray.length ; i ++) { - longArray[i] = i; - } - clInBuff.write(q, LongBuffer.wrap(longArray), true); - kernel.setArg(0, clInBuff); - kernel.setArg(1, clOutBuff); - CLEvent completion = kernel.enqueueNDRange(q, new int[] {size}); - completion.waitFor(); - - - /////////////////////////////////////////////////// - //we tried to make a buffer before the clOutBuff.read() so that it isn't creating new ones - //this way when we're on a loop we won't have to waste memory creating more buffers - //we thought that the read would simply read everything into the LongBuffer, - //and since the LongBuffer is wrapped around the outPrim, it would update the values as soon as it is read. - long[] outPrim = new long[size]; - if (false) { - LongBuffer outBuffJava = LongBuffer.wrap(outPrim); - clOutBuff.read(q, 0, size,outBuffJava, true); - } else { - LongBuffer outBuffJava = NIOUtils.directLongs(size, context.getByteOrder()); - clOutBuff.read(q, 0, size,outBuffJava, true); - //LongBuffer outBuffJava = clOutBuff.read(q, 0, size); - outBuffJava.get(outPrim); - } - System.out.println("test1:\nThese should read 1, 2, 3, 4, 5"); - for(int i = 0 ; i < 5 ; i ++) { - System.out.print(outPrim[i] + ", "); - - } - System.out.println(); - - - //////////////////////////////////////////////////// - //this is the way that we know works, but it creates a new LongBuffer every read, and we also have to do a - //outBuffJava2.get(), which forces us to separate the outPrim2 from the java LongBuffer, and require us to create a new array. - LongBuffer outBuffJava2 = clOutBuff.read(q); - long[] outPrim2 = new long[size]; - outBuffJava2.get(outPrim2, 0, size); - System.out.println("test2:\nThese should read 1, 2, 3, 4, 5"); - for(int i = 0 ; i < 5 ; i ++) { - System.out.print(outPrim2[i] + ", "); - - } - System.out.println(); - - } - - private void initializeCLStuff() { - initializeCLContextAndQueueOrNothing(0, 0); - } - private void compileProgram() throws Exception{ - String sources = IOUtils.readText(BufferReadTest.class.getResourceAsStream("BufferReadTest.c")); - program = context.createProgram(sources).build(); - - } - private synchronized void initializeCLContextAndQueueOrNothing(int platformNumber, int deviceNumber) { - //should check for index out of bounds later. need to figure out how I should throw the errors - if(context==null || q == null) { - CLDevice device = JavaCL.listPlatforms()[platformNumber].listAllDevices(false)[deviceNumber]; - System.out.println("Device = " + device); - context = (JavaCL.createContext(null, device)); - q = (context.createDefaultQueue()); - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java deleted file mode 100644 index 8894aae27..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.util.NIOUtils.directBuffer; -import static com.nativelibs4java.util.NIOUtils.getPrimitiveClass; -import static com.nativelibs4java.util.NIOUtils.getBufferClass; -import static com.nativelibs4java.util.NIOUtils.get; -import static com.nativelibs4java.util.NIOUtils.put; -import static org.junit.Assert.assertEquals; - -import java.nio.*; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.NIOUtils; -import com.sun.jna.Native; -import java.nio.ByteOrder; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unchecked") -public class BufferTest extends AbstractCommon { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Test - public void testReadWrite() { - for (Class primClass : primClasses) - testReadWrite(primClass, 10, 3, 3); - } - public void testReadWrite(Class primClass, int n, int zeroOffset, int zeroLength) { - Class bufferClass = getBufferClass(primClass); - CLBuffer buf = context.createBuffer(CLMem.Usage.InputOutput, primClass, n); - assertEquals(n, buf.getElementCount()); - - Buffer initial = directBuffer(n, context.getByteOrder(), bufferClass); - Buffer zeroes = directBuffer(n, context.getByteOrder(), bufferClass); - for (int i = 0; i < n; i++) { - put(initial, i, i + 1); - put(zeroes, i, 0); - } - - buf.write(queue, initial, true); - - Buffer retrieved = buf.read(queue); - assertEquals(buf.getElementCount(), retrieved.capacity()); - - retrieved.rewind(); - initial.rewind(); - - for (int i = 0; i < n; i++) - assertEquals(bufferClass.getName(), get(initial, i), get(retrieved, i)); - - buf.write(queue, zeroOffset, zeroLength, zeroes, true); - - for (boolean direct : new boolean[] { true, false }) { - String type = direct ? "read to direct buffer" : "read to indirect buffer"; - Buffer readBuffer; - if (direct) - readBuffer = retrieved; - else - readBuffer = NIOUtils.indirectBuffer(n, bufferClass); - buf.read(queue, readBuffer, true); - - for (int i = 0; i < n; i++) { - if (i >= zeroOffset && i < (zeroOffset + zeroLength)) - assertEquals(bufferClass.getName(), get(zeroes, i), get(readBuffer, i)); - else - assertEquals(bufferClass.getName(), get(initial, i), get(readBuffer, i)); - } - } - } - - Class[] bufferClasses = new Class[] { - IntBuffer.class, - LongBuffer.class, - ShortBuffer.class, - ByteBuffer.class, - DoubleBuffer.class, - CharBuffer.class, - FloatBuffer.class - }; - Class[] primClasses = new Class[] { - Integer.class, - Long.class, - Short.class, - Byte.class, - Double.class, - Character.class, - Float.class - }; - @Test - public void testMap() { - for (Class bufferClass : bufferClasses) - testMap(bufferClass); - } - public void testMap(Class bufferClass) { - int size = 10; - ByteBuffer data = NIOUtils.directBytes(size, context.getByteOrder()); - CLBuffer buf = context.createBuffer(CLMem.Usage.Input, data, false); - ByteBuffer mapped = buf.map(queue, CLMem.MapFlags.Read); - - assertEquals(Native.getDirectBufferPointer(data), Native.getDirectBufferPointer(mapped)); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java deleted file mode 100644 index 35d97fdf3..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.JavaCL.listPlatforms; - -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -/** - * @author ochafik - */ -public class CLTestUtils { - public enum Target { - CPU, GPU, CPU_GPU; - - } - public static interface Action1 { - void call(X x); - } - public static interface Action2 { - void call(X x, Y y); - } - public static interface Action3 { - void call(X x, Y y, Z z); - } - /// Calculate the average relative error of operations between two result buffers - public static double avgError(FloatBuffer a, FloatBuffer b, int dataSize) { - double tot = 0; - for (int i = 0; i < dataSize; i++) { - float va = a.get(i), vb = b.get(i); - float d = va - vb; - if (Float.isNaN(d)) - d = d + 0; - if (d < 0) - d = -d; - float m = (va + vb) / 2; - if (m == 0) - continue; - double r = d / (double)m; - tot += r; - } - return tot / dataSize; - } - public static double avgError(DoubleBuffer a, DoubleBuffer b, int dataSize) { - double tot = 0; - for (int i = 0; i < dataSize; i++) { - double va = a.get(i), vb = b.get(i); - double d = va - vb; - if (Double.isNaN(d)) - d = d + 0; - if (d < 0) - d = -d; - double m = (va + vb) / 2; - if (m == 0) - continue; - double r = d / (double)m; - tot += r; - } - return tot / dataSize; - } - - public static void fillBuffersWithSomeData(FloatBuffer a, FloatBuffer b) { - int s = a.capacity(); - for (int i = 0; i < s; i++) { - a.put(i, i); - b.put(i, i); - } - } - public static void fillBuffersWithSomeData(DoubleBuffer a, DoubleBuffer b) { - int s = a.capacity(); - for (int i = 0; i < s; i++) { - a.put(i, i); - b.put(i, i); - } - } - - public static CLDevice[] getDevices(Target target) { - CLPlatform platform = listPlatforms()[0]; - switch (target) { - case CPU: - return platform.listCPUDevices(true); - case GPU: - return platform.listGPUDevices(true); - case CPU_GPU: - return platform.listAllDevices(true); - default: - throw new IllegalArgumentException("Unknown target : " + target); - } - } - public static class ExecResult { - public B buffer; - public double unitTimeNano; - public ExecResult(B buffer, double unitTimeNano) { - this.buffer = buffer; - this.unitTimeNano = unitTimeNano; - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java deleted file mode 100644 index 1ee5cb1ec..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import com.nativelibs4java.opencl.CLImageFormat.ChannelDataType; -import com.nativelibs4java.opencl.CLImageFormat.ChannelOrder; -import static org.junit.Assert.*; - -import java.awt.image.BufferedImage; -import java.nio.IntBuffer; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.ImageUtils; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; -import java.util.Arrays; -import java.util.List; - -/** - * - * @author ochafik - */ -public class ImageTest extends AbstractCommon { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - public boolean supportsImages() { - for (CLDevice device : context.getDevices()) - if (device.hasImageSupport()) - return true; - return false; - } - @Test - public void simpleImage2d() { - if (!supportsImages()) - return; - long width = 100, height = 200; - CLImageFormat format = formatsRead2D[0]; - CLImage2D im = context.createImage2D(CLMem.Usage.InputOutput, format, width, height); - assertEquals(width, im.getWidth()); - assertEquals(height, im.getHeight()); - assertEquals(format, im.getFormat()); - } - - int someARGBPixelValue = 0xff123456; - int someARGBGrayPixelValue = 0xffababab; - int someShortGrayPixelValue = 0xf1f1; - - - @Test - public void testCreateARGBFromImage() { - int width = 2, height = 2; - BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - im.setRGB(1, 0, someARGBPixelValue); - - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, im, true); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - assertEquals(CLImageFormat.INT_ARGB_FORMAT, clim.getFormat()); - assertSameImage(im, clim.read(queue)); - } - - static void assertSameImage(BufferedImage expected, BufferedImage real) { - int width = expected.getWidth(), height = expected.getHeight(); - assertEquals("Bad width", width, real.getWidth()); - assertEquals("Bad height", height, real.getHeight()); - - for (int x = 0; x < width; x++) - for (int y = 0; y < height; y++) - assertEquals("Different value for pixel x = " + x + ", y = " + y, Integer.toHexString(expected.getRGB(x, y)), Integer.toHexString(real.getRGB(x, y))); - } - - @Test - public void testARGBReadWrite() { - int width = 2, height = 2; - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, CLImageFormat.INT_ARGB_FORMAT, width, height); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - - BufferedImage im = clim.read(queue); - assertEquals(BufferedImage.TYPE_INT_ARGB, im.getType()); - int x = 0, y = 1; - im.setRGB(x, y, someARGBPixelValue); - clim.write(queue, im, false, true); - - assertSameImage(im, clim.read(queue)); - } - - @Test - public void testARGBShortGrayReadWrite() { - int width = 2, height = 2; - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, new CLImageFormat(ChannelOrder.RGBA, ChannelDataType.UnsignedInt16), width, height); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - - BufferedImage im = clim.read(queue); - assertEquals(BufferedImage.TYPE_USHORT_GRAY, im.getType()); - int x = 0, y = 1; - im.setRGB(x, y, someARGBGrayPixelValue); - clim.write(queue, im, false, true); - - assertSameImage(im, clim.read(queue)); - } - - - - @Test - public void testMaxWidth() { - if (!supportsImages()) - return; - context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], device.getImage2DMaxWidth() - 1, 1); - //long d = device.getImage3DMaxDepth(); - //TODO FAILING !!! context.createInput3D(formatsRead3D[0], device.getImage3DMaxWidth() - 1, 1, 1); - } - @Test - public void testMaxHeight() { - if (!supportsImages()) - return; - context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], 1, device.getImage2DMaxHeight() - 1); - //long d = device.getImage3DMaxDepth(); - //TODO FAILING !!! context.createInput3D(formatsRead3D[0], 1, device.getImage3DMaxHeight(), 1); - } - @Test - public void testMaxDepth() { - if (!supportsImages()) - return; - context.createImage3D(CLMem.Usage.Input, formatsRead3D[0], 1, 1, device.getImage3DMaxDepth() - 1); - } - - /*@Test(expected=CLException.InvalidImageSize.class) - public void testInvalidImageSize() { - CLImage2D im = context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], device.getImage2DMaxWidth() + 10, 1); - }*/ - public void simpleImage3d() { - long width = 100, height = 200, depth = 50;//device.getImage3DMaxDepth(); - CLImageFormat format = formatsRead3D[0]; - CLImage3D im = context.createImage3D(CLMem.Usage.Input, format, width, height, depth); - assertEquals(width, im.getWidth()); - assertEquals(height, im.getHeight()); - assertEquals(depth, im.getDepth()); - assertEquals(format, im.getFormat()); - //im.blockingMap(queue, CLMem.MapFlags.Read); - } - - @Test - public void testRGBAImageSource() { - if (!supportsImages()) - return; - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - String src = "\n" + - "const sampler_t sampler = \n" + - " CLK_NORMALIZED_COORDS_FALSE | \n" + - " CLK_FILTER_NEAREST | \n" + - " CLK_ADDRESS_CLAMP_TO_EDGE; \n" + - " \n" + - "__kernel void test( \n" + - " __read_only image2d_t src_image, \n" + - " int width, \n" + - " int height, \n" + - " __global float* output) \n" + - "{ \n" + - " int x = get_global_id(0); \n" + - " int y = get_global_id(1); \n" + - " int2 coord = (int2)(x, y); \n" + - " float4 pixel = read_imagef(src_image, sampler, coord); \n" + - " int offset = (y * width + x) * 4; \n" + - " output[offset] = pixel.x; \n" + - " output[offset + 1] = pixel.y; \n" + - " output[offset + 2] = pixel.z; \n" + - " output[offset + 3] = pixel.w; \n" + - "} \n"; - - int width = 16, height = 16; - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - for (int x = 0; x < width; x++) - for (int y = 0; y < height; y++) { - int red = (x + y); - int green = 2 * (x + y); - int blue = (x + 2 * y); - int alpha = (2 * x + y); - - int p = (alpha << 24) | (blue << 16) | (green << 8) | red; - image.setRGB(x, y, p); - } - //image.setRGB(i, 0, i); - //image.setRGB(i, height - 1, i); - - CLProgram program = context.createProgram(src).build(); - //CLIntBuffer cloutput = context.createIntBuffer(CLMem.Usage.Output, width * height * 4); - CLFloatBuffer cloutput = context.createFloatBuffer(CLMem.Usage.Output, width * height * 4); - - CLKernel kernel = program.createKernel("test"); - - ChannelDataType channelDataType = CLImageFormat.INT_ARGB_FORMAT.getChannelDataType(); - for (ChannelOrder channelOrder : Arrays.asList(ChannelOrder.BGRA, ChannelOrder.RGBA)) { - CLImageFormat imageFormat = new CLImageFormat(channelOrder, channelDataType); - - //CLImage2D climage = context.createImage2D(CLMem.Usage.Input, image, true); - CLImage2D climage = context.createImage2D(CLMem.Usage.Input, imageFormat, width, height); - climage.write(queue, image); - kernel.setArgs( - climage, - width, height, - cloutput - ); - - kernel.enqueueNDRange(queue, new int[] {width, height}).waitFor(); - - //IntBuffer output = cloutput.read(queue); - //IntBuffer output = cloutput.readBytes(queue, 0, width * height * 4 * 4).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); - FloatBuffer output = cloutput.read(queue); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - int expected = image.getRGB(x, y); - float expectedRed = (x + y) / (float)0xff; - float expectedGreen = (2 * (x + y)) / (float)0xff; - float expectedBlue = (x + 2 * y) / (float)0xff; - float expectedAlpha = (2 * x + y) / (float)0xff; - - int offset = (y * width + x) * 4; - /*int r = output.get(offset); - int g = output.get(offset + 1); - int b = output.get(offset + 2); - int a = output.get(offset + 3); - System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + Integer.toHexString(expected) + ", r = " + Integer.toHexString(r) + ", g = " + Integer.toHexString(g) + ", b = " + Integer.toHexString(b) + ", a = " + Integer.toHexString(a)); - System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + (expectedChannel / (double)0xff) + ", r = " + (r / (double)Integer.MAX_VALUE) + ", g = " + (g / (double)Integer.MAX_VALUE) + ", b = " + (b / (double)Integer.MAX_VALUE) + ", a = " + (a / (double)Integer.MAX_VALUE));*/ - float px = output.get(offset); - float py = output.get(offset + 1); - float pz = output.get(offset + 2); - float pw = output.get(offset + 3); - - float red, green, blue, alpha; - switch (climage.getFormat().getChannelOrder()) { - case RGBA: - red = px; - green = py; - blue = pz; - alpha = pw; - break; - case ARGB: - alpha = px; - red = py; - green = pz; - blue = pw; - break; - case BGRA: - blue = px; - green = py; - red = pz; - alpha = pw; - break; - default: - assertTrue("Channel order not handled in this test : " + climage.getFormat(), false); - return; - } - float tolerance = 0.00001f; - String rgba = "(r = " + red + ", green = " + green + ", blue = " + blue + ", alpha = " + alpha + ")"; - String expectedRgba = "(r = " + expectedRed + ", green = " + expectedGreen + ", blue = " + expectedBlue + ", alpha = " + expectedAlpha + ")"; - assertEquals("[" + imageFormat + " format] bad red value for (x, y) = (" + x + ", " + y + ") : \n\t Got " + rgba + ", \n\tExpected " + expectedRgba, expectedRed, red, tolerance); - assertEquals("[" + imageFormat + " format] bad green value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedGreen, green, tolerance); - assertEquals("[" + imageFormat + " format] bad blue value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedBlue, blue, tolerance); - assertEquals("[" + imageFormat + " format] bad alpha value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedAlpha, alpha, tolerance); - //System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + (expectedChannel / (double)0xff) + ", r = " + (r) + ", g = " + (g) + ", b = " + (b) + ", a = " + (a)); - - } - } - } - - /* - for (int i = 0; i < width; i++) { - int value = output.get(i); - //System.out.println(value); - Assert.assertEquals(i, value); - } - * - */ - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - - @Test - public void testShortGrayImageSource() { - if (!supportsImages()) - return; - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - String src = "\n" + - "const sampler_t sampler = \n" + - " CLK_NORMALIZED_COORDS_FALSE | \n" + - " CLK_FILTER_NEAREST | \n" + - " CLK_ADDRESS_CLAMP_TO_EDGE; \n" + - " \n" + - "__kernel void test( \n" + - " __read_only image2d_t src_image, \n" + - " int width, \n" + - " int height, \n" + - " __global float* output) \n" + - "{ \n" + - " int x = get_global_id(0); \n" + - " int y = get_global_id(1); \n" + - " int2 coord = (int2)(x, y); \n" + - " float4 pixel = read_imagef(src_image, sampler, coord); \n" + - " int offset = (y * width + x) * 4; \n" + - " output[offset] = pixel.x; \n" + - " output[offset + 1] = pixel.y; \n" + - " output[offset + 2] = pixel.z; \n" + - " output[offset + 3] = pixel.w; \n" + - "} \n"; - - int width = 16, height = 16; - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY); - short[] data = new short[width * height]; - for (short x = 0; x < width; x++) - for (short y = 0; y < height; y++) { - short value = (short) (10 * (x + y)); - data[y * height + x] = value; - } - - image.getRaster().setDataElements(0, 0, width, height, data); - - CLProgram program = context.createProgram(src).build(); - CLFloatBuffer cloutput = context.createFloatBuffer(CLMem.Usage.Output, width * height * 4); - - CLKernel kernel = program.createKernel("test"); - - List formats = Arrays.asList(context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image2D)); - //System.out.println("Supported formats = " + formats); - ChannelDataType channelDataType = ChannelDataType.UNormInt16; - for (ChannelOrder channelOrder : Arrays.asList(ChannelOrder.RGBA)) { - CLImageFormat imageFormat = new CLImageFormat(channelOrder, channelDataType); - - //CLImage2D climage = context.createImage2D(CLMem.Usage.Input, image, true); - CLImage2D climage = context.createImage2D(CLMem.Usage.Input, imageFormat, width, height); - climage.write(queue, image); - kernel.setArgs( - climage, - width, height, - cloutput - ); - - kernel.enqueueNDRange(queue, new int[] {width, height}).waitFor(); - - //IntBuffer output = cloutput.read(queue); - //IntBuffer output = cloutput.readBytes(queue, 0, width * height * 4 * 4).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); - FloatBuffer output = cloutput.read(queue); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - float expected = 10f * (x + y) / (float)0xffff; - int offset = (y * width + x) * 4; - float px = output.get(offset); - float py = output.get(offset + 1); - float pz = output.get(offset + 2); - float pw = output.get(offset + 3); - - float tolerance = 0.00001f; - - assertEquals("[" + imageFormat + " format] different RGB components for gray image", px, py, tolerance); - assertEquals("[" + imageFormat + " format] different RGB components for gray image", px, pz, tolerance); - assertEquals("[" + imageFormat + " format] alpha not solid for gray image", 1f, pw, tolerance); - - float actual = px; - assertEquals("[" + imageFormat + " format] bad value for (x, y) = (" + x + ", " + y + ") : \n\t Got " + actual + ", \n\tExpected " + expected, expected, actual, tolerance); - } - } - } - - /* - for (int i = 0; i < width; i++) { - int value = output.get(i); - //System.out.println(value); - Assert.assertEquals(i, value); - } - * - */ - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java deleted file mode 100644 index 2b4e51f9d..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.test.MiscTestUtils.testGetters; -import static org.junit.Assert.assertFalse; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.BeforeClass; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author ochafik - */ -public class InfoGettersTest { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Before - public void gc() { - System.gc(); - try { - Thread.sleep(100); - } catch (InterruptedException ex) { - Logger.getLogger(InfoGettersTest.class.getName()).log(Level.SEVERE, null, ex); - } - System.gc(); - } - - CLProgram createProgram() { - CLProgram pg = createContext().createProgram("__kernel void f(__global int* a) {}"); - try { - pg.build(); - } catch (CLBuildException ex) { - assertFalse(ex.toString(), true); - } - return pg; - } - - CLPlatform createPlatform() { - return JavaCL.listPlatforms()[0]; - } - - CLDevice createDevice() { - return createPlatform().listAllDevices(true)[0]; - } - - CLContext ctx; - CLContext createContext() { - if (ctx == null) - ctx = createPlatform().createContext(null, createDevice()); - return ctx; - } - - CLKernel createKernel() { - try { - return createProgram().createKernels()[0]; - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to create kernel", ex); - } - } - - CLEvent createEvent() { - CLContext c = createContext(); - return c.createIntBuffer(CLMem.Usage.Input, 10).mapLater(c.createDefaultQueue(), CLMem.MapFlags.Read).getSecond(); - } - - CLSampler createSampler() { - return createContext().createSampler(true, CLSampler.AddressingMode.ClampToEdge, CLSampler.FilterMode.Linear); - } - - CLQueue createQueue() { - CLContext c = createContext(); - CLDevice d = c.getDevices()[0]; - return d.createQueue(c); - } - - @org.junit.Test - public void CLProgramGetters() { - testGetters(createProgram()); - } - - @org.junit.Test - public void CLKernelGetters() { - testGetters(createKernel()); - } - - @org.junit.Test - public void CLMemGetters() { - testGetters(createContext().createByteBuffer(CLMem.Usage.Input, 10)); - testGetters(createContext().createByteBuffer(CLMem.Usage.Output, 10)); - } - - @org.junit.Test - public void CLQueueGetters() { - testGetters(createQueue()); - } - - @org.junit.Test - public void CLDeviceGetters() { - testGetters(createDevice()); - } - - @org.junit.Test - public void CLPlatformGetters() { - testGetters(createPlatform()); - } - - @org.junit.Test - public void CLContextGetters() { - testGetters(createContext()); - } - - @org.junit.Test - public void CLEventGetters() { - testGetters(createEvent()); - } - - @org.junit.Test - public void CLSamplerGetters() { - testGetters(createSampler()); - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java deleted file mode 100644 index 101cf6cea..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.nio.ByteBuffer; -import java.nio.FloatBuffer; -import java.util.concurrent.Semaphore; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JFrame; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.CLMem.GLObjectInfo; -import com.nativelibs4java.util.NIOUtils; - -import javax.media.opengl.*; -import static javax.media.opengl.GL.*; -import static javax.media.opengl.GL2.*; - -import javax.media.opengl.awt.*; - -import com.jogamp.opengl.util.*; -import com.jogamp.common.nio.*; - - -import com.sun.jna.Memory; -import com.sun.jna.PointerUtils; -import java.nio.ByteOrder; - -public class JOGLTest { - - @BeforeClass - public static void initialise() { - //if (Platform.isWindows()) - System.setProperty("sun.java2d.noddraw","true"); - } - - public GLCanvas createGLCanvas(int width, int height) { - //GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - GLCanvas glCanvas = new GLCanvas();//new GLCapabilities(GLProfile.get(GLProfile.GL))); - glCanvas.setSize( width, height ); - glCanvas.setIgnoreRepaint( true ); - - return glCanvas; - } - - @Test - public void testBuffer() { - if (JavaCL.listGPUPoweredPlatforms().length == 0) { - System.out.println("#\n# Warning: There is no GPU-powered OpenCL platform available. Skipping test.\n#"); - return; - } - - try { - final Semaphore sem = new Semaphore(0); - JFrame f = new JFrame(); - GLCanvas canvas = createGLCanvas(100, 100); - f.getContentPane().add("Center", canvas); - final AssertionError[] err = new AssertionError[1]; - final Throwable[] exx = new Throwable[1]; - canvas.addGLEventListener(new GLEventListener() { - - @Override - public void init(GLAutoDrawable drawable) { - try { - CLContext context = JavaCL.createContextFromCurrentGL(); - assertNotNull(context); - if (context != null) { - //int glcontext = gl.glGet.getContext().CONTEXT_CURRENT; - CLQueue queue = context.createDefaultQueue(); - - System.err.println("Initializing..."); - int bufferSize = 1024; - FloatBuffer buffer; - int[] VBO = new int[1]; - int[] Texture = new int[1]; - GL2 gl = (GL2)drawable.getGL(); - buffer = NIOUtils.directFloats(bufferSize, ByteOrder.nativeOrder()); - gl.glGenBuffers(1, VBO, 0); // Get A Valid Name - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO[0]); // Bind The Buffer - gl.glBufferData(GL.GL_ARRAY_BUFFER, bufferSize * 4 /*SIZEOF_FLOAT*/, buffer, GL2.GL_DYNAMIC_READ); - - gl.glGenTextures(1, Texture, 0); - gl.glBindTexture(GL2.GL_TEXTURE_2D, Texture[0]); - //gl.glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - - int width = 2, height = 2, border = 0; - byte bZero = (byte)0, bMin1 = (byte)0xFF; - ByteBuffer texData = NIOUtils.directCopy(ByteBuffer.wrap(new byte[] { - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1 - }), queue.getDevice().getByteOrder()); - gl.glTexImage2D ( - GL2.GL_TEXTURE_2D, - 0, // no mipmap - 4, // 4 colours - width, - height, - border, - GL.GL_LUMINANCE, GL2.GL_UNSIGNED_BYTE, - //GL.GL_RGBA, GL2.GL_UNSIGNED_INT_8_8_8_8, - texData - ); - - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); - gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); - - gl.glFlush(); - - CLFloatBuffer clbuf = context.createBufferFromGLBuffer(CLMem.Usage.Input, VBO[0]).asCLFloatBuffer(); - CLImage2D climg = context.createImage2DFromGLTexture2D(CLMem.Usage.InputOutput, CLContext.GLTextureTarget.Texture2D, Texture[0], 0); - - assertNotNull(clbuf); - assertNotNull(climg); - - queue.enqueueAcquireGLObjects(new CLMem[] { clbuf }); - queue.enqueueAcquireGLObjects(new CLMem[] { climg }); - queue.finish(); - - { - GLObjectInfo info = clbuf.getGLObjectInfo(); - assertNotNull(info); - assertEquals(CLMem.GLObjectType.Buffer, info.getType()); - assertEquals(VBO[0], info.getName()); - } - { - GLObjectInfo info = climg.getGLObjectInfo(); - assertNotNull(info); - assertEquals(CLMem.GLObjectType.Texture2D, info.getType()); - assertEquals(Texture[0], info.getName()); - } - - float expected = 10; - try { - CLKernel kernel = context.createProgram("__kernel void fill(__global float* out) { out[get_global_id(0)] = (float)" + expected + ";}").build().createKernel("fill", clbuf); - kernel.enqueueNDRange(queue, new int[]{bufferSize}).waitFor(); - } catch (CLException.InvalidKernelArgs ex) { - assertTrue("GL-converted buffer was refused as kernel argument", false); - } catch (Throwable ex) { - assertTrue("Unexpected error : " + ex, false); - } - - //inbuf.put(0, expected); - //clbuf.write(queue, 0, 4 * bufferSize, inbuf, true).waitFor(); - - queue.enqueueReleaseGLObjects(new CLMem[] { clbuf }); - queue.finish(); - - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO[0]); // Bind The Buffer - ByteBuffer mb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2.GL_READ_ONLY); - if (mb != null) { - buffer = mb.asFloatBuffer(); - float val = buffer.get(0); - assertEquals(expected, val, 0); - } - } - - } catch (AssertionError ex) { - ex.printStackTrace(); - err[0] = ex; - } catch (Throwable ex) { - ex.printStackTrace(); - exx[0] = ex; - } finally { - System.out.println("Releasing..."); - sem.release(); - } - } - - public void dispose(GLAutoDrawable glad) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @SuppressWarnings("unused") - public void displayChanged(GLAutoDrawable glad, boolean bln, boolean bln1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void display(GLAutoDrawable drawable) { - } - - @Override - public void reshape(GLAutoDrawable drawable, int i, int i1, int i2, int i3) { - } - }); - f.pack(); - f.setVisible(true); - - FPSAnimator animator = new FPSAnimator(canvas, 60); - //animator.setRunAsFastAsPossible(true); - animator.start(); - - System.out.println("Acquiring..."); - sem.acquire(); - System.out.println("Acquired !"); - - f.setVisible(false); - if (err[0] != null) { - throw err[0]; - } - if (exx[0] != null) { - throw exx[0]; - } - } catch (AssertionError ex) { - throw ex; - } catch (Throwable ex) { - Logger.getLogger(JOGLTest.class.getName()).log(Level.SEVERE, null, ex); - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java deleted file mode 100644 index 788b45c56..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java +++ /dev/null @@ -1,98 +0,0 @@ - -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.JavaCL.createBestContext; -import static com.nativelibs4java.util.NIOUtils.directFloats; -import static org.junit.Assert.assertEquals; - -import java.nio.FloatBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.NIOUtils; - -public class OpenCL4JavaBasicTest { - - public static final double ABSOLUTE_FLOAT_ERROR_TOLERANCE = 1e-4; - public static final double RELATIVE_FLOAT_ERROR_TOLERANCE = 1e-8; - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Test - public void simpleTest() { - try { - CLContext context = createBestContext(); - - int dataSize = 10000; - String src = "\n" + - "__kernel void aSinB( \n" + - " __global const float* a, \n" + - " __global const float* b, \n" + - " __global float* output) \n" + - "{ \n" + - " int i = get_global_id(0); \n" + - " output[i] = a[i] * sin(b[i]) + 1; \n" + - "} \n"; - - CLProgram program = context.createProgram(src).build(); - CLKernel kernel = program.createKernel("aSinB"); - CLQueue queue = context.createDefaultQueue(); - - /// Create direct NIO buffers and fill them with data in the correct byte order - FloatBuffer a = NIOUtils.directFloats(dataSize, context.getKernelsDefaultByteOrder()); - FloatBuffer b = NIOUtils.directFloats(dataSize, context.getKernelsDefaultByteOrder()); - for (int i = 0; i < dataSize; i++) { - a.put(i, i); - b.put(i, i); - } - - // Allocate OpenCL-hosted memory for inputs and output, - // with inputs initialized as copies of the NIO buffers - CLFloatBuffer memIn1 = context.createFloatBuffer(CLMem.Usage.Input, a, true); // 'true' : copy provided data - CLFloatBuffer memIn2 = context.createFloatBuffer(CLMem.Usage.Input, b, true); - CLFloatBuffer memOut = context.createFloatBuffer(CLMem.Usage.Output, dataSize); - - // Bind these memory objects to the arguments of the kernel - kernel.setArgs(memIn1, memIn2, memOut); - - // Ask for execution of the kernel with global size = dataSize - // and workgroup size = 1 - kernel.enqueueNDRange(queue, new int[]{dataSize}); - - // Wait for all operations to be performed - queue.finish(); - - // Copy the OpenCL-hosted array back to RAM - FloatBuffer output = memOut.read(queue); - - // Compute absolute and relative average errors wrt Java implem - double totalAbsoluteError = 0, totalRelativeError = 0; - for (int i = 0; i < dataSize; i++) { - float expected = i * (float) Math.sin(i) + 1; - float result = output.get(i); - - double d = result - expected; - if (expected != 0) { - totalRelativeError += d / expected; - } - - totalAbsoluteError += d < 0 ? -d : d; - } - double avgAbsoluteError = totalAbsoluteError / dataSize; - double avgRelativeError = totalRelativeError / dataSize; - System.out.println("Average absolute error = " + avgAbsoluteError); - System.out.println("Average relative error = " + avgRelativeError); - - assertEquals("Bad relative error", 0, avgRelativeError, RELATIVE_FLOAT_ERROR_TOLERANCE); - assertEquals("Bad absolute error", 0, avgAbsoluteError, ABSOLUTE_FLOAT_ERROR_TOLERANCE); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java deleted file mode 100644 index 20688c268..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java +++ /dev/null @@ -1,317 +0,0 @@ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLTestUtils.avgError; -import static com.nativelibs4java.opencl.CLTestUtils.fillBuffersWithSomeData; -import static com.nativelibs4java.test.BenchmarkUtils.gc; -import static com.nativelibs4java.util.NIOUtils.directBytes; - -import java.nio.ByteBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.util.Arrays; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.CLTestUtils.Action2; -import com.nativelibs4java.opencl.CLTestUtils.ExecResult; -import com.nativelibs4java.test.MiscTestUtils; - -//import com.nativelibs4java.scalacl.*; -/// @see http://ati.amd.com/technology/streamcomputing/intro_opencl.html#simple -public class OpenCL4JavaBenchmarkTest { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - static final boolean warmup = true; - - static ExecResult testJava_float_aSinB(int loops, int dataSize) throws CLBuildException { - - FloatBuffer aBuffer = FloatBuffer.allocate(dataSize); - FloatBuffer bBuffer = FloatBuffer.allocate(dataSize); - FloatBuffer outputBuffer = FloatBuffer.allocate(dataSize); - float[] a = aBuffer.array(), b = bBuffer.array(), output = outputBuffer.array(); - - if (warmup) { - System.out.print("Warming up Java operations..."); - for (int i = 0; i < 3000; i++) { - java_aSinB(a, b, output, 100); - } - System.out.println(); - } - - fillBuffersWithSomeData(aBuffer, bBuffer); - gc(); - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - java_aSinB(a, b, output, dataSize); - } - long time = System.nanoTime() - start; - System.out.println("Java operations : " + time + "ns"); - return new ExecResult(outputBuffer, time / (loops * (double) dataSize)); - } - - static ExecResult testJava_double_aSinB(int loops, int dataSize) throws CLBuildException { - - DoubleBuffer aBuffer = DoubleBuffer.allocate(dataSize); - DoubleBuffer bBuffer = DoubleBuffer.allocate(dataSize); - DoubleBuffer outputBuffer = DoubleBuffer.allocate(dataSize); - double[] a = aBuffer.array(), b = bBuffer.array(), output = outputBuffer.array(); - - if (warmup) { - System.out.print("Warming up Java operations..."); - for (int i = 0; i < 3000; i++) { - java_aSinB(a, b, output, 100); - } - System.out.println(); - } - - fillBuffersWithSomeData(aBuffer, bBuffer); - gc(); - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - java_aSinB(a, b, output, dataSize); - } - long time = System.nanoTime() - start; - System.out.println("Java operations : " + time + "ns"); - return new ExecResult(outputBuffer, time / (loops * (double) dataSize)); - } - - static ExecResult testOpenCL_float_aSinB(CLContext context, int loops, int dataSize, boolean hostInOpenCL) throws CLBuildException { - - ExecResult er = testOpenCL_aSinB(context, Prim.Float, loops, dataSize, hostInOpenCL, new Action2() { - - public void call(ByteBuffer a, ByteBuffer b) { - fillBuffersWithSomeData(a.asFloatBuffer(), b.asFloatBuffer()); - } - }); - return new ExecResult(er.buffer.asFloatBuffer(), er.unitTimeNano); - } - - static ExecResult testOpenCL_double_aSinB(CLContext context, int loops, int dataSize, boolean hostInOpenCL) throws CLBuildException { - - ExecResult er = testOpenCL_aSinB(context, Prim.Double, loops, dataSize, hostInOpenCL, new Action2() { - - public void call(ByteBuffer a, ByteBuffer b) { - fillBuffersWithSomeData(a.asDoubleBuffer(), b.asDoubleBuffer()); - } - }); - return new ExecResult(er.buffer.asDoubleBuffer(), er.unitTimeNano); - } - - static ExecResult testOpenCL_aSinB(CLContext context, Prim nativePrim, int loops, int dataSize, boolean hostInOpenCL, Action2 fillBuffersWithSomeData) throws CLBuildException { - - CLKernel kernel = setupASinB(nativePrim, context); - CLQueue queue = context.createDefaultQueue(); - - ByteBuffer input1 = null, input2 = null, output = null; - CLByteBuffer memIn1, memIn2, memOut; - if (hostInOpenCL) { - memIn1 = kernel.program.context.createByteBuffer(CLMem.Usage.Input, dataSize * nativePrim.sizeof()); - memIn2 = kernel.program.context.createByteBuffer(CLMem.Usage.Input, dataSize * nativePrim.sizeof()); - memOut = kernel.program.context.createByteBuffer(CLMem.Usage.Output, dataSize * nativePrim.sizeof()); - } else { - input1 = directBytes(dataSize * nativePrim.sizeof(), context.getByteOrder()); - input2 = directBytes(dataSize * nativePrim.sizeof(), context.getByteOrder()); - output = directBytes(dataSize * nativePrim.sizeof(), context.getByteOrder()); - - memIn1 = kernel.program.context.createByteBuffer(CLMem.Usage.Input, input1, false); - memIn2 = kernel.program.context.createByteBuffer(CLMem.Usage.Input, input2, false); - memOut = kernel.program.context.createByteBuffer(CLMem.Usage.Output, output, false); - } - kernel.setArgs(memIn1, memIn2, memOut); - - if (warmup) { - for (int i = 0; i < 3000; i++) { - kernel.enqueueNDRange(queue, new int[]{dataSize}); - } - queue.finish(); - } - - if (hostInOpenCL) { - input1 = memIn1.map(queue, CLMem.MapFlags.Write); - input2 = memIn2.map(queue, CLMem.MapFlags.Write); - } - fillBuffersWithSomeData.call(input1, input2); - if (hostInOpenCL) { - memIn1.unmap(queue, input1); - memIn2.unmap(queue, input2); - } - queue.finish(); - gc(); - - //if (dataSize < workItemSize) { - // System.err.println("dataSize = " + dataSize + " is lower than max workItemSize for first dim = " + workItemSize + " !!!"); - // workItemSize = 1; - //} - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - kernel.enqueueNDRange(queue, new int[]{dataSize});//, new int[]{workItemSize}); - } - queue.finish(); - long time = System.nanoTime() - start; - - //System.out.println("OpenCL operations(" + target + ") : " + time + "ns"); - if (hostInOpenCL) { - // Copy the OpenCL-hosted array back to RAM - output = memOut.map(queue, CLMem.MapFlags.Read); - //queue.finish(); - ByteBuffer b = directBytes(dataSize * nativePrim.sizeof(), context.getByteOrder()); - b.put(output); - output.rewind(); - b.rewind(); - memOut.unmap(queue, output); - output = b; - } - return new ExecResult(output, time / (loops * (double) dataSize)); - } - - static CLKernel setupASinB(Prim nativeType, CLContext context) throws CLBuildException { - String src = "\n" - //+ "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n" - + "#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable\n" - + (nativeType == Prim.Double ? "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" : "") - + "__kernel void aSinB( \n" - + " __global const " + nativeType + "* a, \n" - + " __global const " + nativeType + "* b, \n" - + " __global " + nativeType + "* output) \n" - + "{ \n" - + " int i = get_global_id(0); \n" - + " float ai = a[i], bi = b[i]; \n" - + " output[i] = ai * sin(bi);// + atan2(ai, bi); \n" - + "} \n"; - - CLProgram program = context.createProgram(src).build(); - CLKernel kernel = program.createKernel("aSinB"); - - return kernel; - } - - public static void java_aSinB(float[] a, float[] b, float[] output, int dataSize) throws CLBuildException { - for (int i = 0; i < dataSize; i++) { - float ai = a[i], bi = b[i]; - output[i] = ai * (float) Math.sin(bi);// + (float)Math.atan2(ai, bi); - } - } - - public static void java_aSinB(double[] a, double[] b, double[] output, int dataSize) throws CLBuildException { - for (int i = 0; i < dataSize; i++) { - double ai = a[i], bi = b[i]; - output[i] = ai * Math.sin(bi);// + Math.atan2(ai, bi); - } - } - - enum Prim { - - Float(4), Double(8), Int(4), Short(2), Half(2); - final int sizeof; - - Prim(int sizeof) { - this.sizeof = sizeof; - } - - public int sizeof() { - return sizeof; - } - - public String toString() { - return name().toLowerCase(); - } - } - - @Test - public void testBenchmark() { - /*for (String s : new String[] { - "C:\\Program Files (x86)\\ATI Stream\\bin\\x86_64\\OpenCL.dll", - "C:\\Program Files (x86)\\ATI Stream\\bin\\x86\\OpenCL.dll", - "C:\\Program Files\\ATI Stream\\bin\\x86\\OpenCL.dll" - }) - if ((f = new File(s)).exists()) - break; - - if (f.exists()) - System.setProperty("OpenCL.library", f.toString()); - //sss */ - try { - System.out.println("#\n# " + OpenCL4JavaBenchmarkTest.class.getName() + "\n#"); - System.out.println("java.vm.name = " + System.getProperty("java.vm.name")); - System.out.println("java.vm.version = " + System.getProperty("java.runtime.version")); - System.out.println("Found platforms : " + Arrays.asList(JavaCL.listPlatforms())); - CLPlatform platform = JavaCL.listPlatforms()[0]; - String v = platform.getVendor(); - System.out.println("Platform Vendor: " + v); - boolean isAMD = v.equals("Advanced Micro Devices, Inc."); - int loops = 10; - int dataSize = isAMD ? 1024 : 1024 * 1024; - - CLContext context = JavaCL.createBestContext(); - boolean hasDoubleSupport = context.isDoubleSupported(); - - if (!hasDoubleSupport) { - System.out.println("OpenCL context does not support double precision computations : skipping second part of the test"); - } else { - System.out.println("#\n# [Double Operations]\n#"); - ExecResult nsByJavaOp = testJava_double_aSinB(loops, dataSize); - ExecResult nsByCLHostedOp = testOpenCL_double_aSinB(context, loops, dataSize, true); - ExecResult nsByNativeHostedCLOp = testOpenCL_double_aSinB(context, loops, dataSize, false); - double errCLHosted = avgError(nsByJavaOp.buffer, nsByCLHostedOp.buffer, dataSize); - double errNativeHosted = avgError(nsByJavaOp.buffer, nsByNativeHostedCLOp.buffer, dataSize); - - System.out.println(" Avg relative error (hosted in CL) = " + errCLHosted); - System.out.println("Avg relative error (hosted in RAM) = " + errNativeHosted); - System.out.println(); - - System.out.println(" java op\t= " + nsByJavaOp.unitTimeNano + " ns"); - System.out.println(); - System.out.println(" opencl (hosted in CL) op\t= " + nsByCLHostedOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByCLHostedOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByCLHostedOp.unitTimeNano)); - System.out.println(); - System.out.println("opencl (hosted in RAM) op\t= " + nsByNativeHostedCLOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByNativeHostedCLOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByNativeHostedCLOp.unitTimeNano)); - } - - if (true) { - System.out.println("#\n# [Float Operations]\n#"); - ExecResult nsByJavaOp = testJava_float_aSinB(loops, dataSize); - ExecResult nsByCLHostedOp = testOpenCL_float_aSinB(context, loops, dataSize, true); - ExecResult nsByNativeHostedCLOp = testOpenCL_float_aSinB(context, loops, dataSize, false); - double errCLHosted = avgError(nsByJavaOp.buffer, nsByCLHostedOp.buffer, dataSize); - double errNativeHosted = avgError(nsByJavaOp.buffer, nsByNativeHostedCLOp.buffer, dataSize); - - /*for (int i = 0; i < 10; i++) { - System.out.print("i\t = " + i + ",\t"); - System.out.print("buf \t=" + nsByJavaOp.buffer.get(i) +",\t"); - System.out.print("nat \t=" + nsByNativeHostedCLOp.buffer.get(i) +",\t"); - System.out.print("ocl \t=" + nsByCLHostedOp.buffer.get(i) +",\t"); - System.out.println(); - }*/ - System.out.println(" Avg relative error (hosted in CL) = " + errCLHosted); - System.out.println("Avg relative error (hosted in RAM) = " + errNativeHosted); - System.out.println(); - - System.out.println(" java op\t= " + nsByJavaOp.unitTimeNano + " ns"); - System.out.println(); - System.out.println(" opencl (hosted in CL) op\t= " + nsByCLHostedOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByCLHostedOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByCLHostedOp.unitTimeNano)); - System.out.println(); - System.out.println("opencl (hosted in RAM) op\t= " + nsByNativeHostedCLOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByNativeHostedCLOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByNativeHostedCLOp.unitTimeNano)); - } - - - - } catch (CLBuildException e) { - e.printStackTrace(); - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java deleted file mode 100644 index e1d2f264c..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.test; - -/** - * - * @author ochafik - */ -public class BenchmarkUtils { - public static void gc() { - try { - System.gc(); - Thread.sleep(200); - System.gc(); - Thread.sleep(200); - } catch (InterruptedException ex) {} - } - -} diff --git a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java b/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java deleted file mode 100644 index b12efc84f..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.test; - -import static org.junit.Assert.assertFalse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.sun.jna.Native; - -/** - * - * @author ochafik - */ -public class MiscTestUtils { - public static void protectJNI() { - Native.setProtected(true); - } - public static void testGetters(Object instance) { - if (instance == null) - return; - Logger log = Logger.getLogger(instance.getClass().getName()); - for (Method m : instance.getClass().getDeclaredMethods()) { - if (Modifier.isStatic(m.getModifiers())) - continue; - if (!Modifier.isPublic(m.getModifiers())) - continue; - if (m.getParameterTypes().length != 0) - continue; - - String name = m.getName(); - if (name.contains("ProfilingCommand")) - continue; - - boolean isToString = name.equals("toString"); - if (name.startsWith("get") && name.length() > 3 || - name.startsWith("has") && name.length() > 3 || - name.startsWith("is") && name.length() > 2 || - isToString && !Modifier.isPublic(m.getDeclaringClass().getModifiers())) - { - String msg = "Failed to call " + m; - try { - m.invoke(instance); - } catch (IllegalAccessException ex) { - if (!isToString) - log.log(Level.WARNING, msg, ex); - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (!(cause instanceof UnsupportedOperationException)) { - log.log(Level.SEVERE, msg, ex.getCause()); - assertFalse(msg, true); - } - } catch (Exception ex) { - log.log(Level.SEVERE, msg, ex); - } - } - } - } -} diff --git a/libraries/OpenCL-JNA/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c b/libraries/OpenCL-JNA/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c deleted file mode 100644 index 0e19e18fc..000000000 --- a/libraries/OpenCL-JNA/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c +++ /dev/null @@ -1,6 +0,0 @@ -__kernel void testLongRead( __global const long* input, - __global long* output) { - int i = get_global_id(0); - - output[i] = input[i] + 1; -} diff --git a/libraries/OpenCL-JNA/Demos/.classpath b/libraries/OpenCL-JNA/Demos/.classpath deleted file mode 100644 index 63fc74ae6..000000000 --- a/libraries/OpenCL-JNA/Demos/.classpath +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Demos/.gitignore b/libraries/OpenCL-JNA/Demos/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/Demos/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/Demos/.project b/libraries/OpenCL-JNA/Demos/.project deleted file mode 100644 index 778f92065..000000000 --- a/libraries/OpenCL-JNA/Demos/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Demos - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL-JNA/Demos/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL-JNA/Demos/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 575a63fe0..000000000 --- a/libraries/OpenCL-JNA/Demos/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:20 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL-JNA/Demos/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL-JNA/Demos/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL-JNA/Demos/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL-JNA/Demos/pom.xml b/libraries/OpenCL-JNA/Demos/pom.xml deleted file mode 100644 index b07d0f1bf..000000000 --- a/libraries/OpenCL-JNA/Demos/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-demos-jna - JavaCL Demos / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl-jna - - - - - org.swinglabs - swing-layout - 1.0.3 - - - - - - - - com.nativelibs4java - javacl-generator-jna - - - - compile - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java deleted file mode 100644 index 7a57ea1bf..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.demos; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.nativelibs4java.opencl.JavaCL; -import com.ochafik.util.SystemUtils; -import com.sun.jna.Platform; - -/** - * - * @author ochafik - */ -public class SetupUtils { - - public static void failWithDownloadProposalsIfOpenCLNotAvailable() { - ///* - try { - JavaCL.listPlatforms(); - return; - } catch (UnsatisfiedLinkError ex) { - ex.printStackTrace(); - } //*/ - String title = "JavaCL Error: OpenCL library not found"; - if (Platform.isMac()) { - JOptionPane.showMessageDialog(null, "Please upgrade Mac OS X to Snow Leopard (10.6) to be able to use OpenCL.", title, JOptionPane.ERROR_MESSAGE); - return; - } - Object[] options = new Object[] { - "NVIDIA graphic card", - "ATI graphic card", - "CPU only", - "Cancel" - }; - //for (;;) { - int option = JOptionPane.showOptionDialog(null, - "You don't appear to have an OpenCL implementation properly configured.\n" + - "Please choose one of the following options to proceed to the download of an appropriate OpenCL implementation :", title, JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[2]); - if (option >= 0 && option != 3) { - String urlString; - if (option == 0) { - /*String nvidiaVersion = "260.99"; - boolean appendPlatform = true; - String sys; - - if (Platform.isWindows()) { - if (System.getProperty("os.name").toLowerCase().contains("xp")) { - sys = "winxp"; - appendPlatform = false; - } else { - sys = "win7_vista"; - } - urlString = "http://www.nvidia.fr/object/" + sys + "_" + nvidiaVersion + (appendPlatform ? "_" + (Platform.is64Bit() ? "64" : "32") + "bit" : "") + "_whql.html"; - } else - urlString = "http://developer.nvidia.com/object/opencl-download.html"; - */ - urlString = "http://www.nvidia.com/Download/Find.aspx"; - } else - urlString = "http://developer.amd.com/GPU/ATISTREAMSDK/Pages/default.aspx"; - - try { - SystemUtils.runSystemOpenURL(new URL(urlString)); - } catch (Exception ex1) { - exception(ex1); - } - } - System.exit(1); - } - - public static void exception(Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "Error in JavaCL Demo", JOptionPane.ERROR_MESSAGE); - } - - static Border etchedBorder; - static synchronized Border getEtchedBorder() { - if (etchedBorder == null) { - etchedBorder = UIManager.getBorder( "TitledBorder.aquaVariant" ); - if (etchedBorder == null) - etchedBorder = BorderFactory.createCompoundBorder(new EtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)); - } - return etchedBorder; - } - public static void setEtchedTitledBorder(JComponent comp, String title) { - comp.setBorder(new TitledBorder(getEtchedBorder(), title)); - } -} diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java deleted file mode 100644 index bd56c9b66..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos.hardware; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.ochafik.util.SystemUtils; -import java.awt.BorderLayout; -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.UIManager; - -/** - * Small program that outputs html reports about the information returned by OpenCL for each device. - * @author ochafik - */ -public class HardwareReport { - - public static Map infoMethods(Class c) { - Map mets = new TreeMap(); - for (Method met : c.getMethods()) { - InfoName name = met.getAnnotation(InfoName.class); - if (name == null) { - continue; - } - mets.put(name.value(), met); - } - return mets; - } - - public static List> listInfos(CLPlatform platform) { - try { - List> ret = new ArrayList>(); - Map platMets = infoMethods(CLPlatform.class); - Map devMets = infoMethods(CLDevice.class); - //for (CLPlatform platform : JavaCL.listPlatforms()) { - Map platInfos = new TreeMap(); - for (Map.Entry platMet : platMets.entrySet()) { - try { - platInfos.put(platMet.getKey(), platMet.getValue().invoke(platform)); - } catch (InvocationTargetException ex) { - if (ex.getCause() instanceof UnsupportedOperationException) - platInfos.put(platMet.getKey(), "n/a"); - else - throw ex; - } - } - for (CLDevice device : platform.listAllDevices(false)) { - Map devInfos = new TreeMap(platInfos); - for (Map.Entry devMet : devMets.entrySet()) { - try { - devInfos.put(devMet.getKey(), devMet.getValue().invoke(device)); - } catch (InvocationTargetException ex) { - if (ex.getCause() instanceof UnsupportedOperationException) - devInfos.put(devMet.getKey(), "n/a"); - else - throw ex; - } - } - ret.add(devInfos); - } - //} - return ret; - } catch (Throwable ex) { - throw new RuntimeException(ex); - } - } - - public static String toString(Object value) { - if (value == null) { - return "null"; - } - Class c = value.getClass(); - try { - if (c.isArray()) { - if (!c.getComponentType().isPrimitive()) { - c = Object[].class; - } - value = Arrays.class.getMethod("toString", c).invoke(null, value); - } - } catch (Exception ex) { - throw new RuntimeException(ex); - } - String s = value.toString(); - if (s.startsWith("[") && s.endsWith("]")) { - s = s.substring(1, s.length() - 1); - s = s.replaceAll(", ", "
    "); - } - return s; - } - - public static String toTable(List> list) { - StringBuilder b = new StringBuilder(); - - b.append("\n"); - if (!list.isEmpty()) { - Set keys = list.get(0).keySet(); - - b.append("\t\n"); - b.append("\t\t"); - for (Map device : list) { - Object value = device.get("CL_DEVICE_NAME"); - b.append("\n"); - } - b.append("\n"); - b.append("\t\n"); - - for (String key : keys) { - b.append("\t\n"); - b.append("\t\t"); - for (Map device : list) { - Object value = device.get(key); - b.append(""); - } - b.append("\n"); - b.append("\t\n"); - } - } - - b.append("
    [" + toString(value) + "]
    " + key + "" + toString(value) + "
    \n"); - return b.toString(); - } - - public static String toHTML(List> list) { - return //"\n" + - "\n" - + "\n" - + toTable(list) - + ""; - } - - public static JComponent getHardwareReportComponent(CLPlatform platform) { - List> list = listInfos(platform); - final String html = toHTML(list); - - JEditorPane ed = new JEditorPane(); - ed.setContentType("text/html"); - ed.setText(html); - ed.setEditable(false); - - JPanel ret = new JPanel(new BorderLayout()); - ret.add("Center", new JScrollPane(ed)); - - final String fileName = "HardwareReport.html"; - JButton bWrite = new JButton("Save " + fileName + "..."); - bWrite.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - FileDialog fd = new FileDialog((Frame)null, "Save " + fileName, FileDialog.SAVE); - fd.setFile(fileName); - fd.setVisible(true); - if (fd.getFile() == null) - return; - - try { - File file = new File(new File(fd.getDirectory()), fd.getFile()); - file.getParentFile().mkdirs(); - Writer w = new OutputStreamWriter(new FileOutputStream(file), "utf-8"); - w.write(html); - w.close(); - - SystemUtils.runSystemOpenFileParent(file); - } catch (Throwable ex) { - SetupUtils.exception(ex); - } - } - - }); - - ret.add("South", bWrite); - return ret; - } - public static void main(String[] args) { - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - try { - JTabbedPane pane = new JTabbedPane(); - for (CLPlatform platform : JavaCL.listPlatforms()) - pane.addTab(platform.toString(), getHardwareReportComponent(platform)); - - JFrame f = new JFrame("OpenCL4Java: Hardware Characteristics"); - f.getContentPane().add("Center", pane); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.pack(); - f.setSize(f.getWidth() + 15, 700); - f.setVisible(true); - - } catch (Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "[Error] OpenCL4Java HardwareReport", JOptionPane.ERROR_MESSAGE); - } - } -} diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java deleted file mode 100644 index 723837fba..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.nativelibs4java.opencl.demos.mandelbrot; - -//package bbbob.gparallel.mandelbrot; -import static com.nativelibs4java.opencl.JavaCL.createBestContext; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.nio.IntBuffer; - -import javax.imageio.ImageIO; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.UIManager; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; - - -/** - * Copied and adapted from Bob Boothby's code : - * http://bbboblog.blogspot.com/2009/10/gpgpu-mandelbrot-with-opencl-and-java.html - */ -public class MandelbrotDemo { - //boundary of view on mandelbrot set - - public static void main(String[] args) throws IOException, CLBuildException { - - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - //Setup variables for parameters - - //Boundaries - float realMin = -2.25f; //-0.19920f; // -2.25 - float realMax = 0.75f; //-0.12954f; // 0.75 - float imaginaryMin = -1.5f; //1.01480f; // -1.5 - float imaginaryMax = 1.5f; //1.06707f; // 1.5 - - //Resolution - int realResolution = 1640; // TODO validate against device capabilities - int imaginaryResolution = 1640; - - //The maximum iterations to perform before returning and assigning 0 to a pixel (infinity) - int maxIter = 64; - - //TODO describe what this number means... - int magicNumber = 4; - - //Derive the distance in imaginary / real coordinates between adjacent pixels of the image. - float deltaReal = (realMax - realMin) / (realResolution-1); - float deltaImaginary = (imaginaryMax - imaginaryMin) / (imaginaryResolution-1); - - //Create a context and program using the devices discovered. - CLContext context = createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - //Setup output buffer - int size = realResolution * imaginaryResolution; - IntBuffer results = NIOUtils.directInts(size, context.getByteOrder()); - - //TODO use an image object directly. - //CL.clCreateImage2D(context.get(), 0, OpenCLLibrary); - //TODO set up a Float4 array in order to be able to provide a colour map. - //This depends on whether we will be able to pass in a Float4 array as an argument in the future. - - //Read the source file. - String src = IOUtils.readTextClose(MandelbrotDemo.class.getResourceAsStream("Mandelbrot.cl")); - - long time = buildAndExecuteKernel(queue, realMin, imaginaryMin, realResolution, imaginaryResolution, maxIter, magicNumber, - deltaReal, deltaImaginary, results, src); - - int nPixels = imaginaryResolution * realResolution; - long timePerPixel = time / nPixels; - String label = "Computed in " + ((time / 1000)) + " microseconds\n(" + ((timePerPixel)) + " nanoseconds per pixel)"; - - BufferedImage image = getImage(realResolution, imaginaryResolution, results); - outputImage(image); - - JFrame f = new JFrame("JavaCL Mandelbrot Demo"); - f.getContentPane().add("Center", new JScrollPane(new JLabel(new ImageIcon(image)))); - f.getContentPane().add("North", new JLabel(label)); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.pack(); - f.setVisible(true); - } - - private static BufferedImage getImage(int realResolution, int imaginaryResolution, - IntBuffer results) { - int[] outputResults = new int[realResolution * imaginaryResolution]; - results.get(outputResults); - int max = Integer.MIN_VALUE; - for (int i = outputResults.length; i-- != 0;) { - int v = outputResults[i]; - if (v > max) - max = v; - } - - for (int i = outputResults.length; i-- != 0;) { - int v = outputResults[i]; - float f = v / (float)max; - outputResults[i] = Color.HSBtoRGB(1 - f, 0.5f, 0.3f + f * 0.7f); - } - - BufferedImage image = new BufferedImage(realResolution, imaginaryResolution, BufferedImage.TYPE_INT_RGB); - image.setRGB(0, 0, realResolution, imaginaryResolution, outputResults, 0, realResolution); - return image; - } - private static void outputImage(BufferedImage image) { - try { - ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next(); - ImageOutputStream stream = ImageIO.createImageOutputStream(new File("test.gif")); - writer.setOutput(stream); - writer.write(image); - } catch (IOException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - static boolean useAutoGenWrapper = true; - private static long buildAndExecuteKernel(CLQueue queue, float realMin, float imaginaryMin, int realResolution, - int imaginaryResolution, int maxIter, int magicNumber, float deltaReal, - float deltaImaginary, IntBuffer results, String src) throws CLBuildException, IOException { - - CLContext context = queue.getContext(); - long startTime = System.nanoTime(); - if (useAutoGenWrapper) { - Mandelbrot mandelbrot = new Mandelbrot(context); - mandelbrot.mandelbrot( - queue, - new float[] { deltaReal, deltaImaginary }, - new float[] { realMin, imaginaryMin }, - - maxIter, - magicNumber, - realResolution, - context.createIntBuffer(CLMem.Usage.Output, results, false), - - new int[]{realResolution, imaginaryResolution}, - new int[]{1,1} - ); - } else { - CLProgram program = context.createProgram(src).build(); - - //Create a kernel instance from the mandelbrot kernel, passing in parameters. - CLKernel kernel = program.createKernel( - "mandelbrot", - new float[] { deltaReal, deltaImaginary }, - new float[] { realMin, imaginaryMin }, - - maxIter, - magicNumber, - realResolution, - context.createIntBuffer(CLMem.Usage.Output, results, false) - ); - - //Enqueue and complete work using a 2D range of work groups corrsponding to individual pizels in the set. - //The work groups are 1x1 in size and their range is defined by the desired resolution. This corresponds - //to one device thread per pixel. - - kernel.enqueueNDRange(queue, new int[]{realResolution, imaginaryResolution}, new int[]{1,1}); - } - queue.finish(); - long time = System.nanoTime() - startTime; - return time; - - } -} diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java deleted file mode 100644 index 439fc9d7c..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.demos.random; - -import com.nativelibs4java.opencl.util.ParallelRandom; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLIntBuffer; -import com.nativelibs4java.opencl.CLMem.MapFlags; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.util.NIOUtils; -import java.io.IOException; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -public class ParallelRandomDemo { - - private static void println(IntBuffer b) { - for (int i = 0, n = b.capacity(); i < n; i++) { - if (i > 0) - System.out.print(", "); - System.out.print(b.get(i)); - - if (i > 32) - System.out.print("..."); - } - System.out.println(); - } - - static class Stat { - long total; - long times; - boolean skippedFirst; - void add(long value) { - if (!skippedFirst) { - skippedFirst = true; - return; - } - - total += value; - times++; - } - long average() { - return times == 0 ? 0 : total / times; - } - } - public static void main(String[] args) { - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - int warmupSize = 16; - ParallelRandom demo = new ParallelRandom(queue, warmupSize, System.currentTimeMillis()); - - println((IntBuffer)demo.getSeeds().read(queue)); - IntBuffer b = demo.next(); - println(b); - b = demo.next(); - println(b); - b = demo.next(); - println(b); - - gc(); - - long start = System.nanoTime(); - int loops = 2800; - Random random = new Random(); - int res = 0; - for (int i = loops; i-- != 0;) { - //demo.next(b); - //demo.next(); - demo.doNext(); - res |= random.nextInt(); - } - demo.getQueue().finish(); - long time = System.nanoTime() - start; - - System.err.println("Warmup took " + time + " ns"); - - - Stat stat; - - - int testSize = 1024 * 1024;//1024 * 1024; - int testLoops = 10; - - System.err.println("n = " + testSize); - demo = new ParallelRandom(queue, testSize, System.currentTimeMillis()); - b = demo.next(); - - gc(); - - stat = new Stat(); - for (int iTest = 0; iTest < testLoops; iTest++) { - start = System.nanoTime(); - //b = demo.next();//b); - demo.doNext(); - demo.getQueue().finish(); - time = System.nanoTime() - start; - stat.add(time); - //System.err.println("[OpenCL] Cost per random number = " + (time / (double)testSize) + " ns"); - - } - long avgCL = stat.average(); - System.err.println("[OpenCL] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); - System.err.println(); - - gc(); - - stat = new Stat(); - for (int iTest = 0; iTest < testLoops; iTest++) { - start = System.nanoTime(); - for (int i = testSize; i-- != 0;) - res |= random.nextInt(); - time = System.nanoTime() - start; - stat.add(time); - //System.err.println("[Random.nextInt()] Cost per random number = " + (time / (double)testSize) + " ns"); - } - long avgJava = stat.average(); - System.err.println("[Random.nextInt()] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); - System.err.println(); - - double timesCLFasterThanJava = avgJava / (double)avgCL; - System.err.println("Java / CL (avg) = " + timesCLFasterThanJava); - System.err.println(res); // make sure no brutal optimization happens - System.err.println(b.get(0)); // make sure no brutal optimization happens - //println(b); - - } catch (IOException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - } - } - static void gc() { - try { - System.gc(); - Thread.sleep(200); - System.gc(); - Thread.sleep(200); - } catch (InterruptedException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - } - } -} diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java deleted file mode 100644 index 485a975a4..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos.sobelfilter; - -import javax.swing.*; - -import java.nio.*; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.*; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.ochafik.util.listenable.Pair; -import java.awt.image.*; -import java.io.*; -import java.nio.FloatBuffer; -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import com.sun.jna.Platform; -import java.awt.FileDialog; -public class SobelFilterDemo { - - static File chooseFile() { - if (Platform.isMac()) { - FileDialog d = new FileDialog((java.awt.Frame)null); - d.setMode(FileDialog.LOAD); - d.show(); - String f = d.getFile(); - if (f != null) - return new File(new File(d.getDirectory()), d.getFile()); - } else { - JFileChooser chooser = new JFileChooser(); - if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) - return chooser.getSelectedFile(); - } - return null; - } - public static void main(String[] args) { - try { - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - File imageFile = chooseFile(); - if (imageFile == null) - return; - - BufferedImage image = ImageIO.read(imageFile); - int width = image.getWidth(), height = image.getHeight(); - //int step = 32; - // image = image.getSubimage(0, 0, (width / step) * step, (height / step) * step); - //image = image.getSubimage(0, 0, 512, 512);//(width / step) * step, (height / step) * step); - - - JFrame f = new JFrame("JavaCL Sobel Filter Demo"); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - SobelFilterDemo demo = new SobelFilterDemo(); - Pair imgs = demo.computeSobel(image); - f.getContentPane().add("Center", - //new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, - // new JScrollPane(new JLabel(new ImageIcon(image))), - new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, - new JScrollPane(new JLabel(new ImageIcon(imgs.getFirst()))), - new JScrollPane(new JLabel(new ImageIcon(imgs.getSecond()))) - ) {/** - * - */ - private static final long serialVersionUID = 8267014922143370639L; - - { - setResizeWeight(0.5); - }} - //) - ); - - f.pack(); - f.setVisible(true); - } catch (Throwable th) { - th.printStackTrace(); - SetupUtils.exception(th); - } - } - - CLContext context; - CLQueue queue; - SimpleSobel sobel; - ReductionUtils.Reductor floatMinReductor; - - - public SobelFilterDemo() throws IOException, CLBuildException { - context = JavaCL.createBestContext(); - queue = context.createDefaultQueue(); - sobel = new SimpleSobel(context); - floatMinReductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Max, OpenCLType.Float, 1); - - } - - public static int roundUp(int group_size, int global_size) - { - int r = global_size % group_size; - return r == 0 ? global_size : global_size + group_size - r; - } - public Pair computeSobel(BufferedImage img) throws IOException, CLBuildException { - int width = img.getWidth(), height = img.getHeight(); - - int dataSize = height * width; - int[] pixels = img.getRGB(0, 0, width, height, null, 0, width); - - CLFloatBuffer - gradients = context.createFloatBuffer(CLMem.Usage.InputOutput, dataSize), - directions = context.createFloatBuffer(CLMem.Usage.InputOutput, dataSize); - - CLEvent evt = sobel.simpleSobel(queue, - context.createIntBuffer(CLMem.Usage.Input, IntBuffer.wrap(pixels), true).asCLByteBuffer(), - width, - height, - gradients, - directions, - new int[] { width, height }, - null//new int[] { 1, 1 } - ); - - //queue.finish(); - - //float[] test = new float[1000]; - //gradients.read(queue).get(test); - - float gradientMax = ((FloatBuffer)floatMinReductor.reduce(queue, gradients, dataSize, 32, evt)).get(); - float dirMax = ((FloatBuffer)floatMinReductor.reduce(queue, directions, dataSize, 32, evt)).get(); - - //CLEvent.waitFor(evtGradMax, evtDirMax); - - CLIntBuffer gradientPixels = context.createIntBuffer(CLMem.Usage.Output, dataSize); - CLIntBuffer directionPixels = context.createIntBuffer(CLMem.Usage.Output, dataSize); - - //CLEvent evtGrad = - sobel.normalizeImage(queue, gradients, gradientMax, gradientPixels.asCLByteBuffer(), new int[] { dataSize }, null); - //CLEvent evtDir = - sobel.normalizeImage(queue, directions, dirMax, directionPixels.asCLByteBuffer(), new int[] { dataSize }, null); - - queue.finish(); - - BufferedImage gradientsImage = getRowsOrderImage(queue, gradientPixels, width, height, pixels);//, evtGrad); - BufferedImage directionsImage = getRowsOrderImage(queue, directionPixels, width, height, pixels);//, evtDir); - - return new Pair(gradientsImage, directionsImage); - } - static BufferedImage getRowsOrderImage(CLQueue queue, CLIntBuffer buffer, int width, int height, int[] pixelsTemp, CLEvent... eventsToWaitFor) { - queue.finish(); - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - int[] pixels = pixelsTemp == null ? new int[width * height] : pixelsTemp; - ((IntBuffer)buffer.read(queue, eventsToWaitFor)).get(pixels); - img.setRGB(0, 0, width,height, pixels, 0, width); - return img; - } -} - diff --git a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java b/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java deleted file mode 100644 index 7e6edfc9d..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.nativelibs4java.opencl.demos.vectoradd; -import com.nativelibs4java.opencl.*; -import java.nio.*; - -/** - * This is about the simplest possible JavaCL program.
    - * It adds two vectors of floats in parallel.
    - * This program can be written more easily with the JavaCL BLAS Library : - * - * LinearAlgebraUtils la = new LinearAlgebraUtils(); - * CLKernel kernel = new LinearAlgebraUtils().getKernel(LinearAlgebraUtils.Fun2.add, LinearAlgebraUtils.Primitive.Float); - * - * @author ochafik - */ -public class VectorAdd { - - public static void main(String[] args) { - try { - FloatBuffer a = FloatBuffer.wrap(new float[] { 1, 2, 3, 4 }); - FloatBuffer b = FloatBuffer.wrap(new float[] { 10, 20, 30, 40 }); - - FloatBuffer sum = add(a, b); - for (int i = 0, n = sum.capacity(); i < n; i++) - System.out.println(sum.get(i)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static FloatBuffer add(FloatBuffer a, FloatBuffer b) throws CLBuildException { - int n = a.capacity(); - - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - String source = - "__kernel void addFloats(__global const float* a, __global const float* b, __global float* output) " + - "{ " + - " int i = get_global_id(0); " + - " output[i] = a[i] + b[i]; " + - "} "; - - CLKernel kernel = context.createProgram(source).createKernel("addFloats"); - CLFloatBuffer aBuf = context.createFloatBuffer(CLMem.Usage.Input, a, true); - CLFloatBuffer bBuf = context.createFloatBuffer(CLMem.Usage.Input, b, true); - CLFloatBuffer outBuf = context.createFloatBuffer(CLMem.Usage.Output, n); - kernel.setArgs(aBuf, bBuf, outBuf); - - kernel.enqueueNDRange(queue, new int[]{n}); - queue.finish(); - - return outBuf.read(queue); - } -} - diff --git a/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl b/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl deleted file mode 100644 index 3d8b544d0..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copied and adapted from Bob Boothby's code : - * http://bbboblog.blogspot.com/2009/10/gpgpu-mandelbrot-with-opencl-and-java.html - */ -__kernel void mandelbrot( - const float2 delta, - const float2 minimum, - const unsigned int maxIter, - const unsigned int magicNumber, - const unsigned int hRes, - __global int* outputi -) -{ - int2 id = (int2)(get_global_id(0), get_global_id(1)); - - float2 pos = minimum + delta * (float2)(id.x, id.y); - float2 squared = pos * pos; - float2 val = pos; - - int iter = 0; - while ( (iter < maxIter) && ((squared.x + squared.y) < magicNumber) ) - { - val.y = (2 * (val.x * val.y)); - val.x = squared.x - squared.y; - val += pos; - squared = val * val; - - iter++; - } - if(iter >= maxIter) - iter = 0; - - outputi[id.y * hRes + id.x] = iter; -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl b/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl deleted file mode 100644 index ae0e40cb0..000000000 --- a/libraries/OpenCL-JNA/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl +++ /dev/null @@ -1,76 +0,0 @@ - -sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; - -#define MX_NW 1 -#define MX_N 2 -#define MX_NE 1 -#define MX_W 0 -#define MX_C 0 -#define MX_E 0 -#define MX_SW -1 -#define MX_S -2 -#define MX_SE -1 - -#define MY_NW 1 -#define MY_N 0 -#define MY_NE -1 -#define MY_W 2 -#define MY_C 0 -#define MY_E -2 -#define MY_SW 1 -#define MY_S 0 -#define MY_SE -1 - -#define PIXEL_TO_INTENSITIES(pixel, coefX, coefY) (uint2)(coefX, coefY) * (uint2)((pixel.x + (int)pixel.y + (int)pixel.z) * pixel.w / 256 / 3) - -__kernel void simpleSobel( - //__read_only image_t inputImage, - __global const uchar4* input, - uint width, uint height, - __global float* gradientOutput, - __global float* directionOutput -) { - int x = get_global_id(0), y = get_global_id(1); - if (x >= width || y >= height) - return; - - int i = y * width + x; - - uint2 total = (uint2)0; - - //total += PIXEL_TO_INTENSITIES(input[i], 1, 1); - - int in = i - width, is = i + width; - bool allowEast = x < width - 1, allowSouth = y < height - 1, allowNorth = y, allowWest = x; - if (allowNorth) { - if (allowWest) - total += PIXEL_TO_INTENSITIES(input[in - 1], MX_NW, MY_NW); - total += PIXEL_TO_INTENSITIES(input[in], MX_N, MY_N); - if (allowEast) - total += PIXEL_TO_INTENSITIES(input[in + 1], MX_NE, MY_NE); - } - - if (allowWest) - total += PIXEL_TO_INTENSITIES(input[i - 1], MX_W, MY_W); - total += PIXEL_TO_INTENSITIES(input[i], MX_C, MY_C); - if (allowEast) - total += PIXEL_TO_INTENSITIES(input[i + 1], MX_E, MY_E); - - if (allowSouth) { - if (allowWest) - total += PIXEL_TO_INTENSITIES(input[is - 1], MX_SW, MY_SW); - total += PIXEL_TO_INTENSITIES(input[is], MX_S, MY_S); - if (allowEast) - total += PIXEL_TO_INTENSITIES(input[is + 1], MX_SE, MY_SE); - } - - uint2 square = total * total; - gradientOutput[i] = sqrt((float)(square.x + square.y)); - directionOutput[i] = atan2((float)total.y, (float)total.x); -} - -__kernel void normalizeImage(__global const float* input, float maxValue, __global uchar4* output) { - int i = get_global_id(0); - uchar v = input[i] / maxValue * 255; - output[i] = (uchar4)(v, v, v, 255); -} diff --git a/libraries/OpenCL-JNA/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java b/libraries/OpenCL-JNA/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java deleted file mode 100644 index 3184c4804..000000000 --- a/libraries/OpenCL-JNA/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.demos; -import com.nativelibs4java.opencl.*; - -import com.nativelibs4java.opencl.demos.hardware.HardwareReport; -import java.util.List; -import java.util.Map; -import org.junit.Test; - -/** - * Test that HardwareReport runs without exception - * @author ochafik - */ -public class TestReport { - - @Test - public void runReport() { - for (CLPlatform platform : JavaCL.listPlatforms()) { - List> list = HardwareReport.listInfos(platform); - HardwareReport.toHTML(list); - } - } -} diff --git a/libraries/OpenCL-JNA/Generator/.classpath b/libraries/OpenCL-JNA/Generator/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/OpenCL-JNA/Generator/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Generator/.gitignore b/libraries/OpenCL-JNA/Generator/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/Generator/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/Generator/.project b/libraries/OpenCL-JNA/Generator/.project deleted file mode 100644 index 7dbd9de12..000000000 --- a/libraries/OpenCL-JNA/Generator/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Generator - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL-JNA/Generator/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL-JNA/Generator/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 45a45b3f0..000000000 --- a/libraries/OpenCL-JNA/Generator/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:18 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL-JNA/Generator/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL-JNA/Generator/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL-JNA/Generator/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL-JNA/Generator/pom.xml b/libraries/OpenCL-JNA/Generator/pom.xml deleted file mode 100644 index aa705f287..000000000 --- a/libraries/OpenCL-JNA/Generator/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-generator-jna - JavaCL OpenCL Wrapper Code Generator / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - maven-plugin - - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - jnaerator - ${jnaerator.version} - shaded - - - - com.nativelibs4java - javacl-core-jna - - - - org.apache.maven - maven-plugin-api - 3.0.3 - - - - org.apache.maven - maven-project - 3.0-alpha-2 - - - - - - - - - diff --git a/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java b/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java deleted file mode 100644 index a4aebc24b..000000000 --- a/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java +++ /dev/null @@ -1,511 +0,0 @@ -package com.nativelibs4java.opencl.generator; - -import com.nativelibs4java.opencl.*; -import com.ochafik.io.IOUtils; -import com.ochafik.lang.jnaerator.*; -import com.ochafik.lang.jnaerator.PreprocessorUtils.MacroUseCallback; -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrimitive; -import com.ochafik.lang.jnaerator.TypeConversion.TypeConversionMode; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; -import java.io.File; -import java.io.*; -import java.util.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -import java.util.regex.Pattern; -import org.anarres.cpp.LexerException; - -public class JavaCLGenerator extends JNAerator { - - static Pattern nameExtPatt = Pattern.compile("(.*?)\\.(\\w+)"); - - public JavaCLGenerator(JNAeratorConfig config) { - super(config); - - config.noCPlusPlus = true; - config.genCPlusPlus = false; - config.gccLong = true; - config.putTopStructsInSeparateFiles = false; - config.runtime = JNAeratorConfig.Runtime.JNAerator;//NL4JStructs; - config.fileToLibrary = new Adapter() { - @Override - public String adapt(File value) { - String[] m = RegexUtils.match(value.getName(), nameExtPatt); - return m == null ? null : m[1]; - } - }; - - config.functionsAccepter = new Adapter() { - @Override - public Boolean adapt(Function value) { - List mods = value.getModifiers(); - if (ModifierType.__kernel.isContainedBy(mods)) - return true; - if (value.getValueType() == null) - return null; - mods = value.getValueType().getModifiers(); - return ModifierType.__kernel.isContainedBy(mods); - } - }; - } - - Map> macrosByFile = new HashMap>(); - - @Override - protected JNAeratorParser createJNAeratorParser() { - return new JNAeratorParser() { - - @Override - protected com.ochafik.lang.jnaerator.parser.ObjCppParser newObjCppParser(TypeConversion typeConverter, String s, boolean verbose, PrintStream errorOut) throws IOException { - com.ochafik.lang.jnaerator.parser.ObjCppParser parser = super.newObjCppParser(typeConverter, s, verbose, errorOut); - parser.allowKinds(ModifierKind.OpenCL); - return parser; - } - - }; - } - - static Set openclPrimitives = new HashSet(); - static { - openclPrimitives.add("half"); - openclPrimitives.add("image2d_t"); - openclPrimitives.add("image3d_t"); - openclPrimitives.add("sampler_t"); - openclPrimitives.add("event_t"); - } - - @Override - public Result createResult(final ClassOutputter outputter, Feedback feedback) { - return new Result(config, outputter, feedback) { - - @Override - public void init() { - typeConverter = new JNATypeConversion(this) { - - @Override - public void initTypes() { - super.initTypes(); - - } - - - @Override - public boolean isObjCppPrimitive(String s) { - int len; - if (s == null || (len = s.length()) == 0) - return false; - - if (super.isObjCppPrimitive(s)) - return true; - - // handle case of "(int|long|short|byte|double|float)\\d" - if (len > 1 && Character.isDigit(s.charAt(len - 1))) { - String ss = s.substring(0, len - 1); - if (ss.charAt(0) == 'u') - ss = ss.substring(1); - - if (super.isObjCppPrimitive(ss)) - return true; - } - - return openclPrimitives.contains(s); - } - - }; - declarationsConverter = new JNADeclarationsConverter(this) { - - @Override - public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, int unused) { - if (isCallback) - return; - - if (!result.config.functionsAccepter.adapt(function)) - return; - - List args = function.getArgs(); - List convArgs = new ArrayList(args.size()); - String queueName = "commandQueue"; - convArgs.add(new Arg(queueName, typeRef(CLQueue.class))); - List convArgExpr = new ArrayList(args.size()); - List extraStatements = new ArrayList(); - - int iArg = 1; - for (Arg arg : args) { - TypeRef tr = arg.createMutatedType(); - if (tr == null) - return; - - try { - tr = result.typeConverter.resolveTypeDef(tr, libraryClassName, true, false); - List mods = tr.getModifiers(); - - TypeRef convTr; - String argName = arg.getName() == null ? "arg" + iArg : arg.getName(); - Expression argExpr; - - if (ModifierType.__local.isContainedBy(mods)) { - argName += "LocalByteSize"; - //convTr = typeRef(Long.TYPE); - //argExpr = new Expression.New(typeRef(CLKernel.LocalSize.class), varRef(argName)); - convTr = typeRef(CLKernel.LocalSize.class); - argExpr = varRef(argName);//new Expression.New(typeRef(CLKernel.LocalSize.class), varRef(argName)); - } else { - Conversion conv = convertTypeToJavaCL(result, argName, tr, TypeConversion.TypeConversionMode.PrimitiveOrBufferParameter, null); - convTr = conv.outerJavaTypeRef; - argExpr = conv.convertedExpr; - extraStatements.addAll(conv.extraStatements); - //String convTrStr = convTr.toString(); - /*if (convTrStr.equals(NativeSize.class.getName()) || convTrStr.equals(NativeLong.class.getName())) - argExpr = new Expression.New(tr, varRef(conv.argName)); - else - argExpr = varRef(ident(argName));*/ - } - - convArgs.add(new Arg(argName, convTr)); - - convArgExpr.add(argExpr);//varRef(argName)); - - } catch (UnsupportedConversionException ex) { - out.addDeclaration(skipDeclaration(function, ex.toString())); - } - iArg++; - } - - String globalWSName = "globalWorkSizes", localWSName = "localWorkSizes", eventsName = "eventsToWaitFor"; - convArgs.add(new Arg(globalWSName, typeRef(int[].class))); - convArgs.add(new Arg(localWSName, typeRef(int[].class))); - convArgs.add(new Arg(eventsName, typeRef(CLEvent.class)).setVarArg(true)); - - String functionName = function.getName().toString(); - String kernelVarName = functionName + "_kernel"; - if (signatures.addVariable(kernelVarName)) - out.addDeclaration(new VariablesDeclaration(typeRef(CLKernel.class), new Declarator.DirectDeclarator(kernelVarName))); - Function method = new Function(Function.Type.JavaMethod, ident(functionName), typeRef(CLEvent.class)); - method.addModifiers(ModifierType.Public, ModifierType.Synchronized); - method.addThrown(typeRef(CLBuildException.class)); - - method.setArgs(convArgs); - List statements = new ArrayList(); - statements.add( - new Statement.If( - expr(varRef(kernelVarName), Expression.BinaryOperator.IsEqual, new Expression.NullExpression()), - stat( - expr( - varRef(kernelVarName), Expression.AssignmentOperator.Equal, - methodCall( - "createKernel", - new Expression.Constant(Expression.Constant.Type.String, functionName, null) - ) - ) - ), - null - ) - ); - statements.addAll(extraStatements); - statements.add( - stat(methodCall( - varRef(kernelVarName), - Expression.MemberRefStyle.Dot, - "setArgs", - convArgExpr.toArray(new Expression[convArgExpr.size()]) - )) - ); - statements.add( - new Statement.Return(methodCall( - varRef(kernelVarName), - Expression.MemberRefStyle.Dot, - "enqueueNDRange", - varRef(queueName), - varRef(globalWSName), - varRef(localWSName), - varRef(eventsName) - )) - ); - method.setBody(block(statements.toArray(new Statement[statements.size()]))); - if (signatures.addMethod(method)) - out.addDeclaration(method); - } - }; - globalsGenerator = new JNAGlobalsGenerator(this); - objectiveCGenerator = new ObjectiveCGenerator(this); - universalReconciliator = new UniversalReconciliator(); - } - - }; - } - - static class CLPrim { - TypeConversion.JavaPrimitive javaPrim; - int arity; - boolean isLong, isShort; - Expression assertExpr; - Statement checkStatement; - Expression convertStatement; - Class argClass; - - public CLPrim(JavaPrimitive javaPrim, int arity) { - this.javaPrim = javaPrim; - this.arity = arity; - } - - static Pattern patt = Pattern.compile("(?:(long|short)\\s+)?(float|double|u?(?:char|long|short|int))(\\d)"); - public static CLPrim parse(Result result, TypeRef tr) { - String s = tr.toString(); - if (s == null || s.length() == 0) - return null; - char c = s.charAt(s.length() - 1); - if (!Character.isDigit(c)) { - //JavaPrim prim = result.typeConverter.getPrimitive( - return null; - } - String[] m = RegexUtils.match(tr.toString(), patt); - if (m == null) - return null; - - - //boolean isShort = false, - //result.typeConverter - return null; - } - } - - static class Conversion { - TypeRef outerJavaTypeRef; - Expression convertedExpr; - String argName; - List extraStatements = new ArrayList(); - } - static Map>> buffersAndArityByType = new HashMap>>(); - static Map>> arraysAndArityByType = new HashMap>>(); - static { - Object[] data = new Object[] { - "char", Byte.TYPE, byte[].class, Byte.class, - "long", Long.TYPE, long[].class, Long.class, - "int", Integer.TYPE, int[].class, Integer.class, - "short", Short.TYPE, short[].class, Short.class, - "wchar_t", Character.TYPE, char[].class, Short.class, - "double", Double.TYPE, double[].class, Double.class, - "float", Float.TYPE, float[].class, Float.class, - "bool", Boolean.TYPE, boolean[].class, Boolean.class - }; - for (int arity : new int[] { 1, 2, 4, 8, 16 }) { - String suffix = arity == 1 ? "" : arity +""; - for (int i = 0; i < data.length; i += 4) { - String rawType = (String)data[i]; - Class scalClass = (Class)data[i + 1]; - Class arrClass = (Class)data[i + 2]; - Class buffClass = (Class)data[i + 3]; - - Pair> - buffPair = new Pair>(arity, buffClass), - arrPair = new Pair>(arity, arity == 1 ? scalClass : arrClass); - - for (String type : new String[] { rawType + suffix, "u" + rawType + suffix}) { - buffersAndArityByType.put(type, buffPair); - arraysAndArityByType.put(type, arrPair); - } - } - } - } - private Conversion convertTypeToJavaCL(Result result, String argName, TypeRef valueType, TypeConversionMode typeConversionMode, Identifier libraryClassName) throws UnsupportedConversionException { - Conversion ret = new Conversion(); - ret.argName = argName; - ret.convertedExpr = varRef(argName); - - if (valueType instanceof TypeRef.Pointer) { - TypeRef target = ((TypeRef.Pointer)valueType).getTarget(); - if (target instanceof TypeRef.SimpleTypeRef) { - TypeRef.SimpleTypeRef starget = (TypeRef.SimpleTypeRef)target; - - Pair> pair = buffersAndArityByType.get(starget.getName().toString()); - if (pair != null) { - ret.outerJavaTypeRef = typeRef(ident(CLBuffer.class, expr(typeRef(pair.getSecond())))); - return ret; - } - } - } else if (valueType instanceof TypeRef.SimpleTypeRef) { - TypeRef.SimpleTypeRef sr = (TypeRef.SimpleTypeRef)valueType; - String name = sr.getName() == null ? sr.toString() : sr.getName().toString(); - if (name.equals("size_t")) { - ret.outerJavaTypeRef = typeRef(Long.TYPE); - ret.convertedExpr = new Expression.New(typeRef(NativeSize.class), ret.convertedExpr); - return ret; - } else { - Pair> pair = arraysAndArityByType.get(name); - if (pair != null) { - ret.outerJavaTypeRef = typeRef(pair.getSecond()); - if (pair.getFirst().intValue() != 1) { - ret.extraStatements.add( - stat( - methodCall( - "checkArrayLength", - varRef(ret.argName), - expr( - Expression.Constant.Type.Int, - pair.getFirst() - ), - expr( - Expression.Constant.Type.String, - ret.argName - ) - ) - ) - ); - } - return ret; - } - } - } - throw new UnsupportedConversionException(valueType, "Unhandled type : " + valueType); - } - - @Override - protected void generateLibraryFiles(SourceFiles sourceFiles, Result result) throws IOException { - //super.generateLibraryFiles(sourceFiles, result); - for (SourceFile sourceFile : sourceFiles.getSourceFiles()) { - String rawSrcFilePath = new File(sourceFile.getElementFile()).getCanonicalPath(); - String srcFilePath = result.config.relativizeFileForSourceComments(rawSrcFilePath); - File srcFile = new File(srcFilePath); - String srcParent = srcFile.getParent(); - String srcFileName = srcFile.getName(); - String[] nameExt = RegexUtils.match(srcFileName, nameExtPatt); - if (nameExt == null) - continue; - String name = nameExt[1], ext = nameExt[2]; - if (!ext.equals("c") && !ext.equals("cl")) - continue; - - String packageName = srcParent == null || srcParent.length() == 0 ? null : srcParent.replace('/', '.').replace('\\', '.'); - Identifier packageIdent = ident(packageName); - String className = (packageName == null ? "" : packageName + ".") + name; - - - Struct interf = new Struct(); - interf.addToCommentBefore("Wrapper around the OpenCL program " + name); - interf.addModifiers(ModifierType.Public); - interf.setTag(ident(name)); - interf.addParent(ident(CLAbstractUserProgram.class)); - interf.setType(Struct.Type.JavaClass); - - String[] constrArgNames = new String[] { "context", "program" }; - Class[] constrArgTypes = new Class[] { CLContext.class, CLProgram.class }; - for (int i = 0; i < constrArgNames.length; i++) { - String argName = constrArgNames[i]; - - Function constr = new Function(Function.Type.JavaMethod, ident(name), null, new Arg(argName, typeRef(constrArgTypes[i]))); - constr.addModifiers(ModifierType.Public); - constr.addThrown(typeRef(IOException.class)); - constr.setBody( - block( - stat( - methodCall( - "super", - varRef(argName), - methodCall( - "readRawSourceForClass", - result.typeConverter.typeLiteral(typeRef(name)) - ) - ) - ) - ) - ); - interf.addDeclaration(constr); - } - - //result.declarationsConverter.convertStructs(null, null, interf, null) - Signatures signatures = new Signatures();//result.getSignaturesForOutputClass(fullLibraryClassName); - result.typeConverter.allowFakePointers = true; - String library = name; - Identifier fullLibraryClassName = ident(className); - result.declarationsConverter.convertStructs(result.structsByLibrary.get(library), signatures, interf, fullLibraryClassName, library); - //result.declarationsConverter.convertCallbacks(result.callbacksByLibrary.get(library), signatures, interf, fullLibraryClassName); - - int declCount = interf.getDeclarations().size(); - result.declarationsConverter.convertFunctions(result.functionsByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertEnums(result.enumsByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertConstants(library, result.definesByLibrary.get(library), sourceFiles, signatures, interf, fullLibraryClassName); - - boolean hasKernels = interf.getDeclarations().size() > declCount; - if (!hasKernels) - continue; - - //for () - - /* - public SampleUserProgram(CLContext context) throws IOException { - super(context, readRawSourceForClass(SampleUserProgram.class)); - }*/ - - - for (Set set : macrosByFile.values()) { - for (String macroName : set) { - if (macroName.equals("__LINE__") || - macroName.equals("__FILE__") || - macroName.equals("__COUNTER__") || - config.preprocessorConfig.macros.containsKey(macroName)) - continue; - - String[] parts = macroName.split("_+"); - List newParts = new ArrayList(parts.length); - for (String part : parts) { - if (part == null || (part = part.trim()).length() == 0) - continue; - newParts.add(StringUtils.capitalize(part)); - } - String functionName = "define" + StringUtils.implode(newParts, ""); - Function macroDef = new Function(Function.Type.JavaMethod, ident(functionName), typeRef("void")); - String valueName = "value"; - macroDef.addArg(new Arg(valueName, typeRef(String.class))); - macroDef.setBody(block(stat(methodCall("defineMacro", expr(Expression.Constant.Type.String, macroName), varRef(valueName))))); - interf.addDeclaration(macroDef); - } - } - - PrintWriter out = result.classOutputter.getClassSourceWriter(className); - result.printJavaClass(packageIdent, interf, out); - //if (packageName != null) - // out.println("package " + packageName + ";"); - //out.println(interf); - out.close(); - } - } - - - @Override - protected void autoConfigure() { - super.autoConfigure(); - - /* - __OPENCL_VERSION__ - __ENDIAN_LITTLE__ - - __IMAGE_SUPPORT__ - __FAST_RELAXED_MATH__ - */ - - } - - public static void main(String[] args) { - JNAerator.main(new JavaCLGenerator(new JNAeratorConfig()), - new String[] { - "-o", "target/generated-sources/main/java", - //"-o", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/generated-sources/main/java", - "-noJar", - "-noComp", - "-v", - "-addRootDir", "src/main/opencl", - "src/main/opencl", - //"-addRootDir", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Blas/target/../src/main/opencl", - //"/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Blas/src/main/opencl/com/nativelibs4java/opencl/blas/LinearAlgebraKernels.c" - //"-addRootDir", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/../src/main/opencl", - //"/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/../src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl" - } - ); - } -} - diff --git a/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java b/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java deleted file mode 100644 index bc4e49733..000000000 --- a/libraries/OpenCL-JNA/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.generator; - -import com.ochafik.io.IOUtils; -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.JNAeratorConfig; -import com.ochafik.lang.jnaerator.JNAeratorConfig.OutputMode; -import com.ochafik.lang.jnaerator.SourceFiles; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.project.MavenProject; -import org.apache.maven.plugin.MojoExecutionException; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.*; -import java.util.ArrayList; -import org.apache.maven.model.Resource; - -/** - * Launch JNAerator to wrap native libraries in Java for use with JNA. - * @goal compile - * @phase generate-sources - * @execute phase=generate-sources - * @description Launches JNAerator with the command-line arguments contained in src/main/jnaerator/config.jnaerator. To launch from command line, use "mvn com.jnaerator:maven-jnaerator:jnaerate" - */ -public class JavaCLGeneratorMojo - extends AbstractMojo -{ - /** - * Configuration file for JNAerator. - * @parameter expression="${project.build.directory}/../src/main/jnaerator/config.jnaerator" - * @required - */ - //private File config; - - /** - * OpenCL sources tree. - * @parameter expression="${project.build.directory}/../src/main/opencl" - * @required - */ - private File sourcesDirectory; - - /** - * OpenCL test sources tree. - * @parameter expression="${project.build.directory}/../src/test/opencl" - * @required - */ - private File testSourcesDirectory; - - /** - * Output directory for JNAerated Java sources. - * @parameter expression="${project.build.directory}/generated-sources/main/java" - * @optional - */ - private File javaOutputDirectory; - - /** - * Output directory for JNAerated Java test sources. - * @parameter expression="${project.build.directory}/generated-sources/test/java" - * @optional - */ - private File testJavaOutputDirectory; - - /** - * Output directory for OpenCL sources. - * @parameter expression="${project.build.directory}/generated-resources/" - * @optional - */ - private File openCLOutputDirectory; - - /** - * Output directory for OpenCL test sources. - * @parameter expression="${project.build.directory}/generated-test-resources/" - * @optional - */ - private File testOpenCLOutputDirectory; - - /** - * @parameter expression="${project}" - * @required - * @readonly - * @since 1.0 - */ - private MavenProject project; - - - static File canonizeDir(File f) throws IOException { - if (!f.exists()) - f.mkdirs(); - return f.getCanonicalFile(); - } - - static void listOpenCLFiles(File f, Collection out) { - if (f.isHidden()) - return; - - String n = f.getName().toLowerCase(); - if (f.isDirectory()) { - if (n.equals(".svn")) - return; - - for (File ff : f.listFiles()) - listOpenCLFiles(ff, out); - } else { - if (n.endsWith(".c") || n.endsWith(".cl") || n.endsWith(".opencl")) - out.add(f); - } - } - - public void generateAll(File root, File javaOutDir, File openCLOutDir) throws IOException, MojoExecutionException { - List sources = new ArrayList(); - root = root.getCanonicalFile(); - listOpenCLFiles(root, sources); - - getLog().info("Found " + sources.size() + " files in " + root); - String rootPath = root.getCanonicalPath(); - String openCLOutPath = openCLOutDir.getCanonicalPath(); - String javaOutPath = javaOutDir.getCanonicalPath(); - for (File file : sources) { - final JNAeratorConfig config = new JNAeratorConfig(); - config.autoConf = true; - config.forceOverwrite = true; - config.outputMode = OutputMode.Directory; - config.outputJar = null; - if (!javaOutDir.exists()) - javaOutDir.mkdirs(); - config.outputDir = javaOutDir; - config.addSourceFile(file, null, false, true); - config.addRootDir(root); - - final String fileName = file.getName(); - String filePath = file.getCanonicalPath(); - File openCLOutFile = new File(openCLOutPath + filePath.substring(rootPath.length())); - - int i = filePath.lastIndexOf("."); - File javaOutFile = new File(javaOutPath + filePath.substring(rootPath.length(), i) + ".java"); - if (javaOutFile.exists() && javaOutFile.lastModified() > file.lastModified()) { - getLog().info("File " + fileName + " is up-to-date. Skipping generation."); - continue; - } - - File openCLOutParent = openCLOutFile.getParentFile(); - if (!openCLOutParent.exists()) - openCLOutParent.mkdirs(); - - getLog().info("Copying " + file + " to " + openCLOutFile); - FileWriter out = new FileWriter(openCLOutFile); - FileReader in = new FileReader(file); - IOUtils.readWrite(in, out); - out.close(); - in.close(); - - JavaCLGenerator generator = new JavaCLGenerator(config); - final Throwable[] ex = new Throwable[1]; - generator.jnaerate(new Feedback() { - - @Override - public void setStatus(String string) { - if (config.verbose) - getLog().info(string); - } - - @Override - public void setFinished(Throwable e) { - getLog().info("JNAeration failed !"); - e.printStackTrace(); - ex[0] = e; - } - - @Override - public void setFinished(File toOpen) { - getLog().info("JNAeration of " + fileName + " completed in " + toOpen.getAbsolutePath()); - } - - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - - } - - @Override - public void wrappersGenerated( - com.ochafik.lang.jnaerator.Result result) { - } - }); - if (ex[0] != null) - throw new MojoExecutionException( "Error JNAerating " + fileName, ex[0]); - } - } - public void execute() - throws MojoExecutionException - { - try - { - project.addCompileSourceRoot(javaOutputDirectory.getAbsolutePath()); - project.addTestCompileSourceRoot(testJavaOutputDirectory.getAbsolutePath()); - - Resource res = new Resource(); - res.setDirectory(openCLOutputDirectory.getAbsolutePath()); - project.addResource(res); - - res = new Resource(); - res.setDirectory(testOpenCLOutputDirectory.getAbsolutePath()); - project.addTestResource(res); - - generateAll(sourcesDirectory, javaOutputDirectory, openCLOutputDirectory); - generateAll(testSourcesDirectory, testJavaOutputDirectory, testOpenCLOutputDirectory); - } - catch (MojoExecutionException e ) - { - throw e; - } - catch (Exception e ) - { - throw new MojoExecutionException( "Error running JNAerator", e ); - } - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/.gitignore b/libraries/OpenCL-JNA/InteractiveImageDemo/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/pom.xml b/libraries/OpenCL-JNA/InteractiveImageDemo/pom.xml deleted file mode 100644 index 19ad19ffd..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-interactive-image-demo-jna - JavaCL Interactive Image Demo / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - com.nativelibs4java.opencl.demos.interactiveimage.InteractiveImageDemo - - - - - - com.nativelibs4java - javacl-core-jna - - - com.nativelibs4java - javacl-demos-jna - - - com.nativelibs4java - libcl - - - com.nativelibs4java - ochafik-swing - ${jnaerator.version} - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/project/build.properties b/libraries/OpenCL-JNA/InteractiveImageDemo/project/build.properties deleted file mode 100644 index faa423a6d..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/project/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -#Project properties -#Fri Dec 17 13:30:54 CET 2010 -project.organization=com.nativelibs4java -project.name=javacl-interactive-image-demo -sbt.version=0.7.4 -project.version=1.0-SNAPSHOT -build.scala.versions=2.8.1 -project.initialize=false diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala b/libraries/OpenCL-JNA/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala deleted file mode 100644 index f127dd3fe..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala +++ /dev/null @@ -1,12 +0,0 @@ -import sbt._ - -class InteractiveImageDemoProject(info: ProjectInfo) extends DefaultProject(info) with AutoCompilerPlugins -{ - val nativelibs4javaRepo = "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - - val jnaeratorVersion = "0.9.6-SNAPSHOT" - val javaclVersion = "1.0-SNAPSHOT" - - val javacl = "com.nativelibs4java" % "javacl" % javaclVersion - val ochafikSwing = "com.ochafik" % "ochafik-swing" % jnaeratorVersion -} diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java deleted file mode 100644 index 3d3373c9e..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java +++ /dev/null @@ -1,554 +0,0 @@ -package com.nativelibs4java.opencl.demos.interactiveimage; - -import com.nativelibs4java.opencl.demos.SetupUtils; -import java.awt.dnd.DropTarget; -import java.net.MalformedURLException; -import java.awt.datatransfer.DataFlavor; -import java.awt.Image; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.dnd.DropTargetEvent; -import java.awt.dnd.DnDConstants; -import java.awt.datatransfer.Transferable; -import java.awt.dnd.DropTargetDragEvent; -import java.awt.dnd.DropTargetListener; -import java.awt.Dimension; -import java.awt.Point; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.nativelibs4java.opencl.*; -import com.ochafik.io.ReadText; -import com.ochafik.io.WriteText; -import javax.swing.*; -import java.awt.event.*; -import javax.imageio.*; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.image.*; -import java.io.*; -import java.awt.FileDialog; -import java.util.*; - -import com.ochafik.swing.UndoRedoUtils; -import com.ochafik.swing.syntaxcoloring.TokenMarker; -import com.ochafik.swing.syntaxcoloring.CCTokenMarker; -import com.ochafik.swing.syntaxcoloring.JEditTextArea; -import com.ochafik.util.SystemUtils; - -import static com.nativelibs4java.opencl.demos.interactiveimage.Utils.*; - -/** -mvn compile exec:java -Dexec.mainClass=com.nativelibs4java.opencl.demos.interactiveimage.InteractiveImageDemo -*/ -public class InteractiveImageDemo extends JPanel { - JSplitPane imgSrcSplitPane, imgsSplitPane; - JLabel origImgLab, resultImgLab, instructionsLabel, timeLabel, progressLabel; - JScrollPane origImgScroll, resultImgScroll; - - JEditTextArea sourceTextArea; - JComboBox devicesCombo, examplesCombo; - //JTextArea sourceTextArea; - - JButton runButton; - BufferedImage image, result; - JProgressBar progressBar; - - JComponent[] toDisable; - File lastOpenedFile; - - static final String RUN_ACTION = "run", SAVE_ACTION = "save"; - File persistentFile = new File(new File(new File(System.getProperty("user.home"), ".javacl"), getClass().getSimpleName()), "Test.cl"); - - boolean load() { - if (!persistentFile.exists()) - return false; - - sourceTextArea.setText(ReadText.readText(persistentFile)); - return true; - } - void save() { - try { - WriteText.writeText(sourceTextArea.getText(), persistentFile); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(this, traceToHTML(ex), "Failed to save file", JOptionPane.ERROR_MESSAGE); - } - } - class SaveAction extends AbstractAction { - public void actionPerformed(ActionEvent e) { - save(); - } - } - void run() { - save(); - try { - final BufferedImage bufferedImage = getImage(); - if (bufferedImage == null) - return; - - // Could just be this : final CLContext context = JavaCL.createBestContext(); - final CLContext context = getContext(); - if (context == null) - return; - - final Point initialViewPosition = origImgScroll.getViewport().getViewPosition(); - - for (JComponent c : toDisable) - c.setEnabled(false); - resultImgLab.setText(null); - resultIcon(null); - resultImgLab.setToolTipText(null); - result = null; - timeLabel.setVisible(false); - progressBar.setIndeterminate(true); - progressBar.setVisible(true); - setProgress("Initializing..."); - - final long[] elapsedTimeNanos = new long[] { -1L }; - new Thread() { public void run() { - try { - setProgress("Creating OpenCL queue..."); - CLQueue queue = context.createDefaultQueue(); - setProgress("Compiling program..."); - CLProgram program = context.createProgram(sourceTextArea.getText()); - CLKernel[] kernels = program.createKernels(); - if (kernels.length == 0) - throw new RuntimeException("No kernels found in the source code ! (please mark a function with __kernel)"); - - setProgress("Creating OpenCL images..."); - int width = bufferedImage.getWidth(), height = bufferedImage.getHeight(); - CLImage2D imageIn = context.createImage2D(CLMem.Usage.InputOutput, bufferedImage, false); - CLImage2D imageOut = context.createImage2D(CLMem.Usage.InputOutput, imageIn.getFormat(), width, height); - - long startTimeNanos = System.nanoTime(); - CLEvent lastEvent = null; - CLImage2D finalImageOut = null; - for (CLKernel kernel : kernels) { - setProgress("Running kernel '" + kernel.getFunctionName() + "'..."); - try { - kernel.setArgs(imageIn, imageOut); - finalImageOut = imageOut; - imageOut = imageIn; - imageIn = finalImageOut; - lastEvent = kernel.enqueueNDRange(queue, new int[] { width, height }, lastEvent); - } catch (CLException ex) { - throw new RuntimeException("Error occurred while running kernel '" + kernel.getFunctionName() + "': " + ex, ex); - } - } - lastEvent.waitFor(); - elapsedTimeNanos[0] = System.nanoTime() - startTimeNanos; - - setProgress("Reading the image output..."); - result = finalImageOut.read(queue); - - imageIn.release(); - imageOut.release(); - for (CLKernel kernel : kernels) - kernel.release(); - program.release(); - queue.release(); - - SwingUtilities.invokeLater(new Runnable() { public void run() { - resultIcon(result == null ? null : new ImageIcon(result)); - resultImgLab.setToolTipText(result == null ? null : "Click to save this image"); - - SwingUtilities.invokeLater(new Runnable() { public void run() { - origImgScroll.getViewport().setViewPosition(initialViewPosition); - }}); - }}); - } catch (Exception ex) { - ex.printStackTrace(); - resultError(ex); - } finally { - SwingUtilities.invokeLater(new Runnable() { public void run() { - setProgress(null); - - for (JComponent c : toDisable) - c.setEnabled(true); - progressBar.setIndeterminate(false); - progressBar.setVisible(false); - if (elapsedTimeNanos[0] >= 0) { - timeLabel.setText("Completed in " + (elapsedTimeNanos[0] / 1000000.0) + " msecs"); - timeLabel.setVisible(true); - } - }}); - } - }}.start(); - } catch (Exception ex) { - ex.printStackTrace(); - resultError(ex); - } - } - class RunAction extends AbstractAction { - public void actionPerformed(ActionEvent e) { - run(); - } - } - - String runKeyStroke = "F5"; - - int spacing = 10; - - class Example { - public Example(String caption, String fileName) { - this.fileName = fileName; - this.caption = caption; - } - public final String fileName, caption; - @Override - public String toString() { - return caption; - } - - } - public InteractiveImageDemo() { - super(new BorderLayout()); - - devicesCombo = new JComboBox(); - List devices = new ArrayList(); - try { - for (CLPlatform platform : JavaCL.listPlatforms()) { - for (CLDevice device : platform.listAllDevices(true)) { - devicesCombo.addItem(device); - devices.add(device); - } - } - if (!devices.isEmpty()) - devicesCombo.setSelectedItem(CLPlatform.getBestDevice(Arrays.asList(CLPlatform.DeviceFeature.MaxComputeUnits), devices)); - } catch (Exception ex) { - ex.printStackTrace(); - devicesCombo.setToolTipText(traceToHTML(ex)); - } - if (devices.isEmpty()) { - devicesCombo.addItem("No OpenCL Device detected"); - } - - examplesCombo = new JComboBox(); - examplesCombo.addItem("Examples..."); - { - final String signature = "__kernel void transform(__global read_only image2d inputImage, __global write_only image2d outputImage)"; - - examplesCombo.setToolTipText("Kernel samples in the form of :\n'" + signature + "'"); - for (Example example : new Example[] { - //"Blur", - new Example("Convolution", "Convolution"), - new Example("Sobel Operator", "SobelFilter"), - new Example("Desaturate Colors", "DesaturateColors"), - new Example("Richardson-Lucy Deconvolution", "RichardsonLucyDeconvolution"), - new Example("Luminance Threshold", "LuminanceThreshold"), - new Example("Naive Denoising", "NaiveDenoising"), - new Example("Identity", "Identity"), - new Example("Image Info", "QueryFormat") - }) { - examplesCombo.addItem(example); - } - examplesCombo.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - String t = sourceTextArea.getText(); - if (t.trim().length() > 0) - t = t + "\n"; - sourceTextArea.setText(t + "__kernel " + signature + " {\n\tint x = get_global_id(0), y = get_global_id(1);\n\t// write here\n}"); - }}); - examplesCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { - Object selection = examplesCombo.getSelectedItem(); - if (selection instanceof Example) { - loadExample(((Example)selection).fileName); - examplesCombo.setSelectedIndex(0); - } - }}); - } - - JPanel srcPanel = new JPanel(new BorderLayout()); - sourceTextArea = textArea(new CCTokenMarker()); - srcPanel.add("Center", withTitle("Image transformation kernel source code", sourceTextArea)); - - runButton = new JButton("Run (" + runKeyStroke + ")"); - { - Box toolbar = Box.createHorizontalBox(); - for (JComponent c : new JComponent[] { examplesCombo, runButton, devicesCombo }) - c.setMaximumSize(c.getPreferredSize()); - - runButton.putClientProperty("JButton.buttonType", "bevel"); - examplesCombo.putClientProperty("JComboBox.isPopDown", Boolean.TRUE); - devicesCombo.putClientProperty("JComboBox.isPopDown", Boolean.TRUE); - - toolbar.add(examplesCombo); - toolbar.add(runButton); - toolbar.add(devicesCombo); - toolbar.add(createLinkLabel("Khronos OpenCL Documentation", "http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/")); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(createLinkLabel("JavaCL FAQ", "http://code.google.com/p/javacl/wiki/FAQ")); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(Box.createHorizontalGlue()); - toolbar.add(progressLabel = new JLabel()); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(progressBar = new JProgressBar()); - progressBar.putClientProperty("JProgressBar.style", "circular"); - toolbar.add(timeLabel = new JLabel()); - progressBar.setMaximumSize(progressBar.getPreferredSize()); - progressLabel.setVisible(false); - progressBar.setVisible(false); - timeLabel.setVisible(false); - srcPanel.add("South", toolbar); - } - origImgScroll = new JScrollPane(origImgLab = new JLabel()); - resultImgScroll = new JScrollPane(resultImgLab = new JLabel()); - for (JScrollPane sp : Arrays.asList(origImgScroll, resultImgScroll)) { - sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - } - resultVertScrollModel = resultImgScroll.getVerticalScrollBar().getModel(); - resultHorzScrollModel = resultImgScroll.getHorizontalScrollBar().getModel(); - - origImgLab.setDropTarget(new DropTarget(origImgLab, DnDConstants.ACTION_COPY, imgDropTargetListener)); - - add("Center", imgSrcSplitPane = new JSplitPane( - JSplitPane.VERTICAL_SPLIT, - imgsSplitPane = new JSplitPane( - JSplitPane.HORIZONTAL_SPLIT, - withTitle("Input", origImgScroll), - withTitle("Output", resultImgScroll) - ), - srcPanel - )); - imgSrcSplitPane.setResizeWeight(0.5); - imgsSplitPane.setResizeWeight(0.5); - - origImgLab.setToolTipText("Click to load a different image"); - origImgLab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - chooseImage(); - }}); - resultImgLab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - saveResult(); - }}); - - runButton.addActionListener(new RunAction()); - - toDisable = new JComponent[] { - examplesCombo, - runButton, - devicesCombo, - sourceTextArea, - //origImgLab, - resultImgLab - }; - - UndoRedoUtils.registerNewUndoManager(sourceTextArea, sourceTextArea.getDocument()); - for (JComponent focusable : Arrays.asList(sourceTextArea, examplesCombo, devicesCombo, runButton)) { - InputMap im = focusable.getInputMap(); - ActionMap am = focusable.getActionMap(); - im.put(KeyStroke.getKeyStroke(runKeyStroke), RUN_ACTION); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, isMac() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK), SAVE_ACTION); - am.put(RUN_ACTION, new RunAction()); - am.put(SAVE_ACTION, new SaveAction()); - } - } - - protected DropTargetListener imgDropTargetListener = new DropTargetListener() { - - public void dragEnter(DropTargetDragEvent dtde) { - try { - if ( - dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || - dtde.isDataFlavorSupported(DataFlavor.stringFlavor) || - dtde.isDataFlavorSupported(DataFlavor.imageFlavor)) - dtde.acceptDrag(DnDConstants.ACTION_COPY); - else - dtde.rejectDrag(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - dtde.acceptDrag(DnDConstants.ACTION_COPY); - } - public void dragExit(DropTargetEvent dte) {} - public void dragOver(DropTargetDragEvent dtde) {} - public void dropActionChanged(DropTargetDragEvent dtde) {} - public void drop(DropTargetDropEvent dtde) { - try { - if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - java.util.List files = (java.util.List)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); - if (files != null && !files.isEmpty()) { - readImage(files.get(0).toURI().toURL()); - } - dtde.dropComplete(true); - } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) { - try { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - readImage(new URL((String)dtde.getTransferable().getTransferData(DataFlavor.stringFlavor))); - dtde.dropComplete(true); - return ; - } catch (MalformedURLException ex) {} - } else if (dtde.isDataFlavorSupported(DataFlavor.imageFlavor)) { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - Image image = (Image)dtde.getTransferable().getTransferData(DataFlavor.imageFlavor); - if (image instanceof BufferedImage) - setImage((BufferedImage)image); - dtde.dropComplete(true); - return; - } - dtde.rejectDrop(); - } catch (Exception ex) { - origImgLab.setToolTipText(traceToHTML(ex)); - } - } - }; - BufferedImage getImage() { - if (image == null) - chooseImage(); - return image; - } - void readImage(URL url) { - try { - setImage(null); - - InputStream in = url.openStream(); - if (in == null) - return; - - lastOpenedFile = new File(url.getFile()); - setImage(ImageIO.read(in)); - - in.close(); - } catch (Exception ex) { - ex.printStackTrace(); - origImgLab.setText(traceToHTML(ex)); - } - } - void setImage(BufferedImage image) { - this.image = image; - origImgLab.setText(null); - origIcon(image == null ? null : new ImageIcon(image)); - } - void readImageResource(String name) { - readImage(getClass().getClassLoader().getResource("images/" + name)); - } - - void chooseImage() { - try { - File f = chooseFile(lastOpenedFile, true); - if (f == null) - return; - - readImage(f.toURI().toURL()); - } catch (Exception ex) { - ex.printStackTrace(); - origImgLab.setText(traceToHTML(ex)); - } - } - String getOutputFormat(File file) { - if (file != null) { - String s = file.getName().toLowerCase(); - if (s.matches(".*?\\.jpe?g")) - return "jpeg"; - for (String ex : new String[] { "png", "gif", "tiff", "pnm", "pbm" }) - if (s.matches(".*?\\." + ex)) - return ex; - } - return "png"; - } - static Pattern fileExtRx = Pattern.compile("(.*?)(\\.[^.]+)?"); - void saveResult() { - if (result == null) - return; - - try { - File f = null; - if (lastOpenedFile != null) { - Matcher matcher = fileExtRx.matcher(lastOpenedFile.getName()); - if (matcher.matches()) { - String body = matcher.group(1); - String ext = matcher.group(2); - f = new File(lastOpenedFile.getParentFile(), body + ".transformed" + (ext == null ? ".png" : ext)); - } - } - - f = chooseFile(f, false); - if (f == null) - return; - - ImageIO.write(result, getOutputFormat(f), f); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(this, traceToHTML(ex), "Failed to write image", JOptionPane.ERROR_MESSAGE); - } - } - CLContext getContext() { - Object selection = devicesCombo.getSelectedItem(); - if (!(selection instanceof CLDevice)) - return null; - - CLDevice device = (CLDevice)selection; - CLContext context = JavaCL.createContext(null, device); - return context; - } - void setProgress(final String caption) { - System.out.println(caption); - SwingUtilities.invokeLater(new Runnable() { public void run() { - //progressLabel.setVisible(caption != null); - //progressLabel.setText(caption); - if (!isMac()) { - progressBar.setStringPainted(caption != null); - progressBar.setString(caption); - } - progressBar.setToolTipText(caption); - }}); - } - BoundedRangeModel resultVertScrollModel, resultHorzScrollModel; - void resultIcon(Icon icon) { - if (icon == null) { - resultImgScroll.getVerticalScrollBar().setModel(resultVertScrollModel); - resultImgScroll.getHorizontalScrollBar().setModel(resultHorzScrollModel); - } else { - resultImgScroll.getVerticalScrollBar().setModel(origImgScroll.getVerticalScrollBar().getModel()); - resultImgScroll.getHorizontalScrollBar().setModel(origImgScroll.getHorizontalScrollBar().getModel()); - } - resultImgLab.setIcon(icon); - } - void origIcon(Icon icon) { - origImgLab.setIcon(icon); - SwingUtilities.invokeLater(new Runnable() { public void run() { - JScrollBar bar; - BoundedRangeModel model; - model = (bar = origImgScroll.getVerticalScrollBar()).getModel(); - model.setValue((model.getMinimum() + model.getMaximum()) / 2); - model = (bar = origImgScroll.getHorizontalScrollBar()).getModel(); - model.setValue((model.getMinimum() + model.getMaximum()) / 2); - - }}); - } - void resultError(Exception ex) { - String html = traceToHTML(ex); - resultIcon(null); - resultImgLab.setText(html); - resultImgLab.setToolTipText(html); - } - void loadExample(String fileName) { - try { - String s = readTextResource("examples/" + fileName + ".cl"); - sourceTextArea.setText(s); - sourceTextArea.setCaretPosition(0); - } catch (Exception ex) { - ex.printStackTrace(); - sourceTextArea.setText("Failed to load example '" + fileName + "' :\n" + traceToString(ex)); - } - } - public static void main(String[] args) { - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - JFrame f = new JFrame("JavaCL's Interactive Image Transform Demo"); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - InteractiveImageDemo demo = new InteractiveImageDemo(); - f.getContentPane().add("Center", demo); - f.setSize(1200, 800); - f.setVisible(true); - - demo.getContext(); - demo.readImageResource("lena.jpg"); - if (!demo.load()) - demo.loadExample("Convolution"); - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java deleted file mode 100644 index 897f4a657..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.nativelibs4java.opencl.demos.interactiveimage; - -import com.nativelibs4java.opencl.*; -import javax.swing.*; -import java.awt.event.*; -import javax.imageio.*; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.image.*; -import java.io.*; -import java.awt.FileDialog; -import java.util.*; - -import com.ochafik.swing.UndoRedoUtils; -import com.ochafik.swing.syntaxcoloring.TokenMarker; -import com.ochafik.swing.syntaxcoloring.CCTokenMarker; -import com.ochafik.swing.syntaxcoloring.JEditTextArea; -import com.ochafik.util.SystemUtils; -import java.net.URL; - -class Utils { - public static C withTitle(String title, C c) { - c.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title), BorderFactory.createLoweredBevelBorder())); - return c; - } - public static JLabel createLinkLabel(String caption, final String urlString) { - final JLabel[] lab = new JLabel[1]; - JLabel ret = lab[0] = createLinkLabel(caption, new Runnable() { public void run() { - try { - SystemUtils.runSystemOpenURL(new URL(urlString)); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(lab[0], traceToHTML(ex), "Failed to open URL", JOptionPane.ERROR_MESSAGE); - } - }}); - ret.setToolTipText(urlString); - return ret; - } - public static JLabel createLinkLabel(String caption, final Runnable action) { - JLabel lab = new JLabel("" + caption + ""); - lab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - lab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - action.run(); - }}); - lab.setMaximumSize(lab.getPreferredSize()); - return lab; - } - - public static boolean isMac() { - return System.getProperty("os.name").startsWith("Mac"); - } - public static File chooseFile(File initialFile, boolean load) { - if (isMac()) { - FileDialog d = new FileDialog((java.awt.Frame)null); - d.setMode(load ? FileDialog.LOAD : FileDialog.SAVE); - if (initialFile != null) { - d.setDirectory(initialFile.getParent()); - d.setFile(initialFile.getName()); - } - d.show(); - String f = d.getFile(); - if (f != null) - return new File(new File(d.getDirectory()), d.getFile()); - } else { - JFileChooser chooser = new JFileChooser(); - if (initialFile != null) - chooser.setSelectedFile(initialFile); - if ((load ? chooser.showOpenDialog(null) : chooser.showSaveDialog(null)) == JFileChooser.APPROVE_OPTION) - return chooser.getSelectedFile(); - } - return null; - } - - public static JEditTextArea textArea(TokenMarker marker) { - JEditTextArea ta = new JEditTextArea() { - private static final long serialVersionUID = 1L; -// int lastCode, lastLocation; -// char lastChar = 0; - - @Override - public void processKeyEvent(KeyEvent evt) { - if (isMac()) { - int m = evt.getModifiers(); - if ((m & InputEvent.META_MASK) != 0) { - m = (m & ~InputEvent.META_MASK) | InputEvent.CTRL_MASK; - evt = new KeyEvent(evt.getComponent(), evt.getID(), evt.getWhen(), m, evt.getKeyCode(), evt.getKeyChar(), evt.getKeyLocation()); - if (evt.getID() == KeyEvent.KEY_TYPED) - return; - } - } - - super.processKeyEvent(evt); - } - @Override - public Dimension getMinimumSize() { - return new Dimension(100, 100); - } - }; - ta.setBorder(BorderFactory.createLoweredBevelBorder()); - ta.setFocusTraversalKeysEnabled(false); - ta.addMouseWheelListener(mouseWheelListener); - ta.setPreferredSize(new Dimension(200, 300)); - ta.setTokenMarker(marker); - return ta; - } - static MouseWheelListener mouseWheelListener = new MouseWheelListener() { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - if (!(e.getSource() instanceof JEditTextArea)) - return; - - JEditTextArea ta = (JEditTextArea)e.getSource(); - - int line = ta.getFirstLine(); - if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { - int u = e.getUnitsToScroll(); - line += u > 0 ? 1 : -1; - if (line < 0) - line = 0; - else if (line >= ta.getLineCount()) - line = ta.getLineCount() - 1; - - ta.setFirstLine(line); - } - } - - }; - public static String traceToHTML(Exception ex) { - return "
    " + traceToString(ex).replaceAll("\n", "
    ") + "
    "; - } - - public static String traceToString(Exception ex) { - StringWriter sout = new StringWriter(); - PrintWriter pout = new PrintWriter(sout); - ex.printStackTrace(pout); - pout.close(); - return sout.toString(); - } - public static String readTextResource(String path) throws IOException { - InputStream in = Utils.class.getClassLoader().getResourceAsStream(path); - if (in == null) - throw new FileNotFoundException(path); - - BufferedReader rin = new BufferedReader(new InputStreamReader(in)); - String line; - StringBuilder b = new StringBuilder(); - while ((line = rin.readLine()) != null) { - b.append(line); - b.append("\n"); - } - return b.toString(); - } -} diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Blur.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Blur.cl deleted file mode 100644 index fd1dfdb73..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Blur.cl +++ /dev/null @@ -1,65 +0,0 @@ -/** - Blur example : naive square blur. - This example also demonstrates the chaining of multiple kernels (see commented code at the end). - Written by Olivier Chafik, no right reserved :-) */ - -void performBlur( - int blurSize, - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - float4 transformedPixel = (float4)0; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - int minDiff = -(blurSize - 1); - for (int dx = minDiff; dx < blurSize; dx++) { - for (int dy = minDiff; dy < blurSize; dy++) { - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx, y + dy)); - transformedPixel += pixel; - } - } - - int n = (2 * blurSize - 1); - n *= n; - - transformedPixel /= (float)n; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - const float matrix[] = { - 3.f, 0.f, -3.f, - 10.f, 0.f, -10.f, - 3.f, 0.f, -3.f, - }; - convolveImage(inputImage, matrix, 3, outputImage); -} - -// Perform a blur -__kernel void pass1(read_only image2d_t inputImage, write_only image2d_t outputImage) { - performBlur(10, inputImage, outputImage); -} - -/** - You can chain as many kernel calls as you want : - each new kernel takes the output of the previous one as input image. -*/ -/* -__kernel void pass2(read_only image2d_t inputImage, write_only image2d_t outputImage) { - performBlur(10, inputImage, outputImage); -} -*/ diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Convolution.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Convolution.cl deleted file mode 100644 index 6cb51dab3..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Convolution.cl +++ /dev/null @@ -1,45 +0,0 @@ -/** - Generic Convolution example with a 5x5 gaussian blur matrix. - This sample also shows how to chain two kernels, with a color to b&w conversion pass ready to be uncommented (see below). - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL's image convolution functions -// See sources here : http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" - -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float gaussian7x7Matrix[] = { - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00038771f, 0.01330373f, 0.11098164f, 0.22508352f, 0.11098164f, 0.01330373f, 0.00038771f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f -}; - - -__kernel void convolve( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - convolveFloatImage(inputImage, gaussian7x7Matrix, 7 /* matrixSize */, outputImage); -} - -// Uncomment this kernel to add a pass that transforms the image from color to gray levels : -/* -__kernel void toGray( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - float luminance = dot(pixel, (float4)(1, 1, 1, 0)) / 3; - write_imagef(outputImage, (int2)(x, y), (float4)(luminance, luminance, luminance, 1)); -} -*/ - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl deleted file mode 100644 index dde70d526..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl +++ /dev/null @@ -1,44 +0,0 @@ -/** - Color Desaturation example : make an image look more gray - Written by Olivier Chafik, no right reserved :-) */ - -void desaturate( - float greyFactor, - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // If the image is of type BGRA, UNormInt8, the pixel is in the form : - // (float4)(red, green, blue, alpha) with each component beinge [0.0f; 1.0f] interval. - - // Compute pixel luminance using a dot product, equivalent to the following two lines : - // float red = pixel.x, green = pixel.y, blue = pixel.z, alpha = pixel.w; - // float luminance = (red + green + blue) / 3; - float luminance = dot((float4)(1/3.f, 1/3.f, 1/3.f, 0), pixel); - - // Lower color saturation of pixel : - const float colorFactor = 1.f - greyFactor; - float4 transformedPixel = colorFactor * pixel + greyFactor * ((float4)(luminance, luminance, luminance, 1.f)); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - -__kernel void pass( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - desaturate(0.5f, inputImage, outputImage); -} - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DummySample.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DummySample.cl deleted file mode 100644 index 2fb843052..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/DummySample.cl +++ /dev/null @@ -1,33 +0,0 @@ -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = - CLK_NORMALIZED_COORDS_FALSE | - CLK_FILTER_NEAREST | - CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - __read_only image2d_t inputImage, - __write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_data_type.html - int channelDataType = get_image_channel_data_type(inputImage); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_order.html - int channelOrder = get_image_channel_order(inputImage); - - int x = get_global_id(0); - int y = get_global_id(1); - int2 coordinates = (int2)(x, y); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, coordinates); - - float4 transformedPixel = (float4)(0);//pixel; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, coordinates, transformedPixel); -} - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Identity.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Identity.cl deleted file mode 100644 index 295769ccb..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/Identity.cl +++ /dev/null @@ -1,32 +0,0 @@ -/** - Identity example : simply copy the input image into the output image. - Written by Olivier Chafik, no right reserved :-) */ - -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // If the image is of type BGRA / UNormInt8, each component is in the [0.0f; 1.0f] interval : - float red = pixel.x, green = pixel.y, blue = pixel.z, alpha = pixel.w; - - // Perform no transformation : - // float4 transformedPixel = pixel; - float4 transformedPixel = (float4)(red, green, blue, alpha); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl deleted file mode 100644 index 4e417b294..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl +++ /dev/null @@ -1,33 +0,0 @@ -/** - Image luminance threshold example : hide pixels that are not bright enough (with gaussian smoothing) - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" -#include "LibCL/SobelOperator.cl" -#include "LibCL/Gaussian7x7.cl" - -__kernel void imageThreshold( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // Get smoothed luminance (averaged from neighborhood with a gaussian) : - float luminance = convolveFloatImagePixelGray(inputImage, x, y, gaussian7x7Matrix, 7); - // Get exact local luminance : - // float luminance = dot((float4)(1/3.f, 1/3.f, 1/3.f, 0), pixel); - - float2 sobel = sobelOperatorRGBFloat(inputImage, x, y); - - float threshold = 0.3f; - if (luminance < threshold && (luminance * sobel.x) < threshold) - pixel.w = 0; // make these pixels transparent - - write_imagef(outputImage, (int2)(x, y), pixel); -} diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl deleted file mode 100644 index ff9087bfe..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl +++ /dev/null @@ -1,52 +0,0 @@ -/** - Naive denoising sample : - Transform RGB to HSL, replace L channel by local average if the sobel operator's value is not too high and the pixel L value is not too different. - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" -#include "LibCL/SobelOperator.cl" -#include "LibCL/rgba2hsla.cl" -#include "LibCL/hsla2rgba.cl" - -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float gaussian7x7Matrix[] = { - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00038771f, 0.01330373f, 0.11098164f, 0.22508352f, 0.11098164f, 0.01330373f, 0.00038771f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f -}; - -__kernel void imageThreshold( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - float sobel = fabs(sobelOperatorRGBFloat(inputImage, x, y).x); - float sobelThreshold = 0.05f; - float averageThreshold = 0.07f; - - if (sobel < sobelThreshold) { - // Get smoothed pixel (averaged from neighborhood with a gaussian) : - float4 averagePixelHSLA = rgba2hsla(convolveFloatImagePixel(inputImage, x, y, gaussian7x7Matrix, 7)); - float4 pixelHSLA = rgba2hsla(pixel); - - pixelHSLA.x = averagePixelHSLA.x; // avoid chromatic aberrations : unconditionally replace Hue channel - - float4 d = fabs(pixelHSLA - averagePixelHSLA); - if (d.x < averageThreshold && d.y < averageThreshold && d.z < averageThreshold) - pixelHSLA.z = averagePixelHSLA.z; // replace Luminance channel by average if it's not too far away - - pixel = hsla2rgba(pixelHSLA); - } - - write_imagef(outputImage, (int2)(x, y), pixel); -} diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl deleted file mode 100644 index e70b9b8ae..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl +++ /dev/null @@ -1,35 +0,0 @@ -/** - QueryFormat example : query image format dynamically inside the kernel - Written by Olivier Chafik, no right reserved :-) */ - -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_data_type.html - int channelDataType = get_image_channel_data_type(inputImage); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_order.html - int channelOrder = get_image_channel_order(inputImage); - - int x = get_global_id(0), y = get_global_id(1); - int2 coordinates = (int2)(x, y); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - //float4 pixel = read_imagef(inputImage, sampler, coordinates); - float4 pixel = read_imagef(inputImage, sampler, coordinates); - float4 transformedPixel = pixel; - //float4 transformedPixel = (float4)(0);//pixel; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, coordinates, transformedPixel); -} - - diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl deleted file mode 100644 index 1cac8ef3e..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl +++ /dev/null @@ -1,40 +0,0 @@ -/** - Deconvolution sample that uses the Richardson-Lucy algorithm. - Knowing the exact "point-spread function" that made an image blurry, this algorithm tries to restore - the original image. - If the point-spread function is not well known, the results aren't good ! - - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/RichardsonLucyImageDeconvolution.cl" - -// Gaussian point-spread function : -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float pointSpreadFunction7x7[] = { - 0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067, - 0.00002292, 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292, - 0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117, - 0.00038771, 0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373, 0.00038771, - 0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117, - 0.00002292, 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292, - 0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067 -}; - -// Blur the initial image -/* -__kernel void blur(read_only image2d_t inputImage, write_only image2d_t outputImage) { - convolveFloatImage(inputImage, pointSpreadFunction7x7, 7, outputImage); -} -*/ - -RICHARDSON_LUCY_DECONVOLUTION_PRE(pointSpreadFunction7x7, 7); - -// Chain a few deconvolution passes : -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 1); -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 2); -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 3); -//RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 4); - -RICHARDSON_LUCY_DECONVOLUTION_POST(); diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl deleted file mode 100644 index aac5facd5..000000000 --- a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl +++ /dev/null @@ -1,45 +0,0 @@ -/** - Sobel filter example : naive edge detection - This sample includes Sobel and Scharr operators, please see below. - See http://en.wikipedia.org/wiki/Sobel_operator - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" - -__constant float2 sobel3x3MatrixXY[] = { - (float2)(-1, -1), (float2)(0, -2), (float2)(1, -1), - (float2)(-2, 0), (float2)(0, 0), (float2)(2, 0), - (float2)(-1, 1), (float2)(0, 2), (float2)(1, 1) -}; -__constant float2 scharr3x3MatrixXY[] = { - (float2)(3, 3), (float2)(0, 10), (float2)(-3, 3), - (float2)(10, 0), (float2)(0, 0), (float2)(-10, 0), - (float2)(3, -3), (float2)(0, -10), (float2)(-3, -3) -}; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - float scaling = 0.3f; // you can adjust this - - // Sobel operator - float2 total = scaling * convolveFloatImagePixelGray2(inputImage, x, y, sobel3x3MatrixXY, 3); - - // Scharr operator (better rotational symmetry) : - // float2 total = scaling * convolveFloatImagePixelGray2(inputImage, x, y, scharr3x3MatrixXY, 3); - -#if 1 - float gradient = fast_length(total); - float value = gradient; -#else - float direction = atan2(total.y, total.x); - float value = direction; -#endif - - write_imagef(outputImage, (int2)(x, y), (float4)(value, value, value, 1.f)); -} diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/lena.jpg b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/lena.jpg deleted file mode 100644 index edac58885..000000000 Binary files a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/lena.jpg and /dev/null differ diff --git a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/mandrill.jpg b/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/mandrill.jpg deleted file mode 100644 index bf756e743..000000000 Binary files a/libraries/OpenCL-JNA/InteractiveImageDemo/src/main/resources/images/mandrill.jpg and /dev/null differ diff --git a/libraries/OpenCL-JNA/JavaCL/.gitignore b/libraries/OpenCL-JNA/JavaCL/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/JavaCL/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/JavaCL/pom.xml b/libraries/OpenCL-JNA/JavaCL/pom.xml deleted file mode 100644 index 336485736..000000000 --- a/libraries/OpenCL-JNA/JavaCL/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-jna - JavaCL / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - -JavaCL is an Object-Oriented API that makes the C OpenCL API available to Java in a very natural way. -It hides away the complexity of cross-platform C bindings, has a clean OO design (with generics, Java enums, NIO buffers, fully typed exceptions...), provides high-level features (OpenGL-interop, array reductions) and comes with samples and demos. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - com.nativelibs4java.opencl - - - - - - com.nativelibs4java - javacl-core-jna - - - org.apache.commons - commons-math - 2.2 - test - - - velocity - velocity - 1.5 - - - - - - - - com.nativelibs4java - javacl-generator-jna - - - - compile - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java deleted file mode 100644 index bf2edad4e..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLDoubleBuffer; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.ReductionUtils; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.IOUtils; -import com.ochafik.util.listenable.Pair; -import static com.nativelibs4java.util.NIOUtils.*; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unused") -public class LinearAlgebraUtils { - - final LinearAlgebraKernels kernels; - final CLQueue queue; - public LinearAlgebraUtils(boolean doubleCapable) throws IOException, CLBuildException { - this(JavaCL.createBestContext(doubleCapable ? DeviceFeature.DoubleSupport : null).createDefaultQueue()); - } - - public LinearAlgebraUtils(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - kernels = new LinearAlgebraKernels(queue.getContext()); - } - - public CLContext getContext() { - return getQueue().getContext(); - } - - public CLQueue getQueue() { - return queue; - } - - - public synchronized CLEvent multiply( - CLBuffer a, int aRows, int aColumns, - CLBuffer b, int bRows, int bColumns, - CLBuffer out, //long outRows, long outColumns, - CLEvent... eventsToWaitFor) throws CLBuildException - { - if (a.getBufferClass() == DoubleBuffer.class) - return multiplyDoubles((CLBuffer)a, aRows, aColumns, (CLBuffer)b, bRows, bColumns, (CLBuffer)out, eventsToWaitFor); - - throw new UnsupportedOperationException(); - } - public synchronized CLEvent multiplyDoubles( - CLBuffer a, int aRows, int aColumns, - CLBuffer b, int bRows, int bColumns, - CLBuffer out, //long outRows, long outColumns, - CLEvent... eventsToWaitFor) throws CLBuildException - { - if (a == null || b == null || out == null) - throw new IllegalArgumentException("Null matrix"); - - if (aColumns != bRows || out.getElementCount() != (aRows * bColumns)) - throw new IllegalArgumentException("Invalid matrix sizes : multiplying matrices of sizes (A, B) and (B, C) requires output of size (A, C)"); - - long outRows = aRows; - long outColumns = bColumns; - return kernels.mulMat(queue, - a, (int)aColumns, - b, (int)bColumns, - out, - new int[] { (int)outRows, (int)outColumns }, - null, - eventsToWaitFor - ); - } - - /*synchronized CLEvent dot(CLVector a b out, CLEvent... eventsToWaitFor) { - CLEvent.waitFor(eventsToWaitFor); - a.waitForRead(); - b.waitForRead(); - out.waitForWrite(); - FV aa = newVector(fallBackLibrary, a); - FV bb = newVector(fallBackLibrary, b); - out.write(aa.dot(bb, null).read()); - return null; - }*/ - - Reductor addReductor; - synchronized Reductor getAddReductor() { - if (addReductor == null) { - try { - addReductor = ReductionUtils.createReductor(getContext(), ReductionUtils.Operation.Add, OpenCLType.Double, 1); - } catch (CLBuildException ex) { - Logger.getLogger(LinearAlgebraUtils.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to create an addition reductor !", ex); - } - } - return addReductor; - } - - public synchronized CLEvent transpose(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - if (a.getBufferClass() == DoubleBuffer.class) - return transposeDoubles((CLBuffer)a, aRows, aColumns, (CLBuffer)out, eventsToWaitFor); - - throw new UnsupportedOperationException(); - } - - public synchronized CLEvent transposeDoubles(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - return kernels.transpose(queue, - a, aRows, aColumns, - out, - new int[] { (int)aColumns, (int)aRows }, - null, - eventsToWaitFor - ); - } - - -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java deleted file mode 100644 index 4c093d5fa..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -public enum OpenCLType { - Int, Char, Long, Short, Byte, Double, Float, Half; - - public String toCType() { - if (this == Byte) - return "char"; - if (this == Char) - return "short"; - return name().toLowerCase(); - } - public static OpenCLType fromClass(Class valueType) { - if (valueType == Integer.TYPE || valueType == Integer.class) - return Int; - if (valueType == java.lang.Long.TYPE || valueType == Long.class) - return Long; - if (valueType == java.lang.Short.TYPE || valueType == Short.class) - return Short; - if (valueType == java.lang.Double.TYPE || valueType == Double.class) - return Double; - if (valueType == java.lang.Float.TYPE || valueType == Float.class) - return Float; - if (valueType == java.lang.Byte.TYPE || valueType == Byte.class) - return Byte; - - if (!valueType.isPrimitive()) - throw new IllegalArgumentException("Value type is not a primitive: '" + valueType.getName() + "' !"); - - throw new IllegalArgumentException("Primitive type not handled: '" + valueType.getName() + "' !"); - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java deleted file mode 100644 index 17d9b7495..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLDoubleBuffer; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.ReductionUtils; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.IOUtils; -import com.ochafik.util.listenable.Pair; -import static com.nativelibs4java.util.NIOUtils.*; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.DoubleBuffer; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unused") -public class ParallelMath { - - protected CLContext context; - protected CLQueue queue; - - public ParallelMath() { - this(JavaCL.createBestContext().createDefaultQueue()); - } - - public ParallelMath(CLQueue queue) { - this.queue = queue; - CLContext context = queue.getContext(); - } - - public CLQueue getQueue() { - return queue; - } - - public CLContext getContext() { - return getQueue().getContext(); - } - - public enum Fun1 { - log, - exp, - sqrt, - sin, - cos, - tan, - atan, - asin, - acos, - sinh, - cosh, - tanh, - asinh, - acosh, - atanh; - - void expr(String a, StringBuilder out) { - out.append(name()).append('(').append(a).append(")"); - } - } - public enum Fun2 { - atan2, - dist, - modulo("%"), - rshift(">>"), - lshift("<<"), - add("+"), - substract("-"), - multiply("*"), - divide("/"); - - String infixOp; - Fun2() {} - Fun2(String infixOp) { - this.infixOp = infixOp; - } - void expr(String a, String b, StringBuilder out) { - if (infixOp == null) - out.append(name()).append('(').append(a).append(", ").append(b).append(")"); - else - out.append(a).append(' ').append(infixOp).append(' ').append(b); - } - } - public enum Primitive { - Float, - Double, - Long, - Int, - Short, - Byte, - - Float2, - Double2, - Long2, - Int2, - Short2, - Byte2, - - Float3, - Double3, - Long3, - Int3, - Short3, - Byte3, - - Float4, - Double4, - Long4, - Int4, - Short4, - Byte4, - - Float8, - Double8, - Long8, - Int8, - Short8, - Byte8, - - Float16, - Double16, - Long16, - Int16, - Short16, - Byte16; - - String type() { - return name().toLowerCase(); - } - } - - protected String createVectFun1Source(Fun1 function, Primitive type, StringBuilder out, boolean inPlace) { - String t = type.type(); - String kernelName = "vect_" + function.name() + "_" + t + (inPlace ? "_inplace" : ""); - out.append("__kernel void " + kernelName + "(\n"); - if (!inPlace) - out.append("\t__global const " + t + "* in,\n"); - out.append("\t__global " + t + "* out\n"); - out.append(") {\n"); - out.append("\tint i = get_global_id(0);\n"); - out.append("\tout[i] = "); - function.expr(inPlace ? "out" : "in", out); - out.append("[i]);\n"); - out.append("}\n"); - return kernelName; - } - - - protected String createVectFun2Source(Fun2 function, Primitive type1, Primitive type2, Primitive typeOut, StringBuilder out) { - String t1 = type1.type(), t2 = type2.type(), to = typeOut.type(); - String kernelName = "vect_" + function.name() + "_" + t1 + "_" + t2 + "_" + to; - out.append("__kernel void " + kernelName + "(\n"); - out.append("\t__global const " + t1 + "* in1,\n"); - out.append("\t__global const " + t2 + "* in2,\n"); - out.append("\t__global " + to + "* out\n"); - out.append(") {\n"); - out.append("\tint i = get_global_id(0);\n"); - out.append("\tout[i] = (" + to + ")"); - function.expr("in1[i]", "in2[i]", out); - out.append(";\n"); - out.append("}\n"); - return kernelName; - } - - - private static class Fun1Kernels { - CLKernel inPlace, notInPlace; - } - private EnumMap> fun1Kernels = new EnumMap>(Fun1.class); - - - public synchronized CLKernel getKernel(Fun1 op, Primitive prim, boolean inPlace) throws CLBuildException { - EnumMap m = fun1Kernels.get(op); - if (m == null) - fun1Kernels.put(op, m = new EnumMap(Primitive.class)); - - Fun1Kernels kers = m.get(prim); - if (kers == null) { - StringBuilder out = new StringBuilder(300); - String inPlaceName = createVectFun1Source(op, prim, out, true); - String notInPlaceName = createVectFun1Source(op, prim, out, false); - CLProgram prog = getContext().createProgram(out.toString()).build(); - kers = new Fun1Kernels(); - kers.inPlace = prog.createKernel(inPlaceName); - kers.notInPlace = prog.createKernel(notInPlaceName); - m.put(prim, kers); - } - return inPlace ? kers.inPlace : kers.notInPlace; - } - - static class PrimitiveTrio extends Pair> { - public PrimitiveTrio(Primitive a, Primitive b, Primitive c) { - super(a, new Pair(b, c)); - } - } - private EnumMap> fun2Kernels = new EnumMap>(Fun2.class); - public synchronized CLKernel getKernel(Fun2 op, Primitive prim) throws CLBuildException { - return getKernel(op, prim, prim, prim); - } - - public synchronized CLKernel getKernel(Fun2 op, Primitive prim1, Primitive prim2, Primitive primOut) throws CLBuildException { - Map m = fun2Kernels.get(op); - if (m == null) - fun2Kernels.put(op, m = new HashMap()); - - PrimitiveTrio key = new PrimitiveTrio(prim1, prim2, primOut); - CLKernel ker = m.get(key); - if (ker == null) { - StringBuilder out = new StringBuilder(300); - String name = createVectFun2Source(op, prim1, prim2, primOut, out); - CLProgram prog = getContext().createProgram(out.toString()).build(); - ker = prog.createKernel(name); - m.put(key, ker); - } - return ker; - } - -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java deleted file mode 100644 index ca9918e37..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import java.io.IOException; -import java.nio.IntBuffer; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLIntBuffer; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.util.NIOUtils; - -/** - * - * @author ochafik - */ -public class ParallelRandom { - - protected final XORShiftRandom randomProgram; - //private final IntBuffer outputBuffer; - //private IntBuffer mappedOutputBuffer; - protected final CLQueue queue; - protected final CLContext context; - protected final int parallelSize; - protected final int[] globalWorkSizes; - - protected int consumedInts = 0; - - boolean preload; - CLEvent preloadEvent; - protected CLIntBuffer seeds, output; - IntBuffer lastData; - boolean isDataFresh; - - public ParallelRandom() throws IOException { - this(JavaCL.createBestContext().createDefaultQueue(), 32 * 1024, System.currentTimeMillis()); - } - public ParallelRandom(CLQueue queue, int parallelSize, final long seed) throws IOException { - try { - this.queue = queue; - this.context = queue.getContext(); - randomProgram = new XORShiftRandom(context); - this.parallelSize = parallelSize; - - int seedsNeededByWorkItem = 4; - //int generatedNumbersByWorkItemIteration = 1; - int maxUnits = queue.getDevice().getMaxComputeUnits(); - int unitsFactor = maxUnits < 10 ? 1 : 16; - int scheduledWorkItems = maxUnits * unitsFactor; - //int countByWorkItem = parallelSize / scheduledWorkItems; - if (scheduledWorkItems > parallelSize / seedsNeededByWorkItem) { - scheduledWorkItems = parallelSize / seedsNeededByWorkItem; - scheduledWorkItems += parallelSize % seedsNeededByWorkItem; - } - //int iterationsByWorkItem = parallelCount / (generatedNumbersByWorkItemIteration * scheduledWorkItems); - globalWorkSizes = new int[] { scheduledWorkItems }; - - //int lws = 1;//(int)queue.getDevice().getMaxWorkGroupSize(); - //if (lws > 32) - // lws = 32; - //localWorkSizes = new int[] { lws }; - - randomProgram.getProgram().defineMacro("NUMBERS_COUNT", parallelSize); - randomProgram.getProgram().defineMacro("WORK_ITEMS_COUNT", scheduledWorkItems); - - final int nSeeds = seedsNeededByWorkItem * parallelSize; - final IntBuffer seedsBuf = NIOUtils.directInts(nSeeds, context.getKernelsDefaultByteOrder()); - initSeeds(seedsBuf, seed); - //println(seedsBuf); - this.seeds = context.createIntBuffer(Usage.InputOutput, seedsBuf, true); - //this.lastOutputData = NIOUtils.directInts(parallelSize, context.getKernelsDefaultByteOrder()); - this.output = context.createIntBuffer(Usage.Output, parallelSize); - } catch (InterruptedException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to initialized parallel random", ex); - } - } - - static final int floatMask = 0x00ffffff; - static final double floatDivid = (1 << 24); - //static final int mask = (1 << 30) - 1; - //static final double divid = (1 << 30); - - public int nextInt() { - waitForData(1); - return lastData.get(consumedInts++); - } - - public synchronized void setPreload(boolean preload) throws CLBuildException { - this.preload = preload; - if (preload && preloadEvent == null) { - if (lastData == null) { - preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null); - } else if (consumedInts > 0) { - preload(); - } - } - } - private synchronized CLEvent preload() throws CLBuildException { - return preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null, preloadEvent); - } - private synchronized void waitForData(int n) { - try { - if (lastData == null) { - //lastOutputData = NIOUtils.directInts(parallelSize, context.getKernelsDefaultByteOrder()); - if (preloadEvent == null) - preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null); - - readLastOutputData(); - } - if (consumedInts > parallelSize - n) { - preload().waitFor(); - consumedInts = 0; - readLastOutputData(); - } - if (preload && preloadEvent == null) - preload(); - } catch (CLBuildException ex) { - throw new RuntimeException(ex); - } - } - private synchronized void readLastOutputData() { - if (lastData == null) - lastData = output.read(queue, preloadEvent); - else - output.read(queue, lastData, true, preloadEvent); - preloadEvent = null; - } - public long nextLong() { - return (((long)nextInt()) << 32) | nextInt(); - } - - private static final int intSignMask = 1 << 31; - public int nextInt(int n) { - if (n <= 0) - throw new IllegalArgumentException("n must be positive"); - - if ((n & -n) == n) // i.e., n is a power of 2 - return (int)((n * (long)(nextInt() & intSignMask)) >> 31); - - int bits, val; - do { - bits = nextInt() & intSignMask; - val = bits % n; - } while (bits - val + (n-1) < 0); - return val; - } - - public float nextFloat() { - return (float)((nextInt() & floatMask) / floatDivid); - } - - private static final int doubleMask = (1 << 27) - 1; - private static final double doubleDivid = 1L << 53; - - public double nextDouble() { - return (((long)(nextInt() & doubleMask) << 27) | (nextInt() & doubleMask)) / doubleDivid; - } - - public CLIntBuffer getSeeds() { - return seeds; - } - public CLQueue getQueue() { - return queue; - } - - /** - * Number of random numbers generated at each call of {@link ParallelRandom#next() } or {@link ParallelRandom#next(IntBuffer) }
    - * The numbers might not all be generated exactly in parallel, the level of parallelism is implementation-dependent. - * @return size of each buffer returned by {@link ParallelRandom#next() } - */ - public int getParallelSize() { - return parallelSize; - } - - public synchronized CLEvent doNext() { - try { - //if (mappedOutputBuffer != null) { - // //output.unmap(queue, mappedOutputBuffer); - // mappedOutputBuffer = null; - //} - return randomProgram.gen_numbers(queue, seeds, //parallelSize, - output, globalWorkSizes, null); - } catch (CLBuildException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to compile the random number generation routine", ex); - } - } - - /** - * Copies the next {@link ParallelRandom#getParallelSize() } random integers in the provided output buffer - * @param output - */ - public synchronized void next(IntBuffer output) { - CLEvent evt = doNext(); - this.output.read(queue, output, true, evt); - } - - - /** - * Returns a direct NIO buffer containing the next {@link ParallelRandom#getParallelSize() } random integers.
    - * This buffer is read only and will only be valid until any of the "next" method is called again. - * @param output buffer of capacity ; see {@link ParallelRandom#getParallelSize() } - */ - public synchronized IntBuffer next() { - CLEvent evt = doNext(); - //queue.finish(); evt = null; - //return outputBuffer; - //return (mappedOutputBuffer = output.map(queue, MapFlags.Read, evt)).asReadOnlyBuffer(); - return output.read(queue, evt); - } - - private void initSeeds(final IntBuffer seedsBuf, final long seed) throws InterruptedException { - final int nSeeds = seedsBuf.capacity(); - - long start = System.nanoTime(); - - // TODO benchmark threshold : - boolean parallelize = nSeeds > 10000; - //parallelize = false; - if (parallelize) { - Random random = new Random(seed); - for (int i = nSeeds; i-- != 0;) - seedsBuf.put(i, random.nextInt()); - } else { - // Parallelize seeds initialization - final int nThreads = Runtime.getRuntime().availableProcessors();// * 2; - ExecutorService service = Executors.newFixedThreadPool(nThreads); - for (int i = 0; i < nThreads; i++) { - final int iThread = i; - service.execute(new Runnable() { - - public void run() { - int n = nSeeds / nThreads; - int offset = n * iThread; - Random random = new Random(seed + iThread);// * System.currentTimeMillis()); - if (iThread == nThreads - 1) - n += nSeeds - n * nThreads; - - for (int i = n; i-- != 0;) - seedsBuf.put(offset++, random.nextInt()); - } - }); - } - service.shutdown(); - service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); - } - - long time = System.nanoTime() - start; - Logger.getLogger(ParallelRandom.class.getName()).log(Level.INFO, "Initialization of " + nSeeds + " seeds took " + (time/1000000) + " ms (" + (time / (double)nSeeds) + " ns per seed)"); - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java deleted file mode 100644 index 17f3221f0..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.*; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.Buffer; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; -import com.ochafik.util.listenable.Pair; - -/** - * - * @author Olivier - */ -public class ReductionUtils { - static String source; - static final String sourcePath = ReductionUtils.class.getPackage().getName().replace('.', '/') + "/" + "Reduction.c"; - static synchronized String getSource() throws IOException { - InputStream in = ReductionUtils.class.getClassLoader().getResourceAsStream(sourcePath); - if (in == null) - throw new FileNotFoundException(sourcePath); - return source = IOUtils.readText(in); - } - - public enum Operation { - Add, - Multiply, - Min, - Max; - } - - public static Pair> getReductionCodeAndMacros(Operation op, OpenCLType valueType, int channels) throws IOException { - Map macros = new LinkedHashMap(); - String cType = valueType.toCType() + (channels == 1 ? "" : channels); - macros.put("OPERAND_TYPE", cType); - String operation, seed; - switch (op) { - case Add: - operation = "_add_"; - seed = "0"; - break; - case Multiply: - operation = "_mul_"; - seed = "1"; - break; - case Min: - operation = "_min_"; - switch (valueType) { - case Int: - seed = Integer.MAX_VALUE + ""; - break; - case Long: - seed = Long.MAX_VALUE + "LL"; - break; - case Short: - seed = Short.MAX_VALUE + ""; - break; - case Float: - seed = "MAXFLOAT"; - break; - case Double: - seed = "MAXDOUBLE"; - break; - default: - throw new IllegalArgumentException("Unhandled seed type: " + valueType); - } - - break; - case Max: - operation = "_max_"; - switch (valueType) { - case Int: - seed = Integer.MIN_VALUE + ""; - break; - case Long: - seed = Long.MIN_VALUE + "LL"; - break; - case Short: - seed = Short.MIN_VALUE + ""; - break; - case Float: - seed = "-MAXFLOAT"; - break; - case Double: - seed = "-MAXDOUBLE"; - break; - default: - throw new IllegalArgumentException("Unhandled seed type: " + valueType); - } - break; - default: - throw new IllegalArgumentException("Unhandled operation: " + op); - } - macros.put("OPERATION", operation); - macros.put("SEED", seed); - return new Pair>(getSource(), macros); - } - public interface Reductor

    { - public CLEvent reduce(CLQueue queue, CLBuffer

    input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor); - public B reduce(CLQueue queue, CLBuffer

    input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor); - public CLEvent reduce(CLQueue queue, CLBuffer

    input, long inputLength, CLBuffer

    output, int maxReductionSize, CLEvent... eventsToWaitFor); - } - /*public interface WeightedReductor { - public CLEvent reduce(CLQueue queue, CLBuffer input, CLBuffer weights, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor); - public CLEvent reduce(CLQueue queue, CLBuffer input, CLBuffer weights, long inputLength, CLBuffer output, int maxReductionSize, CLEvent... eventsToWaitFor); - }*/ - static int getNextPowerOfTwo(int i) { - int shifted = 0; - boolean lost = false; - for (;;) { - int next = i >> 1; - if (next == 0) { - if (lost) - return 1 << (shifted + 1); - else - return 1 << shifted; - } - lost = lost || (next << 1 != i); - shifted++; - i = next; - } - } - - public static

    Reductor

    createReductor(final CLContext context, Operation op, OpenCLType valueType, final int valueChannels) throws CLBuildException { - try { - - - Pair> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels); - CLProgram program = context.createProgram(codeAndMacros.getFirst()); - program.defineMacros(codeAndMacros.getValue()); - program.build(); - CLKernel[] kernels = program.createKernels(); - if (kernels.length != 1) - throw new RuntimeException("Expected 1 kernel, found : " + kernels.length); - final CLKernel kernel = kernels[0]; - return new Reductor

    () { - @SuppressWarnings("unchecked") - @Override - public CLEvent reduce(CLQueue queue, CLBuffer

    input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor) { - input.getBufferClass().cast(output); - Pair, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, maxReductionSize, eventsToWaitFor); - return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond()); - } - @Override - public B reduce(CLQueue queue, CLBuffer

    input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) { - B output = (B)NIOUtils.directBuffer((int)inputLength, context.getByteOrder(), (Class)input.getBufferClass()); - CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor); - //queue.finish(); - //TODO - evt.waitFor(); - return output; - } - @Override - public CLEvent reduce(CLQueue queue, CLBuffer

    input, long inputLength, CLBuffer

    output, int maxReductionSize, CLEvent... eventsToWaitFor) { - Pair, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, maxReductionSize, eventsToWaitFor); - return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond()); - } - @SuppressWarnings("unchecked") - public Pair, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer

    input, int inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) { - if (inputLength == 1) { - return new Pair, CLEvent[]>(input, new CLEvent[0]); - } - CLBuffer[] tempBuffers = new CLBuffer[2]; - int depth = 0; - CLBuffer

    currentOutput = null; - CLEvent[] eventsArr = new CLEvent[1]; - int[] blockCountArr = new int[1]; - - int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0]; - - while (inputLength > 1) { - int blocksInCurrentDepth = inputLength / maxReductionSize; - if (inputLength > blocksInCurrentDepth * maxReductionSize) - blocksInCurrentDepth++; - - int iOutput = depth & 1; - CLBuffer currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1]; - currentOutput = (CLBuffer

    )tempBuffers[iOutput]; - if (currentOutput == null) - currentOutput = (CLBuffer

    )(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, input.getElementClass(), blocksInCurrentDepth * valueChannels)); - - synchronized (kernel) { - kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput); - int workgroupSize = blocksInCurrentDepth; - if (workgroupSize == 1) - workgroupSize = 2; - blockCountArr[0] = workgroupSize; - eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor); - } - eventsToWaitFor = eventsArr; - inputLength = blocksInCurrentDepth; - depth++; - } - return new Pair, CLEvent[]>(currentOutput, eventsToWaitFor); - } - - }; - } catch (IOException ex) { - Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex); - } - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java deleted file mode 100644 index 295faa0e6..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLException; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.util.NIOUtils; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; - -/** - * Generic homogen transformer class - * @author ochafik - * @param NIO buffer class that represents the data consumed and produced by this transformer - * @param primitive array class that represents the data consumed and produced by this transformer - */ -public interface Transformer { - CLContext getContext(); - A transform(CLQueue queue, A input, boolean inverse); - B transform(CLQueue queue, B input, boolean inverse); - CLEvent transform(CLQueue queue, CLBuffer input, CLBuffer output, boolean inverse, CLEvent... eventsToWaitFor) throws CLException; - int computeOutputSize(int inputSize); - - public abstract class AbstractTransformer implements Transformer { - protected final Class primitiveClass; - protected final CLContext context; - - public AbstractTransformer(CLContext context, Class primitiveClass) { - this.primitiveClass = primitiveClass; - this.context = context; - } - - public CLContext getContext() { return context; } - - public int computeOutputSize(int inputSize) { - return inputSize; - } - - public A transform(CLQueue queue, A input, boolean inverse) { - return (A)NIOUtils.getArray(transform(queue, (B)NIOUtils.wrapArray(input), inverse)); - } - public B transform(CLQueue queue, B in, boolean inverse) { - int inputSize = in.capacity(); - int length = inputSize / 2; - - CLBuffer inBuf = context.createBuffer(CLMem.Usage.Input, in, true); // true = copy - CLBuffer outBuf = context.createBuffer(CLMem.Usage.Output, primitiveClass, computeOutputSize(inputSize)); - - CLEvent dftEvt = transform(queue, inBuf, outBuf, inverse); - inBuf.release(); - - B out = (B)outBuf.read(queue, dftEvt); - outBuf.release(); - return out; - } - - } -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java deleted file mode 100644 index 00176cfa5..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import java.io.IOException; -import java.nio.Buffer; - -public abstract class AbstractDFT extends AbstractTransformer { - - // package-private constructor - AbstractDFT(CLContext context, Class primitiveClass) throws IOException, CLException { - super(context, primitiveClass); - } - protected abstract CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException; - - @Override - public CLEvent transform(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - int length = (int)inBuf.getElementCount() / 2; - return dft(queue, inBuf, outBuf, length, inverse ? -1 : 1, new int[]{length}, eventsToWaitFor); - } - } \ No newline at end of file diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java deleted file mode 100644 index f1e09a97f..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import com.nativelibs4java.util.NIOUtils; -import java.nio.Buffer; -import java.nio.IntBuffer; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -// TODO implement something like http://locklessinc.com/articles/non_power_of_2_fft/ -public abstract class AbstractFFTPow2 extends AbstractTransformer { - - AbstractFFTPow2(CLContext context, Class primitiveClass) { - super(context, primitiveClass); - } - - private Map cachedOffsetsBufs = new HashMap(); - protected synchronized CLIntBuffer getOffsetsBuf(int length) { - CLIntBuffer offsetsBuf = cachedOffsetsBufs.get(length); - if (offsetsBuf == null) { - int[] offsets = new int[length]; - fft_compute_offsetsX(offsets, length, 1, 0, 0); - - offsetsBuf = context.createIntBuffer(CLMem.Usage.InputOutput, IntBuffer.wrap(offsets), true); - cachedOffsetsBufs.put(length, offsetsBuf); - } - return offsetsBuf; - } - protected abstract CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException ; - protected abstract CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLIntBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException; - protected abstract CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException; - - Map> cachedTwiddleFactors = new HashMap>(); - protected synchronized CLBuffer getTwiddleFactorsBuf(CLQueue queue, int N) throws CLException { - CLBuffer buf = cachedTwiddleFactors.get(N); - if (buf == null) { - int halfN = N / 2; - buf = context.createBuffer(CLMem.Usage.InputOutput, primitiveClass, N); - CLEvent.waitFor(cooleyTukeyFFTTwiddleFactors(queue, N, buf)); - cachedTwiddleFactors.put(N, buf); - } - return buf; - } - private void fft_compute_offsetsX(int[] offsetsX, int N, int s, int offsetX, int offsetY) { - if (N == 1) { - offsetsX[offsetY] = offsetX; - } else { - int halfN = N / 2; - int twiceS = s * 2; - fft_compute_offsetsX(offsetsX, halfN, twiceS, offsetX, offsetY); - fft_compute_offsetsX(offsetsX, halfN, twiceS, offsetX + s, offsetY + halfN); - } - } - - @Override - public CLEvent transform(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - int length = (int)inBuf.getElementCount() / 2; - if (Integer.bitCount(length) != 1) - throw new UnsupportedOperationException("Only supports FFTs of power-of-two-sized arrays (was given array of length " + length + ")"); - - CLIntBuffer offsetsBuf = getOffsetsBuf(length); - CLEvent copyEvt = cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse, eventsToWaitFor); - CLEvent dftEvt = fft(queue, inBuf, length, 1, inverse ? 1 : 0, 1, outBuf, copyEvt); - return dftEvt; - } - private CLEvent fft(CLQueue queue, CLBuffer X, int N, int s, int inverse, int blocks, CLBuffer Y, CLEvent... eventsToWaitFor) throws CLException { - if (N == 1) { - return null; - } else { - int halfN = N / 2; - int twiceS = s * 2; - - CLEvent[] evts; - if (halfN > 1) { - evts = new CLEvent[] { fft(queue, X, halfN, twiceS, inverse, blocks * 2, Y, eventsToWaitFor) }; - } else { - evts = eventsToWaitFor; - } - - return cooleyTukeyFFT(queue, Y, N, getTwiddleFactorsBuf(queue, N), inverse, new int[] { halfN, blocks }, evts); - } - } - - } - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java deleted file mode 100644 index f8141e3f7..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.nio.DoubleBuffer; - -public class DoubleDFT extends AbstractDFT { - - final DoubleDFTProgram program; - - public DoubleDFT(CLContext context) throws IOException { - super(context, Double.class); - this.program = new DoubleDFTProgram(context); - } - public DoubleDFT() throws IOException { - this(JavaCL.createBestContext(DeviceFeature.DoubleSupport)); - } - - @Override - protected CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException { - return program.dft(queue, inBuf, outBuf, length, sign, dims, null, events); - } - - @Override - public double[] transform(CLQueue queue, double[] input, boolean inverse) { - return super.transform(queue, input, inverse); - } - } diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java deleted file mode 100644 index 8c9127f14..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.nio.DoubleBuffer; - -public class DoubleFFTPow2 extends AbstractFFTPow2 { - - final DoubleFFTProgram program; - - public DoubleFFTPow2(CLContext context) throws IOException, CLException { - super(context, Double.class); - this.program = new DoubleFFTProgram(context); - program.getProgram().setFastRelaxedMath(); - } - public DoubleFFTPow2() throws IOException { - this(JavaCL.createBestContext(DeviceFeature.DoubleSupport)); - } - - protected CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTTwiddleFactors(queue, N, buf, new int[] { N / 2 }, null, evts); - } - protected CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLIntBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse ? 1.0 / length : 1, new int[] { length }, null, evts); - } - protected CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFT(queue, Y, N, twiddleFactors, inverse, dims, null, evts); - } - } - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java deleted file mode 100644 index 51a1cf66e..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.util.*; -import java.io.File; -import java.io.IOException; -import java.nio.FloatBuffer; - -public class FloatDFT extends AbstractDFT { - - final FloatDFTProgram program; - - public FloatDFT(CLContext context) throws IOException, CLException { - super(context, Float.class); - program = new FloatDFTProgram(context); - } - public FloatDFT() throws IOException { - this(JavaCL.createBestContext()); - } - - @Override - protected CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException { - return program.dft(queue, inBuf, outBuf, length, sign, dims, null, events); - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java deleted file mode 100644 index 3113f29cd..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import java.io.IOException; -import java.nio.FloatBuffer; - -public class FloatFFTPow2 extends AbstractFFTPow2 { - - final FloatFFTProgram program; - - public FloatFFTPow2(CLContext context) throws IOException { - super(context, Float.class); - this.program = new FloatFFTProgram(context); - program.getProgram().setFastRelaxedMath(); - } - public FloatFFTPow2() throws IOException { - this(JavaCL.createBestContext()); - } - - protected CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTTwiddleFactors(queue, N, buf, new int[] { N / 2 }, null, evts); - } - protected CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLIntBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse ? 1.0f / length : 1, new int[] { length }, null, evts); - } - protected CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFT(queue, Y, N, twiddleFactors, inverse, dims, null, evts); - } - } - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java deleted file mode 100644 index 90f8f9bbf..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * OpenCL-backed Fourier Analysis classes (DFT, power-of-two FFT and reverse DFT/FFT for complex doubles and floats inputs) - */ -package com.nativelibs4java.opencl.util.fft; diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java b/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java deleted file mode 100644 index dd0377413..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * Utilitary classes (parallel random, parallel reduction, parallel math, linear algebra...) - */ -package com.nativelibs4java.opencl.util; diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c deleted file mode 100644 index 0e55020f8..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c +++ /dev/null @@ -1,46 +0,0 @@ -#pragma OPENCL EXTENSION cl_khr_fp64: enable - -__kernel void mulMat( - __global const double* a, /*size_t aRows,*/ int aColumns, - __global const double* b, /*size_t bRows,*/ int bColumns, - __global double* c -) { - int i = get_global_id(0); - int j = get_global_id(1); - - double total = 0; - - // c[i, j] = sum(a[i, k] * b[k, j]) - int iAOff = i * aColumns; - for (int k = 0; k < aColumns; k++) { - total += a[iAOff + k] * b[k * bColumns + j]; - } - c[i * bColumns + j] = total; -} - -__kernel void mulVec( - __global const double* a, /*size_t aRows,*/ int aColumns, - __global const double* b, int bSize, - __global double* c -) { - size_t globalId = get_global_id(0); - size_t i = globalId; - - double total = 0; - size_t iOff = i * aColumns; - for (size_t k = 0; k < aColumns; k++) { - total += a[iOff + k] * b[k]; - } - c[i] = total; -} - -__kernel void transpose( - __global const double* a, int aRows, int aColumns, - __global double* out -) { - int i = get_global_id(0); - int j = get_global_id(1); - - int outColumns = aRows; - out[i * outColumns + j] = a[j * aColumns + i]; -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c deleted file mode 100644 index 97bd4e9c3..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef NUMBERS_COUNT -#define NUMBERS_COUNT 0 -#endif - -#ifndef WORK_ITEMS_COUNT -#define WORK_ITEMS_COUNT get_global_size(0) -#endif - -/** - * Logic copied from http://en.wikipedia.org/wiki/Xorshift - * Requires 4 initial random seeds for each work item - */ -__kernel void gen_numbers(__global uint4* seeds, /*size_t nNumbersArg, */__global uint* output) -{ - const uint iWorkItem = get_global_id(0); -#if 1 -#define seedsOffset iWorkItem -#define nNumbers NUMBERS_COUNT -#define nWorkItems WORK_ITEMS_COUNT -#define nNumbersByWorkItem (nNumbers / nWorkItems) -#define REMAINDER (nNumbers - nNumbersByWorkItem * WORK_ITEMS_COUNT) - uint nNumbersInThisWorkItem = nNumbersByWorkItem; - if (iWorkItem == nWorkItems - 1) - nNumbersInThisWorkItem += REMAINDER; -#else - const uint seedsOffset = iWorkItem; - const uint nNumbers = nNumbersArg; - const y nWorkItems = get_global_size(0); - const uint nNumbersByWorkItem = nNumbers / nWorkItems; - uint nNumbersInThisWorkItem = nNumbersByWorkItem; - if (iWorkItem == nWorkItems - 1) - nNumbersInThisWorkItem += nNumbers - nNumbersByWorkItem * nWorkItems; -#endif - - output += iWorkItem * nNumbersByWorkItem;//outputOffset; - - //seeds += seedsOffset; - //uint4 seed = *seeds; - uint4 seed = seeds[seedsOffset]; -#if 1 - uint x = seed.x, y = seed.y, z = seed.z, w = seed.w; - for (uint i = 0; i < nNumbersInThisWorkItem; i++) { - //for (uint i = nNumbersInThisWorkItem; i--;) { - uint t = x ^ (x << 11); - x = y; y = z; z = w; - //output[outputOffset + i] = - *(output++) = - w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); - } - //*seeds = (uint4)(x, y, z, w); - seeds[seedsOffset] = (uint4)(x, y, z, w); -#else - for (uint i = 0; i < nNumbersInThisWorkItem; i++) { - uint t = seed.x ^ (seed.x << 11); - seed.xyz = seed.yzw; - *(output++) = seed.w = (seed.w ^ (seed.w >> 19)) ^ (t ^ (t >> 8)); - } - seeds[seedsOffset] = seed; -#endif -} - -#undef seedsOffset -#undef nNumbers -#undef nWorkItems -#undef nNumbersByWorkItem -#undef REMAINDER - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl deleted file mode 100644 index 265ebc419..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl +++ /dev/null @@ -1,44 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -__kernel void dft( - __global const double2 *in, // complex values input - __global double2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - double2 tot = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double2 value = in[k]; - - // Compute sin and cos in a single call : - double c; - double s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (double2)( - dot(value, (double2)(c, -s)), - dot(value, (double2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (double)length; - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl deleted file mode 100644 index 48a913a37..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl +++ /dev/null @@ -1,95 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -double2 rotateValue2(double2 value, double2 sinCos) { - return (double2)( - dot(value, (double2)(sinCos.y, -sinCos.x)), - dot(value, sinCos) - ); -} - -__kernel void cooleyTukeyFFTCopy( - __global const double2* X, - __global double2* Y, - int N, - __global const int* offsetsX, - double factor) -{ - int offsetY = get_global_id(0); - if (offsetY >= N) - return; - - int offsetX = offsetsX[offsetY]; - Y[offsetY] = X[offsetX] * factor; -} - -__kernel void cooleyTukeyFFTTwiddleFactors(int N, __global double2* twiddleFactors) -{ - int k = get_global_id(0); - double param = - M_PI * 2 * k / (double)N; - double c, s = sincos(param, &c); - twiddleFactors[k] = (double2)(s, c); -} -__kernel void cooleyTukeyFFT( - __global double2* Y, - int N, - __global double2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - double2 sinCos = twiddleFactors[k]; - if (inverse) - sinCos.x = -sinCos.x; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - double2 y1 = Y[o1]; - double2 y2 = Y[o2]; - - double2 v = rotateValue2(y2, sinCos); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} -/* -__kernel void cooleyTukeyFFTTwiddleFactors4(int N, __global double2* twiddleFactors) -{ - int k = get_global_id(0); - double param2 = - M_PI * 2 * k / (double)N; - double param3 = param2 * 2; - double param4 = param2 * 3; - double c2, s2 = sincos(param2, &c2); - double c3, s3 = sincos(param3, &c3); - double c4, s4 = sincos(param4, &c4); - int offset = k * 3; - twiddleFactors[offset++] = (double2)(s2, c2); - twiddleFactors[offset++] = (double2)(s3, c3); - twiddleFactors[offset++] = (double2)(s4, c4); -} -__kernel void cooleyTukeyFFT4( - __global double2* Y, - int N, - __global double2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - double2 sinCos = twiddleFactors[k]; - if (inverse) - sinCos.x = -sinCos.x; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - double2 y1 = Y[o1]; - double2 y2 = Y[o2]; - - double2 v = rotateValue2(y2, sinCos); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} -*/ diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl deleted file mode 100644 index ec653992a..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl +++ /dev/null @@ -1,40 +0,0 @@ -__kernel void dft( - __global const float2 *in, // complex values input - __global float2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - float2 tot = 0; - float param = (-2 * sign * i) * 3.141593f / (float)length; - - for (int k = 0; k < length; k++) { - float2 value = in[k]; - - // Compute sin and cos in a single call : - float c; - float s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (float2)( - dot(value, (float2)(c, -s)), - dot(value, (float2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (float)length; - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl b/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl deleted file mode 100644 index 68517a86a..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl +++ /dev/null @@ -1,55 +0,0 @@ - -inline float2 rotateValue2(float2 value, float c, float s) { - return (float2)( - dot(value, (float2)(c, -s)), - dot(value, (float2)(s, c)) - ); -} - -__kernel void cooleyTukeyFFTCopy( - __global const float2* X, - __global float2* Y, - int N, - __global const int* offsetsX, - float factor) -{ - int offsetY = get_global_id(0); - if (offsetY >= N) - return; - - int offsetX = offsetsX[offsetY]; - Y[offsetY] = X[offsetX] * factor; -} - -__kernel void cooleyTukeyFFTTwiddleFactors(int N, __global float2* twiddleFactors) -{ - int k = get_global_id(0); - float param = - 3.14159265359f * 2 * k / (float)N; - float c, s = sincos(param, &c); - twiddleFactors[k] = (float2)(c, s); -} -__kernel void cooleyTukeyFFT( - __global float2* Y, - int N, - __global float2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - float2 tf = twiddleFactors[k]; - float c = tf.x, s = tf.y; - if (inverse) - s = -s; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - float2 y1 = Y[o1]; - float2 y2 = Y[o2]; - - float2 v = rotateValue2(y2, c, s); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} - diff --git a/libraries/OpenCL-JNA/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c b/libraries/OpenCL-JNA/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c deleted file mode 100644 index 2cd1f958e..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c +++ /dev/null @@ -1,41 +0,0 @@ -#define _mul_(tot, x) tot *= x; -#define _add_(tot, x) tot += x; -#define _min_(tot, x) tot = min(tot, x); -#define _max_(tot, x) tot = max(tot, x); - -#ifndef SEED -# error "No aggregation SEED defined !" -#endif - -#ifndef OPERATION -# error "No OPERATION defined !" -#endif - -#ifndef OPERAND_TYPE -#define OPERAND_TYPE int -#endif - -#ifndef OUTPUT_TYPE -#define OUTPUT_TYPE OPERAND_TYPE -#endif - -__kernel void reduce( - __global const OPERAND_TYPE* input, - long blocks, - long dataLength, - long blockLength, - __global OUTPUT_TYPE* output) -{ - long block = get_global_id(0); - if (block >= blocks) - return; - - long inputStart = block * blockLength; - long inputEnd = min(inputStart + blockLength, dataLength); - - OUTPUT_TYPE total = (OUTPUT_TYPE)SEED; - for (int inputOffset = inputStart; inputOffset < inputEnd; inputOffset++) - OPERATION(total, input[inputOffset]); - - output[block] = total; -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java b/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java deleted file mode 100644 index ee7ebce40..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; -import org.apache.commons.math.complex.Complex; -import com.nativelibs4java.opencl.util.fft.*; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.util.*; -import java.nio.*; -import org.apache.commons.math.transform.FastFourierTransformer; -import org.junit.*; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class DiscreteFourierTransformTest { - - static double[] complexToInterleavedDoubles(Complex[] complexInput) { - int length = complexInput.length; - double[] output = new double[length * 2]; - for (int i = 0; i < length; i++) { - int o = i * 2; - Complex c = complexInput[i]; - output[o] = c.getReal(); - output[o + 1] = c.getImaginary(); - } - return output; - } - static Complex[] interleavedDoublesToComplex(double[] input) { - int length = input.length / 2; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - int o = i * 2; - complexOutput[i] = new Complex(input[o], input[o + 1]); - } - return complexOutput; - } - static Complex[] realDoublesToComplex(double[] input) { - int length = input.length; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - complexOutput[i] = new Complex(input[i], 0); - } - return complexOutput; - } - /* - static void assertArrayEquals(String title, Object a, Object b) { - if (a instanceof double[]) { - double[] aa = (double[])a, bb = (double[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionDouble) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } else if (a instanceof float[]) { - float[] aa = (float[])a, bb = (float[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionFloat) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } - }*/ - static final float precisionFloat = 1e-3f, precisionInverseFloat = 1e-2f; - static final double precisionDouble = 1e-10, precisionInverseDouble = 1e-5; - - static Collection createTestDoubleInputs() { - Collection ret = new ArrayList(); - for (int n : new int[] { 1024, 1, 2, 4, 8, 16 }) { - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double)(i + 1); - in[i * 2 + 1] = 0; - } - ret.add(in); - } - return ret; - } - static Collection createTestFloatInputs() { - Collection ret = new ArrayList(); - for (double[] in : createTestDoubleInputs()) - ret.add(toFloat(in)); - return ret; - } - - static float[] toFloat(double[] in) { - float[] out = new float[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = (float)in[i]; - - return out; - } - static double[] scale(double factor, double[] in) { - double[] out = new double[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = factor * in[i]; - - return out; - } - - public void testDoubleValues(String title, Transformer tr) { - FastFourierTransformer apache = new FastFourierTransformer(); - CLQueue queue = tr.getContext() == null ? null : tr.getContext().createDefaultOutOfOrderQueueIfPossible(); - for (double[] data : createTestDoubleInputs()) { - double[] expected = complexToInterleavedDoubles(apache.transform(interleavedDoublesToComplex(data))); - assertArrayEquals(title + " (n = " + (data.length / 2) + ")", expected, tr.transform(queue, data, false), precisionDouble); - } - } - public void testFloatValues(String title, Transformer tr) { - FastFourierTransformer apache = new FastFourierTransformer(); - CLQueue queue = tr.getContext() == null ? null : tr.getContext().createDefaultOutOfOrderQueueIfPossible(); - for (double[] data : createTestDoubleInputs()) { - float[] dataf = toFloat(data); - double[] expected = complexToInterleavedDoubles(apache.transform(interleavedDoublesToComplex(data))); - assertArrayEquals(title + " (n = " + (data.length / 2) + ")", toFloat(expected), tr.transform(queue, dataf, false), precisionFloat); - } - } - - @Ignore - @Test - public void testDoubleFFTValues() throws IOException { - testDoubleValues("Double FFT", new DoubleFFTPow2()); - } - @Test - public void testFloatFFTValues() throws IOException { - testFloatValues("Float FFT", new FloatFFTPow2()); - } - @Test - public void testDoubleDFTValues() throws IOException { - testDoubleValues("Double DFT", new DoubleDFT()); - } - @Test - public void testFloatDFTValues() throws IOException { - testFloatValues("Float DFT", new FloatDFT()); - } - @Test - public void testDoubleDFTInverse() throws IOException, CLException { - testDoubleTransformer("Double FFT Inverse", new DoubleDFT()); - } - @Test - public void testFloatDFTInverse() throws IOException, CLException { - testFloatTransformer("Float DFT Inverse", new FloatDFT()); - } - @Ignore - @Test - public void testDoubleFFTInverse() throws IOException, CLException { - testDoubleTransformer("Double FFT Inverse", new DoubleFFTPow2()); - } - @Test - public void testFloatFFTInverse() throws IOException, CLException { - testFloatTransformer("Float FFT Inverse", new FloatFFTPow2()); - } - void testDoubleTransformer(String title, Transformer t) throws IOException, CLException { - CLQueue queue = t.getContext().createDefaultOutOfOrderQueueIfPossible(); - //System.out.println("Context: " + t.getContext()); - for (double[] in : createTestDoubleInputs()) { - double[] out = t.transform(queue, in, false); - double[] back = t.transform(queue, out, true); - assertArrayEquals(title + " (n = " + (in.length / 2) + ")", in, back, precisionInverseDouble); - } - } - void testFloatTransformer(String title, Transformer t) throws IOException, CLException { - CLQueue queue = t.getContext().createDefaultOutOfOrderQueueIfPossible(); - //System.out.println("Context: " + t.getContext()); - for (float[] in : createTestFloatInputs()) { - float[] out = t.transform(queue, in, false); - float[] back = t.transform(queue, out, true); - assertArrayEquals(title + " (n = " + (in.length / 2) + ")", in, back, precisionInverseFloat); - } - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java b/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java deleted file mode 100644 index 9dd4d3bef..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.JavaCL; -import java.nio.IntBuffer; - -import org.junit.Assert; -import org.junit.Test; - -/** - * - * @author ochafik - */ -public class ParallelRandomTest { - int nPoints = 1024 * 1024; - int nLoops = 10; - long seed = 1; - - static final int mask = 0x00ffffff; - static final double divid = (1 << 24); - //static final int mask = (1 << 30) - 1; - //static final double divid = (1 << 30); - - /** - * http://fr.wikipedia.org/wiki/M%C3%A9thode_de_Monte-Carlo#Exemples - */ - @Test - public void testPICircle() { - try { - ParallelRandom random = new ParallelRandom( - JavaCL.createBestContext().createDefaultQueue(), - nPoints * 2, - seed - ); - - int nInside = 0, nTotalPoints = 0; - - for (int iLoop = 0; iLoop < nLoops; iLoop++) { - IntBuffer values = random.next(); - for (int iPoint = 0; iPoint < nPoints; iPoint++) { - int offset = iPoint * 2; - int ix = values.get(offset), iy = values.get(offset + 1); - float x = (float)((ix & mask) / divid); - float y = (float)((iy & mask) / divid); - - float dist = x * x + y * y; - if (dist <= 1) - nInside++; - } - nTotalPoints += nPoints; - //checkPICircleProba(nInside, nTotalPoints); - } - checkPICircleProba(nInside, nTotalPoints); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - void checkPICircleProba(int nInside, int nTotalPoints) { - double piRef = Math.PI; - double probaInside = nInside / (double)nTotalPoints; // = Pi / 4 - double piApprox = probaInside * 4; - double error = Math.abs(piApprox - piRef); - double relError = error / piRef; - System.out.println(nInside + " points inside the circle quarter over " + nTotalPoints); - System.out.println("Approximated PI = " + piApprox); - System.out.println(" Reference PI = " + piRef); - System.out.println("\tAbsolute error = " + error); - System.out.println("\tRelative error = " + (relError * 100) + " %"); - Assert.assertEquals(piRef, piApprox, 0.001); - } -} diff --git a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java b/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java deleted file mode 100644 index be5512e17..000000000 --- a/libraries/OpenCL-JNA/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java +++ /dev/null @@ -1,134 +0,0 @@ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.*; -import static com.nativelibs4java.opencl.JavaCL.createBestContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.nio.IntBuffer; -import java.nio.FloatBuffer; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.NIOUtils; - -public class ReductionTest { - - @BeforeClass - public static void setup() { - com.sun.jna.Native.setProtected(true); - } - - CLContext context; - CLQueue queue; - - @Before - public void init() { - //context = createBestContext(CLPlatform.DeviceEvaluationStrategy.BestDoubleSupportThenBiggestMaxComputeUnits);// - context = createBestContext(); - //System.out.println("Context = " + Arrays.asList(context.getDevices())); - queue = context.createDefaultQueue(); - } - - @Test - public void testMinMax() { - try { - CLIntBuffer input = context.createIntBuffer(CLMem.Usage.Input, IntBuffer.wrap(new int[] { - 1110, 22, 35535, 3, 1 - }), true); - - int maxReductionSize = 2; - IntBuffer result = NIOUtils.directInts(1, context.getByteOrder()); - - Reductor reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Min, OpenCLType.Int, 1); - reductor.reduce(queue, input, input.getElementCount(), result, maxReductionSize); - queue.finish(); - assertEquals(1, result.get(0)); - - reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Max, OpenCLType.Int, 1); - reductor.reduce(queue, input, input.getElementCount(), result, maxReductionSize); - queue.finish(); - assertEquals(35535, result.get(0)); - - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=26 - @Test - public void testIssue26() { - try { - float[] array = new float[4097]; - for (int i = 0; i < array.length; i++) - array[i] = 1; - - CLBuffer clBufferInput = context.createFloatBuffer(CLMem.Usage.Input, FloatBuffer.wrap(array), true); - - ReductionUtils.Reductor reductor = ReductionUtils.createReductor( - context, - ReductionUtils.Operation.Add, - OpenCLType.Float, - 1 - ); - FloatBuffer result = reductor.reduce(queue, clBufferInput, 4097, 64); - float sum = result.get(0); - float expected = 4097; - System.err.println("[Test of issue 26] Expected " + expected + ", got " + sum); - assertEquals(expected, sum, 0); - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } - @Test - public void testAddReduction() { - try { - int dataSize = 12345; - int channels = 1; - int maxReductionSize = 64; - - IntBuffer inBuf = NIOUtils.directInts(channels * dataSize, context.getByteOrder()); - for (int i = 0; i < dataSize; i++) { - for (int c = 0; c < channels; c++) - inBuf.put(i * channels + c, i); - } - - CLIntBuffer in = context.createIntBuffer(CLMem.Usage.Input, channels * dataSize); - in.write(queue, inBuf, true); - - IntBuffer check = in.read(queue); - for (int i = 0; i < dataSize; i++) - assertEquals(inBuf.get(i), check.get(i)); - - IntBuffer out = NIOUtils.directInts(channels, context.getByteOrder()); - - Reductor reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Add, OpenCLType.Int, channels); - - //CLEvent evt = - reductor.reduce(queue, in, dataSize, out, maxReductionSize); - //if (evt != null) - queue.finish(); - // evt.waitFor(); - //CLEvent[] evts = reductor.reduce(queue, in, 0, dataSize, out, maxReductionSize); - //queue.enqueueWaitForEvents(evts); - - int expected = dataSize * (dataSize - 1) / 2; - System.out.println("Expecting " + expected); - for (int i = 0; i < channels; i++) { - int value = out.get(i); - System.out.println("out." + i + " = " + value); - assertEquals(expected, value); - } - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } -} diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/.gitignore b/libraries/OpenCL-JNA/JavaCLTutorial/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/pom.xml b/libraries/OpenCL-JNA/JavaCLTutorial/pom.xml deleted file mode 100644 index 7370fdee8..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-tutorial-jna - JavaCL Tutorial / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - com.nativelibs4java - javacl-jna - - - org.apache.commons - commons-math - 2.2 - - - org.scala-lang - scala-library - - - - - - - com.nativelibs4java - javacl-generator-jna - - - - compile - - - - - - org.scala-tools - maven-scala-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - org.scala-tools - maven-scala-plugin - ${scala.version} - - - - - - - - diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT.java b/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT.java deleted file mode 100644 index b20a0dadd..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT.java +++ /dev/null @@ -1,102 +0,0 @@ -package tutorial; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.util.*; -import java.io.IOException; -import java.nio.DoubleBuffer; - -public class DFT { - - final CLQueue queue; - final CLContext context; - final CLProgram program; - final CLKernel kernel; - - public DFT(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - this.context = queue.getContext(); - - String source = IOUtils.readText(DFT.class.getResource("DiscreteFourierTransformProgram.cl")); - program = context.createProgram(source); - kernel = program.createKernel("dft"); - } - - /** - * Method that takes complex values in input (sequence of pairs of real and imaginary values) and - * returns the Discrete Fourier Transform of these values if forward == true or the inverse - * transform if forward == false. - */ - public synchronized DoubleBuffer dft(DoubleBuffer in, boolean forward) { - assert in.capacity() % 2 == 0; - int length = in.capacity() / 2; - - // Create an input CLBuffer that will be a copy of the NIO buffer : - CLDoubleBuffer inBuf = context.createDoubleBuffer(CLMem.Usage.Input, in, true); // true = copy - - // Create an output CLBuffer : - CLDoubleBuffer outBuf = context.createDoubleBuffer(CLMem.Usage.Output, length * 2); - - // Set the args of the kernel : - kernel.setArgs(inBuf, outBuf, length, forward ? 1 : -1); - - // Ask for `length` parallel executions of the kernel in 1 dimension : - CLEvent dftEvt = kernel.enqueueNDRange(queue, new int[]{ length }); - - // Return an NIO buffer read from the output CLBuffer : - return outBuf.read(queue, dftEvt); - } - - /// Wrapper method that takes and returns double arrays - public double[] dft(double[] complexValues, boolean forward) { - DoubleBuffer outBuffer = dft(DoubleBuffer.wrap(complexValues), forward); - double[] out = new double[complexValues.length]; - outBuffer.get(out); - return out; - } - - public static void main(String[] args) throws IOException, CLBuildException { - // Create a context with the best double numbers support possible : - // (try using DeviceFeature.GPU, DeviceFeature.CPU...) - CLContext context = JavaCL.createBestContext(DeviceFeature.DoubleSupport); - - // Create a command queue, if possible able to execute multiple jobs in parallel - // (out-of-order queues will still respect the CLEvent chaining) - CLQueue queue = context.createDefaultOutOfOrderQueueIfPossible(); - - DFT dft = new DFT(queue); - //DFT2 dft = new DFT2(queue); - - // Create some fake test data : - double[] in = createTestDoubleData(); - - // Transform the data (spatial -> frequency transform) : - double[] transformed = dft.dft(in, true); - - for (int i = 0; i < transformed.length / 2; i++) { - // Print the transformed complex values (real + i * imaginary) - System.out.println(transformed[i * 2] + "\t + \ti * " + transformed[i * 2 + 1]); - } - - // Reverse-transform the transformed data (frequency -> spatial transform) : - double[] backTransformed = dft.dft(transformed, false); - - // Check the transform + inverse transform give the original data back : - double precision = 1e-5; - for (int i = 0; i < in.length; i++) { - if (Math.abs(in[i] - backTransformed[i]) > precision) - throw new RuntimeException("Different values in back-transformed array than in original array !"); - } - } - - static double[] createTestDoubleData() { - int n = 32; - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double) (i + 1); - in[i * 2 + 1] = 0; - } - return in; - } -} diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT2.java b/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT2.java deleted file mode 100644 index ba5d1005c..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/java/tutorial/DFT2.java +++ /dev/null @@ -1,38 +0,0 @@ -package tutorial; - -import com.nativelibs4java.opencl.*; -import java.io.IOException; -import java.nio.DoubleBuffer; - -public class DFT2 { - - final CLQueue queue; - final CLContext context; - final DiscreteFourierTransformProgram program; - - public DFT2(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - this.context = queue.getContext(); - this.program = new DiscreteFourierTransformProgram(context); - } - - public synchronized DoubleBuffer dft(DoubleBuffer in, boolean forward) throws CLBuildException { - assert in.capacity() % 2 == 0; - int length = in.capacity() / 2; - - CLDoubleBuffer inBuf = context.createDoubleBuffer(CLMem.Usage.Input, in, true); // true = copy - CLDoubleBuffer outBuf = context.createDoubleBuffer(CLMem.Usage.Output, length * 2); - - // The following call is type-safe, thanks to the JavaCL Maven generator : - // (if the OpenCL function signature changes, the generated Java definition will be updated and compilation will fail) - CLEvent dftEvt = program.dft(queue, inBuf, outBuf, length, forward ? 1 : -1, new int[]{length}, null); - return outBuf.read(queue, dftEvt); - } - - public double[] dft(double[] complexValues, boolean forward) throws CLBuildException { - DoubleBuffer outBuffer = dft(DoubleBuffer.wrap(complexValues), forward); - double[] out = new double[complexValues.length]; - outBuffer.get(out); - return out; - } - } diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c b/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c deleted file mode 100644 index 3b6a472df..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c +++ /dev/null @@ -1,33 +0,0 @@ -void dft( - const double *in, // complex values input (packed real and imaginary) - double *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - for (int i = 0; i < length; i++) - { - // Initialize sum and inner arguments - double totReal = 0, totImag = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double valueReal = in[k * 2], valueImag = in[k * 2 + 1]; - double arg = k * param; - double c = cos(arg), sin(arg); - - totReal += valueReal * c - valueImag * s; - totImag += valueReal * s + valueImag * c; - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i * 2] = totReal; - out[i * 2 + 1] = totImag; - } else { - // backward transform (frequential -> space) - out[i * 2] = totReal / (double)length; - out[i * 2 + 1] = totImag / (double)length; - } - } -} diff --git a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl b/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl deleted file mode 100644 index 265ebc419..000000000 --- a/libraries/OpenCL-JNA/JavaCLTutorial/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl +++ /dev/null @@ -1,44 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -__kernel void dft( - __global const double2 *in, // complex values input - __global double2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - double2 tot = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double2 value = in[k]; - - // Compute sin and cos in a single call : - double c; - double s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (double2)( - dot(value, (double2)(c, -s)), - dot(value, (double2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (double)length; - } -} diff --git a/libraries/OpenCL-JNA/LICENSE.header b/libraries/OpenCL-JNA/LICENSE.header deleted file mode 100644 index 5a3466297..000000000 --- a/libraries/OpenCL-JNA/LICENSE.header +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik (http://ochafik.free.fr/) - - This file is part of OpenCL4Java (http://code.google.com/p/nativelibs4java/wiki/OpenCL). - - OpenCL4Java is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 2.1 of the License, or - (at your option) any later version. - - OpenCL4Java is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with OpenCL4Java. If not, see . -*/ - diff --git a/libraries/OpenCL-JNA/NumericalBenchmark/.gitignore b/libraries/OpenCL-JNA/NumericalBenchmark/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/NumericalBenchmark/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/NumericalBenchmark/pom.xml b/libraries/OpenCL-JNA/NumericalBenchmark/pom.xml deleted file mode 100644 index 2a3c68c29..000000000 --- a/libraries/OpenCL-JNA/NumericalBenchmark/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-numerical-benchmark-jna - JavaCL Numerical Benchmark / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - - com.nativelibs4java - javacl-jna - 1.0-SNAPSHOT - - - org.apache.commons - commons-math - 2.2 - - - org.scala-lang - scala-library - - - - - - - com.nativelibs4java - javacl-generator-bridj-jna - 1.0-SNAPSHOT - - - - compile - - - - - - org.scala-tools - maven-scala-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - org.scala-tools - maven-scala-plugin - - - - - - - - diff --git a/libraries/OpenCL-JNA/NumericalBenchmark/src/main/java/fft/FFTBench.java b/libraries/OpenCL-JNA/NumericalBenchmark/src/main/java/fft/FFTBench.java deleted file mode 100644 index dbc997a69..000000000 --- a/libraries/OpenCL-JNA/NumericalBenchmark/src/main/java/fft/FFTBench.java +++ /dev/null @@ -1,217 +0,0 @@ -package fft; - -import com.nativelibs4java.opencl.util.fft.DoubleFFTPow2; -import com.nativelibs4java.opencl.util.fft.FloatFFTPow2; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.util.Transformer; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import com.nativelibs4java.opencl.util.fft.DoubleDFT; -import com.nativelibs4java.opencl.util.fft.FloatDFT; -import com.nativelibs4java.util.*; -import java.io.File; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.commons.math.complex.Complex; -import org.apache.commons.math.transform.FastFourierTransformer; - -/** - * MVN_OPTS=" -XX:+DoEscapeAnalysis -XX:+AggressiveOpts -XX:+UseCompressedOops -XX:+UseBiasedLocking -Xmx4g " mvn compile exec:java -Dexec.mainClass=fft.FFTBench - * @author ochafik - */ -public class FFTBench { - - static double[] complexToInterleavedDoubles(Complex[] complexInput) { - int length = complexInput.length; - double[] output = new double[length * 2]; - for (int i = 0; i < length; i++) { - int o = i * 2; - Complex c = complexInput[i]; - output[o] = c.getReal(); - output[o + 1] = c.getImaginary(); - } - return output; - } - static Complex[] interleavedDoublesToComplex(double[] input) { - int length = input.length / 2; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - int o = i * 2; - complexOutput[i] = new Complex(input[o], input[o + 1]); - } - return complexOutput; - } - static Complex[] realDoublesToComplex(double[] input) { - int length = input.length; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - complexOutput[i] = new Complex(input[i], 0); - } - return complexOutput; - } - static class ApacheComplexFFT extends AbstractTransformer { - FastFourierTransformer fft = new FastFourierTransformer(); - public ApacheComplexFFT() { - super(null, Double.class, DoubleBuffer.class); - } - - @Override - public double[] transform(CLQueue queue, double[] input, boolean inverse) { - Complex[] complexInput = interleavedDoublesToComplex(input); - Complex[] output = inverse ? - fft.inversetransform(complexInput) : - fft.transform(complexInput); - return complexToInterleavedDoubles(output); - } - - @Override - public CLEvent transform(CLQueue queue, CLBuffer input, CLBuffer output, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - throw new UnsupportedOperationException("Not supported yet."); - } - - } - static void assertArrayEquals(String title, Object a, Object b) { - if (a instanceof double[]) { - double[] aa = (double[])a, bb = (double[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionDouble) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } else if (a instanceof float[]) { - float[] aa = (float[])a, bb = (float[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionFloat) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } - } - static final float precisionFloat = 1e-3f; - static final double precisionDouble = 1e-10; - - static void gc() { - try { - System.gc(); - Thread.sleep(100); - System.gc(); - Thread.sleep(100); - } catch (InterruptedException ex) { - Logger.getLogger(FFTBench.class.getName()).log(Level.SEVERE, null, ex); - } - } - - static void test(String title, final Transformer tr, A warmupData, final A data, final CLQueue queue, boolean hasReverse, boolean firstRun) { - int warmups = 2500; - int tests = 5; - - - System.out.println("[" + title + "] Context = " + tr.getContext()); - if (firstRun) { - System.out.print("[" + title + "] Warming up..."); - for (int i = 0; i < warmups; i++) { - tr.transform(queue, warmupData, false); - if (hasReverse) - tr.transform(queue, warmupData, true); - } - System.out.println(); - } - - A trans = null; - if (hasReverse && !"1".equals(System.getenv("NO_REVERSE"))) { - System.out.print("[" + title + "] Checking consistency of inverse..."); - trans = tr.transform(queue, data, false); - A back = tr.transform(queue, trans, true); - assertArrayEquals(title, data, back); - System.out.println(); - } - gc(); - - for (int i = 0; i < tests; i++) { - time(title/* + " (transform)"*/, new Runnable() { public void run() { - tr.transform(queue, data, false); - }}); - gc(); - } - /* - if (hasReverse) - for (int i = 0; i < tests; i++) { - final A invData = trans; - time(title + " (inverse transform)", new Runnable() { public void run() { - tr.transform(queue, invData, true); - }}); - gc(); - } - */ - } - public static void main(String[] args) throws IOException, CLBuildException { - // Create a context with the best double numbers support possible : - // (try using DeviceFeature.GPU, DeviceFeature.CPU...) - - //Native.setPreserveLastError(true); - CLContext contextDoubles = JavaCL.createBestContext(DeviceFeature.DoubleSupport); - CLContext contextFloats = JavaCL.createBestContext(); - - // Create a command queue, if possible able to execute multiple jobs in parallel - // (out-of-order queues will still respect the CLEvent chaining) - CLQueue queueFloats = contextFloats.createDefaultOutOfOrderQueueIfPossible(); - CLQueue queueDoubles = contextDoubles.createDefaultOutOfOrderQueueIfPossible(); - - int nWarm = 8; - double[] warmDoubles = createTestDoubleData(nWarm); - float[] warmFloats = toFloat(warmDoubles); - boolean testDFT = false; - - boolean first = true; - for (int nTest : new int[] { 1024, 4 * 1024, 128 * 1024, 1024 * 1024, 8 * 1024 * 1024 }) { - double[] testDoubles = createTestDoubleData(nTest); - float[] testFloats = toFloat(testDoubles); - - String sizeSuffix = ", n = " + nTest; - test("JavaCL Float FFT" + sizeSuffix, new FloatFFTPow2(contextFloats), warmFloats, testFloats, queueFloats, true, first); - test("JavaCL Double FFT" + sizeSuffix, new DoubleFFTPow2(contextDoubles), warmDoubles, testDoubles, queueDoubles, true, first); - - test("Apache Complex FFT" + sizeSuffix, new ApacheComplexFFT(), warmDoubles, testDoubles, null, true, first); - //test("Apache Real FFT" + sizeSuffix, new ApacheRealFFT(), warmDoubles, testDoubles, null, false); - - if (testDFT) { - test("JavaCL Double DFT" + sizeSuffix, new DoubleDFT(contextDoubles), warmDoubles, testDoubles, queueDoubles, true, first); - test("JavaCL Float DFT" + sizeSuffix, new FloatDFT(contextFloats), warmFloats, testFloats, queueFloats, true, first); - } - if (first) - first = false; - } - } - static void time(String title, Runnable r) { - long start = System.nanoTime(); - r.run(); - long time = System.nanoTime() - start; - System.out.println("[" + title + "] = " + (time / 1000000.0) + " milliseconds"); - } - - static double[] toReal(double[] in) { - double[] inReal = new double[in.length / 2]; - for (int i = 0; i < inReal.length; i++) - inReal[i] = in[i / 2]; - - return inReal; - } - static float[] toFloat(double[] in) { - float[] out = new float[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = (float)in[i]; - - return out; - } - static double[] createTestDoubleData(int n) { - //int n = 1024 * 1024; - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double) (i + 1); - in[i * 2 + 1] = 0; - } - return in; - } -} diff --git a/libraries/OpenCL-JNA/NumericalBenchmark/src/main/scala/fft/FFTScala.scala b/libraries/OpenCL-JNA/NumericalBenchmark/src/main/scala/fft/FFTScala.scala deleted file mode 100644 index f5ff3161c..000000000 --- a/libraries/OpenCL-JNA/NumericalBenchmark/src/main/scala/fft/FFTScala.scala +++ /dev/null @@ -1,292 +0,0 @@ -package fft - -import com.nativelibs4java.opencl._ - -case class Interval(offset: Int, stride: Int, length: Int) { - - def /(parts: Int): Array[Interval] = { - val newLength = length / parts - val newStride = stride * parts - (0 until parts).map(i => Interval(offset + stride * i, newStride, newLength))(collection.breakOut) - } -} -trait Op -case class Op1(i: Interval) extends Op -case class Op2(o1: Op, o2: Op) extends Op -case class Op4(o1: Op, o2: Op, o3: Op, o4: Op) extends Op - -object FFTScala { - import scala.math._ - type Cx = (Double, Double) - - - implicit def tupleOps(a: Cx) = new { - def +(b: Cx) = - (a._1 + b._1, a._2 + b._2) - def -(b: Cx) = - (a._1 - b._1, a._2 - b._2) - - def x = a._1 - def y = a._2 - def r = x - def i = y - } - def sinCos(v: Double) = (sin(v), cos(v)) - def rotateValue(a: Cx, sinCos: Cx) = { - val (s, c) = sinCos - ( - c * a.x - s * a.y, - s * a.x + c * a.y - ) - } - def dot(a: Cx, b: Cx) = - a.x * b.x + a.y * b.y - - def conjugate(a: Cx) = - (-a.y, a.x) - - - def computeOp(i: Interval): Op = { - /*if ((i.length & 3) == 0) { // i.length is a multiple of 4 - val Array(o1, o2, o3, o4) = (i / 4) map computeOp - Op4(o1, o2, o3, o4) - } else*/ if ((i.length & 1) == 0) { // i.length is odd - val Array(o1, o2) = (i / 2) map computeOp - Op2(o1, o2) - } else { - Op1(i) - } - } - - // mvn package && java -classpath target/javacl-tutorial-1.0-beta-6.jar tutorial.FFTScala - // mvn scala:run -DmainClass=tutorial.FFTScala -DaddArgs=8 - def main(args: Array[String]): Unit = { - implicit val context = JavaCL.createBestContext(CLPlatform.DeviceFeature.DoubleSupport) - implicit val queue = context.createDefaultOutOfOrderQueueIfPossible - println("Context = " + context) - - val Array(n) = args.map(_.toInt) - val in = (0 until n).flatMap(i => Seq(i.toDouble, 0/*i / 5.0*/)).toArray//Array(1, 0, 2, 0, 3, 0, 4, 0, 5.0, 0, 6, 0) - println("Data = " + in.toSeq) - - import org.apache.commons.math.complex.Complex - import org.apache.commons.math.transform.FastFourierTransformer - val apache = new FastFourierTransformer - println("Apache = " + apache.transform(in.grouped(2).map({ case Array(x, y) => new Complex(x, y)}).toArray).map(c => (c.getReal, c.getImaginary)).toSeq) - - val outDitFFT2 = ditfft2(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - println("DITFFT2 = " + outDitFFT2.toSeq) - //println("BackDITFFT2 = " + ditfft2(outDitFFT2, false).toSeq) - - val outDitFFT4 = ditfft4InPlace(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - println("DITFFT4 = " + outDitFFT4.toSeq) - //println("BackDITFFT4 = " + ditfft4InPlace(outDitFFT4, false).toSeq) - - //val outDitFFTInPlace = fft.ditfft2InPlace(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - //println("DITFFT2InPlace = " + outDitFFTInPlace.toSeq) - //println("BackDITFFT2InPlace = " + fft.ditfft2InPlace(outDitFFTInPlace, false).toSeq) - - /*val outDitFFTInPlaceCL = fft.ditfft2InPlaceCL(in, true) - println("DITFFT2InPlace = " + outDitFFTInPlaceCL.toSeq) - println("BackDITFFT2InPlaceCL = " + fft.ditfft2InPlaceCL(outDitFFTInPlaceCL, false).toSeq) - */ - - //val outFFT = fft.fft(in, true) - //println("FFT = " + outFFT.toSeq) - //println("BackFFT = " + fft.fft(outFFT, false).toSeq) - } - - // http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm - def ditfft2(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = ditfft2(X, X.length, 1, !forward) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - def ditfft2InPlace(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = new Array[(Double, Double)](X.length) - ditfft2InPlace(X, X.length, 1, !forward, 0, Y, 0) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - - private def ditfft2(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offset: Int = 0): Array[(Double, Double)] = { - assert(N >= 0) - if (N == 1) { - //println("Terminal : " + offset) - Array(X(offset)) - } - else { - val N2 = N / 2 - val s2 = s * 2 - val Y = ditfft2(X, N2, s2, inverse, offset) ++ ditfft2(X, N2, s2, inverse, offset + s) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until N / 2) { - val param: Double = - 2 * Pi * k / N.toDouble * (if (inverse) -1 else 1) - val (s, c) = sinCos(param) - - val (y1Real, y1Imag) = Y(k) - val (y2Real, y2Imag) = Y(k + N / 2) - - // (c + i * s) * (y2Real + i * y2Imag) - - val vReal = c * y2Real - s * y2Imag - val vImag = c * y2Imag + s * y2Real - Y(k) = ( - y1Real + vReal, - y1Imag + vImag - ) - Y(k + N / 2) = ( - y1Real - vReal, - y1Imag - vImag - ) - } - Y - } - } - - def ditfft4InPlace(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = new Array[(Double, Double)](X.length) - ditfft4InPlace(X, X.length, 1, !forward, 0, Y, 0) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - - private def ditfft2InPlace(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offsetX: Int, Y: Array[(Double, Double)], offsetY: Int): Unit = { - //println("Inplace exec N = " + N + ", s = " + s + ", offsetX = " + offsetX + ", offsetY = " + offsetY) - assert(N >= 0) - if (N == 1) { - //println("Terminal : " + offsetX + " going to " + offsetY) - Y(offsetY) = X(offsetX) - //Array(X(offsetX)) - } - else { - val halfN = N / 2 - val twiceS = s * 2 - - ditfft2InPlace(X, halfN, twiceS, inverse, offsetX, Y, offsetY) - ditfft2InPlace(X, halfN, twiceS, inverse, offsetX + s, Y, offsetY + halfN) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until halfN) { - val param: Double = - 2 * Pi * k / N.toDouble * (if (inverse) -1 else 1) - val sc = sinCos(param) - - val p = Y(offsetY + k) - val p1 = Y(offsetY + k + N / 2) - - val t = rotateValue(p1, sc) - - Y(offsetY + k) = p + t - Y(offsetY + k + N / 2) = p - t - } - } - } - private def ditfft4InPlace(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offsetX: Int, Y: Array[(Double, Double)], offsetY: Int): Unit = { - //println("Inplace exec N = " + N + ", s = " + s + ", offsetX = " + offsetX + ", offsetY = " + offsetY) - assert(N > 0) - if (N <= 1) { - //println("Terminal : " + offsetX + " going to " + offsetY) - Y(offsetY) = X(offsetX) - //Array(X(offsetX)) - } - else { - val subN = N / 4 - val subS = s * 4 - - ditfft4InPlace(X, subN, subS, inverse, offsetX, Y, offsetY) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s, Y, offsetY + subN) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s * 2, Y, offsetY + subN * 2) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s * 3, Y, offsetY + subN * 3) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until subN) { - //val fullN = subN//X.length//N - val param: Double = - 2 * Pi * k / subN.toDouble * (if (inverse) -1 else 1) - val sc1 = sinCos(param * 1) - val sc2 = sinCos(param * 2) - val sc3 = sinCos(param * 3) - - val o = offsetY + k - val o1 = o + subN - val o2 = o + subN * 2 - val o3 = o + subN * 3 - - // http://cnx.org/content/m17384/latest/ - // http://perso.telecom-paristech.fr/~danger/amen_old/fft/ - // ftp://www.ce.cmu.edu/hsuantuc/Public/toolbox/rtw/targets/tic6000/tic6000/rtlib/include/c64/dsp_fft16x16t.h - - val p = Y(o) - val p1 = Y(o1) - val p2 = Y(o2) - val p3 = Y(o3) - - def rot(a: Cx, sinCos: Cx) = { - rotateValue(a, sinCos) - /* - val (x, y) = a - val (s, c) = sinCos; - ( - c * x + s * y, - c * y - s * x - )//*/ - } -/* - val t = p + p2 - val t1 = p1 + p3 - val t2 = p - p2 - val t3 = p1 - p3 - - println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = t + t1 - Y(o1) = rot(t2 - conjugate(t3), sc1) - Y(o2) = rot(t - t1, sc2) - Y(o3) = rot(t2 + conjugate(t3), sc3) -*/ - val th = p + p2 - val tl = p - p2 - val th2 = p1 + p3 - val tl2 = p1 - p3 - - println("N = " + N + ", o = " + o + " :\n\tth = " + th + ", tl = " + tl + ", th2 = " + th2 + ", tl2 = " + tl2 + "\n\tsc1 = " + sc1 + ", sc2 = " +sc2 + ", sc3 = " + sc3) - // println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = th + th2 - Y(o1) = rot(tl - conjugate(tl2), sc1) - Y(o2) = rot(th - th2, sc2) - Y(o3) = rot(tl + conjugate(tl2), sc3) - - /* - * - // println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = th + th2 - Y(o1) = rot(tl - conjugate(tl2), sc1) - Y(o2) = rot(th - th2, sc2) - Y(o3) = rot(tl + conjugate(tl2), sc3) - - */ - } - } - } -} -/* - -x x x x x x x x Interval(0, 1, 8) - -x x x x Interval(0, 2, 4) - x x x x Interval(1, 2, 4) - -x x Interval(0, 4, 2) - x x Interval(2, 4, 2) - x x Interval(1, 4, 2) - x x Interval(3, 4, 2) - -*/ \ No newline at end of file diff --git a/libraries/OpenCL-JNA/OpenCL4Java/.classpath b/libraries/OpenCL-JNA/OpenCL4Java/.classpath deleted file mode 100644 index 725911444..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/.classpath +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/.gitignore b/libraries/OpenCL-JNA/OpenCL4Java/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/.project b/libraries/OpenCL-JNA/OpenCL4Java/.project deleted file mode 100644 index acc46e366..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - OpenCL4Java - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 377e7a5f1..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:17 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL-JNA/OpenCL4Java/pom.xml b/libraries/OpenCL-JNA/OpenCL4Java/pom.xml deleted file mode 100644 index e6a0843e8..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - com.nativelibs4java - opencl4java-jna - OpenCL4Java / JNA - http://code.google.com/p/nativelibs4java/wiki/OpenCL - 1.0-SNAPSHOT - jar - - -OpenCL4Java is a thin Java wrapper around OpenCL's C API. -It uses JNA as its interop layer library, which means it works on all of the (many) JNA-supported platforms (see http://jna.dev.java.net/). -It is autogenerated by JNAerator (http://jnaerator.googlecode.com/), so updates to newer OpenCL specs are a matter of seconds. - -Note that OpenCL4Java is used by JavaCL, an Object-Oriented API that presents OpenCL in a much more practical, powerful and idiomatic way to Java. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - jnaerator-runtime - - ${jnaerator.version} - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/regenerate.cmd b/libraries/OpenCL-JNA/OpenCL4Java/regenerate.cmd deleted file mode 100644 index a46b7c5eb..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/regenerate.cmd +++ /dev/null @@ -1,3 +0,0 @@ -mvn com.jnaerator:maven-jnaerator-plugin:jnaerate -del src\main\scala\*.scala -mvn install \ No newline at end of file diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl.h deleted file mode 100644 index e2889a37e..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl.h +++ /dev/null @@ -1,872 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2009 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_address_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_command_queue_properties; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_uint cl_image_info; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - - - -/******************************************************************************/ - -// Error Codes -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 - -// OpenCL Version -#define CL_VERSION_1_0 1 - -// cl_bool -#define CL_FALSE 0 -#define CL_TRUE 1 - -// cl_platform_info -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 - -// cl_device_type - bitfield -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -// cl_device_info -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 - -// cl_device_fp_config - bitfield -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) - -// cl_device_mem_cache_type -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -// cl_device_local_mem_type -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -// cl_device_exec_capabilities - bitfield -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -// cl_command_queue_properties - bitfield -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) - -// cl_context_info -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 - -// cl_context_properties -#define CL_CONTEXT_PLATFORM 0x1084 - -// cl_command_queue_info -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 - -// cl_mem_flags - bitfield -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) - -// cl_channel_order -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 - -// cl_channel_type -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE - -// cl_mem_object_type -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 - -// cl_mem_info -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 - -// cl_image_info -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 - -// cl_addressing_mode -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 - -// cl_filter_mode -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -// cl_sampler_info -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 - -// cl_map_flags - bitfield -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) - -// cl_program_info -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 - -// cl_program_build_info -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 - -// cl_build_status -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -// cl_kernel_info -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 - -// cl_kernel_work_group_info -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 - -// cl_event_info -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 - -// cl_command_type -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 - -// command execution status -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -// cl_profiling_info -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 - -/********************************************************************************************************/ - -// Platform API -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Device APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Context APIs -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (*pfn_notify)(const char *, const void *, size_t, void *) /* pfn_notify */, - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (*pfn_notify)(const char *, const void *, size_t, void *) /* pfn_notify */, - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Command Queue APIs -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetCommandQueueProperty(cl_command_queue /* command_queue */, - cl_command_queue_properties /* properties */, - cl_bool /* enable */, - cl_command_queue_properties * /* old_properties */) CL_API_SUFFIX__VERSION_1_0; - -// Memory Object APIs -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Sampler APIs -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Program Object APIs -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (*pfn_notify)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Kernel Object APIs -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Event Object APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -// Profiling APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Flush and Finish APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -// Enqueued Commands APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* cb */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* cb */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (*user_func)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -// Extension function access -// -// Returns the extension function address for the given function name, -// or NULL if a valid function can not be found. The client must -// check to make sure the address is not NULL, before using or -// calling the returned function address. -// -extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddress(const char * /* func_name */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif // __OPENCL_CL_H - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h deleted file mode 100644 index f8ee05c40..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h +++ /dev/null @@ -1,124 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2009 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 8407 $ on $Date: 2009-06-12 10:56:38 -0700 (Fri, 12 Jun 2009) $ */ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#include -#else -#include -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// NOTE: Make sure that appropriate GL header file is included separately - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; - -// cl_gl_object_type -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 - -// cl_gl_texture_info -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 - -// CL_KHR_gl_sharing -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - GLenum /* target */, - GLint /* miplevel */, - GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - GLenum /* target */, - GLint /* miplevel */, - GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif // __OPENCL_CL_GL_H diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h deleted file mode 100644 index 95810d637..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h +++ /dev/null @@ -1,302 +0,0 @@ -/* ============================================================ - -Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved. - -Redistribution and use of this material is permitted under the following -conditions: - -Redistributions must retain the above copyright notice and all terms of this -license. - -In no event shall anyone redistributing or accessing or using this material -commence or participate in any arbitration or legal action relating to this -material against Advanced Micro Devices, Inc. or any copyright holders or -contributors. The foregoing shall survive any expiration or termination of -this license or any agreement or access or use related to this material. - -ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION -OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. - -THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT -HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY -REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO -SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERATION, OR THAT IT IS FREE -FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER -EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED -WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, -ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. -IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT -OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY -ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES, -INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS -(US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS -THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND -ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, -OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE -FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE -CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR -DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR -CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE -THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL -SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR -ACCESS OR USE RELATED TO THIS MATERIAL. - -NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS -MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO -RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER -COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH -AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS -DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. -MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, -EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, -INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS, -COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS. -MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY -LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. - -NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is -provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to -computer software and technical data, respectively. Use, duplication, -distribution or disclosure by the U.S. Government and/or DOD agencies is -subject to the full extent of restrictions in all applicable regulations, -including those found at FAR52.227 and DFARS252.227 et seq. and any successor -regulations thereof. Use of this material by the U.S. Government and/or DOD -agencies is acknowledgment of the proprietary rights of any copyright holders -and contributors, including those of Advanced Micro Devices, Inc., as well as -the provisions of FAR52.227-14 through 23 regarding privately developed and/or -commercial computer software. - -This license forms the entire agreement regarding the subject matter hereof and -supersedes all proposals and prior discussions and writings between the parties -with respect thereto. This license does not affect any ownership, rights, title, -or interest in, or relating to, this material. No terms of this license can be -modified or waived, and no breach of this license can be excused, unless done -so in a writing signed by all affected parties. Each term of this license is -separately enforceable. If any term of this license is determined to be or -becomes unenforceable or illegal, such term shall be reformed to the minimum -extent necessary in order for this license to remain in effect in accordance - -with its terms as modified by such reformation. This license shall be governed -by and construed in accordance with the laws of the State of Texas without -regard to rules on conflicts of law of any state or jurisdiction or the United -Nations Convention on the International Sale of Goods. All disputes arising out -of this license shall be subject to the jurisdiction of the federal and state -courts in Austin, Texas, and all defenses are hereby waived concerning personal -jurisdiction and venue of these courts. - -============================================================ */ - -#ifndef CL_PLATFORM_H_ -#define CL_PLATFORM_H_ - -#if !defined(_WIN32) -# include -#endif /* !_WIN32 */ -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifdef _MSC_VER -# define __CL_IMPORT __declspec(dllimport) -# define __CL_EXPORT -# define __CL_CALL __stdcall -# define __CL_SUFFIX -#else -# define __CL_IMPORT -# define __CL_EXPORT -# define __CL_CALL -# define __CL_SUFFIX -#endif - -#define CL_API_CALL __CL_CALL -#define CL_API_SUFFIX __CL_SUFFIX -#define CL_API_SUFFIX__VERSION_1_0 CL_API_SUFFIX -#define CL_EXTENSION_WEAK_LINK - -#ifdef OPENCL_EXPORTS -# define CL_API_ENTRY __CL_EXPORT -#else /* !OPENCL_EXPORTS */ -# define CL_API_ENTRY __CL_IMPORT -#endif /* !OPENCL_EXPORTS */ - -#if defined(_WIN32) -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; -typedef unsigned __int16 cl_half; -#else /* !_WIN32 */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short; -typedef uint16_t cl_ushort; -typedef int32_t cl_int; -typedef uint32_t cl_uint; -typedef int64_t cl_long; -typedef uint64_t cl_ulong; -typedef uint16_t cl_half; -#endif /* !_WIN32 */ -typedef float cl_float; -typedef double cl_double; - -typedef union cl_half2 { cl_half i16[2]; } cl_half2; -typedef union cl_half4 { cl_half i16[4]; } cl_half4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_half cl_half8 __attribute__ ((__vector_size__ (16))); -typedef cl_half cl_half16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_half8 { cl_half i16[8]; } cl_half8; -typedef union cl_half16 { cl_half i16[16]; } cl_half16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_char2 { cl_char i8[2]; } cl_char2; -typedef union cl_char4 { cl_char i8[4]; } cl_char4; -typedef union cl_char8 { cl_char i8[8]; } cl_char8; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_char cl_char16 __attribute__ ((__vector_size__ (16))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_char16 { cl_char i8[16]; } cl_char16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uchar2 { cl_uchar u8[2]; } cl_uchar2; -typedef union cl_uchar4 { cl_uchar u8[4]; } cl_uchar4; -typedef union cl_uchar8 { cl_uchar u8[8]; } cl_uchar8; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_uchar cl_uchar16 __attribute__ ((__vector_size__ (16))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uchar16 { cl_uchar u8[16]; } cl_uchar16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_short2 { cl_short i16[2]; } cl_short2; -typedef union cl_short4 { cl_short i16[4]; } cl_short4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_short cl_short8 __attribute__ ((__vector_size__ (16))); -typedef cl_short cl_short16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_short8 { cl_short i16[8]; } cl_short8; -typedef union cl_short16 { cl_short i16[16]; } cl_short16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ushort2 { cl_ushort u16[2]; } cl_ushort2; -typedef union cl_ushort4 { cl_ushort u16[4]; } cl_ushort4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_ushort cl_ushort8 __attribute__ ((__vector_size__ (16))); -typedef cl_ushort cl_ushort16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ushort8 { cl_ushort u16[8]; } cl_ushort8; -typedef union cl_ushort16 { cl_ushort u16[16]; } cl_ushort16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_int2 { cl_int i32[2]; } cl_int2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_int cl_int4 __attribute__ ((__vector_size__ (16))); -typedef cl_int cl_int8 __attribute__ ((__vector_size__ (32))); -typedef cl_int cl_int16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_int4 { cl_int i32[4]; } cl_int4; -typedef union cl_int8 { cl_int i32[8]; } cl_int8; -typedef union cl_int16 { cl_int i32[16]; } cl_int16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uint2 { cl_uint u32[2]; } cl_uint2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_uint cl_uint4 __attribute__ ((__vector_size__ (16))); -typedef cl_uint cl_uint8 __attribute__ ((__vector_size__ (32))); -typedef cl_uint cl_uint16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uint4 { cl_uint u32[4]; } cl_uint4; -typedef union cl_uint8 { cl_uint u32[8]; } cl_uint8; -typedef union cl_uint16 { cl_uint u32[16]; } cl_uint16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_long cl_long2 __attribute__ ((__vector_size__ (16))); -typedef cl_long cl_long4 __attribute__ ((__vector_size__ (32))); -typedef cl_long cl_long8 __attribute__ ((__vector_size__ (64))); -typedef cl_long cl_long16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_long2 { cl_long i64[2]; } cl_long2; -typedef union cl_long4 { cl_long i64[4]; } cl_long4; -typedef union cl_long8 { cl_long i64[8]; } cl_long8; -typedef union cl_long16 { cl_long i64[16]; } cl_long16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_ulong cl_ulong2 __attribute__ ((__vector_size__ (16))); -typedef cl_ulong cl_ulong4 __attribute__ ((__vector_size__ (32))); -typedef cl_ulong cl_ulong8 __attribute__ ((__vector_size__ (64))); -typedef cl_ulong cl_ulong16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ulong2 { cl_ulong u64[2]; } cl_ulong2; -typedef union cl_ulong4 { cl_ulong u64[4]; } cl_ulong4; -typedef union cl_ulong8 { cl_ulong u64[8]; } cl_ulong8; -typedef union cl_ulong16 { cl_ulong u64[16]; } cl_ulong16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_float2 { cl_float f32[2]; } cl_float2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_float cl_float4 __attribute__ ((__vector_size__ (16))); -typedef cl_float cl_float8 __attribute__ ((__vector_size__ (32))); -typedef cl_float cl_float16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_float4 { cl_float f32[4]; } cl_float4; -typedef union cl_float8 { cl_float f32[8]; } cl_float8; -typedef union cl_float16 { cl_float f32[16]; } cl_float16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_double cl_double2 __attribute__ ((__vector_size__ (16))); -typedef cl_double cl_double4 __attribute__ ((__vector_size__ (32))); -typedef cl_double cl_double8 __attribute__ ((__vector_size__ (64))); -typedef cl_double cl_double16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_double2 { cl_double f64[2]; } cl_double2; -typedef union cl_double4 { cl_double f64[4]; } cl_double4; -typedef union cl_double8 { cl_double f64[8]; } cl_double8; -typedef union cl_double16 { cl_double f64[16]; } cl_double16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ - -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX FLT_MAX -#define CL_FLT_MIN FLT_MIN -#define CL_FLT_EPSILON FLT_EPSILON - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX DBL_MAX -#define CL_DBL_MIN DBL_MIN -#define CL_DBL_EPSILON DBL_EPSILON - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* __cplusplus */ - -#endif /* CL_PLATFORM_H_ */ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl.h deleted file mode 100644 index acd18cd2d..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl.h +++ /dev/null @@ -1,997 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_command_queue_properties; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_uint cl_image_info; -typedef cl_uint cl_buffer_create_type; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - - -typedef struct _cl_buffer_region { - size_t origin; - size_t size; -} cl_buffer_region; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 -#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 -#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 - -/* OpenCL Version */ -#define CL_VERSION_1_0 1 -#define CL_VERSION_1_1 1 - -/* cl_bool */ -#define CL_FALSE 0 -#define CL_TRUE 1 - -/* cl_platform_info */ -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 - -/* cl_device_type - bitfield */ -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -/* cl_device_info */ -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 -/* 0x1032 reserved for CL_DEVICE_DOUBLE_FP_CONFIG */ -/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 -#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C -#define CL_DEVICE_OPENCL_C_VERSION 0x103D - -/* cl_device_fp_config - bitfield */ -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) -#define CL_FP_SOFT_FLOAT (1 << 6) - -/* cl_device_mem_cache_type */ -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -/* cl_device_local_mem_type */ -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -/* cl_device_exec_capabilities - bitfield */ -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -/* cl_command_queue_properties - bitfield */ -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) - -/* cl_context_info */ -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 -#define CL_CONTEXT_NUM_DEVICES 0x1083 - -/* cl_context_info + cl_context_properties */ -#define CL_CONTEXT_PLATFORM 0x1084 - -/* cl_command_queue_info */ -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 - -/* cl_mem_flags - bitfield */ -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) - -/* cl_channel_order */ -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 -#define CL_Rx 0x10BA -#define CL_RGx 0x10BB -#define CL_RGBx 0x10BC - -/* cl_channel_type */ -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE - -/* cl_mem_object_type */ -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 - -/* cl_mem_info */ -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 -#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 -#define CL_MEM_OFFSET 0x1108 - -/* cl_image_info */ -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 - -/* cl_addressing_mode */ -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 -#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 - -/* cl_filter_mode */ -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -/* cl_sampler_info */ -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 - -/* cl_map_flags - bitfield */ -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) - -/* cl_program_info */ -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 - -/* cl_program_build_info */ -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 - -/* cl_build_status */ -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -/* cl_kernel_info */ -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 - -/* cl_kernel_work_group_info */ -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 -#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 -#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 - -/* cl_event_info */ -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 -#define CL_EVENT_CONTEXT 0x11D4 - -/* cl_command_type */ -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 -#define CL_COMMAND_READ_BUFFER_RECT 0x1201 -#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 -#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 -#define CL_COMMAND_USER 0x1204 - -/* command execution status */ -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -/* cl_buffer_create_type */ -#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 - -/* cl_profiling_info */ -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 - -/********************************************************************************************************/ - -/* Platform API */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Device APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Context APIs */ -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Command Queue APIs */ -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS -#warning CL_USE_DEPRECATED_OPENCL_1_0_APIS is defined. These APIs are unsupported and untested in OpenCL 1.1! -/* - * WARNING: - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. - * - * Software developers previously relying on this API are instructed to set the command queue - * properties when creating the queue, instead. - */ -extern CL_API_ENTRY cl_int CL_API_CALL -clSetCommandQueueProperty(cl_command_queue /* command_queue */, - cl_command_queue_properties /* properties */, - cl_bool /* enable */, - cl_command_queue_properties * /* old_properties */) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED; -#endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ - -/* Memory Object APIs */ -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateSubBuffer(cl_mem /* buffer */, - cl_mem_flags /* flags */, - cl_buffer_create_type /* buffer_create_type */, - const void * /* buffer_create_info */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetMemObjectDestructorCallback( cl_mem /* memobj */, - void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; - -/* Sampler APIs */ -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Program Object APIs */ -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Kernel Object APIs */ -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Event Object APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateUserEvent(cl_context /* context */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetUserEventStatus(cl_event /* event */, - cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetEventCallback( cl_event /* event */, - cl_int /* command_exec_callback_type */, - void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; - -/* Profiling APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Flush and Finish APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Enqueued Commands APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* cb */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* cb */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin */, - const size_t * /* dst_origin */, - const size_t * /* region */, - size_t /* src_row_pitch */, - size_t /* src_slice_pitch */, - size_t /* dst_row_pitch */, - size_t /* dst_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (*user_func)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Extension function access - * - * Returns the extension function address for the given function name, - * or NULL if a valid function can not be found. The client must - * check to make sure the address is not NULL, before using or - * calling the returned function address. - */ -extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddress(const char * /* func_name */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_H */ - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h deleted file mode 100644 index f5f7371e4..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11687 $ on $Date: 2010-06-11 15:17:22 -0700 (Fri, 11 Jun 2010) $ */ - -/* cl_ext.h contains OpenCL extensions which don't have external */ -/* (OpenGL, D3D) dependencies. */ - -#ifndef __CL_EXT_H -#define __CL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include - #include -#else - #include -#endif - -/* cl_khr_fp64 extension - no extension #define since it has no functions */ -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 - -/* cl_khr_fp16 extension - no extension #define since it has no functions */ -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 - -/* Memory object destruction - * - * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR - * - * Registers a user callback function that will be called when the memory object is deleted and its resources - * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback - * stack associated with memobj. The registered user callback functions are called in the reverse order in - * which they were registered. The user callback functions are called and then the memory object is deleted - * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be - * notified when the memory referenced by host_ptr, specified when the memory object is created and used as - * the storage bits for the memory object, can be reused or freed. - * - * The application may not call CL api's with the cl_mem object passed to the pfn_notify. - * - * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - */ -#define cl_APPLE_SetMemObjectDestructor 1 -cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, - void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/* Context Logging Functions - * - * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). - * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - * - * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger - */ -#define cl_APPLE_ContextLoggingFunctions 1 -extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ -extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ -extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/************************ -* cl_khr_icd extension * -************************/ -#define cl_khr_icd 1 - -/* cl_platform_info */ -#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 - -/* Additional Error Codes */ -#define CL_PLATFORM_NOT_FOUND_KHR -1001 - -extern CL_API_ENTRY cl_int CL_API_CALL -clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( - cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - - -/****************************************** -* cl_nv_device_attribute_query extension * -******************************************/ -/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ -#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 -#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 -#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 -#define CL_DEVICE_WARP_SIZE_NV 0x4003 -#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 -#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 -#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 - - -/********************************* -* cl_amd_device_attribute_query * -*********************************/ -#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 - - -#ifdef CL_VERSION_1_1 - /*********************************** - * cl_ext_device_fission extension * - ***********************************/ - #define cl_ext_device_fission 1 - - extern CL_API_ENTRY cl_int CL_API_CALL - clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int CL_API_CALL - clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef cl_ulong cl_device_partition_property_ext; - extern CL_API_ENTRY cl_int CL_API_CALL - clCreateSubDevicesEXT( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int - ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - /* cl_device_partition_property_ext */ - #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 - #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 - #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 - #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 - - /* clDeviceGetInfo selectors */ - #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 - #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 - #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 - #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 - #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 - - /* error codes */ - #define CL_DEVICE_PARTITION_FAILED_EXT -1057 - #define CL_INVALID_PARTITION_COUNT_EXT -1058 - #define CL_INVALID_PARTITION_NAME_EXT -1059 - - /* CL_AFFINITY_DOMAINs */ - #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 - #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 - #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 - #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 - #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 - #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 - - /* cl_device_partition_property_ext list terminators */ - #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) - - - -#endif /* CL_VERSION_1_1 */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __CL_EXT_H */ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h deleted file mode 100644 index 3b4fe0690..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h +++ /dev/null @@ -1,155 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* - * cl_gl.h contains Khronos-approved (KHR) OpenCL extensions which have - * OpenGL dependencies. The application is responsible for #including - * OpenGL or OpenGL ES headers before #including cl_gl.h. - */ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; -typedef struct __GLsync *cl_GLsync; - -/* cl_gl_object_type */ -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 - -/* cl_gl_texture_info */ -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -/* cl_khr_gl_sharing extension */ - -#define cl_khr_gl_sharing 1 - -typedef cl_uint cl_gl_context_info; - -/* Additional Error Codes */ -#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 - -/* cl_gl_context_info */ -#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 -#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 - -/* Additional cl_context_properties */ -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLContextInfoKHR(const cl_context_properties * /* properties */, - cl_gl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( - const cl_context_properties * properties, - cl_gl_context_info param_name, - size_t param_value_size, - void * param_value, - size_t * param_value_size_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_H */ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h deleted file mode 100644 index 26e47821f..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h +++ /dev/null @@ -1,69 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ -/* OpenGL dependencies. */ - -#ifndef __OPENCL_CL_GL_EXT_H -#define __OPENCL_CL_GL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include -#else - #include -#endif - -/* - * For each extension, follow this template - * /* cl_VEN_extname extension */ -/* #define cl_VEN_extname 1 - * ... define new types, if any - * ... define new tokens, if any - * ... define new APIs, if any - * - * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header - * This allows us to avoid having to decide whether to include GL headers or GLES here. - */ - -/* - * cl_khr_gl_event extension - * See section 9.9 in the OpenCL 1.1 spec for more information - */ -#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromGLsyncKHR(cl_context /* context */, - cl_GLsync /* cl_GLsync */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h deleted file mode 100644 index b102ca5a2..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h +++ /dev/null @@ -1,1175 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __CL_PLATFORM_H -#define __CL_PLATFORM_H - -#ifdef __APPLE__ - /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ - #include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) - #define CL_API_ENTRY - #define CL_API_CALL __stdcall - #define CL_CALLBACK __stdcall -#else - #define CL_API_ENTRY - #define CL_API_CALL - #define CL_CALLBACK -#endif - -#ifdef __APPLE__ - #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) - #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_API_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER -#else - #define CL_EXTENSION_WEAK_LINK - #define CL_API_SUFFIX__VERSION_1_0 - #define CL_EXT_SUFFIX__VERSION_1_0 - #define CL_API_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED -#endif - -#if (defined (_WIN32) && defined(_MSC_VER)) - -/* scalar types */ -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; - -typedef unsigned __int16 cl_half; -typedef float cl_float; -typedef double cl_double; - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 340282346638528859811704183484516925440.0f -#define CL_FLT_MIN 1.175494350822287507969e-38f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 -#define CL_DBL_MIN 2.225073858507201383090e-308 -#define CL_DBL_EPSILON 2.220446049250313080847e-16 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#define CL_NAN (CL_INFINITY - CL_INFINITY) -#define CL_HUGE_VALF ((cl_float) 1e50) -#define CL_HUGE_VAL ((cl_double) 1e500) -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#else - -#include - -/* scalar types */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short __attribute__((aligned(2))); -typedef uint16_t cl_ushort __attribute__((aligned(2))); -typedef int32_t cl_int __attribute__((aligned(4))); -typedef uint32_t cl_uint __attribute__((aligned(4))); -typedef int64_t cl_long __attribute__((aligned(8))); -typedef uint64_t cl_ulong __attribute__((aligned(8))); - -typedef uint16_t cl_half __attribute__((aligned(2))); -typedef float cl_float __attribute__((aligned(4))); -typedef double cl_double __attribute__((aligned(8))); - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 0x1.fffffep127f -#define CL_FLT_MIN 0x1.0p-126f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 0x1.fffffffffffffp1023 -#define CL_DBL_MIN 0x1.0p-1022 -#define CL_DBL_EPSILON 0x1.0p-52 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#if defined( __GNUC__ ) - #define CL_HUGE_VALF __builtin_huge_valf() - #define CL_HUGE_VAL __builtin_huge_val() - #define CL_NAN __builtin_nanf( "" ) -#else - #define CL_HUGE_VALF ((cl_float) 1e50) - #define CL_HUGE_VAL ((cl_double) 1e500) - float nanf( const char * ); - #define CL_NAN nanf( "" ) -#endif -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#endif - -#include - -/* Mirror types to GL types. Mirror types allow us to avoid deciding which headers to load based on whether we are using GL or GLES here. */ -typedef unsigned int cl_GLuint; -typedef int cl_GLint; -typedef unsigned int cl_GLenum; - -/* - * Vector types - * - * Note: OpenCL requires that all types be naturally aligned. - * This means that vector types must be naturally aligned. - * For example, a vector of four floats must be aligned to - * a 16 byte boundary (calculated as 4 * the natural 4-byte - * alignment of the float). The alignment qualifiers here - * will only function properly if your compiler supports them - * and if you don't actively work to defeat them. For example, - * in order for a cl_float4 to be 16 byte aligned in a struct, - * the start of the struct must itself be 16-byte aligned. - * - * Maintaining proper alignment is the user's responsibility. - */ - -/* Define basic vector types */ -#if defined( __VEC__ ) - #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ - typedef vector unsigned char __cl_uchar16; - typedef vector signed char __cl_char16; - typedef vector unsigned short __cl_ushort8; - typedef vector signed short __cl_short8; - typedef vector unsigned int __cl_uint4; - typedef vector signed int __cl_int4; - typedef vector float __cl_float4; - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_UINT4__ 1 - #define __CL_INT4__ 1 - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef float __cl_float4 __attribute__((vector_size(16))); - #else - typedef __m128 __cl_float4; - #endif - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE2__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); - typedef cl_char __cl_char16 __attribute__((vector_size(16))); - typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); - typedef cl_short __cl_short8 __attribute__((vector_size(16))); - typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); - typedef cl_int __cl_int4 __attribute__((vector_size(16))); - typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); - typedef cl_long __cl_long2 __attribute__((vector_size(16))); - typedef cl_double __cl_double2 __attribute__((vector_size(16))); - #else - typedef __m128i __cl_uchar16; - typedef __m128i __cl_char16; - typedef __m128i __cl_ushort8; - typedef __m128i __cl_short8; - typedef __m128i __cl_uint4; - typedef __m128i __cl_int4; - typedef __m128i __cl_ulong2; - typedef __m128i __cl_long2; - typedef __m128d __cl_double2; - #endif - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_INT4__ 1 - #define __CL_UINT4__ 1 - #define __CL_ULONG2__ 1 - #define __CL_LONG2__ 1 - #define __CL_DOUBLE2__ 1 -#endif - -#if defined( __MMX__ ) - #include - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); - typedef cl_char __cl_char8 __attribute__((vector_size(8))); - typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); - typedef cl_short __cl_short4 __attribute__((vector_size(8))); - typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); - typedef cl_int __cl_int2 __attribute__((vector_size(8))); - typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); - typedef cl_long __cl_long1 __attribute__((vector_size(8))); - typedef cl_float __cl_float2 __attribute__((vector_size(8))); - #else - typedef __m64 __cl_uchar8; - typedef __m64 __cl_char8; - typedef __m64 __cl_ushort4; - typedef __m64 __cl_short4; - typedef __m64 __cl_uint2; - typedef __m64 __cl_int2; - typedef __m64 __cl_ulong1; - typedef __m64 __cl_long1; - typedef __m64 __cl_float2; - #endif - #define __CL_UCHAR8__ 1 - #define __CL_CHAR8__ 1 - #define __CL_USHORT4__ 1 - #define __CL_SHORT4__ 1 - #define __CL_INT2__ 1 - #define __CL_UINT2__ 1 - #define __CL_ULONG1__ 1 - #define __CL_LONG1__ 1 - #define __CL_FLOAT2__ 1 -#endif - -#if defined( __AVX__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_float __cl_float8 __attribute__((vector_size(32))); - typedef cl_double __cl_double4 __attribute__((vector_size(32))); - #else - typedef __m256 __cl_float8; - typedef __m256d __cl_double4; - #endif - #define __CL_FLOAT8__ 1 - #define __CL_DOUBLE4__ 1 -#endif - -/* Define alignment keys */ -#if defined( __GNUC__ ) - #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) -#elif defined( _WIN32) && (_MSC_VER) - /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ - /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ - /* #include */ - /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ - #define CL_ALIGNED(_x) -#else - #warning Need to implement some method to align data here - #define CL_ALIGNED(_x) -#endif - -/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - /* .xyzw and .s0123...{f|F} are supported */ - #define CL_HAS_NAMED_VECTOR_FIELDS 1 - /* .hi and .lo are supported */ - #define CL_HAS_HI_LO_VECTOR_FIELDS 1 -#endif - -/* Define cl_vector types */ - -/* ---- cl_charn ---- */ -typedef union -{ - cl_char CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y; }; - __extension__ struct{ cl_char s0, s1; }; - __extension__ struct{ cl_char lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2; -#endif -}cl_char2; - -typedef union -{ - cl_char CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3; }; - __extension__ struct{ cl_char2 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[2]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4; -#endif -}cl_char4; - -/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ -typedef cl_char4 cl_char3; - -typedef union -{ - cl_char CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_char4 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[4]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[2]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8; -#endif -}cl_char8; - -typedef union -{ - cl_char CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_char8 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[8]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[4]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8[2]; -#endif -#if defined( __CL_CHAR16__ ) - __cl_char16 v16; -#endif -}cl_char16; - - -/* ---- cl_ucharn ---- */ -typedef union -{ - cl_uchar CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y; }; - __extension__ struct{ cl_uchar s0, s1; }; - __extension__ struct{ cl_uchar lo, hi; }; -#endif -#if defined( __cl_uchar2__) - __cl_uchar2 v2; -#endif -}cl_uchar2; - -typedef union -{ - cl_uchar CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3; }; - __extension__ struct{ cl_uchar2 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[2]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4; -#endif -}cl_uchar4; - -/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ -typedef cl_uchar4 cl_uchar3; - -typedef union -{ - cl_uchar CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uchar4 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[4]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[2]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8; -#endif -}cl_uchar8; - -typedef union -{ - cl_uchar CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uchar8 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[8]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[4]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8[2]; -#endif -#if defined( __CL_UCHAR16__ ) - __cl_uchar16 v16; -#endif -}cl_uchar16; - - -/* ---- cl_shortn ---- */ -typedef union -{ - cl_short CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y; }; - __extension__ struct{ cl_short s0, s1; }; - __extension__ struct{ cl_short lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2; -#endif -}cl_short2; - -typedef union -{ - cl_short CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3; }; - __extension__ struct{ cl_short2 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[2]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4; -#endif -}cl_short4; - -/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ -typedef cl_short4 cl_short3; - -typedef union -{ - cl_short CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_short4 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[4]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[2]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8; -#endif -}cl_short8; - -typedef union -{ - cl_short CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_short8 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[8]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[4]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8[2]; -#endif -#if defined( __CL_SHORT16__ ) - __cl_short16 v16; -#endif -}cl_short16; - - -/* ---- cl_ushortn ---- */ -typedef union -{ - cl_ushort CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y; }; - __extension__ struct{ cl_ushort s0, s1; }; - __extension__ struct{ cl_ushort lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2; -#endif -}cl_ushort2; - -typedef union -{ - cl_ushort CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3; }; - __extension__ struct{ cl_ushort2 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[2]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4; -#endif -}cl_ushort4; - -/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ -typedef cl_ushort4 cl_ushort3; - -typedef union -{ - cl_ushort CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ushort4 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[4]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[2]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8; -#endif -}cl_ushort8; - -typedef union -{ - cl_ushort CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ushort8 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[8]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[4]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8[2]; -#endif -#if defined( __CL_USHORT16__ ) - __cl_ushort16 v16; -#endif -}cl_ushort16; - -/* ---- cl_intn ---- */ -typedef union -{ - cl_int CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y; }; - __extension__ struct{ cl_int s0, s1; }; - __extension__ struct{ cl_int lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2; -#endif -}cl_int2; - -typedef union -{ - cl_int CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3; }; - __extension__ struct{ cl_int2 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[2]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4; -#endif -}cl_int4; - -/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ -typedef cl_int4 cl_int3; - -typedef union -{ - cl_int CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_int4 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[4]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[2]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8; -#endif -}cl_int8; - -typedef union -{ - cl_int CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_int8 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[8]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[4]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8[2]; -#endif -#if defined( __CL_INT16__ ) - __cl_int16 v16; -#endif -}cl_int16; - - -/* ---- cl_uintn ---- */ -typedef union -{ - cl_uint CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y; }; - __extension__ struct{ cl_uint s0, s1; }; - __extension__ struct{ cl_uint lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2; -#endif -}cl_uint2; - -typedef union -{ - cl_uint CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3; }; - __extension__ struct{ cl_uint2 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[2]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4; -#endif -}cl_uint4; - -/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ -typedef cl_uint4 cl_uint3; - -typedef union -{ - cl_uint CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uint4 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[4]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[2]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8; -#endif -}cl_uint8; - -typedef union -{ - cl_uint CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uint8 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[8]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[4]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8[2]; -#endif -#if defined( __CL_UINT16__ ) - __cl_uint16 v16; -#endif -}cl_uint16; - -/* ---- cl_longn ---- */ -typedef union -{ - cl_long CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y; }; - __extension__ struct{ cl_long s0, s1; }; - __extension__ struct{ cl_long lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2; -#endif -}cl_long2; - -typedef union -{ - cl_long CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3; }; - __extension__ struct{ cl_long2 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[2]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4; -#endif -}cl_long4; - -/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ -typedef cl_long4 cl_long3; - -typedef union -{ - cl_long CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_long4 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[4]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[2]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8; -#endif -}cl_long8; - -typedef union -{ - cl_long CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_long8 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[8]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[4]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8[2]; -#endif -#if defined( __CL_LONG16__ ) - __cl_long16 v16; -#endif -}cl_long16; - - -/* ---- cl_ulongn ---- */ -typedef union -{ - cl_ulong CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y; }; - __extension__ struct{ cl_ulong s0, s1; }; - __extension__ struct{ cl_ulong lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2; -#endif -}cl_ulong2; - -typedef union -{ - cl_ulong CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3; }; - __extension__ struct{ cl_ulong2 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[2]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4; -#endif -}cl_ulong4; - -/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ -typedef cl_ulong4 cl_ulong3; - -typedef union -{ - cl_ulong CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ulong4 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[4]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[2]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8; -#endif -}cl_ulong8; - -typedef union -{ - cl_ulong CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ulong8 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[8]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[4]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8[2]; -#endif -#if defined( __CL_ULONG16__ ) - __cl_ulong16 v16; -#endif -}cl_ulong16; - - -/* --- cl_floatn ---- */ - -typedef union -{ - cl_float CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y; }; - __extension__ struct{ cl_float s0, s1; }; - __extension__ struct{ cl_float lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2; -#endif -}cl_float2; - -typedef union -{ - cl_float CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3; }; - __extension__ struct{ cl_float2 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[2]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4; -#endif -}cl_float4; - -/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ -typedef cl_float4 cl_float3; - -typedef union -{ - cl_float CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_float4 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[4]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[2]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8; -#endif -}cl_float8; - -typedef union -{ - cl_float CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_float8 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[8]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[4]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8[2]; -#endif -#if defined( __CL_FLOAT16__ ) - __cl_float16 v16; -#endif -}cl_float16; - -/* --- cl_doublen ---- */ - -typedef union -{ - cl_double CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y; }; - __extension__ struct{ cl_double s0, s1; }; - __extension__ struct{ cl_double lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2; -#endif -}cl_double2; - -typedef union -{ - cl_double CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3; }; - __extension__ struct{ cl_double2 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[2]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4; -#endif -}cl_double4; - -/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ -typedef cl_double4 cl_double3; - -typedef union -{ - cl_double CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_double4 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[4]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[2]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8; -#endif -}cl_double8; - -typedef union -{ - cl_double CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_double8 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[8]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[4]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8[2]; -#endif -#if defined( __CL_DOUBLE16__ ) - __cl_double16 v16; -#endif -}cl_double16; - - -#ifdef __cplusplus -} -#endif - -#endif /* __CL_PLATFORM_H */ diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/opencl.h b/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/opencl.h deleted file mode 100644 index 26a638997..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/headers/1.1/CL/opencl.h +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_H -#define __OPENCL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - -#include -#include -#include -#include - -#else - -#include -#include -#include -#include - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_H */ - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java b/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java deleted file mode 100644 index 16cbeaa66..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java +++ /dev/null @@ -1,1496 +0,0 @@ -package com.nativelibs4java.opencl.library; -import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; -import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalCallback; -import com.sun.jna.Callback; -import com.sun.jna.Library; -import com.sun.jna.win32.StdCallLibrary; -import com.sun.jna.Native; -import com.sun.jna.NativeLibrary; -import com.sun.jna.Pointer; -import com.sun.jna.PointerType; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.LongByReference; -import com.sun.jna.ptr.PointerByReference; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -/** - * JNA Wrapper for library OpenCL
    - * This file was autogenerated by
    JNAerator,
    - * a tool written by Olivier Chafik that uses a few opensource projects..
    - * For help, please visit NativeLibs4Java , Rococoa, or JNA. - */ -public interface OpenCLLibrary extends Library { - public static final int CL_DEVICE_TYPE_CPU = (1 << 1); - public static final int CL_SCHAR_MAX = 127; - public static final int CL_FP_INF_NAN = (1 << 1); - public static final int CL_GLX_DISPLAY_KHR = 8202; - public static final int CL_GLOBAL = 2; - public static final int CL_DEVICE_GLOBAL_MEM_SIZE = 4127; - public static final int CL_KERNEL_LOCAL_MEM_SIZE = 4530; - public static final int CL_MEM_READ_ONLY = (1 << 2); - public static final int CL_PROGRAM_REFERENCE_COUNT = 4448; - public static final double CL_M_PI_2 = 1.5707963267948966; - public static final float CL_M_LOG2E_F = 1.442695F; - public static final double CL_M_PI_4 = 0.7853981633974483; - public static final int CL_FLT_MIN_EXP = -125; - public static final int CL_DEVICE_VENDOR_ID = 4097; - public static final int CL_FLOAT = 4318; - public static final int CL_NONE = 0; - public static final int CL_BGRA = 4278; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR = 4150; - public static final int CL_UNSIGNED_INT32 = 4316; - public static final int CL_DEVICE_MAX_COMPUTE_UNITS = 4098; - public static final int CL_RGBx = 4284; - public static final int CL_DEVICE_REGISTERS_PER_BLOCK_NV = 16386; - public static final int CL_PLATFORM_EXTENSIONS = 2308; - public static final int CL_DEVICE_TYPE_GPU = (1 << 2); - public static final float CL_M_PI_F = 3.1415927F; - public static final int CL_READ_ONLY_CACHE = 1; - public static final int CL_IMAGE_FORMAT_MISMATCH = -9; - public static final int CL_OUT_OF_RESOURCES = -5; - public static final int CL_INVALID_IMAGE_SIZE = -40; - public static final int CL_INVALID_EVENT_WAIT_LIST = -57; - public static final int cl_APPLE_SetMemObjectDestructor = 1; - public static final int CL_UNSIGNED_INT16 = 4315; - public static final int CL_COMMAND_NDRANGE_KERNEL = 4592; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT = 4106; - public static final int CL_DEVICE_MAX_CONSTANT_ARGS = 4129; - public static final int CL_CHAR_BIT = 8; - public static final int CL_DEVICE_TYPE_ALL = -1; - public static final int CL_QUEUED = 3; - public static final double CL_M_LN10 = 2.302585092994046; - public static final int CL_INVALID_MIP_LEVEL = -62; - public static final int CL_ADDRESS_NONE = 4400; - public static final int CL_RGBA = 4277; - public static final int CL_CONTEXT_DEVICES = 4225; - public static final int CL_INVALID_PARTITION_NAME_EXT = -1059; - public static final int CL_INVALID_WORK_ITEM_SIZE = -55; - public static final int CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV = 16389; - public static final int CL_INVALID_WORK_GROUP_SIZE = -54; - public static final int CL_DEVICE_ERROR_CORRECTION_SUPPORT = 4132; - public static final int CL_DBL_RADIX = 2; - public static final int CL_DEVICE_LOCAL_MEM_SIZE = 4131; - public static final int CL_COMMAND_RELEASE_GL_OBJECTS = 4608; - public static final int CL_ADDRESS_MIRRORED_REPEAT = 4404; - public static final int CL_INVALID_KERNEL_ARGS = -52; - public static final int CL_CONTEXT_PLATFORM = 4228; - public static final int CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE = 0x10000000; - public static final int CL_HAS_HI_LO_VECTOR_FIELDS = 1; - public static final int CL_MEM_MAP_COUNT = 4356; - public static final int CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT = 256; - public static final int CL_PROFILING_COMMAND_SUBMIT = 4737; - public static final int CL_DBL_MIN_EXP = -1021; - public static final double CL_M_SQRT2 = 1.4142135623730951; - public static final int CL_COMMAND_ACQUIRE_GL_OBJECTS = 4607; - public static final int CL_UINT_MAX = -1; - public static final float CL_M_SQRT1_2_F = 0.70710677F; - public static final double CL_M_2_SQRTPI = 1.1283791670955126; - public static final int CL_COMMAND_NATIVE_KERNEL = 4594; - public static final int CL_IMAGE_WIDTH = 4372; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG = 4105; - public static final int CL_INVALID_DEVICE_TYPE = -31; - public static final int CL_COMMAND_COPY_IMAGE_TO_BUFFER = 4601; - public static final int CL_GL_TEXTURE_TARGET = 8196; - public static final int CL_QUEUE_PROPERTIES = 4243; - public static final float CL_M_2_PI_F = 0.63661975F; - public static final int CL_COMMAND_WRITE_BUFFER_RECT = 4610; - public static final int CL_MEM_ASSOCIATED_MEMOBJECT = 4359; - public static final int CL_INVALID_ARG_VALUE = -50; - public static final int CL_CONTEXT_REFERENCE_COUNT = 4224; - public static final int CL_DEVICE_TYPE = 4096; - public static final int CL_QUEUE_CONTEXT = 4240; - public static final int CL_DEVICE_SINGLE_FP_CONFIG = 4123; - public static final int CL_SNORM_INT16 = 4305; - public static final int CL_ARGB = 4279; - public static final int CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV = 16385; - public static final int CL_EVENT_COMMAND_QUEUE = 4560; - public static final int CL_SUCCESS = 0; - public static final int CL_PROFILING_INFO_NOT_AVAILABLE = -7; - public static final int CL_INVALID_BUFFER_SIZE = -61; - public static final int CL_INVALID_ARG_SIZE = -51; - public static final int CL_QUEUE_PROFILING_ENABLE = (1 << 1); - public static final int CL_KERNEL_REFERENCE_COUNT = 4498; - public static final int CL_MEM_ALLOC_HOST_PTR = (1 << 4); - public static final int CL_DEVICE_IMAGE2D_MAX_WIDTH = 4113; - public static final int CL_BUILD_PROGRAM_FAILURE = -11; - public static final int CL_COMMAND_COPY_BUFFER = 4597; - public static final int CL_KERNEL_NUM_ARGS = 4497; - public static final int CL_BUFFER_CREATE_TYPE_REGION = 4640; - public static final int CL_UNORM_SHORT_555 = 4309; - public static final int CL_PROGRAM_SOURCE = 4452; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR = 4102; - public static final int CL_DEVICE_COMPILER_AVAILABLE = 4136; - public static final int CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE = 4125; - public static final int CL_FP_ROUND_TO_INF = (1 << 4); - public static final int CL_IMAGE_ROW_PITCH = 4370; - public static final int CL_INVALID_ARG_INDEX = -49; - public static final int CL_DEVICE_ENDIAN_LITTLE = 4134; - public static final int CL_COMMAND_READ_BUFFER = 4595; - public static final int CL_UNORM_INT_101010 = 4310; - public static final int CL_KERNEL_WORK_GROUP_SIZE = 4528; - public static final int CL_COMMAND_UNMAP_MEM_OBJECT = 4605; - public static final int CL_INVALID_PLATFORM = -32; - public static final int CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR = -1000; - public static final int CL_FLT_RADIX = 2; - public static final int CL_DEVICE_PARTITION_BY_NAMES_EXT = 16466; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT = 4104; - public static final int CL_SHRT_MIN = (-32767 - 1); - public static final int CL_INVALID_EVENT = -58; - public static final int CL_RG = 4274; - public static final int CL_RA = 4275; - public static final int CL_PROGRAM_BUILD_OPTIONS = 4482; - public static final int CL_INVALID_COMMAND_QUEUE = -36; - public static final int cl_khr_icd = 1; - public static final int CL_FP_ROUND_TO_NEAREST = (1 << 2); - public static final int CL_HALF_FLOAT = 4317; - public static final int CL_INVALID_BINARY = -42; - public static final int CL_COMMAND_WRITE_IMAGE = 4599; - public static final int CL_INVALID_KERNEL_DEFINITION = -47; - public static final int CL_ADDRESS_CLAMP = 4402; - public static final int CL_COMMAND_USER = 4612; - public static final int CL_UNORM_SHORT_565 = 4308; - public static final int CL_UNORM_INT16 = 4307; - public static final double CL_M_2_PI = 0.6366197723675814; - public static final int CL_ADDRESS_REPEAT = 4403; - public static final int CL_FALSE = 0; - public static final int CL_Rx = 4282; - public static final int CL_INVALID_GLOBAL_OFFSET = -56; - public static final int CL_INVALID_PROGRAM = -44; - public static final int CL_INVALID_KERNEL = -48; - public static final int CL_MEM_SIZE = 4354; - public static final int CL_AFFINITY_DOMAIN_L1_CACHE_EXT = 1; - public static final int CL_PROGRAM_BINARIES = 4454; - public static final int CL_DEVICE_TYPE_DEFAULT = (1 << 0); - public static final int CL_DEVICE_IMAGE2D_MAX_HEIGHT = 4114; - public static final int CL_INVALID_BUILD_OPTIONS = -43; - public static final int CL_DEVICE_NOT_AVAILABLE = -2; - public static final int CL_INVALID_VALUE = -30; - public static final int CL_AFFINITY_DOMAIN_L3_CACHE_EXT = 3; - public static final int CL_DEVICE_MEM_BASE_ADDR_ALIGN = 4121; - public static final int CL_DEVICE_MAX_WORK_GROUP_SIZE = 4100; - public static final int CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE = (1 << 0); - public static final int CL_SAMPLER_NORMALIZED_COORDS = 4434; - public static final int CL_EVENT_REFERENCE_COUNT = 4562; - public static final int CL_MEM_HOST_PTR = 4355; - public static final float CL_M_1_PI_F = 0.31830987F; - public static final int CL_MEM_OBJECT_ALLOCATION_FAILURE = -4; - public static final int CL_INVALID_MEM_OBJECT = -38; - public static final double CL_M_LN2 = 0.6931471805599453; - public static final int CL_COMPLETE = 0; - public static final int CL_INTENSITY = 4280; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF = 4156; - public static final int CL_INVALID_PROGRAM_EXECUTABLE = -45; - public static final int CL_MEM_WRITE_ONLY = (1 << 1); - public static final int CL_PROGRAM_CONTEXT = 4449; - public static final int CL_PLATFORM_ICD_SUFFIX_KHR = 2336; - public static final int CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST = -14; - public static final int CL_SAMPLER_ADDRESSING_MODE = 4435; - public static final int CL_MEM_CONTEXT = 4358; - public static final int CL_DEVICE_IMAGE3D_MAX_HEIGHT = 4116; - public static final int CL_DEVICE_MAX_READ_IMAGE_ARGS = 4110; - public static final int CL_DEVICE_NOT_FOUND = -1; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF = 4148; - public static final int CL_RGx = 4283; - public static final int CL_DEVICE_MAX_PARAMETER_SIZE = 4119; - public static final int CL_DEVICE_IMAGE3D_MAX_DEPTH = 4117; - public static final int CL_GL_OBJECT_TEXTURE2D = 8193; - public static final int CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT = 16467; - public static final int CL_MEM_USE_HOST_PTR = (1 << 3); - public static final int CL_SIGNED_INT8 = 4311; - public static final int CL_DEVICE_WARP_SIZE_NV = 16387; - public static final int CL_DEVICE_OPENCL_C_VERSION = 4157; - public static final int CL_DEVICE_ADDRESS_BITS = 4109; - public static final int CL_DEVICE_PARTITION_BY_COUNTS_EXT = 16465; - public static final int CL_GL_OBJECT_BUFFER = 8192; - public static final int CL_SAMPLER_CONTEXT = 4433; - public static final int CL_GL_OBJECT_TEXTURE3D = 8194; - public static final int CL_PLATFORM_VERSION = 2305; - public static final int CL_DEVICE_LOCAL_MEM_TYPE = 4130; - public static final int CL_DRIVER_VERSION = 4141; - public static final int CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE = 4122; - public static final int CL_DEVICE_VERSION = 4143; - public static final int CL_PLATFORM_NOT_FOUND_KHR = -1001; - public static final float CL_M_2_SQRTPI_F = 1.1283792F; - public static final int CL_SIGNED_INT32 = 4313; - public static final int CL_READ_WRITE_CACHE = 2; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT = 4151; - public static final int CL_KERNEL_COMPILE_WORK_GROUP_SIZE = 4529; - public static final int CL_PLATFORM_PROFILE = 2304; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT = 4154; - public static final float CL_M_PI_4_F = 0.7853982F; - public static final int CL_PROFILING_COMMAND_END = 4739; - public static final int CL_DEVICE_PROFILE = 4142; - public static final int CL_INVALID_OPERATION = -59; - public static final int CL_DEVICE_REFERENCE_COUNT_EXT = 16471; - public static final int CL_MEM_TYPE = 4352; - public static final int CL_KERNEL_CONTEXT = 4499; - public static final int CL_DEVICE_MAX_CLOCK_FREQUENCY = 4108; - public static final int CL_EVENT_CONTEXT = 4564; - public static final int CL_CONTEXT_NUM_DEVICES = 4227; - public static final int CL_HAS_NAMED_VECTOR_FIELDS = 1; - public static final int CL_GL_CONTEXT_KHR = 8200; - public static final int CL_DEVICE_PROFILING_TIMER_RESOLUTION = 4133; - public static final int CL_PROGRAM_BUILD_STATUS = 4481; - public static final int CL_DEVICE_GLOBAL_MEM_CACHE_TYPE = 4124; - public static final int CL_SUBMITTED = 2; - public static final int CL_PLATFORM_NAME = 2306; - public static final int CL_COMMAND_COPY_BUFFER_RECT = 4611; - public static final int CL_COMPILER_NOT_AVAILABLE = -3; - public static final int CL_SNORM_INT8 = 4304; - public static final int CL_FP_FMA = (1 << 5); - public static final int CL_PROFILING_COMMAND_START = 4738; - public static final int CL_COMMAND_COPY_IMAGE = 4600; - public static final int CL_DEVICE_MAX_WORK_ITEM_SIZES = 4101; - public static final int CL_IMAGE_ELEMENT_SIZE = 4369; - public static final int CL_DEVICE_PARTITION_EQUALLY_EXT = 16464; - public static final int CL_INVALID_CONTEXT = -34; - public static final int CL_IMAGE_HEIGHT = 4373; - public static final int CL_DEVICE_HOST_UNIFIED_MEMORY = 4149; - public static final int CL_COMMAND_MARKER = 4606; - public static final int CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR = 8205; - public static final int CL_AFFINITY_DOMAIN_L2_CACHE_EXT = 2; - public static final int CL_EXEC_NATIVE_KERNEL = (1 << 1); - public static final int CL_USHRT_MAX = 65535; - public static final int CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR = 8198; - public static final int CL_KERNEL_PRIVATE_MEM_SIZE = 4532; - public static final int CL_COMMAND_MAP_IMAGE = 4604; - public static final int CL_EXEC_KERNEL = (1 << 0); - public static final int CL_INVALID_GL_OBJECT = -60; - public static final int CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV = 16384; - public static final int CL_COMMAND_READ_BUFFER_RECT = 4609; - public static final int CL_QUEUE_DEVICE = 4241; - public static final int CL_DEVICE_GPU_OVERLAP_NV = 16388; - public static final int CL_DEVICE_EXTENSIONS = 4144; - public static final int CL_DEVICE_PARENT_DEVICE_EXT = 16468; - public static final int CL_MISALIGNED_SUB_BUFFER_OFFSET = -13; - public static final int CL_EVENT_COMMAND_EXECUTION_STATUS = 4563; - public static final int CL_DEVICE_MAX_WRITE_IMAGE_ARGS = 4111; - public static final int CL_INVALID_HOST_PTR = -37; - public static final float CL_M_SQRT2_F = 1.4142135F; - public static final int CL_VERSION_1_1 = 1; - public static final int CL_VERSION_1_0 = 1; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE = 4107; - public static final double CL_M_LOG2E = 1.4426950408889634; - public static final int CL_SHRT_MAX = 32767; - public static final int CL_UNORM_INT8 = 4306; - public static final int CL_DEVICE_QUEUE_PROPERTIES = 4138; - public static final int CL_BUILD_SUCCESS = 0; - public static final int CL_FP_DENORM = (1 << 0); - public static final float CL_M_LOG10E_F = 0.4342945F; - public static final int CL_GL_MIPMAP_LEVEL = 8197; - public static final int CL_SIGNED_INT16 = 4312; - public static final int CL_INT_MIN = (-2147483647 - 1); - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT = 4103; - public static final int CL_DEVICE_PARTITION_STYLE_EXT = 16472; - public static final int CL_COMMAND_MAP_BUFFER = 4603; - public static final int CL_MAP_WRITE = (1 << 1); - public static final double CL_M_SQRT1_2 = 0.7071067811865476; - public static final float CL_M_LN10_F = 2.3025851F; - public static final int CL_FILTER_NEAREST = 4416; - public static final int CL_KERNEL_FUNCTION_NAME = 4496; - public static final int cl_khr_gl_sharing = 1; - public static final int CL_BUILD_ERROR = -2; - public static final int CL_OUT_OF_HOST_MEMORY = -6; - public static final int CL_DEVICE_GLOBAL_MEM_CACHE_SIZE = 4126; - public static final int CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = 4099; - public static final int CL_EVENT_COMMAND_TYPE = 4561; - public static final int CL_A = 4273; - public static final int CL_DEVICES_FOR_GL_CONTEXT_KHR = 8199; - public static final int CL_MEM_OFFSET = 4360; - public static final int CL_RGB = 4276; - public static final int CL_PROGRAM_BINARY_SIZES = 4453; - public static final int CL_INVALID_DEVICE = -33; - public static final int CL_R = 4272; - public static final int CL_COMMAND_WRITE_BUFFER = 4596; - public static final int CL_INVALID_PARTITION_COUNT_EXT = -1058; - public static final int CL_EGL_DISPLAY_KHR = 8201; - public static final int CL_TRUE = 1; - public static final int CL_BUILD_IN_PROGRESS = -3; - public static final int CL_MEM_OBJECT_BUFFER = 4336; - public static final float CL_M_PI_2_F = 1.5707964F; - public static final int CL_DEVICE_AFFINITY_DOMAINS_EXT = 16470; - public static final int CL_CONTEXT_PROPERTIES = 4226; - public static final int CL_SCHAR_MIN = (-127 - 1); - public static final int CL_FP_SOFT_FLOAT = (1 << 6); - public static final int CL_DEVICE_VENDOR = 4140; - public static final int CL_BUILD_NONE = -1; - public static final int CL_FLT_DIG = 6; - public static final int CL_MEM_OBJECT_IMAGE2D = 4337; - public static final double CL_M_PI = 3.141592653589793; - public static final int CL_IMAGE_FORMAT = 4368; - public static final int CL_PLATFORM_VENDOR = 2307; - public static final int CL_DEVICE_MAX_MEM_ALLOC_SIZE = 4112; - public static final int CL_PROFILING_COMMAND_QUEUED = 4736; - public static final float CL_M_LN2_F = 0.6931472F; - public static final int CL_DEVICE_PARTITION_TYPES_EXT = 16469; - public static final int CL_FILTER_LINEAR = 4417; - public static final int CL_DEVICE_TYPE_ACCELERATOR = (1 << 3); - public static final int CL_DEVICE_IMAGE_SUPPORT = 4118; - public static final int CL_PROGRAM_BUILD_LOG = 4483; - public static final int CL_IMAGE_DEPTH = 4374; - public static final int CL_KERNEL_PROGRAM = 4500; - public static final int CL_MEM_OBJECT_IMAGE3D = 4338; - public static final double CL_M_1_PI = 0.3183098861837907; - public static final float CL_M_E_F = 2.7182817F; - public static final int CL_FLT_MANT_DIG = 24; - public static final int CL_LOCAL = 1; - public static final int CL_DEVICE_PROFILING_TIMER_OFFSET_AMD = 16438; - public static final int CL_QUEUE_REFERENCE_COUNT = 4242; - public static final int CL_DEVICE_PARTITION_FAILED_EXT = -1057; - public static final double CL_M_LOG10E = 0.4342944819032518; - public static final int CL_IMAGE_FORMAT_NOT_SUPPORTED = -10; - public static final int CL_DEVICE_AVAILABLE = 4135; - public static final int CL_UCHAR_MAX = 255; - public static final int CL_DBL_MIN_10_EXP = -307; - public static final int CL_DEVICE_MAX_SAMPLERS = 4120; - public static final int CL_MEM_COPY_OVERLAP = -8; - public static final int CL_MAP_READ = (1 << 0); - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE = 4155; - public static final int CL_COMMAND_READ_IMAGE = 4598; - public static final int CL_PROGRAM_NUM_DEVICES = 4450; - public static final int CL_UNSIGNED_INT8 = 4314; - public static final int CL_DBL_DIG = 15; - public static final int cl_APPLE_ContextLoggingFunctions = 1; - public static final int CL_WGL_HDC_KHR = 8203; - public static final int CL_DBL_MANT_DIG = 53; - public static final int CL_COMMAND_COPY_BUFFER_TO_IMAGE = 4602; - public static final int CL_CGL_SHAREGROUP_KHR = 8204; - public static final int CL_PROGRAM_DEVICES = 4451; - public static final int CL_SAMPLER_REFERENCE_COUNT = 4432; - public static final int CL_MEM_READ_WRITE = (1 << 0); - public static final int CL_INVALID_KERNEL_NAME = -46; - public static final int CL_DEVICE_EXECUTION_CAPABILITIES = 4137; - public static final int CL_DEVICE_NAME = 4139; - public static final int CL_DEVICE_INTEGRATED_MEMORY_NV = 16390; - public static final int CL_MEM_REFERENCE_COUNT = 4357; - public static final int CL_INVALID_IMAGE_FORMAT_DESCRIPTOR = -39; - public static final int cl_ext_device_fission = 1; - public static final int CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE = 4128; - public static final int CL_MAP_FAILURE = -12; - public static final int CL_IMAGE_SLICE_PITCH = 4371; - public static final int CL_LUMINANCE = 4281; - public static final int CL_ADDRESS_CLAMP_TO_EDGE = 4401; - public static final int CL_GL_OBJECT_RENDERBUFFER = 8195; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_INT = 4152; - public static final int CL_SAMPLER_FILTER_MODE = 4436; - public static final int CL_INVALID_QUEUE_PROPERTIES = -35; - public static final int CL_INVALID_GLOBAL_WORK_SIZE = -63; - public static final int CL_INT_MAX = 2147483647; - public static final int CL_AFFINITY_DOMAIN_NUMA_EXT = 16; - public static final int CL_FLT_MIN_10_EXP = -37; - public static final int CL_AFFINITY_DOMAIN_L4_CACHE_EXT = 4; - public static final int CL_MEM_COPY_HOST_PTR = (1 << 5); - public static final int CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE = 4531; - public static final int CL_MEM_FLAGS = 4353; - public static final int CL_DEVICE_DOUBLE_FP_CONFIG = 4146; - public static final int CL_COMMAND_TASK = 4593; - public static final int CL_DEVICE_HALF_FP_CONFIG = 4147; - public static final int CL_FP_ROUND_TO_ZERO = (1 << 3); - public static final int CL_RUNNING = 1; - public static final int CL_DEVICE_IMAGE3D_MAX_WIDTH = 4115; - public static final int CL_INVALID_WORK_DIMENSION = -53; - public static final int CL_DEVICE_PLATFORM = 4145; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG = 4153; - public static final double CL_M_E = 2.718281828459045; - public static final int CL_INVALID_SAMPLER = -41; - public static final int CL_CHAR_MIN = -127 - 1; - public static final int CL_CHAR_MAX = OpenCLLibrary.CL_SCHAR_MAX; - public interface clGetGLContextInfoKHR_fn extends Callback { - int invoke(NativeSizeByReference properties, int param_name, NativeSize param_value_size, Pointer param_value, NativeSizeByReference param_value_size_ret); - }; - public interface clIcdGetPlatformIDsKHR_fn extends Callback { - int invoke(int cl_uint1, PointerByReference cl_platform_idPtr1, IntByReference cl_uintPtr1); - }; - public interface clReleaseDeviceEXT_fn extends Callback { - int invoke(OpenCLLibrary.cl_device_id cl_device_id1); - }; - public interface clRetainDeviceEXT_fn extends Callback { - int invoke(OpenCLLibrary.cl_device_id cl_device_id1); - }; - public interface clCreateContext_arg1_callback extends Callback { - void invoke(Pointer charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - }; - public interface clCreateContextFromType_arg1_callback extends Callback { - void invoke(Pointer charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - }; - public interface clSetMemObjectDestructorCallback_arg1_callback extends Callback { - /// @param cl_mem1 user_data - void invoke(OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1); - }; - public interface clBuildProgram_arg1_callback extends Callback { - /// @param cl_program1 user_data - void invoke(OpenCLLibrary.cl_program cl_program1, Pointer voidPtr1); - }; - public interface clSetEventCallback_arg1_callback extends Callback { - void invoke(OpenCLLibrary.cl_event cl_event1, int cl_int1, Pointer voidPtr1); - }; - public interface user_func extends Callback { - void invoke(Pointer voidPtr1); - }; - public interface clSetMemObjectDestructorAPPLE_arg1_callback extends Callback { - /// @param cl_mem1 user_data - void invoke(OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1); - }; - public interface clCreateSubDevicesEXT_fn_callback extends Callback { - int invoke(OpenCLLibrary.cl_device_id cl_device_id1, LongByReference cl_device_partition_property_extPtr1, int cl_uint1, PointerByReference cl_device_idPtr1, IntByReference cl_uintPtr1); - }; - /** - * Platform API
    - * Original signature : cl_int clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*)
    - * @see Khronos Documentation for clGetPlatformIDs
    - * @deprecated use the safer methods {@link #clGetPlatformIDs(int, com.sun.jna.ptr.PointerByReference, java.nio.IntBuffer)} and {@link #clGetPlatformIDs(int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clGetPlatformIDs(int cl_uint1, PointerByReference cl_platform_idPtr1, IntByReference cl_uintPtr1); - /** - * Platform API
    - * Original signature : cl_int clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*)
    - * @see Khronos Documentation for clGetPlatformIDs - */ - int clGetPlatformIDs(int cl_uint1, PointerByReference cl_platform_idPtr1, IntBuffer cl_uintPtr1); - /** - * Platform API
    - * Original signature : cl_int clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*)
    - * @see Khronos Documentation for clGetPlatformIDs - */ - int clGetPlatformIDs(int cl_uint1, OpenCLLibrary.cl_platform_id cl_platform_idPtr1[], IntByReference cl_uintPtr1); - /** - * Original signature : cl_int clGetPlatformInfo(cl_platform_id, cl_platform_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetPlatformInfo - */ - int clGetPlatformInfo(OpenCLLibrary.cl_platform_id cl_platform_id1, int cl_platform_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Device APIs
    - * Original signature : cl_int clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*)
    - * @see Khronos Documentation for clGetDeviceIDs
    - * @deprecated use the safer methods {@link #clGetDeviceIDs(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id, long, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], java.nio.IntBuffer)} and {@link #clGetDeviceIDs(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id, long, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clGetDeviceIDs(OpenCLLibrary.cl_platform_id cl_platform_id1, long cl_device_type1, int cl_uint1, PointerByReference cl_device_idPtr1, IntByReference cl_uintPtr1); - /** - * Device APIs
    - * Original signature : cl_int clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*)
    - * @see Khronos Documentation for clGetDeviceIDs - */ - int clGetDeviceIDs(OpenCLLibrary.cl_platform_id cl_platform_id1, long cl_device_type1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], IntBuffer cl_uintPtr1); - /** - * Device APIs
    - * Original signature : cl_int clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*)
    - * @see Khronos Documentation for clGetDeviceIDs - */ - int clGetDeviceIDs(OpenCLLibrary.cl_platform_id cl_platform_id1, long cl_device_type1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], IntByReference cl_uintPtr1); - /** - * Original signature : cl_int clGetDeviceInfo(cl_device_id, cl_device_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetDeviceInfo - */ - int clGetDeviceInfo(OpenCLLibrary.cl_device_id cl_device_id1, int cl_device_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Context APIs
    - * Original signature : cl_context clCreateContext(const cl_context_properties*, cl_uint, const cl_device_id*, clCreateContext_arg1_callback, void*, cl_int*)
    - * @see Khronos Documentation for clCreateContext
    - * @deprecated use the safer methods {@link #clCreateContext(com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.nativelibs4java.opencl.library.OpenCLLibrary.clCreateContext_arg1_callback, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateContext(com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.nativelibs4java.opencl.library.OpenCLLibrary.clCreateContext_arg1_callback, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_context clCreateContext(NativeSizeByReference cl_context_propertiesPtr1, int cl_uint1, PointerByReference cl_device_idPtr1, OpenCLLibrary.clCreateContext_arg1_callback arg1, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Context APIs
    - * Original signature : cl_context clCreateContext(const cl_context_properties*, cl_uint, const cl_device_id*, clCreateContext_arg1_callback, void*, cl_int*)
    - * @see Khronos Documentation for clCreateContext - */ - OpenCLLibrary.cl_context clCreateContext(NativeSizeByReference cl_context_propertiesPtr1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], OpenCLLibrary.clCreateContext_arg1_callback arg1, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Context APIs
    - * Original signature : cl_context clCreateContext(const cl_context_properties*, cl_uint, const cl_device_id*, clCreateContext_arg1_callback, void*, cl_int*)
    - * @see Khronos Documentation for clCreateContext - */ - OpenCLLibrary.cl_context clCreateContext(NativeSizeByReference cl_context_propertiesPtr1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], OpenCLLibrary.clCreateContext_arg1_callback arg1, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Original signature : cl_context clCreateContextFromType(const cl_context_properties*, cl_device_type, clCreateContextFromType_arg1_callback, void*, cl_int*)
    - * @see Khronos Documentation for clCreateContextFromType
    - * @deprecated use the safer methods {@link #clCreateContextFromType(com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, long, com.nativelibs4java.opencl.library.OpenCLLibrary.clCreateContextFromType_arg1_callback, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateContextFromType(com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, long, com.nativelibs4java.opencl.library.OpenCLLibrary.clCreateContextFromType_arg1_callback, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_context clCreateContextFromType(NativeSizeByReference cl_context_propertiesPtr1, long cl_device_type1, OpenCLLibrary.clCreateContextFromType_arg1_callback arg1, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Original signature : cl_context clCreateContextFromType(const cl_context_properties*, cl_device_type, clCreateContextFromType_arg1_callback, void*, cl_int*)
    - * @see Khronos Documentation for clCreateContextFromType - */ - OpenCLLibrary.cl_context clCreateContextFromType(NativeSizeByReference cl_context_propertiesPtr1, long cl_device_type1, OpenCLLibrary.clCreateContextFromType_arg1_callback arg1, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clRetainContext(cl_context)
    - * @see Khronos Documentation for clRetainContext - */ - int clRetainContext(OpenCLLibrary.cl_context cl_context1); - /** - * Original signature : cl_int clReleaseContext(cl_context)
    - * @see Khronos Documentation for clReleaseContext - */ - int clReleaseContext(OpenCLLibrary.cl_context cl_context1); - /** - * Original signature : cl_int clGetContextInfo(cl_context, cl_context_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetContextInfo - */ - int clGetContextInfo(OpenCLLibrary.cl_context cl_context1, int cl_context_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Command Queue APIs
    - * Original signature : cl_command_queue clCreateCommandQueue(cl_context, cl_device_id, cl_command_queue_properties, cl_int*)
    - * @see Khronos Documentation for clCreateCommandQueue
    - * @deprecated use the safer methods {@link #clCreateCommandQueue(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id, long, java.nio.IntBuffer)} and {@link #clCreateCommandQueue(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id, long, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_command_queue clCreateCommandQueue(OpenCLLibrary.cl_context cl_context1, OpenCLLibrary.cl_device_id cl_device_id1, long cl_command_queue_properties1, IntByReference cl_intPtr1); - /** - * Command Queue APIs
    - * Original signature : cl_command_queue clCreateCommandQueue(cl_context, cl_device_id, cl_command_queue_properties, cl_int*)
    - * @see Khronos Documentation for clCreateCommandQueue - */ - OpenCLLibrary.cl_command_queue clCreateCommandQueue(OpenCLLibrary.cl_context cl_context1, OpenCLLibrary.cl_device_id cl_device_id1, long cl_command_queue_properties1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clRetainCommandQueue(cl_command_queue)
    - * @see Khronos Documentation for clRetainCommandQueue - */ - int clRetainCommandQueue(OpenCLLibrary.cl_command_queue cl_command_queue1); - /** - * Original signature : cl_int clReleaseCommandQueue(cl_command_queue)
    - * @see Khronos Documentation for clReleaseCommandQueue - */ - int clReleaseCommandQueue(OpenCLLibrary.cl_command_queue cl_command_queue1); - /** - * Original signature : cl_int clGetCommandQueueInfo(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetCommandQueueInfo - */ - int clGetCommandQueueInfo(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_command_queue_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * WARNING:
    - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED
    - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the
    - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably.
    - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk.
    - * * Software developers previously relying on this API are instructed to set the command queue
    - * properties when creating the queue, instead.
    - * Original signature : cl_int clSetCommandQueueProperty(cl_command_queue, cl_command_queue_properties, cl_bool, cl_command_queue_properties*)
    - * @see Khronos Documentation for clSetCommandQueueProperty
    - * @deprecated use the safer methods {@link #clSetCommandQueueProperty(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, long, int, java.nio.LongBuffer)} and {@link #clSetCommandQueueProperty(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, long, int, com.sun.jna.ptr.LongByReference)} instead - */ - @java.lang.Deprecated - int clSetCommandQueueProperty(OpenCLLibrary.cl_command_queue cl_command_queue1, long cl_command_queue_properties1, int cl_bool1, LongByReference cl_command_queue_propertiesPtr1); - /** - * WARNING:
    - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED
    - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the
    - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably.
    - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk.
    - * * Software developers previously relying on this API are instructed to set the command queue
    - * properties when creating the queue, instead.
    - * Original signature : cl_int clSetCommandQueueProperty(cl_command_queue, cl_command_queue_properties, cl_bool, cl_command_queue_properties*)
    - * @see Khronos Documentation for clSetCommandQueueProperty - */ - int clSetCommandQueueProperty(OpenCLLibrary.cl_command_queue cl_command_queue1, long cl_command_queue_properties1, int cl_bool1, LongBuffer cl_command_queue_propertiesPtr1); - /** - * Memory Object APIs
    - * Original signature : cl_mem clCreateBuffer(cl_context, cl_mem_flags, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateBuffer
    - * @deprecated use the safer methods {@link #clCreateBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateBuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, NativeSize size_t1, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Memory Object APIs
    - * Original signature : cl_mem clCreateBuffer(cl_context, cl_mem_flags, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateBuffer - */ - OpenCLLibrary.cl_mem clCreateBuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, NativeSize size_t1, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_mem clCreateSubBuffer(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*)
    - * @see Khronos Documentation for clCreateSubBuffer
    - * @deprecated use the safer methods {@link #clCreateSubBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, long, int, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateSubBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, long, int, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateSubBuffer(OpenCLLibrary.cl_mem cl_mem1, long cl_mem_flags1, int cl_buffer_create_type1, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateSubBuffer(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*)
    - * @see Khronos Documentation for clCreateSubBuffer - */ - OpenCLLibrary.cl_mem clCreateSubBuffer(OpenCLLibrary.cl_mem cl_mem1, long cl_mem_flags1, int cl_buffer_create_type1, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_mem clCreateImage2D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateImage2D
    - * @deprecated use the safer methods {@link #clCreateImage2D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.nativelibs4java.opencl.library.cl_image_format, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateImage2D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.nativelibs4java.opencl.library.cl_image_format, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateImage2D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateImage2D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateImage2D - */ - OpenCLLibrary.cl_mem clCreateImage2D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_mem clCreateImage3D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateImage3D
    - * @deprecated use the safer methods {@link #clCreateImage3D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.nativelibs4java.opencl.library.cl_image_format, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #clCreateImage3D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, com.nativelibs4java.opencl.library.cl_image_format, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateImage3D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, NativeSize size_t5, Pointer voidPtr1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateImage3D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*)
    - * @see Khronos Documentation for clCreateImage3D - */ - OpenCLLibrary.cl_mem clCreateImage3D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, NativeSize size_t5, Pointer voidPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clRetainMemObject(cl_mem)
    - * @see Khronos Documentation for clRetainMemObject - */ - int clRetainMemObject(OpenCLLibrary.cl_mem cl_mem1); - /** - * Original signature : cl_int clReleaseMemObject(cl_mem)
    - * @see Khronos Documentation for clReleaseMemObject - */ - int clReleaseMemObject(OpenCLLibrary.cl_mem cl_mem1); - /** - * Original signature : cl_int clGetSupportedImageFormats(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*)
    - * @see Khronos Documentation for clGetSupportedImageFormats
    - * @deprecated use the safer methods {@link #clGetSupportedImageFormats(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, com.nativelibs4java.opencl.library.cl_image_format, java.nio.IntBuffer)} and {@link #clGetSupportedImageFormats(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, com.nativelibs4java.opencl.library.cl_image_format, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clGetSupportedImageFormats(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_mem_object_type1, int cl_uint1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, IntByReference cl_uintPtr1); - /** - * Original signature : cl_int clGetSupportedImageFormats(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*)
    - * @see Khronos Documentation for clGetSupportedImageFormats - */ - int clGetSupportedImageFormats(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_mem_object_type1, int cl_uint1, com.nativelibs4java.opencl.library.cl_image_format cl_image_formatPtr1, IntBuffer cl_uintPtr1); - /** - * Original signature : cl_int clGetMemObjectInfo(cl_mem, cl_mem_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetMemObjectInfo - */ - int clGetMemObjectInfo(OpenCLLibrary.cl_mem cl_mem1, int cl_mem_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_int clGetImageInfo(cl_mem, cl_image_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetImageInfo - */ - int clGetImageInfo(OpenCLLibrary.cl_mem cl_mem1, int cl_image_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_int clSetMemObjectDestructorCallback(cl_mem, clSetMemObjectDestructorCallback_arg1_callback, void*)
    - * @see Khronos Documentation for clSetMemObjectDestructorCallback - */ - int clSetMemObjectDestructorCallback(OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.clSetMemObjectDestructorCallback_arg1_callback arg1, Pointer voidPtr1); - /** - * Sampler APIs
    - * Original signature : cl_sampler clCreateSampler(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*)
    - * @see Khronos Documentation for clCreateSampler
    - * @deprecated use the safer methods {@link #clCreateSampler(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, int, int, java.nio.IntBuffer)} and {@link #clCreateSampler(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, int, int, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_sampler clCreateSampler(OpenCLLibrary.cl_context cl_context1, int cl_bool1, int cl_addressing_mode1, int cl_filter_mode1, IntByReference cl_intPtr1); - /** - * Sampler APIs
    - * Original signature : cl_sampler clCreateSampler(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*)
    - * @see Khronos Documentation for clCreateSampler - */ - OpenCLLibrary.cl_sampler clCreateSampler(OpenCLLibrary.cl_context cl_context1, int cl_bool1, int cl_addressing_mode1, int cl_filter_mode1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clRetainSampler(cl_sampler)
    - * @see Khronos Documentation for clRetainSampler - */ - int clRetainSampler(OpenCLLibrary.cl_sampler cl_sampler1); - /** - * Original signature : cl_int clReleaseSampler(cl_sampler)
    - * @see Khronos Documentation for clReleaseSampler - */ - int clReleaseSampler(OpenCLLibrary.cl_sampler cl_sampler1); - /** - * Original signature : cl_int clGetSamplerInfo(cl_sampler, cl_sampler_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetSamplerInfo - */ - int clGetSamplerInfo(OpenCLLibrary.cl_sampler cl_sampler1, int cl_sampler_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Program Object APIs
    - * Original signature : cl_program clCreateProgramWithSource(cl_context, cl_uint, const char**, const size_t*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithSource
    - * @deprecated use the safer methods {@link #clCreateProgramWithSource(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, java.lang.String[], com.ochafik.lang.jnaerator.runtime.NativeSize[], java.nio.IntBuffer)} and {@link #clCreateProgramWithSource(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, com.sun.jna.ptr.PointerByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_program clCreateProgramWithSource(OpenCLLibrary.cl_context cl_context1, int cl_uint1, PointerByReference charPtrPtr1, NativeSizeByReference size_tPtr1, IntByReference cl_intPtr1); - /** - * Program Object APIs
    - * Original signature : cl_program clCreateProgramWithSource(cl_context, cl_uint, const char**, const size_t*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithSource - */ - OpenCLLibrary.cl_program clCreateProgramWithSource(OpenCLLibrary.cl_context cl_context1, int cl_uint1, java.lang.String charPtrPtr1[], NativeSize size_tPtr1[], IntBuffer cl_intPtr1); - /** - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithBinary
    - * @deprecated use the safer methods {@link #clCreateProgramWithBinary(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.sun.jna.ptr.PointerByReference, java.nio.IntBuffer, java.nio.IntBuffer)} and {@link #clCreateProgramWithBinary(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.sun.jna.ptr.PointerByReference, com.sun.jna.ptr.IntByReference, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, PointerByReference cl_device_idPtr1, NativeSizeByReference size_tPtr1, PointerByReference charPtrPtr1, IntByReference cl_intPtr1, IntByReference cl_intPtr2); - /** - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithBinary - */ - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSize size_tPtr1[], PointerByReference charPtrPtr1, IntBuffer cl_intPtr1, IntBuffer cl_intPtr2); - /** - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithBinary - */ - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSize size_tPtr1[], String[] charPtrPtr1, IntBuffer cl_intPtr1, IntBuffer cl_intPtr2); - /** - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithBinary - */ - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSizeByReference size_tPtr1, PointerByReference charPtrPtr1, IntByReference cl_intPtr1, IntByReference cl_intPtr2); - /** - * Original signature : cl_int clRetainProgram(cl_program)
    - * @see Khronos Documentation for clRetainProgram - */ - int clRetainProgram(OpenCLLibrary.cl_program cl_program1); - /** - * Original signature : cl_int clReleaseProgram(cl_program)
    - * @see Khronos Documentation for clReleaseProgram - */ - int clReleaseProgram(OpenCLLibrary.cl_program cl_program1); - /** - * Original signature : cl_int clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, clBuildProgram_arg1_callback, void*)
    - * @see Khronos Documentation for clBuildProgram
    - * @deprecated use the safer methods {@link #clBuildProgram(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], java.lang.String, com.nativelibs4java.opencl.library.OpenCLLibrary.clBuildProgram_arg1_callback, com.sun.jna.Pointer)} and {@link #clBuildProgram(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.sun.jna.Pointer, com.nativelibs4java.opencl.library.OpenCLLibrary.clBuildProgram_arg1_callback, com.sun.jna.Pointer)} instead - */ - @java.lang.Deprecated - int clBuildProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, PointerByReference cl_device_idPtr1, Pointer charPtr1, OpenCLLibrary.clBuildProgram_arg1_callback arg1, Pointer voidPtr1); - /** - * Original signature : cl_int clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, clBuildProgram_arg1_callback, void*)
    - * @see Khronos Documentation for clBuildProgram - */ - int clBuildProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], java.lang.String charPtr1, OpenCLLibrary.clBuildProgram_arg1_callback arg1, Pointer voidPtr1); - /** - * Original signature : cl_int clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, clBuildProgram_arg1_callback, void*)
    - * @see Khronos Documentation for clBuildProgram - */ - int clBuildProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], Pointer charPtr1, OpenCLLibrary.clBuildProgram_arg1_callback arg1, Pointer voidPtr1); - /** - * Original signature : cl_int clUnloadCompiler()
    - * @see Khronos Documentation for clUnloadCompiler - */ - int clUnloadCompiler(); - /** - * Original signature : cl_int clGetProgramInfo(cl_program, cl_program_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetProgramInfo - */ - int clGetProgramInfo(OpenCLLibrary.cl_program cl_program1, int cl_program_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_int clGetProgramBuildInfo(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetProgramBuildInfo - */ - int clGetProgramBuildInfo(OpenCLLibrary.cl_program cl_program1, OpenCLLibrary.cl_device_id cl_device_id1, int cl_program_build_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Kernel Object APIs
    - * Original signature : cl_kernel clCreateKernel(cl_program, const char*, cl_int*)
    - * @see Khronos Documentation for clCreateKernel
    - * @deprecated use the safer methods {@link #clCreateKernel(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, java.lang.String, java.nio.IntBuffer)} and {@link #clCreateKernel(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_kernel clCreateKernel(OpenCLLibrary.cl_program cl_program1, Pointer charPtr1, IntByReference cl_intPtr1); - /** - * Kernel Object APIs
    - * Original signature : cl_kernel clCreateKernel(cl_program, const char*, cl_int*)
    - * @see Khronos Documentation for clCreateKernel - */ - OpenCLLibrary.cl_kernel clCreateKernel(OpenCLLibrary.cl_program cl_program1, java.lang.String charPtr1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clCreateKernelsInProgram(cl_program, cl_uint, cl_kernel*, cl_uint*)
    - * @see Khronos Documentation for clCreateKernelsInProgram
    - * @deprecated use the safer methods {@link #clCreateKernelsInProgram(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel[], java.nio.IntBuffer)} and {@link #clCreateKernelsInProgram(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clCreateKernelsInProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, PointerByReference cl_kernelPtr1, IntByReference cl_uintPtr1); - /** - * Original signature : cl_int clCreateKernelsInProgram(cl_program, cl_uint, cl_kernel*, cl_uint*)
    - * @see Khronos Documentation for clCreateKernelsInProgram - */ - int clCreateKernelsInProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, OpenCLLibrary.cl_kernel cl_kernelPtr1[], IntBuffer cl_uintPtr1); - /** - * Original signature : cl_int clCreateKernelsInProgram(cl_program, cl_uint, cl_kernel*, cl_uint*)
    - * @see Khronos Documentation for clCreateKernelsInProgram - */ - int clCreateKernelsInProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, OpenCLLibrary.cl_kernel cl_kernelPtr1[], IntByReference cl_uintPtr1); - /** - * Original signature : cl_int clRetainKernel(cl_kernel)
    - * @see Khronos Documentation for clRetainKernel - */ - int clRetainKernel(OpenCLLibrary.cl_kernel cl_kernel1); - /** - * Original signature : cl_int clReleaseKernel(cl_kernel)
    - * @see Khronos Documentation for clReleaseKernel - */ - int clReleaseKernel(OpenCLLibrary.cl_kernel cl_kernel1); - /** - * Original signature : cl_int clSetKernelArg(cl_kernel, cl_uint, size_t, const void*)
    - * @see Khronos Documentation for clSetKernelArg - */ - int clSetKernelArg(OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, NativeSize size_t1, Pointer voidPtr1); - /** - * Original signature : cl_int clGetKernelInfo(cl_kernel, cl_kernel_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetKernelInfo - */ - int clGetKernelInfo(OpenCLLibrary.cl_kernel cl_kernel1, int cl_kernel_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_int clGetKernelWorkGroupInfo(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetKernelWorkGroupInfo - */ - int clGetKernelWorkGroupInfo(OpenCLLibrary.cl_kernel cl_kernel1, OpenCLLibrary.cl_device_id cl_device_id1, int cl_kernel_work_group_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Event Object APIs
    - * Original signature : cl_int clWaitForEvents(cl_uint, const cl_event*)
    - * @see Khronos Documentation for clWaitForEvents
    - * @deprecated use the safer method {@link #clWaitForEvents(int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clWaitForEvents(int cl_uint1, PointerByReference cl_eventPtr1); - /** - * Event Object APIs
    - * Original signature : cl_int clWaitForEvents(cl_uint, const cl_event*)
    - * @see Khronos Documentation for clWaitForEvents - */ - int clWaitForEvents(int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[]); - /** - * Original signature : cl_int clGetEventInfo(cl_event, cl_event_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetEventInfo - */ - int clGetEventInfo(OpenCLLibrary.cl_event cl_event1, int cl_event_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_event clCreateUserEvent(cl_context, cl_int*)
    - * @see Khronos Documentation for clCreateUserEvent
    - * @deprecated use the safer methods {@link #clCreateUserEvent(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, java.nio.IntBuffer)} and {@link #clCreateUserEvent(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_event clCreateUserEvent(OpenCLLibrary.cl_context cl_context1, IntByReference cl_intPtr1); - /** - * Original signature : cl_event clCreateUserEvent(cl_context, cl_int*)
    - * @see Khronos Documentation for clCreateUserEvent - */ - OpenCLLibrary.cl_event clCreateUserEvent(OpenCLLibrary.cl_context cl_context1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clRetainEvent(cl_event)
    - * @see Khronos Documentation for clRetainEvent - */ - int clRetainEvent(OpenCLLibrary.cl_event cl_event1); - /** - * Original signature : cl_int clReleaseEvent(cl_event)
    - * @see Khronos Documentation for clReleaseEvent - */ - int clReleaseEvent(OpenCLLibrary.cl_event cl_event1); - /** - * Original signature : cl_int clSetUserEventStatus(cl_event, cl_int)
    - * @see Khronos Documentation for clSetUserEventStatus - */ - int clSetUserEventStatus(OpenCLLibrary.cl_event cl_event1, int cl_int1); - /** - * Original signature : cl_int clSetEventCallback(cl_event, cl_int, clSetEventCallback_arg1_callback, void*)
    - * @see Khronos Documentation for clSetEventCallback - */ - int clSetEventCallback(OpenCLLibrary.cl_event cl_event1, int cl_int1, OpenCLLibrary.clSetEventCallback_arg1_callback arg1, Pointer voidPtr1); - /** - * Profiling APIs
    - * Original signature : cl_int clGetEventProfilingInfo(cl_event, cl_profiling_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetEventProfilingInfo - */ - int clGetEventProfilingInfo(OpenCLLibrary.cl_event cl_event1, int cl_profiling_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Flush and Finish APIs
    - * Original signature : cl_int clFlush(cl_command_queue)
    - * @see Khronos Documentation for clFlush - */ - int clFlush(OpenCLLibrary.cl_command_queue cl_command_queue1); - /** - * Original signature : cl_int clFinish(cl_command_queue)
    - * @see Khronos Documentation for clFinish - */ - int clFinish(OpenCLLibrary.cl_command_queue cl_command_queue1); - /** - * Enqueued Commands APIs
    - * Original signature : cl_int clEnqueueReadBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadBuffer
    - * @deprecated use the safer method {@link #clEnqueueReadBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueReadBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Enqueued Commands APIs
    - * Original signature : cl_int clEnqueueReadBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadBuffer - */ - int clEnqueueReadBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueReadBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadBufferRect
    - * @deprecated use the safer methods {@link #clEnqueueReadBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueReadBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueReadBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueReadBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadBufferRect - */ - int clEnqueueReadBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_tPtr3[], NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueReadBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadBufferRect - */ - int clEnqueueReadBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueWriteBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteBuffer
    - * @deprecated use the safer method {@link #clEnqueueWriteBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueWriteBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueWriteBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteBuffer - */ - int clEnqueueWriteBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueWriteBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteBufferRect
    - * @deprecated use the safer methods {@link #clEnqueueWriteBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueWriteBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueWriteBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueWriteBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteBufferRect - */ - int clEnqueueWriteBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_tPtr3[], NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueWriteBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteBufferRect - */ - int clEnqueueWriteBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyBuffer(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBuffer
    - * @deprecated use the safer method {@link #clEnqueueCopyBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueCopyBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueCopyBuffer(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBuffer - */ - int clEnqueueCopyBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyBufferRect(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferRect
    - * @deprecated use the safer methods {@link #clEnqueueCopyBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueCopyBufferRect(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueCopyBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueCopyBufferRect(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferRect - */ - int clEnqueueCopyBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_tPtr3[], NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyBufferRect(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferRect - */ - int clEnqueueCopyBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSize size_t1, NativeSize size_t2, NativeSize size_t3, NativeSize size_t4, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueReadImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadImage
    - * @deprecated use the safer methods {@link #clEnqueueReadImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueReadImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueReadImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueReadImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadImage - */ - int clEnqueueReadImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueReadImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReadImage - */ - int clEnqueueReadImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueWriteImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteImage
    - * @deprecated use the safer methods {@link #clEnqueueWriteImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueWriteImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueWriteImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueWriteImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteImage - */ - int clEnqueueWriteImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueWriteImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueWriteImage - */ - int clEnqueueWriteImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, NativeSize size_t2, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyImage(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImage
    - * @deprecated use the safer methods {@link #clEnqueueCopyImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueCopyImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueCopyImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueCopyImage(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImage - */ - int clEnqueueCopyImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_tPtr3[], int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyImage(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImage - */ - int clEnqueueCopyImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyImageToBuffer(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImageToBuffer
    - * @deprecated use the safer methods {@link #clEnqueueCopyImageToBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueCopyImageToBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueCopyImageToBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueCopyImageToBuffer(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImageToBuffer - */ - int clEnqueueCopyImageToBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_t1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyImageToBuffer(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyImageToBuffer - */ - int clEnqueueCopyImageToBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSize size_t1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyBufferToImage(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferToImage
    - * @deprecated use the safer methods {@link #clEnqueueCopyBufferToImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueCopyBufferToImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueCopyBufferToImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_t1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueCopyBufferToImage(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferToImage - */ - int clEnqueueCopyBufferToImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_t1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueCopyBufferToImage(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueCopyBufferToImage - */ - int clEnqueueCopyBufferToImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, NativeSize size_t1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : void* clEnqueueMapBuffer(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapBuffer
    - * @deprecated use the safer methods {@link #clEnqueueMapBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, long, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], java.nio.IntBuffer)} and {@link #clEnqueueMapBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, long, com.ochafik.lang.jnaerator.runtime.NativeSize, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - Pointer clEnqueueMapBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSize size_t1, NativeSize size_t2, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2, IntByReference cl_intPtr1); - /** - * Original signature : void* clEnqueueMapBuffer(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapBuffer - */ - Pointer clEnqueueMapBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSize size_t1, NativeSize size_t2, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[], IntBuffer cl_intPtr1); - /** - * Original signature : void* clEnqueueMapBuffer(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapBuffer - */ - Pointer clEnqueueMapBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSize size_t1, NativeSize size_t2, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[], IntByReference cl_intPtr1); - /** - * Original signature : void* clEnqueueMapImage(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapImage
    - * @deprecated use the safer methods {@link #clEnqueueMapImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, long, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], java.nio.IntBuffer)} and {@link #clEnqueueMapImage(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, int, long, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - Pointer clEnqueueMapImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSizeByReference size_tPtr4, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2, IntByReference cl_intPtr1); - /** - * Original signature : void* clEnqueueMapImage(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapImage - */ - Pointer clEnqueueMapImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSizeByReference size_tPtr3, NativeSizeByReference size_tPtr4, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[], IntBuffer cl_intPtr1); - /** - * Original signature : void* clEnqueueMapImage(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*)
    - * @see Khronos Documentation for clEnqueueMapImage - */ - Pointer clEnqueueMapImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, long cl_map_flags1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, NativeSizeByReference size_tPtr4, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[], IntByReference cl_intPtr1); - /** - * Original signature : cl_int clEnqueueUnmapMemObject(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueUnmapMemObject
    - * @deprecated use the safer method {@link #clEnqueueUnmapMemObject(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.sun.jna.Pointer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueUnmapMemObject(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueUnmapMemObject(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueUnmapMemObject - */ - int clEnqueueUnmapMemObject(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueNDRangeKernel
    - * @deprecated use the safer methods {@link #clEnqueueNDRangeKernel(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel, int, com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], com.ochafik.lang.jnaerator.runtime.NativeSize[], int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} and {@link #clEnqueueNDRangeKernel(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel, int, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, com.ochafik.lang.jnaerator.runtime.NativeSizeByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueNDRangeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, int cl_uint2, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueNDRangeKernel - */ - int clEnqueueNDRangeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, NativeSize size_tPtr1[], NativeSize size_tPtr2[], NativeSize size_tPtr3[], int cl_uint2, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueNDRangeKernel - */ - int clEnqueueNDRangeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, NativeSizeByReference size_tPtr1, NativeSizeByReference size_tPtr2, NativeSizeByReference size_tPtr3, int cl_uint2, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueTask(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueTask
    - * @deprecated use the safer method {@link #clEnqueueTask(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueTask(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueTask(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueTask - */ - int clEnqueueTask(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_kernel cl_kernel1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueNativeKernel(cl_command_queue, user_func, void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueNativeKernel
    - * @deprecated use the safer method {@link #clEnqueueNativeKernel(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.user_func, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem[], com.sun.jna.ptr.PointerByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueNativeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.user_func arg1, Pointer voidPtr1, NativeSize size_t1, int cl_uint1, PointerByReference cl_memPtr1, PointerByReference voidPtrPtr1, int cl_uint2, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueNativeKernel(cl_command_queue, user_func, void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueNativeKernel - */ - int clEnqueueNativeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.user_func arg1, Pointer voidPtr1, NativeSize size_t1, int cl_uint1, OpenCLLibrary.cl_mem cl_memPtr1[], PointerByReference voidPtrPtr1, int cl_uint2, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueMarker(cl_command_queue, cl_event*)
    - * @see Khronos Documentation for clEnqueueMarker
    - * @deprecated use the safer method {@link #clEnqueueMarker(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueMarker(OpenCLLibrary.cl_command_queue cl_command_queue1, PointerByReference cl_eventPtr1); - /** - * Original signature : cl_int clEnqueueMarker(cl_command_queue, cl_event*)
    - * @see Khronos Documentation for clEnqueueMarker - */ - int clEnqueueMarker(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_event cl_eventPtr1[]); - /** - * Original signature : cl_int clEnqueueWaitForEvents(cl_command_queue, cl_uint, const cl_event*)
    - * @see Khronos Documentation for clEnqueueWaitForEvents
    - * @deprecated use the safer method {@link #clEnqueueWaitForEvents(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueWaitForEvents(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, PointerByReference cl_eventPtr1); - /** - * Original signature : cl_int clEnqueueWaitForEvents(cl_command_queue, cl_uint, const cl_event*)
    - * @see Khronos Documentation for clEnqueueWaitForEvents - */ - int clEnqueueWaitForEvents(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, OpenCLLibrary.cl_event cl_eventPtr1[]); - /** - * Original signature : cl_int clEnqueueBarrier(cl_command_queue)
    - * @see Khronos Documentation for clEnqueueBarrier - */ - int clEnqueueBarrier(OpenCLLibrary.cl_command_queue cl_command_queue1); - /** - * Extension function access
    - * * Returns the extension function address for the given function name,
    - * or NULL if a valid function can not be found. The client must
    - * check to make sure the address is not NULL, before using or
    - * calling the returned function address.
    - * func_name
    - * Original signature : void* clGetExtensionFunctionAddress(const char*)
    - * @see Khronos Documentation for clGetExtensionFunctionAddress
    - * @deprecated use the safer methods {@link #clGetExtensionFunctionAddress(java.lang.String)} and {@link #clGetExtensionFunctionAddress(com.sun.jna.Pointer)} instead - */ - @java.lang.Deprecated - Pointer clGetExtensionFunctionAddress(Pointer charPtr1); - /** - * Extension function access
    - * * Returns the extension function address for the given function name,
    - * or NULL if a valid function can not be found. The client must
    - * check to make sure the address is not NULL, before using or
    - * calling the returned function address.
    - * func_name
    - * Original signature : void* clGetExtensionFunctionAddress(const char*)
    - * @see Khronos Documentation for clGetExtensionFunctionAddress - */ - Pointer clGetExtensionFunctionAddress(java.lang.String charPtr1); - /** - * Original signature : cl_mem clCreateFromGLBuffer(cl_context, cl_mem_flags, cl_GLuint, int*)
    - * @see Khronos Documentation for clCreateFromGLBuffer
    - * @deprecated use the safer methods {@link #clCreateFromGLBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, java.nio.IntBuffer)} and {@link #clCreateFromGLBuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateFromGLBuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLuint1, IntByReference intPtr1); - /** - * Original signature : cl_mem clCreateFromGLBuffer(cl_context, cl_mem_flags, cl_GLuint, int*)
    - * @see Khronos Documentation for clCreateFromGLBuffer - */ - OpenCLLibrary.cl_mem clCreateFromGLBuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLuint1, IntBuffer intPtr1); - /** - * Original signature : cl_mem clCreateFromGLTexture2D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLTexture2D
    - * @deprecated use the safer methods {@link #clCreateFromGLTexture2D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, int, java.nio.IntBuffer)} and {@link #clCreateFromGLTexture2D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, int, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateFromGLTexture2D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateFromGLTexture2D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLTexture2D - */ - OpenCLLibrary.cl_mem clCreateFromGLTexture2D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_mem clCreateFromGLTexture3D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLTexture3D
    - * @deprecated use the safer methods {@link #clCreateFromGLTexture3D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, int, java.nio.IntBuffer)} and {@link #clCreateFromGLTexture3D(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, int, int, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateFromGLTexture3D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateFromGLTexture3D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLTexture3D - */ - OpenCLLibrary.cl_mem clCreateFromGLTexture3D(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_mem clCreateFromGLRenderbuffer(cl_context, cl_mem_flags, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLRenderbuffer
    - * @deprecated use the safer methods {@link #clCreateFromGLRenderbuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, java.nio.IntBuffer)} and {@link #clCreateFromGLRenderbuffer(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, long, int, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_mem clCreateFromGLRenderbuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLuint1, IntByReference cl_intPtr1); - /** - * Original signature : cl_mem clCreateFromGLRenderbuffer(cl_context, cl_mem_flags, cl_GLuint, cl_int*)
    - * @see Khronos Documentation for clCreateFromGLRenderbuffer - */ - OpenCLLibrary.cl_mem clCreateFromGLRenderbuffer(OpenCLLibrary.cl_context cl_context1, long cl_mem_flags1, int cl_GLuint1, IntBuffer cl_intPtr1); - /** - * Original signature : cl_int clGetGLObjectInfo(cl_mem, cl_gl_object_type*, cl_GLuint*)
    - * @see Khronos Documentation for clGetGLObjectInfo
    - * @deprecated use the safer methods {@link #clGetGLObjectInfo(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, java.nio.IntBuffer, java.nio.IntBuffer)} and {@link #clGetGLObjectInfo(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem, com.sun.jna.ptr.IntByReference, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clGetGLObjectInfo(OpenCLLibrary.cl_mem cl_mem1, IntByReference cl_gl_object_typePtr1, IntByReference cl_GLuintPtr1); - /** - * Original signature : cl_int clGetGLObjectInfo(cl_mem, cl_gl_object_type*, cl_GLuint*)
    - * @see Khronos Documentation for clGetGLObjectInfo - */ - int clGetGLObjectInfo(OpenCLLibrary.cl_mem cl_mem1, IntBuffer cl_gl_object_typePtr1, IntBuffer cl_GLuintPtr1); - /** - * Original signature : cl_int clGetGLTextureInfo(cl_mem, cl_gl_texture_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetGLTextureInfo - */ - int clGetGLTextureInfo(OpenCLLibrary.cl_mem cl_mem1, int cl_gl_texture_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_int clEnqueueAcquireGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueAcquireGLObjects
    - * @deprecated use the safer method {@link #clEnqueueAcquireGLObjects(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem[], int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueAcquireGLObjects(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, PointerByReference cl_memPtr1, int cl_uint2, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueAcquireGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueAcquireGLObjects - */ - int clEnqueueAcquireGLObjects(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, OpenCLLibrary.cl_mem cl_memPtr1[], int cl_uint2, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clEnqueueReleaseGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReleaseGLObjects
    - * @deprecated use the safer method {@link #clEnqueueReleaseGLObjects(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem[], int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[], com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event[])} instead - */ - @java.lang.Deprecated - int clEnqueueReleaseGLObjects(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, PointerByReference cl_memPtr1, int cl_uint2, PointerByReference cl_eventPtr1, PointerByReference cl_eventPtr2); - /** - * Original signature : cl_int clEnqueueReleaseGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*)
    - * @see Khronos Documentation for clEnqueueReleaseGLObjects - */ - int clEnqueueReleaseGLObjects(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, OpenCLLibrary.cl_mem cl_memPtr1[], int cl_uint2, OpenCLLibrary.cl_event cl_eventPtr1[], OpenCLLibrary.cl_event cl_eventPtr2[]); - /** - * Original signature : cl_int clGetGLContextInfoKHR(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*)
    - * @see Khronos Documentation for clGetGLContextInfoKHR - */ - int clGetGLContextInfoKHR(NativeSizeByReference cl_context_propertiesPtr1, int cl_gl_context_info1, NativeSize size_t1, Pointer voidPtr1, NativeSizeByReference size_tPtr1); - /** - * Original signature : cl_event clCreateEventFromGLsyncKHR(cl_context, cl_GLsync, cl_int*)
    - * @see Khronos Documentation for clCreateEventFromGLsyncKHR
    - * @deprecated use the safer methods {@link #clCreateEventFromGLsyncKHR(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, com.nativelibs4java.opencl.library.OpenCLLibrary.__GLsync, java.nio.IntBuffer)} and {@link #clCreateEventFromGLsyncKHR(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context, com.nativelibs4java.opencl.library.OpenCLLibrary.__GLsync, com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - OpenCLLibrary.cl_event clCreateEventFromGLsyncKHR(OpenCLLibrary.cl_context cl_context1, OpenCLLibrary.__GLsync cl_GLsync1, IntByReference cl_intPtr1); - /** - * Original signature : cl_event clCreateEventFromGLsyncKHR(cl_context, cl_GLsync, cl_int*)
    - * @see Khronos Documentation for clCreateEventFromGLsyncKHR - */ - OpenCLLibrary.cl_event clCreateEventFromGLsyncKHR(OpenCLLibrary.cl_context cl_context1, OpenCLLibrary.__GLsync cl_GLsync1, IntBuffer cl_intPtr1); - public static final int CL_INVALID_GL_CONTEXT_APPLE = -1000; - /** - * context
    - * Original signature : cl_int clGetGLContextInfoAPPLE(cl_context context, void *platform_gl_ctx, cl_gl_platform_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret) - */ - int clGetGLContextInfoAPPLE(cl_context context, NativeSize platform_gl_ctx, int param_name, NativeSize param_value_size, Pointer param_value, NativeSizeByReference param_value_size_ret); - /** - * memobj
    - * Original signature : cl_int clSetMemObjectDestructorAPPLE(cl_mem, clSetMemObjectDestructorAPPLE_arg1_callback, void*) - */ - int clSetMemObjectDestructorAPPLE(OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.clSetMemObjectDestructorAPPLE_arg1_callback arg1, Pointer voidPtr1); - /** - * errstr
    - * Original signature : void clLogMessagesToSystemLogAPPLE(const char*, const void*, size_t, void*)
    - * @deprecated use the safer methods {@link #clLogMessagesToSystemLogAPPLE(java.lang.String, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} and {@link #clLogMessagesToSystemLogAPPLE(com.sun.jna.Pointer, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} instead - */ - @java.lang.Deprecated - void clLogMessagesToSystemLogAPPLE(Pointer charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * errstr
    - * Original signature : void clLogMessagesToSystemLogAPPLE(const char*, const void*, size_t, void*) - */ - void clLogMessagesToSystemLogAPPLE(java.lang.String charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStdout sends all log messages to the file descriptor stdout
    - * errstr
    - * Original signature : void clLogMessagesToStdoutAPPLE(const char*, const void*, size_t, void*)
    - * @deprecated use the safer methods {@link #clLogMessagesToStdoutAPPLE(java.lang.String, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} and {@link #clLogMessagesToStdoutAPPLE(com.sun.jna.Pointer, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} instead - */ - @java.lang.Deprecated - void clLogMessagesToStdoutAPPLE(Pointer charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStdout sends all log messages to the file descriptor stdout
    - * errstr
    - * Original signature : void clLogMessagesToStdoutAPPLE(const char*, const void*, size_t, void*) - */ - void clLogMessagesToStdoutAPPLE(java.lang.String charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStderr sends all log messages to the file descriptor stderr
    - * errstr
    - * Original signature : void clLogMessagesToStderrAPPLE(const char*, const void*, size_t, void*)
    - * @deprecated use the safer methods {@link #clLogMessagesToStderrAPPLE(java.lang.String, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} and {@link #clLogMessagesToStderrAPPLE(com.sun.jna.Pointer, com.sun.jna.Pointer, com.ochafik.lang.jnaerator.runtime.NativeSize, com.sun.jna.Pointer)} instead - */ - @java.lang.Deprecated - void clLogMessagesToStderrAPPLE(Pointer charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStderr sends all log messages to the file descriptor stderr
    - * errstr
    - * Original signature : void clLogMessagesToStderrAPPLE(const char*, const void*, size_t, void*) - */ - void clLogMessagesToStderrAPPLE(java.lang.String charPtr1, Pointer voidPtr1, NativeSize size_t1, Pointer voidPtr2); - /** - * Original signature : cl_int clIcdGetPlatformIDsKHR(cl_uint, cl_platform_id*, cl_uint*)
    - * @deprecated use the safer methods {@link #clIcdGetPlatformIDsKHR(int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id[], java.nio.IntBuffer)} and {@link #clIcdGetPlatformIDsKHR(int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clIcdGetPlatformIDsKHR(int cl_uint1, PointerByReference cl_platform_idPtr1, IntByReference cl_uintPtr1); - /// Original signature : cl_int clIcdGetPlatformIDsKHR(cl_uint, cl_platform_id*, cl_uint*) - int clIcdGetPlatformIDsKHR(int cl_uint1, OpenCLLibrary.cl_platform_id cl_platform_idPtr1[], IntBuffer cl_uintPtr1); - /// Original signature : cl_int clIcdGetPlatformIDsKHR(cl_uint, cl_platform_id*, cl_uint*) - int clIcdGetPlatformIDsKHR(int cl_uint1, OpenCLLibrary.cl_platform_id cl_platform_idPtr1[], IntByReference cl_uintPtr1); - /// Original signature : cl_int clReleaseDeviceEXT(cl_device_id) - int clReleaseDeviceEXT(OpenCLLibrary.cl_device_id cl_device_id1); - /// Original signature : cl_int clRetainDeviceEXT(cl_device_id) - int clRetainDeviceEXT(OpenCLLibrary.cl_device_id cl_device_id1); - /** - * Original signature : cl_int clCreateSubDevicesEXT(cl_device_id, const cl_device_partition_property_ext*, cl_uint, cl_device_id*, cl_uint*)
    - * @deprecated use the safer methods {@link #clCreateSubDevicesEXT(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id, java.nio.LongBuffer, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], java.nio.IntBuffer)} and {@link #clCreateSubDevicesEXT(com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id, com.sun.jna.ptr.LongByReference, int, com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id[], com.sun.jna.ptr.IntByReference)} instead - */ - @java.lang.Deprecated - int clCreateSubDevicesEXT(OpenCLLibrary.cl_device_id cl_device_id1, LongByReference cl_device_partition_property_extPtr1, int cl_uint1, PointerByReference cl_device_idPtr1, IntByReference cl_uintPtr1); - /// Original signature : cl_int clCreateSubDevicesEXT(cl_device_id, const cl_device_partition_property_ext*, cl_uint, cl_device_id*, cl_uint*) - int clCreateSubDevicesEXT(OpenCLLibrary.cl_device_id cl_device_id1, LongBuffer cl_device_partition_property_extPtr1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], IntBuffer cl_uintPtr1); - /// Original signature : cl_int clCreateSubDevicesEXT(cl_device_id, const cl_device_partition_property_ext*, cl_uint, cl_device_id*, cl_uint*) - int clCreateSubDevicesEXT(OpenCLLibrary.cl_device_id cl_device_id1, LongByReference cl_device_partition_property_extPtr1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], IntByReference cl_uintPtr1); - //public static final GlobalCallback clCreateSubDevicesEXT_fn = new GlobalCallback(com.nativelibs4java.opencl.library.OpenCLLibrary.JNA_NATIVE_LIB, clCreateSubDevicesEXT_fn_callback.class, "clCreateSubDevicesEXT_fn"); - /// Pointer to unknown (opaque) type - public static class __GLsync extends PointerType { - public __GLsync(Pointer address) { - super(address); - } - public __GLsync() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_device_id extends PointerType { - public cl_device_id(Pointer address) { - super(address); - } - public cl_device_id() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_mem extends PointerType { - public cl_mem(Pointer address) { - super(address); - } - public cl_mem() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_platform_id extends PointerType { - public cl_platform_id(Pointer address) { - super(address); - } - public cl_platform_id() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_event extends PointerType { - public cl_event(Pointer address) { - super(address); - } - public cl_event() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_command_queue extends PointerType { - public cl_command_queue(Pointer address) { - super(address); - } - public cl_command_queue() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_context extends PointerType { - public cl_context(Pointer address) { - super(address); - } - public cl_context() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_sampler extends PointerType { - public cl_sampler(Pointer address) { - super(address); - } - public cl_sampler() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_program extends PointerType { - public cl_program(Pointer address) { - super(address); - } - public cl_program() { - super(); - } - }; - /// Pointer to unknown (opaque) type - public static class cl_kernel extends PointerType { - public cl_kernel(Pointer address) { - super(address); - } - public cl_kernel() { - super(); - } - }; -} diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java b/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java deleted file mode 100644 index f270f676f..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.nativelibs4java.opencl.library; -/** - * JNA Wrapper for library OpenGL
    - * This file was autogenerated by JNAerator,
    - * a tool written by Olivier Chafik that uses a few opensource projects..
    - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public interface OpenGLContextUtils extends com.sun.jna.Library { - public static final java.lang.String JNA_LIBRARY_NAME = - com.sun.jna.Platform.isWindows() ? "OpenGL32" : - com.sun.jna.Platform.isLinux() ? "GL" : - "OpenGL"; - //public static final java.lang.String JNA_LIBRARY_NAME = com.ochafik.lang.jnaerator.runtime.LibraryExtractor.getLibraryPath("OpenGL", true, OpenGLApple.class); - //public static final com.sun.jna.NativeLibrary JNA_NATIVE_LIB = com.sun.jna.NativeLibrary.getInstance(OpenGLApple.JNA_LIBRARY_NAME, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS); - public static final OpenGLContextUtils INSTANCE = (OpenGLContextUtils)com.sun.jna.Native.loadLibrary(JNA_LIBRARY_NAME, OpenGLContextUtils.class);//OpenGLApple.JNA_LIBRARY_NAME, OpenGLApple.class, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS); - - /// Original signature : CGLShareGroupObj CGLGetShareGroup(CGLContextObj) - com.ochafik.lang.jnaerator.runtime.NativeSize CGLGetShareGroup(com.ochafik.lang.jnaerator.runtime.NativeSize ctx); - /** - * * Current context functions
    - * Original signature : CGLError CGLSetCurrentContext(CGLContextObj) - */ - int CGLSetCurrentContext(com.sun.jna.Pointer ctx); - /// Original signature : CGLContextObj CGLGetCurrentContext() - com.ochafik.lang.jnaerator.runtime.NativeSize CGLGetCurrentContext(); - - /** - * * Version numbers
    - * Original signature : void CGLGetVersion(GLint*, GLint*) - */ - void CGLGetVersion(java.nio.IntBuffer majorvers, java.nio.IntBuffer minorvers); - /** - * * Convert an error code to a string
    - * Original signature : char* CGLErrorString(CGLError)
    - * @param error @see CGLError - */ - java.lang.String CGLErrorString(int error); - - com.ochafik.lang.jnaerator.runtime.NativeSize wglGetCurrentDC(); - com.ochafik.lang.jnaerator.runtime.NativeSize wglGetCurrentContext(); - com.ochafik.lang.jnaerator.runtime.NativeSize glXGetCurrentDisplay(); - com.ochafik.lang.jnaerator.runtime.NativeSize glXGetCurrentContext(); -} diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java b/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java deleted file mode 100644 index 134bb1fd3..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.nativelibs4java.opencl.library; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.Structure; -/** - * This file was autogenerated by JNAerator,
    - * a tool written by Olivier Chafik that uses a few opensource projects..
    - * For help, please visit NativeLibs4Java , Rococoa, or JNA. - */ -public class cl_buffer_region extends Structure { - public NativeSize origin; - public NativeSize size; - public cl_buffer_region() { - super(); - } - public cl_buffer_region(NativeSize origin, NativeSize size) { - super(); - this.origin = origin; - this.size = size; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected cl_buffer_region newInstance() { return new cl_buffer_region(); } - public static cl_buffer_region[] newArray(int arrayLength) { - return Structure.newArray(cl_buffer_region.class, arrayLength); - } - public static class ByReference extends cl_buffer_region implements Structure.ByReference { - - }; - public static class ByValue extends cl_buffer_region implements Structure.ByValue { - - }; -} diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java b/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java deleted file mode 100644 index 788a7563a..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.nativelibs4java.opencl.library; -import com.ochafik.lang.jnaerator.runtime.Structure; -/** - * This file was autogenerated by JNAerator,
    - * a tool written by Olivier Chafik that uses a few opensource projects..
    - * For help, please visit NativeLibs4Java , Rococoa, or JNA. - */ -public class cl_image_format extends Structure { - /// C type : cl_channel_order - public int image_channel_order; - /// C type : cl_channel_type - public int image_channel_data_type; - public cl_image_format() { - super(); - } - /** - * @param image_channel_order C type : cl_channel_order
    - * @param image_channel_data_type C type : cl_channel_type - */ - public cl_image_format(int image_channel_order, int image_channel_data_type) { - super(); - this.image_channel_order = image_channel_order; - this.image_channel_data_type = image_channel_data_type; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected cl_image_format newInstance() { return new cl_image_format(); } - public static cl_image_format[] newArray(int arrayLength) { - return Structure.newArray(cl_image_format.class, arrayLength); - } - public static class ByReference extends cl_image_format implements Structure.ByReference { - - }; - public static class ByValue extends cl_image_format implements Structure.ByValue { - - }; -} diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java b/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java deleted file mode 100644 index 746ee8c0d..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Raw OpenCL API bindings. - */ -package com.nativelibs4java.opencl.library; diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator b/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator deleted file mode 100644 index 0d692eb98..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator +++ /dev/null @@ -1,11 +0,0 @@ -"$(DIR)/OpenCL.base.jnaerator" - --DAVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER= --D__APPLE__= - --framework OpenCL - -//-framework OpenGL -//-package com.nativelibs4java.opengl.library -framework OpenGL - --v diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator b/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator b/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator deleted file mode 100644 index 3f21a9046..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator +++ /dev/null @@ -1,11 +0,0 @@ -"$(DIR)/OpenCL.base.jnaerator" - -"-Dcl_bitfield=unsigned long" --library OpenCL - "-D_MSC_VER=1" -// "-D__CL_IMPORT=__declspec(dllimport)" - "C:\Program Files\ATI Stream\include\CL\cl_platform.h" - "-IC:\Program Files\ATI Stream\include" - "C:\Program Files\ATI Stream\include\CL\cl.h" - "C:\Program Files\ATI Stream\include\CL\cl_gl.h" - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator b/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/config.jnaerator b/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/config.jnaerator deleted file mode 100644 index d75fcaa4c..000000000 --- a/libraries/OpenCL-JNA/OpenCL4Java/src/main/jnaerator/config.jnaerator +++ /dev/null @@ -1,36 +0,0 @@ --nocpp --noMangling --noJar -noComp --runtime JNAerator - --gccLong --limitComments - -"-Dextern=" -"-D__stdcall=" -"-D__declspec(x)=x" -"-D__extension__=" - --U_MSC_VER -//-U__APPLE__ -//-U__cplusplus -//-U_WIN32 --DCL_USE_DEPRECATED_OPENCL_1_0_APIS=1 - -//-o "$(DIR)/../../../target/generated-sources/java" - -//-choicesOut "$(DIR)/OpenCL.choices" --v - --package com.nativelibs4java.opencl.library --libraryNamingPrefixes cl --library OpenCL - "-I$(DIR)/../headers/1.1" - "$(DIR)/../headers/1.1/CL/cl_platform.h" - "$(DIR)/../headers/1.1/CL/opencl.h" - "$(DIR)/../headers/1.1/CL/cl.h" - "$(DIR)/../headers/1.1/CL/cl_ext.h" - "$(DIR)/../headers/1.1/CL/cl_gl.h" - "$(DIR)/../headers/1.1/CL/cl_gl_ext.h" - --onlineDoc "Khronos Documentation for {0}" "http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/{0}.html" diff --git a/libraries/OpenCL-JNA/OpenGLDemos/.gitignore b/libraries/OpenCL-JNA/OpenGLDemos/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL-JNA/OpenGLDemos/pom.xml b/libraries/OpenCL-JNA/OpenGLDemos/pom.xml deleted file mode 100644 index adfe4b5e0..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-opengl-demos-jna - JavaCL OpenGL Demos / JNA - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl-demos-jna - - - - org.swinglabs - swing-layout - 1.0.3 - - - - - - - - com.nativelibs4java - javacl-generator-jna - - - - compile - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form b/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form deleted file mode 100644 index cce20a24c..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form +++ /dev/null @@ -1,196 +0,0 @@ - - -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java b/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java deleted file mode 100644 index 0e93d0c43..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos; - -import com.nativelibs4java.opencl.CLDevice; -import com.nativelibs4java.opencl.CLPlatform; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.demos.hardware.HardwareReport; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLProfile; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -/** - * - * @author ochafik - */ -public class JavaCLSettingsPanel extends javax.swing.JPanel { - - /** - * - */ - private static final long serialVersionUID = -3840797355369910724L; - - public void removeOpenGLComponents() { - configFromGLCheck.getParent().remove(configFromGLCheck); - awtRenderingCheck.getParent().remove(awtRenderingCheck); - invalidate(); - } - - /** Creates new form JavaCLSettingsPanel */ - public JavaCLSettingsPanel() { - initComponents(); - - Border border = UIManager.getBorder( "TitledBorder.aquaVariant" ); - if (border == null) - border = new EtchedBorder(); - settingsPanel.setBorder(new TitledBorder(border, "OpenCL & OpenGL Settings")); - platformCombo.setModel(new DefaultComboBoxModel(getPlatforms().toArray())); - platformChanged(null); - normalButtActionPerformed(null); - } - - public boolean isDirectGLRendering() { - return awtRenderingCheck.isSelected(); - } - public void setDirectGLRendering(boolean b) { - awtRenderingCheck.setSelected(b); - } - - public CLDevice getDevice() { - return (CLDevice)deviceCombo.getSelectedItem(); - } - - public List getPlatforms() { - CLPlatform[] platforms = JavaCL.listPlatforms(); - boolean hasSharing = false; - plat: for (CLPlatform platform : platforms) - if (platform.isGLSharingSupported()) - for (CLDevice device : platform.listAllDevices(false)) - if (device.isGLSharingSupported()) { - hasSharing = true; - break plat; - } - - configFromGLCheck.setEnabled(hasSharing); - if (!hasSharing) { - configFromGLCheck.setText(configFromGLCheck.getText() + " (unavailable option)"); - configFromGLCheck.setToolTipText("Did not find any OpenCL platform with OpenGL sharing support."); - } - - return Arrays.asList(platforms); - } - - public List getGLProfiles() { - List list = new ArrayList(); - list.add(GLProfile.GL2); - return list; - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - @SuppressWarnings("unchecked") - // //GEN-BEGIN:initComponents - private void initComponents() { - - settingsPanel = new javax.swing.JPanel(); - fastestButt = new javax.swing.JButton(); - safestButt = new javax.swing.JButton(); - normalButt = new javax.swing.JButton(); - detailsButt = new javax.swing.JButton(); - awtRenderingCheck = new javax.swing.JCheckBox(); - configFromGLCheck = new javax.swing.JCheckBox(); - platformLab = new javax.swing.JLabel(); - platformCombo = new javax.swing.JComboBox(); - deviceLab = new javax.swing.JLabel(); - deviceCombo = new javax.swing.JComboBox(); - - fastestButt.setText("Fastest (unstable)"); - fastestButt.setToolTipText("Best performance, typically unstable."); - fastestButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - fastestButtActionPerformed(evt); - } - }); - - safestButt.setText("Safest (slow)"); - safestButt.setToolTipText("Choose this if you've experienced crashes or black screens with the other modes"); - safestButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - safestButtActionPerformed(evt); - } - }); - - normalButt.setFont(normalButt.getFont().deriveFont(normalButt.getFont().getStyle() | java.awt.Font.BOLD)); - normalButt.setText("Normal (advised)"); - normalButt.setToolTipText("Usually the best compromise."); - normalButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - normalButtActionPerformed(evt); - } - }); - - detailsButt.setText("Details"); - detailsButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - detailsButtActionPerformed(evt); - } - }); - - awtRenderingCheck.setSelected(true); - awtRenderingCheck.setText("Direct OpenGL AWT Rendering (faster)"); - awtRenderingCheck.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - awtRenderingCheckActionPerformed(evt); - } - }); - - configFromGLCheck.setText("Configure from OpenGL context"); - configFromGLCheck.setToolTipText("Attempt to share data between OpenCL and OpenGL. \nThis is not well supported by existing graphic card drivers might crash the program."); - configFromGLCheck.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - configFromGLChanged(evt); - } - }); - configFromGLCheck.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - configFromGLCheckActionPerformed(evt); - } - }); - - platformLab.setText("Platform"); - - platformCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - platformCombo.setMinimumSize(new java.awt.Dimension(16, 27)); - platformCombo.addItemListener(new java.awt.event.ItemListener() { - public void itemStateChanged(java.awt.event.ItemEvent evt) { - platformChanged(evt); - } - }); - platformCombo.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - platformComboActionPerformed(evt); - } - }); - - deviceLab.setText("Device"); - - deviceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - deviceCombo.setMinimumSize(new java.awt.Dimension(16, 27)); - - org.jdesktop.layout.GroupLayout settingsPanelLayout = new org.jdesktop.layout.GroupLayout(settingsPanel); - settingsPanel.setLayout(settingsPanelLayout); - settingsPanelLayout.setHorizontalGroup( - settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanelLayout.createSequentialGroup() - .addContainerGap() - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) - .add(platformLab) - .add(deviceLab)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanelLayout.createSequentialGroup() - .add(fastestButt) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(normalButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(safestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .add(configFromGLCheck) - .add(awtRenderingCheck) - .add(org.jdesktop.layout.GroupLayout.TRAILING, settingsPanelLayout.createSequentialGroup() - .add(platformCombo, 0, 354, Short.MAX_VALUE) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(detailsButt)) - .add(org.jdesktop.layout.GroupLayout.TRAILING, deviceCombo, 0, 448, Short.MAX_VALUE)) - .addContainerGap()) - ); - settingsPanelLayout.setVerticalGroup( - settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(org.jdesktop.layout.GroupLayout.TRAILING, settingsPanelLayout.createSequentialGroup() - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(safestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .add(fastestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .add(normalButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(configFromGLCheck) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(platformCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .add(platformLab) - .add(detailsButt)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(deviceCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .add(deviceLab)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(awtRenderingCheck)) - ); - - org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); - this.setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - ); - layout.setVerticalGroup( - layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - ); - }// //GEN-END:initComponents - - private void configFromGLCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configFromGLCheckActionPerformed - - }//GEN-LAST:event_configFromGLCheckActionPerformed - - private void awtRenderingCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_awtRenderingCheckActionPerformed - // TODO add your handling code here: - }//GEN-LAST:event_awtRenderingCheckActionPerformed - - private void platformComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_platformComboActionPerformed - // TODO add your handling code here: - }//GEN-LAST:event_platformComboActionPerformed - - private void platformChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_platformChanged - CLPlatform platform = (CLPlatform)platformCombo.getSelectedItem(); - if (platform != null) { - CLDevice[] devices = platform.listAllDevices(true); - deviceCombo.setModel(new DefaultComboBoxModel(devices)); - setDevice(platform.getBestDevice()); - } else { - deviceCombo.setModel(new DefaultComboBoxModel(new Object[0])); - } - }//GEN-LAST:event_platformChanged - - - private void fastestButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fastestButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(true); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(true); - }//GEN-LAST:event_fastestButtActionPerformed - - private void normalButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_normalButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(true); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(false); - }//GEN-LAST:event_normalButtActionPerformed - - private void safestButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_safestButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(false); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(false); - }//GEN-LAST:event_safestButtActionPerformed - - private void configFromGLChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_configFromGLChanged - platformCombo.setEnabled(!configFromGLCheck.isSelected()); - deviceCombo.setEnabled(!configFromGLCheck.isSelected()); - platformLab.setEnabled(!configFromGLCheck.isSelected()); - deviceLab.setEnabled(!configFromGLCheck.isSelected()); - }//GEN-LAST:event_configFromGLChanged - - private void detailsButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_detailsButtActionPerformed - CLPlatform platform = (CLPlatform)platformCombo.getSelectedItem(); - if (platform != null) { - JComponent c = HardwareReport.getHardwareReportComponent(platform); - c.setMaximumSize(new Dimension(600, 600)); - c.setPreferredSize(new Dimension(600, 600)); - JOptionPane.showMessageDialog(this, c, "HardwareReport for platform '" + platform.getName() + "'", JOptionPane.INFORMATION_MESSAGE); - } - }//GEN-LAST:event_detailsButtActionPerformed - - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JCheckBox awtRenderingCheck; - private javax.swing.JCheckBox configFromGLCheck; - private javax.swing.JButton detailsButt; - private javax.swing.JComboBox deviceCombo; - private javax.swing.JLabel deviceLab; - private javax.swing.JButton fastestButt; - private javax.swing.JButton normalButt; - private javax.swing.JComboBox platformCombo; - private javax.swing.JLabel platformLab; - private javax.swing.JButton safestButt; - private javax.swing.JPanel settingsPanel; - // End of variables declaration//GEN-END:variables - - private void setDevice(CLDevice device) { - if (device == null) { - deviceCombo.setSelectedIndex(-1); - return; - } - - CLPlatform platform = device.getPlatform(); - if (!platform.equals(platformCombo.getSelectedItem())) - platformCombo.setSelectedItem(platform); - - for (int i = 0, len = deviceCombo.getModel().getSize(); i < len; i++) { - CLDevice d = (CLDevice)deviceCombo.getModel().getElementAt(i); - if (device.equals(d)) { - deviceCombo.setSelectedItem(d); - break; - } - } - } - - private void selectBestDevice() { - setDevice(JavaCL.getBestDevice()); - } - - public boolean isGLSharingEnabled() { - return configFromGLCheck.isEnabled() && configFromGLCheck.isSelected(); - } - - public void setGLSharingEnabled(boolean b) { - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(b); - } - -} diff --git a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java b/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java deleted file mode 100644 index 6769b3b5d..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java +++ /dev/null @@ -1,656 +0,0 @@ -/*********************************************************************** - - Copyright (c) 2008, 2009, Memo Akten, www.memo.tv - *** The Mega Super Awesome Visuals Company *** - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of MSA Visuals nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. - * - * ***********************************************************************/ - -package com.nativelibs4java.opencl.demos.particles; - - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.demos.JavaCLSettingsPanel; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.nativelibs4java.util.*; -import com.ochafik.util.SystemUtils; -import com.sun.jna.Platform; -import java.io.IOException; -import java.util.logging.*; - -import javax.swing.*; -import java.nio.FloatBuffer; - -import javax.media.opengl.*; -import static javax.media.opengl.GL.*; -import javax.media.opengl.awt.*; - -import com.jogamp.opengl.util.*; -import com.jogamp.common.nio.*; - -import java.awt.*; -import java.awt.event.*; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileReader; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; -import java.util.Map; -import java.util.Random; -import javax.imageio.ImageIO; -import static javax.media.opengl.GL.*; -import javax.media.opengl.glu.GLU; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.basic.BasicMenuUI.ChangeHandler; - -/** - * - * @author Olivier (ported to JavaCL/OpenCL4Java) - */ -public class ParticlesDemo implements GLEventListener { - - public static Component createGLCanvas(int width, int height, boolean useSwing) { - GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - Component canvas = useSwing ? new GLJPanel(caps) : new GLCanvas(caps); - canvas.setSize(width, height); - canvas.setIgnoreRepaint(true); - canvas.setPreferredSize(new Dimension(width, height)); - canvas.setSize(new Dimension(width, height)); - - return canvas; - } - - static File lastFile; - volatile boolean paused; - final static float DEFAULT_MOUSE_WEIGHT = 0.7f; - volatile float mouseWeight = DEFAULT_MOUSE_WEIGHT; - - static class ParticlesCountItem { - public int count; - public String string; - public ParticlesCountItem(int count, String string) { - this.count = count; - this.string = string; - } - @Override - public String toString() { - return string; - } - - } - - public static void main(String[] args) { - try { - System.setProperty("sun.java2d.noddraw","true"); - - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - - JFrame f = new JFrame("JavaCL Particles Demo"); - Box tb = Box.createHorizontalBox(); - final JButton openImage = new JButton("Import"), saveImage = new JButton("Export"), changeBlend = new JButton("Change Blend"); - tb.add(openImage); - //tb.add(saveImage); - tb.add(changeBlend); - //final JCheckBox limi - final AssertionError[] err = new AssertionError[1]; - - - final ParticlesDemo demo = new ParticlesDemo(); - final int nSpeeds = 21; - - final JSlider speedSlider = new JSlider(0, nSpeeds - 1); - speedSlider.setValue(nSpeeds / 2); - //f.getContentPane().add("West", slider); - - tb.add(speedSlider); - //slider.setOrientation(JSlider.VERTICAL); - speedSlider.addChangeListener(new ChangeListener() { - - @Override - public void stateChanged(ChangeEvent e) { - int d = speedSlider.getValue() - nSpeeds / 2; - demo.speedFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * DEFAULT_SPEED_FACTOR; - } - - }); - - changeBlend.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent ae) { - demo.iBlend = (demo.iBlend + 1) % demo.blends.length; - } - - }); - - final Component canvas = createGLCanvas(1000, 800, demo.settings.isDirectGLRendering()); - f.setLayout(new BorderLayout()); - f.add("Center", canvas); - - saveImage.addActionListener(new ActionListener() { - - @SuppressWarnings("deprecation") - @Override - public void actionPerformed(ActionEvent ae) { - boolean paused = demo.paused; - demo.paused = true; - - BufferedImage im = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics g = im.createGraphics(); - canvas.paint(g); - g.dispose(); - - FileDialog fc = new FileDialog((Frame)null); - fc.setMode(FileDialog.SAVE); - fc.show(); - if (fc.getFile() != null) { - try { - ImageIO.write(im, "jpeg", lastFile = new File(new File(fc.getDirectory()), fc.getFile())); - } catch (Exception ex) { - ParticlesDemo.exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - demo.paused = paused; - } - - }); - - openImage.addActionListener(new ActionListener() { - - @SuppressWarnings("deprecation") - @Override - public void actionPerformed(ActionEvent ae) { - boolean paused = demo.paused; - demo.paused = true; - - FileDialog fc = new FileDialog((Frame)null); - fc.setMode(FileDialog.LOAD); - fc.show(); - if (fc.getFile() != null) { - try { - BufferedImage im = ImageIO.read(lastFile = new File(new File(fc.getDirectory()), fc.getFile())); - demo.setImage(im); - } catch (Exception ex) { - ParticlesDemo.exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - demo.paused = paused; - } - - }); - - canvas.addMouseWheelListener(new MouseWheelListener() { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - if (e.getUnitsToScroll() > 0) - for (int i = e.getUnitsToScroll(); i-- != 0;) - demo.mouseWeight *= 1.1f; - else - for (int i = -e.getUnitsToScroll(); i-- != 0;) - demo.mouseWeight /= 1.1f; - } - }); - canvas.addKeyListener(new KeyAdapter() { - - @Override - public void keyPressed(KeyEvent ke) { - switch (ke.getKeyCode()) { - case KeyEvent.VK_SPACE: - demo.paused = !demo.paused; - break; - case KeyEvent.VK_DELETE: - case KeyEvent.VK_BACK_SPACE: - demo.mouseWeight = 1; - break; - } - } - - - - }); - final JSlider sliderMass = new JSlider(0, nSpeeds - 1); - sliderMass.setValue(nSpeeds / 2); - //f.getContentPane().add("East", sliderMass); - //sliderMass.setOrientation(JSlider.VERTICAL); - sliderMass.addChangeListener(new ChangeListener() { - - @Override - public void stateChanged(ChangeEvent e) { - int d = sliderMass.getValue() - nSpeeds / 2; - demo.massFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * DEFAULT_MASS_FACTOR; - } - - }); - tb.add(sliderMass); - - f.add("North", tb); - - canvas.addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent me) { - if (me.getButton() != MouseEvent.BUTTON1 || me.isMetaDown() || me.isControlDown()) - demo.mouseWeight = 1; - else - demo.paused = !demo.paused; - } - - @Override - public void mouseExited(MouseEvent e) { - demo.hasMouse = false; - } - - @Override - public void mouseEntered(MouseEvent e) { - demo.hasMouse = true; - } - - - - - }); - canvas.addMouseMotionListener(new MouseMotionAdapter() { - - @Override - public void mouseMoved(MouseEvent e) { - demo.mouseX = e.getX(); - demo.mouseY = e.getY(); - demo.lastMouseMove = System.currentTimeMillis(); - } - - }); - - //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.addWindowListener(new WindowAdapter() { - - @Override - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - f.pack(); - - f.setVisible(true); - - FPSAnimator animator; - if (canvas instanceof GLCanvas) { - ((GLCanvas)canvas).addGLEventListener(demo); - animator = new FPSAnimator(((GLCanvas)canvas), 30); - } else { - ((GLJPanel)canvas).addGLEventListener(demo); - animator = new FPSAnimator(((GLJPanel)canvas), 30); - } - - //animator.setRunAsFastAsPossible(true); - animator.start(); - } catch (Exception ex) { - exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public void setImage(BufferedImage image) { - mouseWeight = DEFAULT_MOUSE_WEIGHT; - - int iWidth = image.getWidth(), iHeight = image.getHeight(); - int[] pixels = image.getRGB(0, 0, iWidth, iHeight, null, 0, iWidth); - int nPixels = iWidth * iHeight; - float[] nonEmptyPixelsX = new float[nPixels], nonEmptyPixelsY = new float[nPixels]; - int[] nonEmptyPixels = new int[nPixels]; - - int nNonEmptyPixels = 0; - int hw = iWidth / 2, hh = iHeight / 2; - for (int iPixel = 0; iPixel < nPixels; iPixel++) { - int pixel = pixels[iPixel]; - if ((pixel & 0xff000000) != 0) - { - int y = iPixel / iWidth, x = iPixel - y * iWidth; - nonEmptyPixels[nNonEmptyPixels] = pixel; - nonEmptyPixelsX[nNonEmptyPixels] = x - hw; - nonEmptyPixelsY[nNonEmptyPixels] = hh - y; - nNonEmptyPixels++; - } - } - - queue.finish(); - - FloatBuffer positionsView = interleavedColorAndPositionsTemp.asFloatBuffer(); - IntBuffer colorView = interleavedColorAndPositionsTemp.asIntBuffer(); - for (int iPoint = 0; iPoint < particlesCount; iPoint++) { - int iPixel = (int)(random.nextFloat() * (nNonEmptyPixels - 1)); - - velocities.put(iPixel, 0); - velocities.put(iPixel + 1, 0); - - int colorOffset = iPoint * (elementSize / 4); - int posOffset = iPoint * (elementSize / 4) + 1; - - colorView.put(colorOffset, nonEmptyPixels[iPixel]); - positionsView.put(posOffset, nonEmptyPixelsX[iPixel]); - positionsView.put(posOffset + 1, nonEmptyPixelsY[iPixel]); - } - velocities.rewind(); - velocitiesMem.write(queue, velocities, false); - - if (useOpenGLContext) - interleavedColorAndPositionsMem.acquireGLObject(queue); - interleavedColorAndPositionsMem.write(queue, interleavedColorAndPositionsTemp, false); - if (useOpenGLContext) - interleavedColorAndPositionsMem.releaseGLObject(queue); - - queue.finish(); - } - - CLContext context; - CLQueue queue; - - boolean useOpenGLContext = false; - int particlesCount; - int[] vbo = new int[1]; - - static final float DEFAULT_SLOWDOWN_FACTOR = 0.7f; - static final float DEFAULT_SPEED_FACTOR = 2f, DEFAULT_MASS_FACTOR = 2; - float mouseX, mouseY, width, height, massFactor = DEFAULT_MASS_FACTOR, speedFactor = DEFAULT_SPEED_FACTOR, slowDownFactor = DEFAULT_SLOWDOWN_FACTOR; - boolean hasMouse = false; - boolean limitToScreen = false; - - long lastMouseMove; - FloatBuffer velocities; - //CLKernel updateParticleKernel; - ParticlesDemoProgram particlesProgram; - CLFloatBuffer massesMem, velocitiesMem; - CLByteBuffer interleavedColorAndPositionsMem; - ByteBuffer interleavedColorAndPositionsTemp; - - int elementSize = 4 * 4;//4 + 2 * 4 + 4; // 4 color bytes and 2 position floats, 1 dummy alignment float - - CLByteBuffer colorsMem; - - Random random = new Random(System.nanoTime()); - JavaCLSettingsPanel settings = new JavaCLSettingsPanel(); - - public ParticlesDemo() { - - ParticlesCountItem[] items = new ParticlesCountItem[] { - new ParticlesCountItem(1024, "1K"), - new ParticlesCountItem(1024 * 10,"10K"), - new ParticlesCountItem(1024 * 100,"100K"), - new ParticlesCountItem(1024 * 1000,"1M"), - new ParticlesCountItem(1024 * 10000,"10M") - }; - JComboBox cb = new JComboBox(items); - cb.setSelectedIndex(2); - JLabel lb = new JLabel("Number of particles"); - Box countPanel = Box.createHorizontalBox(); - SetupUtils.setEtchedTitledBorder(countPanel, "Particles Demo Settings"); - countPanel.add(lb); - countPanel.add(Box.createHorizontalStrut(5)); - countPanel.add(cb); - cb.setMinimumSize(new Dimension(100, 10)); - cb.setMaximumSize(new Dimension(200, Integer.MAX_VALUE)); - countPanel.add(Box.createHorizontalGlue()); - - - //sett.removeOpenGLComponents(); - - final JPanel opts = new JPanel(new BorderLayout()); - JLabel detailsLab = new JLabel("Advanced OpenCL settings...", JLabel.RIGHT); - detailsLab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - opts.add("Center", detailsLab); - detailsLab.addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent e) { - opts.removeAll(); - opts.add("Center", settings); - opts.invalidate(); - Component c = opts.getParent(); - while (c != null) { - if (c instanceof Frame) { - ((Frame)c).pack(); - break; - } - if (c instanceof JDialog) { - ((JDialog)c).pack(); - break; - } - c = c.getParent(); - } - } - - }); - - int opt = JOptionPane.showConfirmDialog(null, new Object[] { countPanel, opts }, "JavaCL Particles Demo", JOptionPane.OK_CANCEL_OPTION); - if (opt != JOptionPane.OK_OPTION) - System.exit(0); - - useOpenGLContext = settings.isGLSharingEnabled(); - particlesCount = ((ParticlesCountItem)cb.getSelectedItem()).count; - } - - int[] blends = new int[] { - GL_ONE_MINUS_SRC_ALPHA, - GL_ONE, - GL_ONE_MINUS_DST_ALPHA, - GL_ONE_MINUS_DST_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_SRC_ALPHA, - GL_DST_ALPHA, - GL_SRC_COLOR, - GL_DST_COLOR, - }; - volatile int iBlend = 0; - - public static void exception(Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "[Error] " + ParticlesDemo.class.getSimpleName() + " JavaCL Demo", JOptionPane.ERROR_MESSAGE); - } - @Override - public void init(GLAutoDrawable glad) { - try { - GL2 gl = (GL2)glad.getGL(); - gl.glClearColor(0, 0, 0, 1); - gl.glClear(GL_COLOR_BUFFER_BIT); - //gl.glViewport(0, 0, (int)width, (int)height); - gl.glEnable(GL_BLEND); - gl.glEnable(GL2.GL_POINT_SMOOTH); - - try { - if (useOpenGLContext) { - context = JavaCL.createContextFromCurrentGL(); - } - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, "Sharing of context between OpenCL and OpenGL failed.\n" + - "The demo will run fine without anyway.", "JavaCL Demo", JOptionPane.OK_OPTION); - } - if (context == null) { - useOpenGLContext = false; - CLDevice device = settings.getDevice(); - if (device == null) - device = JavaCL.getBestDevice(); - context = JavaCL.createContext(null, device); - } - queue = context.createDefaultQueue(); - - FloatBuffer masses = NIOUtils.directFloats(particlesCount, context.getByteOrder()); - velocities = NIOUtils.directFloats(2 * particlesCount, context.getByteOrder()); - interleavedColorAndPositionsTemp = NIOUtils.directBytes(elementSize * particlesCount, context.getByteOrder()); - - FloatBuffer positionsView = interleavedColorAndPositionsTemp.asFloatBuffer(); - for (int i = 0; i < particlesCount; i++) { - masses.put(0.5f + 0.5f * random.nextFloat()); - - velocities.put((random.nextFloat() - 0.5f) * 0.2f); - velocities.put((random.nextFloat() - 0.5f) * 0.2f); - - int colorOffset = i * elementSize; - int posOffset = i * (elementSize / 4) + 1; - - byte r = (byte)128, g = r, b = r, a = r; - interleavedColorAndPositionsTemp.put(colorOffset++, r); - interleavedColorAndPositionsTemp.put(colorOffset++, g); - interleavedColorAndPositionsTemp.put(colorOffset++, b); - interleavedColorAndPositionsTemp.put(colorOffset, a); - - float x = (random.nextFloat() - 0.5f) * 200, - y = (random.nextFloat() - 0.5f) * 200; - - positionsView.put(posOffset, x); - positionsView.put(posOffset + 1, y); - - } - velocities.rewind(); - masses.rewind(); - interleavedColorAndPositionsTemp.rewind(); - - velocitiesMem = context.createFloatBuffer(Usage.InputOutput, velocities, false); - massesMem = context.createFloatBuffer(Usage.Input, masses, true); - - gl.glGenBuffers(1, vbo, 0); - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - gl.glBufferData(GL_ARRAY_BUFFER, (int) NIOUtils.getSizeInBytes(interleavedColorAndPositionsTemp), interleavedColorAndPositionsTemp, GL2.GL_DYNAMIC_COPY); - gl.glBindBuffer(GL_ARRAY_BUFFER, 0); - - if (useOpenGLContext) { - interleavedColorAndPositionsMem = context.createBufferFromGLBuffer(Usage.InputOutput, vbo[0]); - } else - interleavedColorAndPositionsMem = context.createByteBuffer(Usage.InputOutput, interleavedColorAndPositionsTemp, false); - - String hsv2rgbSrc = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("HSVtoRGB.c")); - //String src = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("ParticlesDemo.c")); - CLProgram program = context.createProgram(hsv2rgbSrc); - particlesProgram = new ParticlesDemoProgram(program); - //updateParticleKernel = program.build().createKernel("updateParticle"); - - updateKernelArgs(); - - gl.glPointSize(2f); - - } catch (Exception ex) { - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - ex.printStackTrace(); - exception(ex); - System.exit(1); - } - } - - @Override - public void dispose(GLAutoDrawable glad) { - - } - - @Override - public void display(GLAutoDrawable glad) { - - GL2 gl = (GL2)glad.getGL(); - - gl.glBlendFunc(GL_SRC_ALPHA, blends[iBlend]); - - gl.glMatrixMode(GL2.GL_PROJECTION); - gl.glLoadIdentity(); - new GLU().gluOrtho2D(-width / 2 - 1, width / 2 + 1, -height/2 - 1, height/2 + 1); - gl.glMatrixMode(GL2.GL_MODELVIEW); - - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - - if (useOpenGLContext) { - queue.finish(); - } else { - //interleavedColorAndPositionsMem.map(queue, CLMem.MapFlags.Read); - interleavedColorAndPositionsMem.read(queue, interleavedColorAndPositionsTemp, true); - gl.glBufferSubData(GL_ARRAY_BUFFER, 0, (int)NIOUtils.getSizeInBytes(interleavedColorAndPositionsTemp), interleavedColorAndPositionsTemp); - //interleavedColorAndPositionsMem.unmap(queue, interleavedColorAndPositionsTemp); - } - - gl.glClear(GL_COLOR_BUFFER_BIT); - - gl.glColor3f(1.0f, 1.0f, 1.0f); - //gl.glEnableClientState(GL_VERTEX_ARRAY); - //gl.glEnableClientState(GL_COLOR_ARRAY); - - //gl.glColorPointer(4, GL_UNSIGNED_BYTE, elementSize, - gl.glInterleavedArrays(GL2.GL_C4UB_V2F, elementSize, 0); - - gl.glDrawArrays(GL_POINTS, 0, particlesCount); - gl.glBindBuffer(GL_ARRAY_BUFFER, 0); - - if (!paused) - updateKernelArgs(); - } - - @Override - public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) { - this.width = width; - this.height = height; - - } - - private synchronized void updateKernelArgs() { - if (useOpenGLContext) - interleavedColorAndPositionsMem.acquireGLObject(queue); - - try { - CLEvent evt = particlesProgram.updateParticle( - queue, - massesMem, - velocitiesMem, - interleavedColorAndPositionsMem.asCLFloatBuffer(), - new float[] {mouseX - width / 2f, height / 2f - mouseY}, - new float[] {width, height}, - massFactor, - speedFactor, - slowDownFactor, - hasMouse ? mouseWeight : 0, - (byte)(limitToScreen ? 1 : 0), - new int[] { particlesCount }, null - ); - evt.release(); // the gc might be to slow to reclaim the event, so do manual memory management here - - } catch (Throwable ex) { - exception(ex); - System.exit(1); - } - - if (useOpenGLContext) - interleavedColorAndPositionsMem.releaseGLObject(queue); - } -} diff --git a/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c b/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c deleted file mode 100644 index 3e2384d3f..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c +++ /dev/null @@ -1,55 +0,0 @@ - -// Copied from http://www.cs.rit.edu/~ncs/color/t_convert.html - -uchar4 HSVAtoRGBA(float4 hsva) -{ - float h = hsva.x, s = hsva.y, v = hsva.z, a = hsva.w; - float r, g, b; - - int i; - float f, p, q, t; - if (s == 0) { - // achromatic (grey) - r = g = b = v; - return (uchar4)(r * 255, g * 255, b * 255, a * 255); - } - h /= 60; // sector 0 to 5 - i = floor( h ); - f = h - i; // factorial part of h - p = v * ( 1 - s ); - q = v * ( 1 - s * f ); - t = v * ( 1 - s * ( 1 - f ) ); - switch( i ) { - case 0: - r = v; - g = t; - b = p; - break; - case 1: - r = q; - g = v; - b = p; - break; - case 2: - r = p; - g = v; - b = t; - break; - case 3: - r = p; - g = q; - b = v; - break; - case 4: - r = t; - g = p; - b = v; - break; - default: // case 5: - r = v; - g = p; - b = q; - break; - } - return (uchar4)(r * 255, g * 255, b * 255, a * 255); -} \ No newline at end of file diff --git a/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c b/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c deleted file mode 100644 index 3fc83c8cb..000000000 --- a/libraries/OpenCL-JNA/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c +++ /dev/null @@ -1,105 +0,0 @@ -/*********************************************************************** - - Copyright (c) 2008, 2009, Memo Akten, www.memo.tv - *** The Mega Super Awesome Visuals Company *** - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of MSA Visuals nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. - * - * ***********************************************************************/ - -// Ported to JavaCL/OpenCL4Java (+ added colors) by Olivier Chafik - -#define REPULSION_FORCE 4.0f -#define CENTER_FORCE2 0.0005f - -#define PI 3.141f - -//#pragma OpenCL cl_khr_byte_addressable_store : enable - -__kernel void updateParticle( - __global float* masses, - __global float2* velocities, - //__global Particle* particles, - __global float4* particles, - //__global char* pParticles, - const float2 mousePos, - const float2 dimensions, - float massFactor, - float speedFactor, - float slowDownFactor, - float mouseWeight, - char limitToScreen -) { - int id = get_global_id(0); - - float4 particle = particles[id]; - - uchar4 color = as_uchar4(particle.x); - - float2 position = particle.yz; - float2 diff = mousePos - position; - - float invDistSQ = 1.0f / dot(diff, diff); - diff *= 200.0f * invDistSQ; - - float mass = massFactor * masses[id]; - float2 velocity = velocities[id]; - velocity -= mass * position * CENTER_FORCE2 - diff * mass * mouseWeight; - position += speedFactor * velocities[id]; - - if (limitToScreen) { - float2 halfDims = dimensions / 2.0f; - position = clamp(position, -halfDims, halfDims); - } - - float dirDot = cross((float4)(diff, (float2)0), (float4)(velocity, (float2)0)).z; - float speed = length(velocity); - - float f = speed / 4 / mass; - float hue = (dirDot < 0 ? f : f + 1) / 2; - hue = clamp(hue, 0.0f, 1.0f) * 360; - - float opacity = clamp(0.1f + f, 0.0f, 1.0f); - float saturation = mass / 2; - float brightness = 0.6f + opacity * 0.3f; - - uchar4 targetColor = HSVAtoRGBA((float4)(hue, saturation, brightness, opacity)); - - float colorSpeedFactor = min(0.01f * speedFactor, 1.0f), otherColorSpeedFactor = 1 - colorSpeedFactor; - color = (uchar4)( - (uchar)(targetColor.x * colorSpeedFactor + color.x * otherColorSpeedFactor), - (uchar)(targetColor.y * colorSpeedFactor + color.y * otherColorSpeedFactor), - (uchar)(targetColor.z * colorSpeedFactor + color.z * otherColorSpeedFactor), - (uchar)(targetColor.w * colorSpeedFactor + color.w * otherColorSpeedFactor) - ); - - particle.x = as_float(color); - particle.yz = position; - - particles[id] = particle; - - velocity *= slowDownFactor; - velocities[id] = velocity; -} diff --git a/libraries/OpenCL-JNA/README.md b/libraries/OpenCL-JNA/README.md new file mode 100644 index 000000000..ad4d58596 --- /dev/null +++ b/libraries/OpenCL-JNA/README.md @@ -0,0 +1,5 @@ +[JavaCL](http://javacl.googlecode.com) has migrated to its own repository: [ochafik/JavaCL](http://github.com/ochafik/JavaCL). + +Note: The legacy JNA version is in the JNA branch, but it is not supported anymore and its last release was 1.0.0-RC3. Please [migrate to the BridJ version](https://code.google.com/p/javacl/wiki/MigratingFromJNAToBridJ). + +Please [file issues there](http://github.com/ochafik/JavaCL/issues). diff --git a/libraries/OpenCL-JNA/ScalaCL.svg b/libraries/OpenCL-JNA/ScalaCL.svg deleted file mode 100644 index 5da756bf3..000000000 --- a/libraries/OpenCL-JNA/ScalaCL.svg +++ /dev/null @@ -1,235 +0,0 @@ - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - OpenCL - - - CPU - - - - GPU - - OpenCL4Java - JNA - - Java - - Scala - ScalaCL - - diff --git a/libraries/OpenCL-JNA/getJOGL b/libraries/OpenCL-JNA/getJOGL deleted file mode 100644 index 013c92d8a..000000000 --- a/libraries/OpenCL-JNA/getJOGL +++ /dev/null @@ -1,37 +0,0 @@ - -BASE_URL="http://jogamp.org/deployment/webstart" -OS_NAMES="macosx-universal linux-i586 linux-amd64 windows-i586 windows-amd64" - -mkdir jogl -cd jogl - -for OS_NAME in $OS_NAMES ; do - mkdir $OS_NAME - cd $OS_NAME - - for N in gluegen-rt jogl.all nativewindow.all ; do - wget $BASE_URL/$N.jar.gz - gzip -d $N.jar.gz ; - done - - for N in gluegen-rt jogl nativewindow ; do - wget $BASE_URL/$N-natives-$OS_NAME.jar - unzip $N-natives-$OS_NAME.jar - rm $N-natives-$OS_NAME.jar - rm -fR META-INF ; - done - - zip ../jogl-$OS_NAME.zip * - - cd .. - rm -fR $OS_NAME - - cp jogl-$OS_NAME.zip jogl-$OS_NAME-`date '+%Y%m%d'`.zip - mv jogl-$OS_NAME.zip jogl-$OS_NAME-latest.zip ; -done - -for OS_NAME in $OS_NAMES ; do - echo "Platform $OS_NAME :" - unzip -l jogl-$OS_NAME-latest.zip - echo "" ; -done diff --git a/libraries/OpenCL-JNA/patchFromBridJ b/libraries/OpenCL-JNA/patchFromBridJ deleted file mode 100644 index f418b5ec2..000000000 --- a/libraries/OpenCL-JNA/patchFromBridJ +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -DIFF_FILE=OpenCL-`date '+%Y%m%d'`.diff - -cd ../OpenCL -svn diff > $DIFF_FILE - -cd ../OpenCL-JNA -patch -p0 < ../OpenCL-JNA/$DIFF_FILE diff --git a/libraries/OpenCL-JNA/pom.xml b/libraries/OpenCL-JNA/pom.xml deleted file mode 100644 index 9086a8218..000000000 --- a/libraries/OpenCL-JNA/pom.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-parent-jna - 1.0-SNAPSHOT - pom - Legacy JavaCL-JNA Parent Project - 2009 - http://code.google.com/p/nativelibs4java/wiki/OpenCL - - - 1.0-SNAPSHOT - - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - OpenCL4Java, JavaCL and ScalaCL are OpenCL binding libraries for the Java platform. - - - - InteractiveImageDemo - Generator - OpenCL4Java - Demos - JavaCL - Core - OpenGLDemos - JavaCLTutorial - - - - - - com.nativelibs4java - libcl - ${project.version} - - - com.nativelibs4java - opencl4java-jna - ${project.version} - - - com.nativelibs4java - javacl-blas-jna - ${project.version} - - - com.nativelibs4java - javacl-core-jna - ${project.version} - - - com.nativelibs4java - javacl-demos-jna - ${project.version} - - - com.nativelibs4java - javacl-numerical-benchmark-jna - ${project.version} - - - com.nativelibs4java - javacl-generator-jna - ${project.version} - - - com.nativelibs4java - javacl-opengl-demos-jna - ${project.version} - - - com.nativelibs4java - javacl-jna - ${project.version} - - - com.nativelibs4java - javacl-tutorial-jna - ${project.version} - - - com.nativelibs4java - jnaerator - ${jnaerator.version} - - - - - - - - - com.nativelibs4java - maven-javacl-plugin - ${project.version} - - - - compile - - - - - - - - - - diff --git a/libraries/OpenCL-JNA/runComp b/libraries/OpenCL-JNA/runComp deleted file mode 100644 index 4c0c47482..000000000 --- a/libraries/OpenCL-JNA/runComp +++ /dev/null @@ -1,2 +0,0 @@ -cd target/classes -scala -classpath ~/.m2/repository/com/jnaerator/jnaerator-runtime/0.9.2-SNAPSHOT/jnaerator-runtime-0.9.2-SNAPSHOT.jar:. scalacl.ScalaCLTestRun diff --git a/libraries/OpenCL-JNA/runComp.cmd b/libraries/OpenCL-JNA/runComp.cmd deleted file mode 100644 index f1022354d..000000000 --- a/libraries/OpenCL-JNA/runComp.cmd +++ /dev/null @@ -1,9 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -set M2REPO=\Users\Olivier\.m2\repository -pushd . -cd target\classes -scala -classpath %M2REPO%\com\jnaerator\jnaerator-runtime\0.9.3-SNAPSHOT\jnaerator-runtime-0.9.3-SNAPSHOT.jar;. scalacl.ScalaCLTestRun - -popd diff --git a/libraries/OpenCL/.gitignore b/libraries/OpenCL/.gitignore deleted file mode 100644 index b509eebe8..000000000 --- a/libraries/OpenCL/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target -project/boot -project/target -*~ -Tests diff --git a/libraries/OpenCL/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9c0c21ef3..000000000 --- a/libraries/OpenCL/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:24 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 09e51cf49..000000000 --- a/libraries/OpenCL/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Sat Jan 30 11:48:04 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/Blas/.classpath b/libraries/OpenCL/Blas/.classpath deleted file mode 100644 index 3abb79c11..000000000 --- a/libraries/OpenCL/Blas/.classpath +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/libraries/OpenCL/Blas/.gitignore b/libraries/OpenCL/Blas/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Blas/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Blas/.project b/libraries/OpenCL/Blas/.project deleted file mode 100644 index 85ec62de1..000000000 --- a/libraries/OpenCL/Blas/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Blas - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL/Blas/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/Blas/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 0a83a7292..000000000 --- a/libraries/OpenCL/Blas/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:19 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/Blas/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/Blas/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index a03b0328b..000000000 --- a/libraries/OpenCL/Blas/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:13 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/Blas/javacl-blas-bridj.iml b/libraries/OpenCL/Blas/javacl-blas-bridj.iml deleted file mode 100644 index 1a89a3153..000000000 --- a/libraries/OpenCL/Blas/javacl-blas-bridj.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Blas/javacl-blas.iml b/libraries/OpenCL/Blas/javacl-blas.iml deleted file mode 100644 index 2b7d843d9..000000000 --- a/libraries/OpenCL/Blas/javacl-blas.iml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Blas/pom.xml b/libraries/OpenCL/Blas/pom.xml deleted file mode 100644 index b94c6c32d..000000000 --- a/libraries/OpenCL/Blas/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-blas - JavaCL BLAS / BridJ - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl - - - - org.ujmp - ujmp-core - 0.2.4 - - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - - - - - diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLDefaultMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLDefaultMatrix2D.java deleted file mode 100644 index cb20a8650..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLDefaultMatrix2D.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.util.Primitive; -import org.bridj.Pointer; - -/** - * - * @author ochafik - */ -public class CLDefaultMatrix2D implements CLMatrix2D { - protected final Primitive primitive; - protected final Class primitiveClass; - protected final long rows, columns, length; - - protected final CLKernels kernels; - protected final CLBuffer buffer; - protected final CLQueue queue; - protected final CLContext context; - protected CLEvents _events = new CLEvents(); - - public CLDefaultMatrix2D(Primitive primitive, CLBuffer buffer, long rows, long columns, CLKernels kernels) { - this.primitive = primitive; - this.primitiveClass = (Class)primitive.primitiveType; - this.length = rows * columns; - this.buffer = buffer == null ? (CLBuffer)kernels.getContext().createBuffer(Usage.InputOutput, primitive.primitiveType, length) : buffer; - this.kernels = kernels; - this.rows = rows; - this.columns = columns; - this.queue = kernels.getQueue(); - this.context = kernels.getContext(); - } - - public CLMatrix2D blankClone() { - return blankMatrix(getRowCount(), getColumnCount()); - } - public CLMatrix2D blankMatrix(long rows, long columns) { - return new CLDefaultMatrix2D(primitive, null, rows, columns, kernels); - } - - public long getRowCount() { - return rows; - } - - public long getColumnCount() { - return columns; - } - - public CLEvents getEvents() { - return _events; - } - - public void write(final Pointer b) { - getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return buffer.write(queue, b, false, events); - } - }); - } - - public void read(final Pointer b) { - getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return buffer.read(queue, b, true, events); - } - }); - } - public Pointer read() { - Pointer out = Pointer.allocateArray(primitiveClass, length); - read(out); - return out; - } - - - public CLBuffer getBuffer() { - return buffer; - } - - public CLContext getContext() { - return context; - } - - public synchronized CLQueue getQueue() { - return queue; - } - - /* - public synchronized void setQueue(CLQueue queue) { - if (this.queue != null && queue != null) { - if (this.queue.equals(queue)) - return; - } - getEvents().waitFor(); - this.queue = queue; - } - * */ - - public Primitive getPrimitive() { - return primitive; - } - - public Class getPrimitiveClass() { - return primitiveClass; - } - - public CLKernels getKernels() { - return kernels; - } - -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLEvents.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLEvents.java deleted file mode 100644 index f78a714fe..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLEvents.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas; - -import com.nativelibs4java.opencl.CLEvent; -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author ochafik - */ -public class CLEvents { - CLEvent lastWriteEvent; - List readEvents = new ArrayList(); - - List listeners = new ArrayList(); - - public interface Listener { - void writing(CLEvents evts); - void reading(CLEvents evts); - } - public interface Action { - CLEvent perform(CLEvent[] events); - } - - public synchronized void addListener(Listener l) { - listeners.add(l); - } - public synchronized void removeListener(Listener l) { - listeners.remove(l); - } - static final CLEvent[] EMPTY_EVENTS = new CLEvent[0]; - protected synchronized CLEvent clearEvents(Action action) { - int nReads = readEvents.size(); - boolean hasWrite = lastWriteEvent != null; - int n = nReads + (hasWrite ? 1 : 0); - CLEvent[] evts = n == 0 ? EMPTY_EVENTS : readEvents.toArray(new CLEvent[n]); - if (hasWrite) - evts[nReads] = lastWriteEvent; - CLEvent evt = action.perform(evts); - lastWriteEvent = null; - readEvents.clear(); - return evt; - } - public synchronized CLEvent performRead(Action action) { - for (Listener listener : listeners) - listener.writing(this); - CLEvent evt = action.perform(lastWriteEvent == null ? EMPTY_EVENTS : new CLEvent[] { lastWriteEvent }); - if (evt != null) { - readEvents.add(evt); - lastWriteEvent = null; // read completed only if the optional write also completed - } - return evt; - } - - public synchronized void performRead(Runnable action) { - for (Listener listener : listeners) - listener.reading(this); - waitForRead(); - action.run(); - } - - public synchronized CLEvent performWrite(Action action) { - return lastWriteEvent = clearEvents(action); - } - - /** - * Wait until all write operations are completed so that the data is readable. - */ - public synchronized void waitForRead() { - CLEvent.waitFor(lastWriteEvent); - lastWriteEvent = null; - } - /** - * Wait for all associated operations to complete (read or write). - */ - public synchronized void waitFor() { - clearEvents(new Action() { - public CLEvent perform(CLEvent[] evts) { - CLEvent.waitFor(evts); - return null; - } - }); - } -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLKernels.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLKernels.java deleted file mode 100644 index 4f236333c..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLKernels.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas; - -import com.nativelibs4java.opencl.CLProgram; -import java.io.IOException; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.Fun1; -import com.nativelibs4java.opencl.util.Fun2; -import com.nativelibs4java.opencl.util.LinearAlgebraUtils; -import com.nativelibs4java.opencl.util.ParallelMath; -import com.nativelibs4java.opencl.util.Primitive; -import static org.bridj.Pointer.*; -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author ochafik - */ -public class CLKernels { - protected final LinearAlgebraUtils kernels; - protected final ParallelMath math; - protected final CLContext context; - protected final CLQueue queue; - - private static volatile CLKernels instance; - - public static synchronized void setInstance(CLKernels kernels) { - instance = kernels; - } - public static synchronized CLKernels getInstance() { - if (instance == null) { - try { - instance = new CLKernels(); - } catch (Throwable ex) { - throw new RuntimeException(ex); - } - } - return instance; - } - - public CLKernels() throws IOException, CLBuildException { - this( - JavaCL.createBestContext( - DeviceFeature.DoubleSupport, - DeviceFeature.MaxComputeUnits - ).createDefaultQueue() - ); - } - public CLKernels(CLQueue queue) throws IOException, CLBuildException { - kernels = new LinearAlgebraUtils(queue); - math = new ParallelMath(queue); - context = queue.getContext(); - this.queue = queue; - } - - public CLEvent op1(Primitive prim, Fun1 fun, CLBuffer a, long rows, long columns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - long length = rows * columns; - if (out == null || out.getElementCount() != length) - throw new IllegalArgumentException("Expected buffer of length " + length + ", got " + out); - //if (out != null) - // out = (CLBuffer)context.createBuffer(Usage.Output, prim.primitiveType, length); - - CLKernel kernel = math.getKernel(fun, prim); - synchronized (kernel) { - kernel.setArgs(a, out, length); - CLEvent evt = kernel.enqueueNDRange(queue, new int [] { (int)length }, eventsToWaitFor); - return evt; - } - } - - public CLEvent op2(Primitive prim, Fun2 fun, CLBuffer a, CLBuffer b, long rows, long columns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - long length = rows * columns; - if (out == null || out.getElementCount() != length) - throw new IllegalArgumentException("Expected buffer of length " + length + ", got " + out); - //if (out != null) - // out = (CLBuffer)context.createBuffer(Usage.Output, prim.primitiveType, length); - - CLKernel kernel = math.getKernel(fun, prim, false); - synchronized (kernel) { - kernel.setArgs(a, b, out, length); - CLEvent evt = kernel.enqueueNDRange(queue, new int [] { (int)length }, eventsToWaitFor); - return evt; - } - } - - public CLEvent op2(Primitive prim, Fun2 fun, CLBuffer a, T b, long rows, long columns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - long length = rows * columns; - if (out == null || out.getElementCount() != length) - throw new IllegalArgumentException("Expected buffer of length " + length + ", got " + out); - //if (out != null) - // out = (CLBuffer)context.createBuffer(Usage.Output, prim.primitiveType, length); - - CLKernel kernel = math.getKernel(fun, prim, true); - synchronized (kernel) { - kernel.setArgs(a, b, out, length); - CLEvent evt = kernel.enqueueNDRange(queue, new int [] { (int)length }, eventsToWaitFor); - return evt; - } - } - - Map containsValueKernels = new HashMap(); - public boolean containsValue(Primitive primitive, CLBuffer buffer, long length, V value, CLEvent... eventsToWaitFor) throws CLBuildException { - CLKernel kernel; - synchronized (containsValueKernels) { - kernel = containsValueKernels.get(primitive); - if (kernel == null) { - kernel = context.createProgram(( - primitive.getRequiredPragmas() + - "__kernel void containsValue( \n" + - " __global const double* a, \n" + - " int length, \n" + - " double value, \n" + - " __global int* pOut \n" + - ") { \n" + - " int i = get_global_id(0);\n" + - " if (i >= length) \n" + - " return; \n" + - " \n" + - " if (a[i] == value) \n" + - " *pOut = 1; \n" + - "} \n" - ).replaceAll("double", primitive.clTypeName())).createKernel("containsValue"); - containsValueKernels.put(primitive, kernel); - } - } - synchronized(kernel) { - CLBuffer pOut = context.createBuffer(Usage.Output, pointerToInt(0)); - kernel.setArgs(buffer, (int)length, value, pOut); - kernel.enqueueNDRange(queue, new int[] { (int)length }, eventsToWaitFor).waitFor(); - return pOut.read(queue).getInt() != 0; - } - } - - Map clearKernels = new HashMap(); - public CLEvent clear(Primitive primitive, CLBuffer buffer, long length, CLEvent... eventsToWaitFor) throws CLBuildException { - CLKernel kernel; - synchronized (clearKernels) { - kernel = clearKernels.get(primitive); - if (kernel == null) { - kernel = context.createProgram(( - primitive.getRequiredPragmas() + - "__kernel void clear_buffer( \n" + - " __global double* a, \n" + - " int length \n" + - ") { \n" + - " int i = get_global_id(0); \n" + - " if (i >= length) \n" + - " return; \n" + - " \n" + - " a[i] = (double)0; \n" + - "} \n" - ).replaceAll("double", primitive.clTypeName())).createKernel("clear_buffer"); - clearKernels.put(primitive, kernel); - } - } - synchronized(kernel) { - kernel.setArgs(buffer, (int)length); - CLEvent evt = kernel.enqueueNDRange(queue, new int[] { (int)length }, eventsToWaitFor); - //Object array = buffer.read(queue, evt).getArray(); - return evt; - } - } - - Map matrixMultiplyKernels = new HashMap(); - public CLEvent matrixMultiply(Primitive prim, CLBuffer a, long aRows, long aColumns, CLBuffer b, long bRows, long bColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - if (out == null) - throw new IllegalArgumentException("Null output matrix !"); - //if (out != null) - // out = (CLBuffer)context.createBuffer(Usage.Output, prim.primitiveType, aRows * bColumns); - - CLKernel kernel; - synchronized (matrixMultiplyKernels) { - kernel = matrixMultiplyKernels.get(prim); - if (kernel == null) { - String src = - prim.getRequiredPragmas() + - "__kernel void mulMat( " + - " __global const double* a, int aRows, int aColumns, " + - " __global const double* b, int bColumns, " + - " __global double* c " + - ") { " + - " int i = get_global_id(0); " + - " int j = get_global_id(1); " + - " " + - " if (i >= aRows || j >= bColumns) return; " + - " double total = 0; " + - " size_t iOff = i * (size_t)aColumns; " + - " for (long k = 0; k < aColumns; k++) { " + - " total += a[iOff + k] * b[k * (size_t)bColumns + j]; " + - " } " + - " c[i * (size_t)bColumns + j] = total; " + - "} " - ; - String clTypeName = prim.clTypeName(); - src = src.replaceAll("double", clTypeName); - kernel = context.createProgram(src).createKernel("mulMat"); - matrixMultiplyKernels.put(prim, kernel); - } - } - synchronized (kernel) { - kernel.setArgs(a, (int)aRows, (int)aColumns, b, (int)bColumns, out); - CLEvent evt = kernel.enqueueNDRange(queue, new int [] { (int)aRows, (int)bColumns }, eventsToWaitFor); - return evt; - } - } - - Map matrixTransposeKernels = new HashMap(); - public CLEvent matrixTranspose(Primitive prim, CLBuffer a, long aRows, long aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - if (out == null) - throw new IllegalArgumentException("Null output matrix !"); - //if (out != null) - // out = (CLBuffer)context.createBuffer(Usage.Output, prim.primitiveType, aRows * aColumns); - - CLKernel[] kernels; - synchronized (matrixTransposeKernels) { - kernels = matrixTransposeKernels.get(prim); - if (kernels == null) { - String src = - prim.getRequiredPragmas() + - "__kernel void transposeSelf( \n" + - " __global double* a, int aRows, int aColumns \n" + - ") { \n" + - " int i = get_global_id(0); \n" + - " int j = get_global_id(1); \n" + - " \n" + - " if (i >= aRows || j >= aColumns || j >= i) return; \n" + - " \n" + - " size_t aIndex = i * aColumns + j; \n" + - " size_t outIndex = j * aRows + i; \n" + - " double temp = a[outIndex]; \n" + - " a[outIndex] = a[aIndex]; \n" + - " a[aIndex] = temp; \n" + - "} \n" + - "__kernel void transposeOther( \n" + - " __global const double* a, int aRows, int aColumns, \n" + - " __global double* out \n" + - ") { \n" + - " int i = get_global_id(0); \n" + - " int j = get_global_id(1); \n" + - " \n" + - " if (i >= aRows || j >= aColumns) return; \n" + - " \n" + - " size_t aIndex = i * aColumns + j; \n" + - " size_t outIndex = j * aRows + i; \n" + - " out[outIndex] = a[aIndex]; \n" + - "} \n" - ; - String clTypeName = prim.clTypeName(); - src = src.replaceAll("double", clTypeName); - CLProgram program = context.createProgram(src); - kernels = new CLKernel[] { program.createKernel("transposeSelf"), program.createKernel("transposeOther") }; - matrixTransposeKernels.put(prim, kernels); - } - } - boolean self = a.equals(out); - CLKernel kernel = kernels[self ? 0 : 1]; - synchronized (kernel) { - if (self) - kernel.setArgs(a, (int)aRows, (int)aColumns); - else - kernel.setArgs(a, (int)aRows, (int)aColumns, out); - - CLEvent evt = kernel.enqueueNDRange(queue, new int [] { (int)aRows, (int)aColumns }, eventsToWaitFor); - return evt; - } - } - - public CLContext getContext() { - return context; - } - - public CLQueue getQueue() { - return queue; - } - -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrix2D.java deleted file mode 100644 index bc5631221..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrix2D.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.util.Primitive; -import org.bridj.Pointer; - -/** - * - * @author ochafik - */ -public interface CLMatrix2D { - Primitive getPrimitive(); - Class getPrimitiveClass(); - CLEvents getEvents(); - CLBuffer getBuffer(); - CLContext getContext(); - CLQueue getQueue(); - long getRowCount(); - long getColumnCount(); - CLMatrix2D blankClone(); - CLMatrix2D blankMatrix(long rows, long columns); - CLKernels getKernels(); - - void write(final Pointer b); - void read(final Pointer b); - Pointer read(); -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrixUtils.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrixUtils.java deleted file mode 100644 index 4dd7e205f..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/CLMatrixUtils.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.util.Fun1; -import com.nativelibs4java.opencl.util.Fun2; -import com.nativelibs4java.opencl.util.Primitive; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; - -/** - * - * @author ochafik - */ -public class CLMatrixUtils { - - static CLEvent[] join(CLEvent[]... evts) { - int n = 0; - for (CLEvent[] e : evts) - n += e.length; - CLEvent[] out = new CLEvent[n]; - n = 0; - for (CLEvent[] e : evts) - System.arraycopy(e, 0, out, n, e.length); - - return out; - } - - - public static void matrixMultiply( - final CLMatrix2D a, - final CLMatrix2D b, - final CLMatrix2D out) - throws CLBuildException - { - final CLKernels kernels = a.getKernels(); - final Primitive primitive = a.getPrimitive(); - a.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] aevents) { - return b.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] bevents) { - return out.getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] cevents) { - CLEvent evt = kernels.matrixMultiply( - primitive, - a.getBuffer(), (int)a.getRowCount(), (int)a.getColumnCount(), - b.getBuffer(), (int)b.getRowCount(), (int)b.getColumnCount(), - out.getBuffer(), - join(aevents, bevents, cevents) - ); - return evt; - } - }); - } - }); - } - }); - } - - static final int MAX_REDUCTION_SIZE = 32; - - public static void reduce( - final CLMatrix2D in, - final CLMatrix2D out, - final Reductor reductor - ) { - in.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] ievents) { - return out.getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] oevents) { - return reductor.reduce(in.getQueue(), in.getBuffer(), in.getBuffer().getElementCount(), out.getBuffer(), MAX_REDUCTION_SIZE, join(ievents, oevents)); - } - }); - } - }); - } - public static void matrixTranspose( - final CLMatrix2D a, - final CLMatrix2D out) - throws CLBuildException - { - final Primitive primitive = a.getPrimitive(); - final CLKernels kernels = a.getKernels(); - a.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] aevents) { - return out.getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] cevents) { - CLEvent evt = kernels.matrixTranspose( - primitive, - a.getBuffer(), (int)a.getRowCount(), (int)a.getColumnCount(), - out.getBuffer(), - join(aevents, cevents) - ); - return evt; - } - }); - } - }); - } - - public static CLMatrix2D clone(final CLMatrix2D matrix) { - final CLMatrix2D out = matrix.blankClone(); - matrix.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] aevents) { - return out.getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] bevents) { - return matrix.getBuffer().copyTo(matrix.getQueue(), out.getBuffer(), CLMatrixUtils.join(aevents, bevents)); - } - }); - } - }); - return out; - } - - - public static CLMatrix2D createMatrix(long rows, long columns, Class elementClass, CLKernels kernels) { - if (elementClass == Double.class) - return (CLMatrix2D)new CLDefaultMatrix2D(Primitive.Double, null, rows, columns, kernels); - - throw new UnsupportedOperationException("Cannot build buffers of " + elementClass.getName() + " yet"); - } - - - public static CLMatrix2D op1(final CLMatrix2D in, final Fun1 fun, final CLMatrix2D out) throws CLBuildException { - in.getEvents().performRead(new CLEvents.Action() { - - public CLEvent perform(final CLEvent[] ievents) { - return out.getEvents().performWrite(new CLEvents.Action() { - - public CLEvent perform(CLEvent[] oevents) { - return in.getKernels().op1(in.getPrimitive(), fun, in.getBuffer(), in.getRowCount(), in.getColumnCount(), out.getBuffer(), join(ievents, oevents)); - } - }); - } - }); - return out; - } - - - public static CLMatrix2D op2(final CLMatrix2D in1, final Fun2 fun, final CLMatrix2D in2, final CLMatrix2D out) throws CLBuildException { - in1.getEvents().performRead(new CLEvents.Action() { - - public CLEvent perform(final CLEvent[] i1events) { - return in2.getEvents().performRead(new CLEvents.Action() { - - public CLEvent perform(final CLEvent[] i2events) { - return out.getEvents().performWrite(new CLEvents.Action() { - - public CLEvent perform(CLEvent[] oevents) { - return in1.getKernels().op2(in1.getPrimitive(), fun, in1.getBuffer(), in2.getBuffer(), in1.getRowCount(), in1.getColumnCount(), out.getBuffer(), join(i1events, i2events, oevents)); - } - }); - } - }); - } - }); - return out; - } - public static CLMatrix2D op2(final CLMatrix2D in, final Fun2 fun, final V s2, final CLMatrix2D out) throws CLBuildException { - in.getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(final CLEvent[] ievents) { - return out.getEvents().performWrite(new CLEvents.Action() { - - public CLEvent perform(CLEvent[] oevents) { - return in.getKernels().op2(in.getPrimitive(), fun, in.getBuffer(), s2, in.getRowCount(), in.getColumnCount(), out.getBuffer(), join(ievents, oevents)); - } - }); - } - }); - return out; - } - -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2D.java deleted file mode 100644 index 903bd6278..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2D.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLMatrix2D; -import com.nativelibs4java.opencl.blas.CLMatrixUtils; -import com.nativelibs4java.opencl.blas.CLDefaultMatrix2D; -import com.nativelibs4java.opencl.blas.CLKernels; -import com.nativelibs4java.opencl.blas.CLEvents.Action; -import java.nio.DoubleBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.ujmp.core.Matrix; -import org.ujmp.core.calculation.Calculation.Ret; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.exceptions.MatrixException; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLMem.MapFlags; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.util.LinearAlgebraUtils; -import com.nativelibs4java.opencl.util.Primitive; -import com.nativelibs4java.util.NIOUtils; -import java.nio.Buffer; -import org.bridj.Pointer; -import org.ujmp.core.doublematrix.stub.AbstractDenseDoubleMatrix2D; -import org.ujmp.core.matrix.Matrix2D; - -/** - * - * @author ochafik - */ -public class CLDenseDoubleMatrix2D extends AbstractDenseDoubleMatrix2D { - - protected final CLDenseMatrix2DImpl impl; - - public CLDenseMatrix2DImpl getImpl() { - return impl; - } - public CLDenseDoubleMatrix2D(CLDenseMatrix2DImpl impl) { - this.impl = impl; - } - public CLDenseDoubleMatrix2D(CLMatrix2D matrix) { - this(new CLDenseMatrix2DImpl(matrix)); - } - public CLDenseDoubleMatrix2D(long rows, long columns, CLKernels kernels) { - this(new CLDefaultMatrix2D(Primitive.Double, null, rows, columns, kernels)); - } - public CLDenseDoubleMatrix2D(long rows, long columns) { - this(rows, columns, CLKernels.getInstance()); - } - public CLDenseDoubleMatrix2D(long size) { - this(size, size); - } - public CLDenseDoubleMatrix2D(long... size) { - this(size[0], size[1], CLKernels.getInstance()); - } - - public void write(Pointer p) { - getImpl().write(p); - } - - public void read(Pointer p) { - getImpl().read(p); - } - - public Pointer read() { - return getImpl().read(); - } - - static CLDenseDoubleMatrix2D inst(CLMatrix2D matrix) { - return new CLDenseDoubleMatrix2D(matrix); - } - - static CLDenseDoubleMatrix2D inst(CLDenseMatrix2DImpl matrix) { - return new CLDenseDoubleMatrix2D(matrix); - } - - @Override - public Matrix mtimes(Ret returnType, boolean ignoreNaN, Matrix matrix) throws MatrixException { - if (matrix instanceof Matrix2D) { - return inst(getImpl().multiply(returnType, ignoreNaN, (Matrix2D)matrix)); - } else { - return super.mtimes(returnType, ignoreNaN, matrix); - } - } - - @Override - public Matrix mtimes(Matrix matrix) throws MatrixException { - return mtimes(Ret.NEW, true, matrix); - } - - - - @Override - public Iterable allValues() { - return (Pointer)impl.read(); - } - - - - - @Override - public Matrix min(Ret returnType, int dimension) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.min(returnType, dimension); - case ALL: - try { - return inst(impl.min()); - } catch (CLBuildException ex) { - throw new MatrixException("Failed to compute min", ex); - } - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public Matrix max(Ret returnType, int dimension) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.max(returnType, dimension); - case ALL: - try { - return inst(impl.max()); - } catch (CLBuildException ex) { - throw new MatrixException("Failed to compute max", ex); - } - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public Matrix mean(Ret returnType, int dimension, boolean ignoreNaN) throws MatrixException { - // TODO - return super.mean(returnType, dimension, ignoreNaN); - } - - @Override - public Matrix center(Ret returnType, int dimension, boolean ignoreNaN) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.center(returnType, dimension, ignoreNaN); - case ALL: - return minus(returnType, ignoreNaN, mean(Ret.NEW, dimension, ignoreNaN).getAsDouble(0, 0)); - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public synchronized Matrix copy() throws MatrixException { - return inst(impl.clone()); - } - - @Override - public Matrix transpose(Ret returnType) throws MatrixException { - return inst(impl.transpose(returnType)); - } - - @Override - public synchronized Matrix transpose() throws MatrixException { - return transpose(Ret.NEW); - } - - public long[] getSize() { - return impl.getSize(); - } - - public double getDouble(long row, long column) { - return impl.get(row, column); - } - public void setDouble(double value, long row, long column) { - impl.set(value, row, column); - } - - public double getDouble(int row, int column) { - return getDouble((long)row, (long)column); - } - - public void setDouble(double value, int row, int column) { - setDouble(value, (long)row, (long)column); - } - - - - @Override - public Matrix sin(Ret returnType) throws MatrixException { - return inst(impl.sin(returnType)); - } - - @Override - public Matrix cos(Ret returnType) throws MatrixException { - return inst(impl.cos(returnType)); - } - - @Override - public Matrix sinh(Ret returnType) throws MatrixException { - return inst(impl.sinh(returnType)); - } - - @Override - public Matrix cosh(Ret returnType) throws MatrixException { - return inst(impl.cosh(returnType)); - } - - @Override - public Matrix tan(Ret returnType) throws MatrixException { - return inst(impl.tan(returnType)); - } - - @Override - public Matrix tanh(Ret returnType) throws MatrixException { - return inst(impl.tanh(returnType)); - } - - //@Override - public Matrix asin(Ret returnType) throws MatrixException { - return inst(impl.asin(returnType)); - } - - //@Override - public Matrix acos(Ret returnType) throws MatrixException { - return inst(impl.acos(returnType)); - } - - //@Override - public Matrix asinh(Ret returnType) throws MatrixException { - return inst(impl.asinh(returnType)); - } - - //@Override - public Matrix acosh(Ret returnType) throws MatrixException { - return inst(impl.acosh(returnType)); - } - - //@Override - public Matrix atan(Ret returnType) throws MatrixException { - return inst(impl.atan(returnType)); - } - - //@Override - public Matrix atanh(Ret returnType) throws MatrixException { - return inst(impl.atanh(returnType)); - } - - @Override - public Matrix minus(Matrix m) throws MatrixException { - return minus(Ret.NEW, true, m); - } - - @Override - public Matrix minus(double m) throws MatrixException { - return minus(Ret.NEW, true, m); - } - - @Override - public Matrix minus(Ret returnType, boolean ignoreNaN, Matrix m) throws MatrixException { - return inst(impl.minus(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)m).getImpl())); - } - @Override - public Matrix minus(Ret returnType, boolean ignoreNaN, double v) throws MatrixException { - return inst(impl.minus(returnType, ignoreNaN, v)); - } - - @Override - public Matrix plus(Matrix m) throws MatrixException { - return plus(Ret.NEW, true, m); - } - - @Override - public Matrix plus(double m) throws MatrixException { - return plus(Ret.NEW, true, m); - } - - @Override - public Matrix plus(Ret returnType, boolean ignoreNaN, Matrix m) throws MatrixException { - return inst(impl.plus(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)m).getImpl())); - } - - @Override - public Matrix plus(Ret returnType, boolean ignoreNaN, double v) throws MatrixException { - return inst(impl.plus(returnType, ignoreNaN, v)); - } - - @Override - public Matrix times(Matrix m) throws MatrixException { - return times(Ret.NEW, true, m); - } - - @Override - public Matrix times(double m) throws MatrixException { - return times(Ret.NEW, true, m); - } - - @Override - public Matrix times(Ret returnType, boolean ignoreNaN, Matrix factor) throws MatrixException { - return inst(impl.times(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)factor).getImpl())); - } - - @Override - public Matrix times(Ret returnType, boolean ignoreNaN, double factor) throws MatrixException { - return inst(impl.times(returnType, ignoreNaN, factor)); - } - - @Override - public Matrix divide(Matrix m) throws MatrixException { - return divide(Ret.NEW, true, m); - } - - @Override - public Matrix divide(double m) throws MatrixException { - return divide(Ret.NEW, true, m); - } - - @Override - public Matrix divide(Ret returnType, boolean ignoreNaN, Matrix factor) throws MatrixException { - return inst(impl.divide(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)factor).getImpl())); - } - - @Override - public Matrix divide(Ret returnType, boolean ignoreNaN, double factor) throws MatrixException { - return inst(impl.divide(returnType, ignoreNaN, factor)); - } - - @Override - public double[][] toDoubleArray() throws MatrixException { - Pointer b = impl.read(); - int rows = (int)impl.rows, columns = (int)impl.columns; - double[][] ret = new double[rows][]; - for (int i = 0; i < rows; i++) { - ret[i] = b.getDoublesAtOffset(i * columns, columns); - } - return ret; - } - - - @Override - public boolean containsDouble(double v) { - try { - return impl.containsValue(v); - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to test value presence", ex); - } - } - - @Override - public void clear() { - try { - impl.clear(); - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to clear matrix", ex); - } - } - - public void waitFor() { - impl.waitFor(); - } -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2DFactory.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2DFactory.java deleted file mode 100644 index c869b5ba4..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseDoubleMatrix2DFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.CLPlatform; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.LinearAlgebraUtils; -import com.nativelibs4java.opencl.util.Primitive; -import org.ujmp.core.doublematrix.DenseDoubleMatrix2D; -import org.ujmp.core.doublematrix.factory.AbstractDoubleMatrix2DFactory; -import org.ujmp.core.exceptions.MatrixException; - -/** - * - * @author ochafik - */ -public class CLDenseDoubleMatrix2DFactory extends AbstractDoubleMatrix2DFactory { - - public DenseDoubleMatrix2D dense(long rows, long columns) - throws MatrixException { - return new CLDenseDoubleMatrix2D(rows, columns); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2D.java deleted file mode 100644 index d320f7df2..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2D.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLMatrix2D; -import com.nativelibs4java.opencl.blas.CLMatrixUtils; -import com.nativelibs4java.opencl.blas.CLDefaultMatrix2D; -import com.nativelibs4java.opencl.blas.CLKernels; -import com.nativelibs4java.opencl.blas.CLEvents.Action; -import java.nio.DoubleBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.ujmp.core.Matrix; -import org.ujmp.core.calculation.Calculation.Ret; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.exceptions.MatrixException; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLMem.MapFlags; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.util.LinearAlgebraUtils; -import com.nativelibs4java.opencl.util.Primitive; -import com.nativelibs4java.util.NIOUtils; -import java.nio.Buffer; -import org.bridj.Pointer; -import org.ujmp.core.doublematrix.stub.AbstractDenseDoubleMatrix2D; -import org.ujmp.core.floatmatrix.FloatMatrix2D; -import org.ujmp.core.floatmatrix.stub.AbstractDenseFloatMatrix2D; -import org.ujmp.core.matrix.Matrix2D; - -/** - * - * @author ochafik - */ -public class CLDenseFloatMatrix2D extends AbstractDenseFloatMatrix2D { - - protected final CLDenseMatrix2DImpl impl; - - public CLDenseMatrix2DImpl getImpl() { - return impl; - } - public CLDenseFloatMatrix2D(CLDenseMatrix2DImpl impl) { - this.impl = impl; - } - public CLDenseFloatMatrix2D(CLMatrix2D matrix) { - this(new CLDenseMatrix2DImpl(matrix)); - } - public CLDenseFloatMatrix2D(long rows, long columns, CLKernels clUJMP) { - this(new CLDefaultMatrix2D(Primitive.Float, null, rows, columns, clUJMP)); - } - public CLDenseFloatMatrix2D(long rows, long columns) { - this(rows, columns, CLKernels.getInstance()); - } - public CLDenseFloatMatrix2D(long size) { - this(size, size); - } - public CLDenseFloatMatrix2D(long... size) { - this(size[0], size[1], CLKernels.getInstance()); - } - - public void write(Pointer p) { - getImpl().write(p); - } - - public void read(Pointer p) { - getImpl().read(p); - } - - public Pointer read() { - return getImpl().read(); - } - - static CLDenseFloatMatrix2D inst(CLMatrix2D matrix) { - return new CLDenseFloatMatrix2D(matrix); - } - - static CLDenseFloatMatrix2D inst(CLDenseMatrix2DImpl matrix) { - return new CLDenseFloatMatrix2D(matrix); - } - - @Override - public Matrix mtimes(Ret returnType, boolean ignoreNaN, Matrix matrix) throws MatrixException { - if (matrix instanceof Matrix2D) { - return inst(getImpl().multiply(returnType, ignoreNaN, (Matrix2D)matrix)); - } else { - return super.mtimes(returnType, ignoreNaN, matrix); - } - } - - @Override - public Matrix mtimes(Matrix matrix) throws MatrixException { - return mtimes(Ret.NEW, true, matrix); - } - - - @Override - public Iterable allValues() { - return (Pointer)impl.read(); - } - - - @Override - public Matrix min(Ret returnType, int dimension) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.min(returnType, dimension); - case ALL: - try { - return inst(impl.min()); - } catch (CLBuildException ex) { - throw new MatrixException("Failed to compute min", ex); - } - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public Matrix max(Ret returnType, int dimension) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.max(returnType, dimension); - case ALL: - try { - return inst(impl.max()); - } catch (CLBuildException ex) { - throw new MatrixException("Failed to compute max", ex); - } - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public Matrix mean(Ret returnType, int dimension, boolean ignoreNaN) throws MatrixException { - // TODO - return super.mean(returnType, dimension, ignoreNaN); - } - - @Override - public Matrix center(Ret returnType, int dimension, boolean ignoreNaN) throws MatrixException { - switch (dimension) { - case ROW: - case COLUMN: - // TODO - return super.center(returnType, dimension, ignoreNaN); - case ALL: - return minus(returnType, ignoreNaN, mean(Ret.NEW, dimension, ignoreNaN).getAsFloat(0, 0)); - default: - throw new IllegalArgumentException("Invalid dimension : " + dimension); - } - } - - @Override - public synchronized Matrix copy() throws MatrixException { - return inst(impl.clone()); - } - - @Override - public Matrix transpose(Ret returnType) throws MatrixException { - return inst(impl.transpose(returnType)); - } - - @Override - public synchronized Matrix transpose() throws MatrixException { - return transpose(Ret.NEW); - } - - public long[] getSize() { - return impl.getSize(); - } - - public float getFloat(long row, long column) { - return impl.get(row, column); - } - public void setFloat(float value, long row, long column) { - impl.set(value, row, column); - } - - public float getFloat(int row, int column) { - return getFloat((long)row, (long)column); - } - - public void setFloat(float value, int row, int column) { - setFloat(value, (long)row, (long)column); - } - - - - @Override - public Matrix sin(Ret returnType) throws MatrixException { - return inst(impl.sin(returnType)); - } - - @Override - public Matrix cos(Ret returnType) throws MatrixException { - return inst(impl.cos(returnType)); - } - - @Override - public Matrix sinh(Ret returnType) throws MatrixException { - return inst(impl.sinh(returnType)); - } - - @Override - public Matrix cosh(Ret returnType) throws MatrixException { - return inst(impl.cosh(returnType)); - } - - @Override - public Matrix tan(Ret returnType) throws MatrixException { - return inst(impl.tan(returnType)); - } - - @Override - public Matrix tanh(Ret returnType) throws MatrixException { - return inst(impl.tanh(returnType)); - } - - //@Override - public Matrix asin(Ret returnType) throws MatrixException { - return inst(impl.asin(returnType)); - } - - //@Override - public Matrix acos(Ret returnType) throws MatrixException { - return inst(impl.acos(returnType)); - } - - //@Override - public Matrix asinh(Ret returnType) throws MatrixException { - return inst(impl.asinh(returnType)); - } - - //@Override - public Matrix acosh(Ret returnType) throws MatrixException { - return inst(impl.acosh(returnType)); - } - - //@Override - public Matrix atan(Ret returnType) throws MatrixException { - return inst(impl.atan(returnType)); - } - - //@Override - public Matrix atanh(Ret returnType) throws MatrixException { - return inst(impl.atanh(returnType)); - } - - @Override - public Matrix minus(Matrix m) throws MatrixException { - return minus(Ret.NEW, true, m); - } - - @Override - public Matrix minus(double m) throws MatrixException { - return minus(Ret.NEW, true, m); - } - - @Override - public Matrix minus(Ret returnType, boolean ignoreNaN, Matrix m) throws MatrixException { - return inst(impl.minus(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)m).getImpl())); - } - @Override - public Matrix minus(Ret returnType, boolean ignoreNaN, double v) throws MatrixException { - return inst(impl.minus(returnType, ignoreNaN, (float)v)); - } - - @Override - public Matrix plus(Matrix m) throws MatrixException { - return plus(Ret.NEW, true, m); - } - - @Override - public Matrix plus(double m) throws MatrixException { - return plus(Ret.NEW, true, m); - } - - @Override - public Matrix plus(Ret returnType, boolean ignoreNaN, Matrix m) throws MatrixException { - return inst(impl.plus(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)m).getImpl())); - } - - @Override - public Matrix plus(Ret returnType, boolean ignoreNaN, double v) throws MatrixException { - return inst(impl.plus(returnType, ignoreNaN, (float)v)); - } - - @Override - public Matrix times(Matrix m) throws MatrixException { - return times(Ret.NEW, true, m); - } - - @Override - public Matrix times(double m) throws MatrixException { - return times(Ret.NEW, true, m); - } - - @Override - public Matrix times(Ret returnType, boolean ignoreNaN, Matrix factor) throws MatrixException { - return inst(impl.times(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)factor).getImpl())); - } - - @Override - public Matrix times(Ret returnType, boolean ignoreNaN, double factor) throws MatrixException { - return inst(impl.times(returnType, ignoreNaN, (float)factor)); - } - - @Override - public Matrix divide(Matrix m) throws MatrixException { - return divide(Ret.NEW, true, m); - } - - @Override - public Matrix divide(double m) throws MatrixException { - return divide(Ret.NEW, true, m); - } - - @Override - public Matrix divide(Ret returnType, boolean ignoreNaN, Matrix factor) throws MatrixException { - return inst(impl.divide(returnType, ignoreNaN, ((CLDenseFloatMatrix2D)factor).getImpl())); - } - - @Override - public Matrix divide(Ret returnType, boolean ignoreNaN, double factor) throws MatrixException { - return inst(impl.divide(returnType, ignoreNaN, (float)factor)); - } - - @Override - public boolean containsDouble(double v) { - return containsFloat((float)v); - } - - - @Override - public boolean containsFloat(float v) { - try { - return impl.containsValue((float)v); - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to test value presence", ex); - } - } - - @Override - public void clear() { - try { - impl.clear(); - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to clear matrix", ex); - } - } - - public void waitFor() { - impl.waitFor(); - } - - - @Override - public float[][] toFloatArray() throws MatrixException { - Pointer b = impl.read(); - float[][] ret = new float[(int)impl.rows][]; - for (int i = 0; i < impl.rows; i++) { - ret[i] = b.getFloatsAtOffset(i * impl.columns, (int)impl.columns); - } - return ret; - } - - @Override - public double[][] toDoubleArray() throws MatrixException { - Pointer b = impl.read(); - double[][] ret = new double[(int)impl.rows][(int)impl.columns]; - for (int i = 0; i < impl.rows; i++) { - float[] floats = b.getFloatsAtOffset(i * impl.columns, (int) impl.columns); - double[] doubles = ret[i]; - for (int j = 0; j < floats.length; j++) - doubles[j] = floats[j]; - } - return ret; - } -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2DFactory.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2DFactory.java deleted file mode 100644 index 0a520fc79..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseFloatMatrix2DFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.util.LinearAlgebraUtils; -import com.nativelibs4java.opencl.util.Primitive; -import org.ujmp.core.floatmatrix.DenseFloatMatrix2D; -import org.ujmp.core.floatmatrix.factory.AbstractFloatMatrix2DFactory; -import org.ujmp.core.exceptions.MatrixException; - -/** - * - * @author ochafik - */ -public class CLDenseFloatMatrix2DFactory extends AbstractFloatMatrix2DFactory { - public DenseFloatMatrix2D dense(long rows, long columns) - throws MatrixException { - return new CLDenseFloatMatrix2D(rows, columns); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseMatrix2DImpl.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseMatrix2DImpl.java deleted file mode 100644 index 7f415598b..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLDenseMatrix2DImpl.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLMatrix2D; -import com.nativelibs4java.opencl.blas.CLEvents; -import com.nativelibs4java.opencl.blas.CLMatrixUtils; -import com.nativelibs4java.opencl.blas.CLKernels; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import org.ujmp.core.Matrix; - -import org.ujmp.core.calculation.Calculation.Ret; -import org.ujmp.core.exceptions.MatrixException; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.Fun1; -import com.nativelibs4java.opencl.util.Fun2; -import com.nativelibs4java.opencl.util.OpenCLType; -import com.nativelibs4java.opencl.util.Primitive; -import com.nativelibs4java.opencl.util.ReductionUtils; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.matrix.Matrix2D; - -/** - * - * @author ochafik - */ -public class CLDenseMatrix2DImpl { - protected final CLMatrix2D _matrix; - protected final long rows, columns, size[]; - protected Pointer cache; - protected int uncachedGetCount; - protected static final int GET_COUNT_BEFORE_CACHING = 3; - - public CLDenseMatrix2DImpl(CLMatrix2D _matrix) { - this._matrix = _matrix; - this.rows = _matrix.getRowCount(); - this.columns = _matrix.getColumnCount(); - this.size = new long[] { rows, columns }; - _matrix.getEvents().addListener(new CLEvents.Listener() { - public void writing(CLEvents evts) { - synchronized (CLDenseMatrix2DImpl.this) { - cache = null; - uncachedGetCount = 0; - } - } - - public void reading(CLEvents evts) {} - }); - } - - protected CLMatrix2D getMatrix() { - return _matrix; - } - - protected long getStorageIndex(long row, long column) { - return row * columns + column; - } - - protected synchronized void cache() { - if (cache != null) - return; - - cache = read(); - uncachedGetCount = 0; - } - public V get(long row, long column) { - final long offset = getStorageIndex(row, column); - synchronized (this) { - if (uncachedGetCount >= GET_COUNT_BEFORE_CACHING) - cache(); - - if (cache != null) - return cache.get(offset); - else - uncachedGetCount++; - } - final Pointer out = allocate(getMatrix().getPrimitiveClass()).order(getMatrix().getContext().getByteOrder()); - getMatrix().getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return getMatrix().getBuffer().read(getMatrix().getQueue(), offset, 1, out, true, events); - } - }); - return out.get(); - } - public CLDenseMatrix2DImpl clone() { - return new CLDenseMatrix2DImpl(CLMatrixUtils.clone(getMatrix())); - } - public void waitFor() { - getMatrix().getEvents().waitFor(); - } - public void write(Pointer p) { - getMatrix().write(p); - } - public void read(Pointer p) { - synchronized (this) { - if (cache != null) { - cache.copyTo(p); - return; - } - } - getMatrix().read(p); - } - public Pointer read() { - synchronized (this) { - if (cache != null) - return cache.clone(); - } - Pointer b = (Pointer)Pointer.allocateArray(getMatrix().getPrimitiveClass(), rows * columns); - getMatrix().read(b); - return b; - } - - public void set(V value, long row, long column) { - final long offset = getStorageIndex(row, column); - final Pointer in = allocate(getMatrix().getPrimitiveClass()).order(getMatrix().getContext().getByteOrder()); - in.set(value); - getMatrix().getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return getMatrix().getBuffer().write(getMatrix().getQueue(), offset, 1, in, false, events); - } - }); - } - - /* - public Matrix mtimes(Matrix matrix) throws MatrixException { - if (matrix instanceof DoubleMatrix2D) { - CLMatrix2D - b = CLMatrixUtils.asInputMatrix((DoubleMatrix2D)matrix, queue, context), - out = blankMatrix(getRowCount(), matrix.getColumnCount()); - - CLMatrixUtils.mtimes(this, b, out, primitive, clUJMP); - return (Matrix)out; - } else { - return super.mtimes(matrix); - } - } - */ - - - public CLDenseMatrix2DImpl copy() throws MatrixException { - return new CLDenseMatrix2DImpl(CLMatrixUtils.clone(getMatrix())); - } - - public CLDenseMatrix2DImpl multiply(Ret returnType, boolean ignoreNaN, Matrix2D matrix) throws MatrixException { - CLKernels clUJMP = getMatrix().getKernels(); - CLMatrix2D - in1 = getMatrix(), - in2 = CLWrappedMatrix2D.wrap(matrix, clUJMP), - out = returnType == Ret.ORIG ? in1 : in1.blankMatrix(in1.getRowCount(), in2.getColumnCount()); - - CLMatrixUtils.matrixMultiply(in1, in2, out); - return new CLDenseMatrix2DImpl(out); - } - public CLDenseMatrix2DImpl transpose(Ret returnType) throws MatrixException { - CLMatrix2D - in = getMatrix(), - out = returnType == Ret.ORIG ? in : in.blankMatrix(columns, rows); - CLMatrixUtils.matrixTranspose(in, out); - return new CLDenseMatrix2DImpl(out); - } - - public long[] getSize() { - return size; - } - - public static CLDenseMatrix2DImpl op1(final CLMatrix2D in, final Fun1 fun, Ret returnType) throws MatrixException { - final CLMatrix2D out = returnType == Ret.ORIG ? in : in.blankClone(); - return new CLDenseMatrix2DImpl(CLMatrixUtils.op1(in, fun, out)); - } - public CLDenseMatrix2DImpl sin(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.sin, returnType); - } - - - public CLDenseMatrix2DImpl cos(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.cos, returnType); - } - - - public CLDenseMatrix2DImpl sinh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.sinh, returnType); - } - - - public CLDenseMatrix2DImpl cosh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.cosh, returnType); - } - - - public CLDenseMatrix2DImpl tan(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.tan, returnType); - } - - - public CLDenseMatrix2DImpl tanh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.tanh, returnType); - } - - - public CLDenseMatrix2DImpl asin(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.asin, returnType); - } - - - public CLDenseMatrix2DImpl acos(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.acos, returnType); - } - - - public CLDenseMatrix2DImpl asinh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.asinh, returnType); - } - - - public CLDenseMatrix2DImpl acosh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.acosh, returnType); - } - - - public CLDenseMatrix2DImpl atan(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.atan, returnType); - } - - - public CLDenseMatrix2DImpl atanh(Ret returnType) throws MatrixException { - return op1(getMatrix(), Fun1.atanh, returnType); - } - - public static CLDenseMatrix2DImpl op2(CLMatrix2D in1, Fun2 fun, CLMatrix2D in2, Ret returnType) throws MatrixException { - final CLMatrix2D out = returnType == Ret.ORIG ? in1 : in1.blankClone(); - return new CLDenseMatrix2DImpl(CLMatrixUtils.op2(in1, fun, in2, out)); - } - public static CLDenseMatrix2DImpl op2(CLMatrix2D in1, Fun2 fun, V in2, Ret returnType) throws MatrixException { - final CLMatrix2D out = returnType == Ret.ORIG ? in1 : in1.blankClone(); - return new CLDenseMatrix2DImpl(CLMatrixUtils.op2(in1, fun, in2, out)); - } - - - public CLDenseMatrix2DImpl minus(Ret returnType, boolean ignoreNaN, CLDenseMatrix2DImpl m) throws MatrixException { - return op2(getMatrix(), Fun2.substract, m.getMatrix(), returnType); - } - - public CLDenseMatrix2DImpl minus(Ret returnType, boolean ignoreNaN, V v) throws MatrixException { - return op2(getMatrix(), Fun2.substract, v, returnType); - } - - public CLDenseMatrix2DImpl plus(Ret returnType, boolean ignoreNaN, CLDenseMatrix2DImpl m) throws MatrixException { - return op2(getMatrix(), Fun2.add, m.getMatrix(), returnType); - } - - public CLDenseMatrix2DImpl plus(Ret returnType, boolean ignoreNaN, V v) throws MatrixException { - return op2(getMatrix(), Fun2.add, v, returnType); - } - - public CLDenseMatrix2DImpl times(Ret returnType, boolean ignoreNaN, CLDenseMatrix2DImpl factor) throws MatrixException { - return op2(getMatrix(), Fun2.multiply, factor.getMatrix(), returnType); - } - - public CLDenseMatrix2DImpl times(Ret returnType, boolean ignoreNaN, V factor) throws MatrixException { - return op2(getMatrix(), Fun2.multiply, factor, returnType); - } - - public CLDenseMatrix2DImpl divide(Ret returnType, boolean ignoreNaN, CLDenseMatrix2DImpl factor) throws MatrixException { - return op2(getMatrix(), Fun2.divide, factor.getMatrix(), returnType); - } - - public CLDenseMatrix2DImpl divide(Ret returnType, boolean ignoreNaN, V factor) throws MatrixException { - return op2(getMatrix(), Fun2.divide, factor, returnType); - } - //protected abstract Matrix createMatrix(CLMatrixImpl mi); - - - static final int MAX_REDUCTION_SIZE = 32; - volatile Reductor minReductor; - public CLDenseMatrix2DImpl min() throws CLBuildException { - synchronized (this) { - if (minReductor == null) - minReductor = ReductionUtils.createReductor(getMatrix().getContext(), ReductionUtils.Operation.Min, getMatrix().getPrimitive().oclType, 1); - } - CLMatrix2D out = getMatrix().blankMatrix(1, 1); - CLMatrixUtils.reduce(getMatrix(), out, minReductor); - return new CLDenseMatrix2DImpl(out); - } - volatile Reductor maxReductor; - public CLDenseMatrix2DImpl max() throws CLBuildException { - synchronized (this) { - if (maxReductor == null) - maxReductor = ReductionUtils.createReductor(getMatrix().getContext(), ReductionUtils.Operation.Max, getMatrix().getPrimitive().oclType, 1); - } - CLMatrix2D - in = getMatrix(), - out = in.blankMatrix(1, 1); - CLMatrixUtils.reduce(in, out, minReductor); - return new CLDenseMatrix2DImpl(out); - } - - public boolean containsValue(final V value) throws CLBuildException { - final boolean ret[] = new boolean[1]; - getMatrix().getEvents().performRead(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - ret[0] = getMatrix().getKernels().containsValue(getMatrix().getPrimitive(), getMatrix().getBuffer(), getMatrix().getBuffer().getElementCount(), value, events); - return null; - } - }); - return ret[0]; - } - - public void clear() throws CLBuildException { - getMatrix().getEvents().performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return getMatrix().getKernels().clear(getMatrix().getPrimitive(), getMatrix().getBuffer(), getMatrix().getBuffer().getElementCount(), events); - } - }); - } - - public CLQueue getQueue() { - return getMatrix().getQueue(); - } - -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLMatrixBenchmark.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLMatrixBenchmark.java deleted file mode 100644 index 5714e3c18..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLMatrixBenchmark.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLKernels; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import org.ujmp.core.Matrix; -import org.ujmp.core.benchmark.AbstractMatrix2DBenchmark; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.exceptions.MatrixException; - -/** - * - * @author ochafik - */ -public class CLMatrixBenchmark extends AbstractMatrix2DBenchmark { - - @Override - public DoubleMatrix2D createMatrix(long... size) throws MatrixException { - return new CLDenseDoubleMatrix2D(size); - } - - @Override - public DoubleMatrix2D createMatrix(Matrix source) throws MatrixException { - if (source instanceof CLDenseDoubleMatrix2D) - return (DoubleMatrix2D)((CLDenseDoubleMatrix2D)source).copy(); - else { - DoubleMatrix2D dsource = (DoubleMatrix2D)source; - long rows = dsource.getRowCount(), columns = dsource.getColumnCount(); - Pointer b = allocateDoubles(rows * columns).order(CLKernels.getInstance().getContext().getKernelsDefaultByteOrder()); - for (long i = 0; i < rows; i++) { - long offset = i * columns; - for (long j = 0; j < columns; j++) { - b.set(offset + i, dsource.getDouble(i, j)); - } - } - CLDenseDoubleMatrix2D copy = new CLDenseDoubleMatrix2D(rows, columns); - copy.write(b); - return copy; - } - } - -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLWrappedMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLWrappedMatrix2D.java deleted file mode 100644 index fbc0adb71..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/CLWrappedMatrix2D.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLMatrix2D; -import com.nativelibs4java.opencl.blas.CLEvents; -import com.nativelibs4java.opencl.blas.CLMatrixUtils; -import com.nativelibs4java.opencl.blas.CLKernels; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.util.Primitive; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.floatmatrix.FloatMatrix2D; -import org.ujmp.core.matrix.Matrix2D; - -/** - * - * @author ochafik - */ -public class CLWrappedMatrix2D implements CLMatrix2D { - public static CLMatrix2D wrap(final Matrix2D matrix, final CLKernels clUJMP) { - if (matrix instanceof CLMatrix2D) - return (CLMatrix2D)matrix; - - return new CLWrappedMatrix2D(matrix, clUJMP); - } - - final Matrix2D matrix; - final CLKernels kernels; - final Primitive primitive; - final Class elementType; - - CLWrappedMatrix2D(Matrix2D matrix, CLKernels kernels) { - this.matrix = matrix; - this.kernels = kernels; - - if (matrix instanceof DoubleMatrix2D) - this.primitive = Primitive.Double; - else if (matrix instanceof FloatMatrix2D) - this.primitive = Primitive.Float; - else - throw new UnsupportedOperationException(); - - elementType = (Class)primitive.primitiveType; - } - - final CLEvents events = new CLEvents(); - public CLEvents getEvents() { - return events; - } - - public CLKernels getKernels() { - return kernels; - } - - - public Primitive getPrimitive() { - return primitive; - } - - volatile CLBuffer buffer; - volatile Pointer data; - public synchronized CLBuffer getBuffer() { - long length = matrix.getRowCount() * matrix.getColumnCount(); - - // Read data - if (data == null) - data = allocateArray(elementType, length).order(getContext().getByteOrder()); - MatrixUtils.read(matrix, data); - - // Write data to CLBuffer - if (buffer == null) - buffer = kernels.getContext().createBuffer(Usage.Input, elementType, length); - - events.performWrite(new CLEvents.Action() { - public CLEvent perform(CLEvent[] events) { - return buffer.write(getQueue(), data, false, events); - } - }); - - return buffer; - } - - public long getRowCount() { - return matrix.getRowCount(); - } - - public long getColumnCount() { - return matrix.getColumnCount(); - } - - public CLContext getContext() { - return kernels.getContext(); - } - public CLQueue getQueue() { - return kernels.getQueue(); - } - - public CLMatrix2D blankClone() { - return CLMatrixUtils.createMatrix(getRowCount(), getColumnCount(), elementType, getKernels()); - } - - public Class getPrimitiveClass() { - throw new UnsupportedOperationException("Not supported yet."); - } - - public CLMatrix2D blankMatrix(long rows, long columns) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void write(Pointer b) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void read(Pointer b) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public Pointer read() { - throw new UnsupportedOperationException("Not supported yet."); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2D.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2D.java deleted file mode 100644 index fb491d4e0..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2D.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLKernels; -import org.ujmp.core.doublematrix.stub.AbstractDenseDoubleMatrix2D; -import org.ujmp.core.interfaces.Wrapper; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -/** - * - * @author ochafik - */ -public class DirectNIODenseDoubleMatrix2D extends AbstractDenseDoubleMatrix2D { - - /** - * - */ - private static final long serialVersionUID = 8936390922363132043L; - final Pointer data; - final long rows, columns; - - public DirectNIODenseDoubleMatrix2D(Pointer data, long rows, long columns) { - this.rows = rows; - this.columns = columns; - this.data = data; - } - - public DirectNIODenseDoubleMatrix2D(long rows, long columns) { - this(allocateDoubles(rows * columns).order(CLKernels.getInstance().getContext().getKernelsDefaultByteOrder()), rows, columns); - } - - public DirectNIODenseDoubleMatrix2D(long[] size) { - this(size[0], size[1]); - if (size.length != 2) - throw new IllegalArgumentException("Size is not 2D !"); - } - - - public Pointer getData() { - return data; - } - - public Pointer getReadableData() { - return getData(); - } - - - public Pointer getWritableData() { - return getData(); - } - - public long[] getSize() { - return new long[] { rows, columns }; - } - - public double getDouble(long row, long column) { - return data.getDoubleAtOffset((row * columns + column) << 3); - } - - @Override - public void setDouble(double value, long row, long column) { - data.setDoubleAtOffset((row * columns + column) << 3, value); - } - - @Override - public double getDouble(int row, int column) { - return getDouble((long)row, column); - } - - @Override - public void setDouble(double value, int row, int column) { - setDouble(value, (long)row, column); - } -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2DFactory.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2DFactory.java deleted file mode 100644 index 62adea170..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/DirectNIODenseDoubleMatrix2DFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import org.ujmp.core.doublematrix.DenseDoubleMatrix2D; -import org.ujmp.core.doublematrix.factory.AbstractDoubleMatrix2DFactory; -import org.ujmp.core.exceptions.MatrixException; - -/** - * - * @author ochafik - */ -public class DirectNIODenseDoubleMatrix2DFactory extends - AbstractDoubleMatrix2DFactory { - private static final long serialVersionUID = 4390694808314618187L; - - - public DenseDoubleMatrix2D dense(long rows, long columns) - throws MatrixException { - return new DirectNIODenseDoubleMatrix2D(rows, columns); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/MatrixUtils.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/MatrixUtils.java deleted file mode 100644 index 12f60ab95..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/MatrixUtils.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.blas.CLKernels; -import org.ujmp.core.floatmatrix.FloatMatrix2D; -import org.ujmp.core.doublematrix.DoubleMatrix2D; -import org.ujmp.core.matrix.Matrix2D; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -/** - * - * @author ochafik - */ -public class MatrixUtils { - public static void write(double[] b, DoubleMatrix2D out) { - write(pointerToDoubles(b), out); - } - public static void write(float[] b, FloatMatrix2D out) { - write(pointerToFloats(b), out); - } - public static void write(Pointer b, DoubleMatrix2D out) { - long rows = out.getRowCount(), columns = out.getColumnCount(); - if (b.getValidElements() < rows * columns) - throw new IllegalArgumentException("Not enough data in input buffer to write into " + rows + "x" + columns + " matrix (only has " + b.getValidElements() + ")"); - if (out instanceof CLDenseDoubleMatrix2D) { - CLDenseDoubleMatrix2D mout = (CLDenseDoubleMatrix2D)out; - mout.write(b); - } else { - for (long i = 0; i < rows; i++) { - long offset = i * columns; - for (long j = 0; j < columns; j++) - out.setDouble(b.get(offset + j), i, j); - } - } - } - public static void write(Pointer b, FloatMatrix2D out) { - long rows = out.getRowCount(), columns = out.getColumnCount(); - if (b.getValidElements() < rows * columns) - throw new IllegalArgumentException("Not enough data in input buffer to write into " + rows + "x" + columns + " matrix (only has " + b.getValidElements() + ")"); - if (out instanceof CLDenseFloatMatrix2D) { - CLDenseFloatMatrix2D mout = (CLDenseFloatMatrix2D)out; - mout.write(b); - } else { - for (long i = 0; i < rows; i++) { - long offset = i * columns; - for (long j = 0; j < columns; j++) - out.setFloat(b.get(offset + j), i, j); - } - } - } - - public static Pointer read(DoubleMatrix2D m) { - Pointer buffer = allocateDoubles(m.getColumnCount() * m.getRowCount()).order(CLKernels.getInstance().getContext().getKernelsDefaultByteOrder()); - read(m, buffer); - return buffer; - } - public static void read(Matrix2D m, Pointer out) { - if (m instanceof DoubleMatrix2D) - read((DoubleMatrix2D)m, (Pointer)out); - else if (m instanceof FloatMatrix2D) - read((FloatMatrix2D)m, (Pointer)out); - else - throw new UnsupportedOperationException("Can only read DoubleMatrix2D into DoubleBuffer for now"); - } - public static void read(DoubleMatrix2D m, Pointer out) { - long rows = m.getRowCount(), columns = m.getColumnCount(); - if (out.getValidElements() < rows * columns) - throw new IllegalArgumentException("Not enough space in output buffer to read into " + rows + "x" + columns + " matrix (only has " + out.getValidElements() + ")"); - - if (m instanceof CLDenseDoubleMatrix2D) { - CLDenseDoubleMatrix2D mm = (CLDenseDoubleMatrix2D)m; - mm.read(out); - } else { - for (long i = 0; i < rows; i++) { - long offset = i * columns; - for (long j = 0; j < columns; j++) { - out.set(offset + j, m.getDouble(i, j)); - } - } - } - } - - public static Pointer read(FloatMatrix2D m) { - Pointer buffer = allocateFloats(m.getColumnCount() * m.getRowCount()).order(CLKernels.getInstance().getContext().getKernelsDefaultByteOrder()); - read(m, buffer); - return buffer; - } - public static void read(FloatMatrix2D m, Pointer out) { - long rows = m.getRowCount(), columns = m.getColumnCount(); - if (out.getValidElements() < rows * columns) - throw new IllegalArgumentException("Not enough space in output buffer to read into " + rows + "x" + columns + " matrix (only has " + out.getValidElements() + ")"); - - if (m instanceof CLDenseFloatMatrix2D) { - CLDenseFloatMatrix2D mm = (CLDenseFloatMatrix2D)m; - mm.read(out); - } else { - for (long i = 0; i < rows; i++) { - long offset = i * columns; - for (long j = 0; j < columns; j++) { - out.set(offset + j, m.getFloat(i, j)); - } - } - } - } -} diff --git a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/package-info.java b/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/package-info.java deleted file mode 100644 index 1de7bac31..000000000 --- a/libraries/OpenCL/Blas/src/main/java/com/nativelibs4java/opencl/blas/ujmp/package-info.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * OpenCL UJMP float/double dense matrix implementations with many asynchronous accelerated operations (multiplication, transpose, piece-wise unary or binary operations...).
    - * To install these implementations, please use the following calls : - *
    {@code
    - * MatrixMapper.getInstance().setDenseDoubleMatrix2DClass(CLDenseDoubleMatrix2D.class);
    - * MatrixMapper.getInstance().setDenseFloatMatrix2DClass(CLDenseFloatMatrix2D.class);
    - * }
    - */ -package com.nativelibs4java.opencl.blas.ujmp; diff --git a/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/PerformanceTest.java b/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/PerformanceTest.java deleted file mode 100644 index 85adee2a5..000000000 --- a/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/PerformanceTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.blas.ujmp; - -import com.nativelibs4java.opencl.CLDevice; -import org.ujmp.core.calculation.Calculation.Ret; -import org.ujmp.core.floatmatrix.impl.DefaultDenseFloatMatrix2D; -import org.ujmp.core.Matrix; -import com.nativelibs4java.util.Pair; -import com.nativelibs4java.opencl.blas.CLKernels; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class PerformanceTest { - - public PerformanceTest() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Test - public void testGPUPerfFloat() throws IOException { - //CLKernels.setInstance(new CLKernels(JavaCL.createBestContext(DeviceFeature.GPU).createDefaultQueue())); - - //int size = 100; - - for (int size : new int[] { 10, 50, 100/*, 200, 400*/ }) { - - DefaultDenseFloatMatrix2D mJava = new DefaultDenseFloatMatrix2D(size, size); - Matrix pJava = testPerf("Java(size = " + size +")", mJava).getValue(); - - for (DeviceFeature feat : new DeviceFeature[] { DeviceFeature.CPU, DeviceFeature.GPU }) { - CLKernels.setInstance(new CLKernels(JavaCL.createBestContext(feat).createDefaultQueue())); - CLDevice device = CLKernels.getInstance().getQueue().getDevice(); - - CLDenseFloatMatrix2D mCL = new CLDenseFloatMatrix2D(size, size); - Matrix pCL = testPerf("OpenCL(size = " + size +", device = " + device + ")", mCL).getValue(); - - assertEquals(pJava, pCL); - } - } - } - - interface Action { - V perform(); - } - - private Pair testMillis(String title, Action action) { - int times = 10; - double total = 0; - V v = null; - for (int i = 0; i <= times; i++) { - long start = System.nanoTime(); - v = action.perform(); - double time = (System.nanoTime() - start) / 1000000.0; - if (i > 0) // skip first value (rough warmup) - total += time; - } - double avg = total / times; - System.out.println("Time[ " + title + " ] = " + avg + " ms"); - return new Pair(avg, v); - } - - private Pair testPerf(String title, final Matrix _m) { - final int pow = 100; - - System.out.println(); - testMillis("svd(" + title + ")", new Action() { - final Matrix m = _m.copy(); - public Void perform() { - Matrix[] svd = m.svd(); - for (Matrix s : svd) - s.getAsDouble(0, 0); - return null; - } - }); - - testMillis("sq(" + title + ")", new Action() { - final Matrix m = _m.copy(); - public Matrix perform() { - Matrix sq = m.mtimes(Ret.NEW, true, m); - sq.getAsDouble(0, 0); - return sq; - } - }); - - testMillis("add(" + title + ")", new Action() { - final Matrix m = _m.copy(); - public Matrix perform() { - Matrix mm = m.plus(Ret.ORIG, true, m).plus(Ret.ORIG, true, m).plus(Ret.ORIG, true, m).plus(Ret.ORIG, true, m); - mm.getAsDouble(0, 0); - return mm; - } - }); - - testMillis("sin(" + title + ")", new Action() { - final Matrix m = _m.copy(); - public Matrix perform() { - Matrix mm = m.sin(Ret.ORIG); - mm.getAsDouble(0, 0); - return mm; - } - }); - - testMillis("transpose(" + title + ")", new Action() { - final Matrix m = _m.copy(); - public Matrix perform() { - Matrix sq = m.transpose(Ret.ORIG).transpose(Ret.ORIG).transpose(Ret.ORIG).transpose(Ret.ORIG); - sq.getAsDouble(0, 0); - return sq; - } - }); - - return testMillis("pow(" + title + ", " + pow + ")", new Action() { - final Matrix m = _m.copy(); - public Matrix perform() { - Matrix power = m; - for (int i = 1; i < pow; i++) - power.mtimes(Ret.ORIG, true, m); - //Matrix power = m.power(Ret.NEW, pow); - power.getAsDouble(0, 0); - return power; - } - }); - } -} diff --git a/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/UJMPOpenCLTest.java b/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/UJMPOpenCLTest.java deleted file mode 100644 index 4a5f28597..000000000 --- a/libraries/OpenCL/Blas/src/test/java/com/nativelibs4java/opencl/blas/ujmp/UJMPOpenCLTest.java +++ /dev/null @@ -1,169 +0,0 @@ -package com.nativelibs4java.opencl.blas.ujmp; - -import java.io.IOException; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.blas.CLKernels; -import static com.nativelibs4java.opencl.blas.ujmp.MatrixUtils.read; -import static com.nativelibs4java.opencl.blas.ujmp.MatrixUtils.write; -import com.nativelibs4java.util.Pair; -import static org.junit.Assert.*; - -import static java.lang.Math.*; - -import org.junit.Before; -import org.junit.Test; -import org.ujmp.core.Matrix; -import org.ujmp.core.MatrixFactory; -import org.ujmp.core.calculation.Calculation.Ret; -import org.ujmp.core.doublematrix.DenseDoubleMatrix2D; -import org.ujmp.core.doublematrix.impl.DefaultDenseDoubleMatrix2D; -import org.ujmp.core.floatmatrix.DenseFloatMatrix2D; -import org.ujmp.core.floatmatrix.FloatMatrix2D; -import org.ujmp.core.floatmatrix.impl.DefaultDenseFloatMatrix2D; -import org.ujmp.core.mapper.MatrixMapper; -/** - * - * @author ochafik - */ - -public class UJMPOpenCLTest { - - @Before - public void installUJMPCL() { - try { - MatrixMapper.getInstance().setDenseDoubleMatrix2DClass(CLDenseDoubleMatrix2D.class); - } catch (Exception ex) { - ex.printStackTrace(); - throw new RuntimeException(ex); - } - } - - @Test - public void testInstalledUJMPCL() { - Matrix m = MatrixFactory.dense(1, 1); - assertTrue(m instanceof CLDenseDoubleMatrix2D); - } - - @Test - public void testOp2() { - - DenseFloatMatrix2D a = new CLDenseFloatMatrix2D(2, 2); - DenseFloatMatrix2D b = new CLDenseFloatMatrix2D(2, 2); - - float[] fa = new float[] { 10, 20, 30, 40 }, fb = new float[] { 1, 2, 3, 4 }; - write(fa, a); - write(fb, b); - - assertArrayEquals("failed plus", new float[] { 11, 22, 33, 44 }, read((FloatMatrix2D)a.plus(b)).getFloats(), 0); - assertArrayEquals("failed minus", new float[] { 9, 18, 27, 36 }, read((FloatMatrix2D)a.minus(b)).getFloats(), 0); - assertArrayEquals("failed times", new float[] { 10, 40, 90, 160 }, read((FloatMatrix2D)a.times(b)).getFloats(), 0); - assertArrayEquals("failed divide", new float[] { 10, 10, 10, 10 }, read((FloatMatrix2D)a.divide(b)).getFloats(), 0); - - assertArrayEquals("failed scalar plus", new float[] { 11, 21, 31, 41 }, read((FloatMatrix2D)a.plus(1)).getFloats(), 0); - assertArrayEquals("failed scalar minus", new float[] { 9, 19, 29, 39 }, read((FloatMatrix2D)a.minus(1)).getFloats(), 0); - assertArrayEquals("failed scalar times", new float[] { 20, 40, 60, 80 }, read((FloatMatrix2D)a.times(2)).getFloats(), 0); - assertArrayEquals("failed scalar divide", new float[] { 1, 2, 3, 4 }, read((FloatMatrix2D)a.divide(10)).getFloats(), 0); - - assertArrayEquals("failed sin", new float[] { (float)sin(fa[0]), (float)sin(fa[1]), (float)sin(fa[2]), (float)sin(fa[3]) }, - read((FloatMatrix2D)a.sin(Ret.NEW)).getFloats(), 0.0001f); - assertArrayEquals("failed cos", new float[] { (float)cos(fa[0]), (float)cos(fa[1]), (float)cos(fa[2]), (float)cos(fa[3]) }, - read((FloatMatrix2D)a.cos(Ret.NEW)).getFloats(), 0.0001f); - assertArrayEquals("failed tan", new float[] { (float)tan(fa[0]), (float)tan(fa[1]), (float)tan(fa[2]), (float)tan(fa[3]) }, - read((FloatMatrix2D)a.tan(Ret.NEW)).getFloats(), 0.0001f); - - } - - @Test - public void testMultFloat() { - - DenseFloatMatrix2D m = new CLDenseFloatMatrix2D(3, 3); - DenseFloatMatrix2D v = new CLDenseFloatMatrix2D(3, 1); - //CLBuffer buffer = ((CLDenseFloatMatrix2D)m).getBuffer(); - CLQueue queue = ((CLDenseFloatMatrix2D)m).getImpl().getQueue(); - //System.out.println("Context = " + buffer.getContext()); - - float[] min = new float[] { 0, 0, 1, 0, 1, 0, 1, 0, 0 }; - write(min, m); - Pointer back = read(m); - for (int i = 0, cap = (int)back.getValidElements(); i < cap; i++) { - assertEquals(min[i], back.get(i), 0); - //System.out.println(back.get(i)); - } - - queue.finish(); - DenseFloatMatrix2D mout = (DenseFloatMatrix2D) m.mtimes(m); - queue.finish(); - - //System.out.println("m = \n" + m); - //System.out.println("mout = \n" + mout); - - //if (la instanceof CLLinearAlgebra) - // ((CLLinearAlgebra)la).queue.finish(); - //dmout.write((FloatBuffer)mout.read()); - - back = read(mout); - //for (int i = 0, cap = (int)back.getValidElements(); i < cap; i++) - // System.out.println(back.get(i)); - - assertEquals(0, mout.getFloat(0, 1), 0); - assertEquals(0, mout.getFloat(1, 0), 0); - - assertEquals(1, mout.getFloat(0, 0), 0); - assertEquals(1, mout.getFloat(1, 1), 0); - assertEquals(1, mout.getFloat(2, 2), 0); - - write(new float[] { 1, 0, 0}, v); - DenseFloatMatrix2D vout = (DenseFloatMatrix2D)m.mtimes(v); - //System.out.println(v); - //System.out.println(vout); - - assertEquals(0, vout.getFloat(0, 0), 0); - assertEquals(0, vout.getFloat(1, 0), 0); - assertEquals(1, vout.getFloat(2, 0), 0); - } - - @Test - public void testContainsDouble() throws IOException { - - CLKernels.setInstance(new CLKernels()); - - CLDenseDoubleMatrix2D m = (CLDenseDoubleMatrix2D)MatrixFactory.dense(2, 2); - int row = 1, column = 1; - m.setDouble(1.1, row, column); - assertEquals(1.1, m.getDouble(row, column), 0.0); - assertTrue(m.containsDouble(1.1)); - assertTrue(!m.containsDouble(2.0)); - } - - - @Test - public void testContainsFloat() { - CLDenseFloatMatrix2D m = new CLDenseFloatMatrix2D(2, 2); - int row = 1, column = 1; - m.setFloat(1.1f, row, column); - assertEquals(1.1f, m.getFloat(row, column), 0.0); - assertTrue(m.containsFloat(1.1f)); - assertTrue(!m.containsFloat(2.0f)); - } - - @Test - public void testClearFloat() { - CLDenseFloatMatrix2D m = new CLDenseFloatMatrix2D(2, 2); - int row = 0, column = 1; - m.setFloat(1.1f, row, column); - assertEquals(1.1f, m.getFloat(row, column), 0.0); - m.clear(); - assertEquals(0f, m.getFloat(row, column), 0.0); - } - - static void sleep(long millis) { - try { Thread.sleep(millis); } catch (Exception ex) { ex.printStackTrace(); } - } - -} diff --git a/libraries/OpenCL/CHANGELOG b/libraries/OpenCL/CHANGELOG deleted file mode 100644 index a924d2109..000000000 --- a/libraries/OpenCL/CHANGELOG +++ /dev/null @@ -1,182 +0,0 @@ -Current development version (1.0-SNAPSHOT) - -- Fixed handling of image2d_t and image3d_t in Maven plugin (contrib. from Remi Emonet, request #308 and issue #307) -- Fixed OpenGL interop on Windows (issue #312) -- Added CLEvent.FIRE_AND_FORGET to avoid returning events from all the methods that accept a vararg eventsToWaitFor. -- Optimized low-level bindings on OpenCL 1.1+ platforms, with dynamic runtime switch (removed synchronized keyword from all native calls) -- Optimized performance of many calls (CLKernel.setArgs/enqueueNDRange, CLBuffer.read/write...) - -Version 1.0.0-RC2 (20120415, commit 6bc061dfce06b941086a29f696195e82fbaffbdc) - -- Release artifacts are available in Maven Central -- Added support for sub-images reading/writing from/to CLImage2D (slower than with full images) -- Fixed endianness issues with CLBuffer (issue #80) -- Fixed migration of cached binaries to newer versions of OS (e.g. upgrading from Snow Leopard to Lion) (issue #81) -- Fixed handling compiler options containing spaces (issue #274) -- Fixed tutorial artifact pom repositories (issue #279) -- Fixed many Javadoc typos -- Fixed support of Intel's OpenCL Windows runtime (issue #297) -- Enhanced LocalSize API (added static factory methods for all primitive types) -- Deprecated CLContext.getKernelsDefaultByteOrder() and CLDevice.getKernelsDefaultByteOrder() -- Added more informative exceptions when passing null pointers to CLBuffer.writeBytes (issue #257) -- Updated to OpenCL 1.2 headers -- Added -cl-nv-verbose, -cl-nv-maxrregcount, -cl-nv-opt-level + proper log even without error when nv-verbose is set -- Enhanced handling of endianness : warn when creating contexts with devices that have mismatching endianness, throw when creating buffer out of Buffer / Pointer with bad endianness -- Changed signature of CLPlatform.listDevices (now takes a single CLDevice.Type, including All, instead of an EnumSet thereof) -- Moved sources to github (https://github.com/ochafik/nativelibs4java/tree/master/libraries/OpenCL) - -Version 1.0.0-RC1 (r2130, 20110621) - -- BridJ version now becomes the default : the JNA version is still maintained and available with all Maven artifact ids suffixed with "-jna" (BridJ-based JavaCL's main artifact is now "javacl", while the JNA-based version is "javacl-jna") -- added simple Fourier-analysis classes (package com.nativelibs4java.opencl.util.fft), with double and float variants, usable with primitive arrays or OpenCL buffers : - - naive Discrete Fourier Transform (DFT) - - Fast Fourier Transform (FFT) for power-of-two arrays / buffers (performs better than Apache Commons on a CPU) -- added some compiler options to CLProgram : - - setFastRelaxedMath() (triggers all the others !) - - setFiniteMathOnly() - - setUnsafeMathOptimizations() - - setMadEnable() - - setNoSignedZero() -- added CLContext.createBuffer(Usage, Buffer) -- added CLBuffer.copyTo(CLQueue, CLMem destination, CLEvent...) and CLBuffer.emptyClone(Usage) -- added NIOUtils.indirectBuffer(size, bufferClass) -- added CLContext.toString -- deprecated CLXXXBuffer in favor of CLBuffer (CLIntBuffer becomes CLBuffer, etc...) -- changed CLContext.createBuffer(Usage, length, class) to createBuffer(Usage, class, length) to match the JavaCL/BridJ API (and provoke migration issues : people should now use a primitive class rather than an NIO buffer class !!! -- complete rewrite of CLBuffer genericity to unify with the BridJ port : CLBuffer is now CLBuffer, and CLBuffer.read/write/map are no longer strongly typed (it is implicitely typed with Buffer subclasses for compatibility with existing code). The BridJ port will be favoured, and its read/write/map methods use typed Pointer. -- complete rewrite of UJMP Matrix implementation, using principles borrowed from ScalaCL -- fixed issue #66 (create temp files in ~/.javacl subdirectories instead of /tmp) -- fixed OpenGL sharing on MacOS X -- fixed CLProgram.getBinaries() in some cases -- fixed CLBuffer.read on indirect buffers -- fixed NPE that happens with null varargs CLEvent[] array -- fixed length = 1 case in reduction utility -- fixed ATI detection ("ATI Stream" now replaced by "AMD Accelerated Parallel Processing", cf. Csaba's comment in issue #39) -- fixed issue #55 : applied Kazo Csaba's patch to fix the bounds of CLBuffer.map's returned buffer -- fixed inheritance of CLBuildException (now derives from CLException) - -Version 1.0-beta-6 (r1637, 20100204) - -- Fixed support of ATI Stream 2.3 (CPU) -- New interactive image kernel demo : lets you edit and test image kernels in a snap (bundled with a few samples) -- Experimental BridJ port with same functionality as JNA-powered version, but smaller and faster (JAR weighs 750 kB instead of 1.8 MB, overhead per-function call about 10x smaller) -- Added automatic and transparent program binaries caching : - - Disabled by default on ATI Stream. - - Can force on/off with : - - property -Djavacl.cacheBinaries=true/false - - environment variable JAVACL_CACHE_BINARIES=1/0 - - methods CLContext.setCacheBinaries and CLProgram.setCached -- JavaCL.createBestContext now takes an ordered list of CLPlatform.DeviceFeature enums that help prioritize the features considered as "best" (list can be empty or contain any of CPU, GPU, DoubleSupport, MaxComputeUnits, NativeEndianness, ImageSupport, MostImageFormats...). These features are preferences, not requirements : with createBestContext(GPU, MaxComputeUnits) you might end up getting a CPU-based context if there's no GPU available, but you'll have the most powerful GPU (in terms of compute units) if there are two of them. -- Kernels can now include files that are in the classpath (+ added CLProgram.addInclude that accepts directories and base URLs) -- Added LibCL : growing collection of OpenCL functions that can be included from any JavaCL kernel -- CLKernel.enqueueNDRange has a new overload without localWorkSizes argument (it's then adjusted to a good value by the OpenCL implementation). -- ScalaCLv2 was rewritten to fit nicely into Scala's collections framework. -- Added CLContext.createProgram(Map) to create from saved binaries (contribution from Kazo Csaba, issue #30) -- Added CLProgram.addBuildOption(String) -- Fixed CLBuffer.copyTo -- Demos now use the latest jogamp JOGL binaries (see the updated build instructions : http://code.google.com/p/javacl/wiki/Build) - -Version 1.0-beta-5 (r1067, 20100717) - -- Now using a nice configuration dialog when launching ParticlesDemo : has -optional OpenCL settings with "Fastest", "Normal" and "Safest" presets + -detailed platform and device choice (with optional OpenGL sharing choice). -- Added optional context properties map argument to JavaCL.createContext (can be nulled -out) -- Fixed issue #18: CLImage.write calls enqueueImageRead ! -- Documented workaround for Linux crashes (issue #20) : http://code.google.com/p/javacl/wiki/TroubleShootingJavaCLOnLinux -- Fixed issue #21: NIOUtils.put() doesn't accept ByteBuffer -- Fixed issue #25: CLEvent.waitFor bug causes segfault -- OpenCL 1.1 support : - - CLContext.createUserEvent() - - CLUserEvent.setStatus(int), setCompleted() - - CLEvent.setCallback(status, callbac), setCompletionCallback(callback) - - CLBuffer.createSubBuffer(usage, offset, length) - - CLContext.getDeviceCount() - - CLDevice.getOpenCLVersion() - - CLDevice.isHostUnifiedMemory() - - CLDevice.getNativeVectorWidthXXX() methods - - CLMem.setDestructorCallback(callback) - - CLKernel.getPreferredWorkGroupSizeMultiple() - - CLKernel.enqueueNDRange overload with potentially non-null globalOffsets - - CLImageFormat.ChannelOrder.Rx, RGx, RGBx -- Faster enums -- Check for cl_amd_fp64 in CLDevice.isDoubleSupported() -- Fixed CLProgram.getBinaries() -- Fixed issue #22 (maven pom issue) - -Version 1.0-beta-4 (r760, 20100121) - -- Changed semantics of offset & length arguments in typed CLxxxBuffer.read / write / map methods : now expressed in elements, not in bytes (e.g. 4 bytes per element for CLIntBuffer) -- Added OpenGL interoperability methods to CLContext and CLQueue (can create a CLByteBuffer from an OpenGL buffer object, a CLImage2D/3D from an OpenGL 2D/3D texture or a renderbuffer). -- Added OpenGL-compatible context creation methods to JavaCL & CLPlatform classes -- Added basic reduction support in ReductionUtils (cumulative additions, multiplications, min, max...) -- Created javacl-demos package, with Particles, Hardware Report and Mandelbrot demos... -- Finished migration from NativeLong to NativeSize (changes only the low-level bindings) -- Added profiling methods to CLEvent (+ facility CLDevice.createProfilingQueue()) -- Better JavaDoc for low-level bindings (links to Khronos online manual pages) -- Added deferred program allocation : CLProgram.addSource(String), CLProgram.allocate() (called automatically)... -- Added very simple OpenCL backend for UJMP (Universal Java Matrix Package), which does matrix multiplications in OpenCL. -- Created a kernel wrapper autogenerator (Maven plugin based on JNAerator) : translates all constants on the Java side and presents kernels as methods with the correct Java argument types. It assumes OpenCL kernels (*.c, *.cl) are in src/main/opencl -- Added wrappers around clGetKernelWorkGroupInfo -- Fixed respect of endianness of devices that have different endianness than platform -- Fixed issue #10: "getMaxWorkItemSizes() fails on win7 64 GTX260" - -Version 1.0-beta-3 (r , 20091030) - -- Fixed Issue #8 : NativeLong's can not represent size_t on windows x64 system (all user code that uses the low-level bindings needs to be updated : NativeLong -> NativeSize) -- Added CLContext/CLDevice.isDoubleSupported, isHalfSupported, isByteAddressableStoreSupported -- Added If function to ScalaCL (operates on statements or on expressions) -- Added CLAbstractEntity.release() -- Fixed Issue #4 : CLContext.createContext(CLDevice... devices) created context on only one device -- Regenerated the low level bindings with latest JNAerator : now using NativeSize class instead of NativeLong for size_t (fixes Issue #8) -- Fixed Issue #5 : fixed formatting of CLPlatform.toString() -- Fixed Issue #6 : use max X workgroup dimension for better benchmark speed -- Fixed Issue #7 : CLMem class bug in Usage.WriteOnly and Usage.ReadWrite -- Fixed Issue #11 : call clRetainMemObject when sharing a cl_mem between CLBuffer instances. -- Choose 'best' device in benchmark test - -Version 1.0-beta-2 - -- JAR is now self-sufficient (includes JNA + JNAerator's runtime classes) -- Added CLKernel.setLocalArg(argIndex, localArgByteLength) -- Allow localWorkSizes to be null in enqueueNDRange -- Added support for barriers and markers in CLQueue -- Fixed issue #2 : enqueueNDRange does not work for nDim > 1 -- Added CLDevice.getMaxWorkItemSizes() -- CLDevice.toString() now only prints the name -- Moved method createContext from CLContext to CLPlatform -- Added all the CL_DEVICE_PREFERRED_VECTOR_WIDTH_XXX infos to CLDevice as getPreferredVectorWithXXX() -- Changed return type of getExtensions() method of both CLPlatform and CLDevice from String to String[] -- Added com.nativelibs4java.opencl.HardwareReport (with main method) : outputs html report with devices stats -- Rationalized naming of all enums : CL_ENTITY_ATTRIBUTE_SOME_VALUE = CLEntity.Attribute.SomeValue (enum item SomeValue in enum Attribute in class CLEntity) -- Added full support of images : - - CLContext.getSupportedImageFormats + CLImageFormat and associated enums - - CLImage2D, CLImage3D and corresponding creation methods in CLContext + all image info getters -- CLMem is now an abstract base class - - CLBuffer with typed subclasses (CLByteBuffer, CLIntBuffer..) - - To create a CLBuffer : context.createIntBuffer(Input, size) - - Added CLBuffer.copyTo (clEnqueueCopyBuffer) - - Each typed CLBuffer subclass has map, mapLater, read methods that return typed NIO buffers -- Added full typing of OpenCL Exceptions (now possible to selectively catch a CLException.OutOfHostMemory, for instance) -- Added hashCode and equals method to most classes -- Added ability to create out of order queues and change queue properties after creation - -Version 1.0-beta-1 - -- New CLPlatform class (~ OpenCL implementation) which now hosts the list*Devices(...) methods -- Entry point of library is now OpenCL4Java.listPlatforms() -- New CLEvent class, returned by all enqueue* methods (with methods waitFor, invokeUponCompletion...) -- Better separation between blocking and non blocking calls -- New CLSampler class supported as argument of CLKernel -- Many info getters with typesafe enums / enum sets in classes CLDevice, CLPlatform, CLKernel... -- Much more complete JavaDoc : http://nativelibs4java.sourceforge.net/sites/OpenCL4Java/apidocs/ -- Example & benchmark classes became JUnit tests and moved here : http://code.google.com/p/nativelibs4java/source/browse/#svn/trunk/lib... - -While this release is rather OpenCL4Java-focused, ScalaCL also got its bunch of enhancements : -- Added scalar variables IntVar, FloatVar, ShortVar... -- 'local' keyword can be added to variables so they're local to the programs : val x = FloatVar local -- Added many OpenCL math functions -- Added methods ArrayVar.write(Range), ArrayVar.write(Seq) -- Various bugfixes - diff --git a/libraries/OpenCL/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java b/libraries/OpenCL/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java deleted file mode 100644 index 33a54c41b..000000000 --- a/libraries/OpenCL/Contributions/Kazo Csaba/BinaryKernelTest - issue 30.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.util.NIOUtils.directBuffer; -import java.util.Map; -import static org.junit.Assert.assertEquals; - -import java.nio.IntBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author Kazó Csaba - */ -@SuppressWarnings("unchecked") -public class BinaryKernelTest extends AbstractCommon { - - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - - @Test - public void simpleTest() throws CLBuildException { - CLProgram program = context.createProgram( - "__kernel void copy(__global int* a, __global int* b) {\n" + - " int i = get_global_id(0);\n" + - " b[i]=a[i];\n" + - "} "); - program.build(); - Map binaries = program.getBinaries(); - program.release(); - - CLProgram binaryProgram = context.createProgram(binaries); - CLKernel kernel=binaryProgram.createKernel("copy"); - - CLIntBuffer a=context.createIntBuffer(CLMem.Usage.Input, 4); - CLIntBuffer b=context.createIntBuffer(CLMem.Usage.Output, 4); - - IntBuffer source = directBuffer(4, context.getByteOrder(), IntBuffer.class); - for (int i=0; i<4; i++) - source.put(i, 3*i+10); - - a.write(queue, source, true); - - kernel.setArgs(a, b); - kernel.enqueueNDRange(queue, new int[]{4}, new int[]{1}).waitFor(); - - IntBuffer target = b.read(queue); - - assertEquals(target.capacity(), source.capacity()); - for (int i=0; i<4; i++) - assertEquals(source.get(i), target.get(i)); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README b/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README deleted file mode 100644 index b156bfaac..000000000 --- a/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.README +++ /dev/null @@ -1,8 +0,0 @@ -See http://code.google.com/p/nativelibs4java/issues/detail?id=30 - -kazocsaba's first comment : -<<< -Certainly, I'm happy to contribute the patch under LGPL and BSD. - -Csaba ->>> diff --git a/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff b/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff deleted file mode 100644 index 3d25a7389..000000000 --- a/libraries/OpenCL/Contributions/Kazo Csaba/CreateBinaryProgram - issue 30.diff +++ /dev/null @@ -1,82 +0,0 @@ -Index: OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java -=================================================================== ---- OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java (revision 993) -+++ OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLContext.java (working copy) -@@ -64,6 +64,7 @@ - import com.sun.jna.Platform; - import com.sun.jna.Pointer; - import com.sun.jna.ptr.IntByReference; -+import java.util.Map; - - /** - * OpenCL context.
    -@@ -189,6 +190,10 @@ - return program; - } - -+ public CLProgram createProgram(Map binaries) { -+ return new CLProgram(this, binaries); -+ } -+ - //cl_queue queue; - @Override - protected void clear() { -Index: OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java -=================================================================== ---- OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java (revision 993) -+++ OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java (working copy) -@@ -47,6 +47,7 @@ - import com.sun.jna.Native; - import com.sun.jna.Pointer; - import com.sun.jna.ptr.IntByReference; -+import com.sun.jna.ptr.PointerByReference; - - /** - * OpenCL program.
    -@@ -83,7 +84,30 @@ - this.context = context; - this.devices = devices == null || devices.length == 0 ? context.getDevices() : devices; - } -+ CLProgram(CLContext context, Map binaries) { -+ super(null, true); -+ this.context = context; -+ this.devices = binaries.keySet().toArray(new CLDevice[binaries.size()]); - -+ NativeSize[] lengths = new NativeSize[devices.length]; -+ cl_device_id[] deviceIds = new cl_device_id[devices.length]; -+ String[] binptr=new String[devices.length]; -+ for (int i = 0; i < devices.length; i++) { -+ final byte[] binary = binaries.get(devices[i]); -+ lengths[i] = toNS(binary.length); -+ deviceIds[i] = devices[i].getEntity(); -+ binptr[i]=new String(binary); -+ } -+ -+ IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); -+ cl_program program; -+ int previousAttempts = 0; -+ do { -+ program = CL.clCreateProgramWithBinary(context.getEntity(), devices.length, deviceIds, lengths, binptr, null, errBuff); -+ } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); -+ entity = program; -+ } -+ - List sources = new ArrayList(); - Map programByDevice = new HashMap(); - -Index: OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java -=================================================================== ---- OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java (revision 993) -+++ OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java (working copy) -@@ -595,6 +595,11 @@ - * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    - * @see Khronos Documentation for clCreateProgramWithBinary - */ -+ OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSize size_tPtr1[], String[] charPtrPtr1, IntBuffer cl_intPtr1, IntBuffer cl_intPtr2); -+ /** -+ * Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*)
    -+ * @see Khronos Documentation for clCreateProgramWithBinary -+ */ - OpenCLLibrary.cl_program clCreateProgramWithBinary(OpenCLLibrary.cl_context cl_context1, int cl_uint1, OpenCLLibrary.cl_device_id cl_device_idPtr1[], NativeSizeByReference size_tPtr1, PointerByReference charPtrPtr1, IntByReference cl_intPtr1, IntByReference cl_intPtr2); - /** - * Original signature : cl_int clRetainProgram(cl_program)
    diff --git a/libraries/OpenCL/Core/.classpath b/libraries/OpenCL/Core/.classpath deleted file mode 100644 index 921941cea..000000000 --- a/libraries/OpenCL/Core/.classpath +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/.gitignore b/libraries/OpenCL/Core/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Core/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Core/.project b/libraries/OpenCL/Core/.project deleted file mode 100644 index 8004803d0..000000000 --- a/libraries/OpenCL/Core/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Core - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL/Core/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/Core/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 45a45b3f0..000000000 --- a/libraries/OpenCL/Core/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:18 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/Core/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/Core/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 1a131b4c8..000000000 --- a/libraries/OpenCL/Core/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:12 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/Core/javacl-core-bridj.iml b/libraries/OpenCL/Core/javacl-core-bridj.iml deleted file mode 100644 index 6e7ab88dd..000000000 --- a/libraries/OpenCL/Core/javacl-core-bridj.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/javacl-core.iml b/libraries/OpenCL/Core/javacl-core.iml deleted file mode 100644 index 58668dc8e..000000000 --- a/libraries/OpenCL/Core/javacl-core.iml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/nb-configuration.xml b/libraries/OpenCL/Core/nb-configuration.xml deleted file mode 100644 index 3486bc9d7..000000000 --- a/libraries/OpenCL/Core/nb-configuration.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - all - - diff --git a/libraries/OpenCL/Core/nbactions.xml b/libraries/OpenCL/Core/nbactions.xml deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL/Core/nbactions.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL/Core/pom.xml b/libraries/OpenCL/Core/pom.xml deleted file mode 100644 index 09f6fc220..000000000 --- a/libraries/OpenCL/Core/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-core - JavaCL Core / BridJ - http://code.google.com/p/javacl/ - jar - - - -JavaCL is an Object-Oriented API that makes the C OpenCL API available to Java in a very natural way. -It hides away the complexity of cross-platform C bindings, has a clean OO design (with generics, Java enums, NIO buffers, fully typed exceptions...), provides high-level features (OpenGL-interop, array reductions) and comes with samples and demos. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - opencl4java - - - com.nativelibs4java - nativelibs4java-utils - 1.5-SNAPSHOT - - - - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.4 - - - - - - - - com.nativelibs4java - maven-velocity-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/Header.vm b/libraries/OpenCL/Core/src/main/Header.vm deleted file mode 100644 index a46714b76..000000000 --- a/libraries/OpenCL/Core/src/main/Header.vm +++ /dev/null @@ -1,118 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2012, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -#macro (declareReusablePtrs) - ReusablePointers ptrs = ReusablePointers.get(); -#end - -#macro (declareEventsIn) - int[] eventsInCount = new int[1]; - Pointer eventsIn = - CLAbstractEntity.copyNonNullEntities(eventsToWaitFor, eventsInCount, ptrs.events_in); -#end - -#macro (declareEventOut) - Pointer eventOut = - eventsToWaitFor == null || CLEvent.containsFireAndForget(eventsToWaitFor) - ? null - : ptrs.event_out; -#end - -#macro (declareEventsOutBlockable) - Pointer eventOut = - blocking || eventsToWaitFor == null || CLEvent.containsFireAndForget(eventsToWaitFor) - ? null - : ptrs.event_out; -#end - -#macro (declarePErr) - Pointer pErr = ptrs.pErr; -#end - -#macro (declareReusablePtrsAndPErr) - #declareReusablePtrs() - #declarePErr() -#end - -#macro (checkPErr) - error(pErr.getInt()); -#end - -#macro (declareReusablePtrsAndEventsInOut) - #declareReusablePtrs() - #declareEventsIn() - #declareEventOut() -#end - -#macro (declareReusablePtrsAndEventsInOutBlockable) - #declareReusablePtrs() - #declareEventsIn() - #declareEventsOutBlockable() -#end - -#macro (eventOutArg) eventOut #end -#macro (eventOutArgRaw) getPeer(eventOut) #end - -#macro (eventsInArgsRaw) eventsInCount[0], getPeer(eventsIn) #end -#macro (eventsInArgs) eventsInCount[0], eventsIn #end - -#macro (eventsInOutArgsRaw) #eventsInArgsRaw(), #eventOutArgRaw() #end -#macro (eventsInOutArgs) #eventsInArgs(), #eventOutArg() #end - -#macro (eventOutWrapper $queue) CLEvent.createEventFromPointer($queue, eventOut) #end -#macro (returnEventOut $queue) return #eventOutWrapper($queue); #end - -#macro (declareInfosGetter $name $function) - protected static CLInfoGetter $name = new CLInfoGetter() { - @Override - protected int getInfo(long entity, int infoTypeEnum, long size, Pointer out, Pointer sizeOut) { - return $function(entity, infoTypeEnum, size, getPeer(out), getPeer(sizeOut)); - } - }; -#end - -#macro (documentEventsToWaitFor) - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. Special value {@link CLEvent#FIRE_AND_FORGET} can be used to avoid returning a CLEvent. -#end - -#macro (documentEventsToWaitForAndReturn) -#documentEventsToWaitFor() - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete, or null if eventsToWaitFor contains {@link CLEvent#FIRE_AND_FORGET}. -#end - -#macro (documentEventsToWaitForAndPairReturn $firstContent) -#documentEventsToWaitFor() - * @return Pair with $firstContent and event object that identifies this command and can be used to query or queue a wait for the command to complete, or null if eventsToWaitFor contains {@link CLEvent#FIRE_AND_FORGET}. -#end - -#macro (documentCallsFunction $functionName) - * Calls $functionName.
    -#end - diff --git a/libraries/OpenCL/Core/src/main/java/com/ochafik/util/string/StringUtils.java b/libraries/OpenCL/Core/src/main/java/com/ochafik/util/string/StringUtils.java deleted file mode 100644 index 9dbe70e9c..000000000 --- a/libraries/OpenCL/Core/src/main/java/com/ochafik/util/string/StringUtils.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util.string; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -public class StringUtils { - public static String htmlize(String text) { - return text.startsWith("") ? - text : ""+ - text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\n","
    ")+ - ""; - } - - static Pattern spacePattern; - public static List explode(String s) { - if (spacePattern == null) { - spacePattern = Pattern.compile("\\s+"); - } - return explode(s, spacePattern); - } - public static List explode(String s, String sep) { - StringTokenizer st=new StringTokenizer(s,sep); - List v = new ArrayList(); - for (;st.hasMoreTokens();) { - v.add(st.nextToken()); - } - return v; - } - -/* - public static final String implode(Object[] strings, String separator) { - return implode(Arrays.asList(strings), separator); - } -*/ - public static String implode(double[] array, String separator) { - StringBuffer out = new StringBuffer(); - boolean first = true; - for (double v : array) { - if (first) first = false; - else out.append(separator); - out.append(v); - } - return out.toString(); - } - - public static String implode(Object[] values) { - return implode(values, ", "); - } - public static String implode(Object[] values, Object separator) { - return implode(Arrays.asList(values), separator); - } - public static final String implode(Iterable elements, Object separator) { - String sepStr = separator.toString(); - StringBuilder out = new StringBuilder(); - boolean first = true; - for (Object s : elements) { - if (s == null) - continue; - - if (first) - first = false; - else - out.append(sepStr); - out.append(s); - } - return out.toString(); - } - public static final String implode(Iterable strings) { - return implode(strings, ", "); - } - /* - public static final String implode(Collection strings, String separator) { - int size = 0, n = strings.size(); - for (Object s : strings) - if (s != null) - size += s.toString().length(); - - StringBuffer out = new StringBuffer(size + separator.length() * (n == 0 ? 0 : n - 1)); - boolean first = true; - for (Object s : strings) { - if (s == null) - continue; - - if (first) first = false; - else out.append(separator); - out.append(s); - } - return out.toString(); - } - */ - public static final List explode(String string, Pattern separator) { - int lastIndex = 0, len = string.length(); - - Matcher matcher = separator.matcher(string); - List ret = new LinkedList(); - - while (matcher.find()) { - String s = string.substring(lastIndex, matcher.start()); - if (s.length() > 0) ret.add(s); - lastIndex = matcher.end(); - } - String s = string.substring(lastIndex, len); - if (s.length() > 0) ret.add(s); - - return ret; - } - - public static String replace(String pattern, String replace, String s) { - return concatWithSeparator(explode(s,pattern).toArray(new String[0]),replace); - } - public static final String concat(String[] a) { - StringBuffer b=new StringBuffer(); - for (int i=0;i127||Character.isISOControl(c)) { - b.append("\\u"); - String nb=Integer.toString((int)c,16); - int nblen=nb.length(); - switch (nblen) { - case 1: - b.append(0); - case 2: - b.append(0); - case 3: - b.append(0); - case 4: - b.append(nb); - break; - default: - throw new IllegalArgumentException("Should not happen !"); - } - } else b.append(c); - } - } - return b.toString(); - } - public static final String javaUnEscape(String s) { - char c; - int len=s.length(); - StringBuffer b=new StringBuffer(len); - for (int i=0;i strings, String separator) { - List cap = new ArrayList(strings.size()); - for (String s : strings) - cap.add(capitalize(s)); - return implode(cap, separator); - } - - public static String uncapitalize(String string) { - return string.length() == 0 ? "" : Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - public static final String LINE_SEPARATOR; - static { - LINE_SEPARATOR = System.getProperty("line.separator"); - } - -} diff --git a/libraries/OpenCL/Core/src/main/javadoc/overview.html b/libraries/OpenCL/Core/src/main/javadoc/overview.html deleted file mode 100644 index 03e8f3de8..000000000 --- a/libraries/OpenCL/Core/src/main/javadoc/overview.html +++ /dev/null @@ -1,75 +0,0 @@ - - - -

    -JavaCL is an Object-Oriented API that wraps the OpenCL API.
    -It makes it easy to do cross-platform GPGPU with Java. -

    - -

    -Core classes : -

      -
    • JavaCL: entry point of JavaCL, useful to list platforms, create contexts. -
    • CLContext: all the JavaCL data and programs must be created from a context instance. -
    • CLQueue: OpenCL operations can be executed immediately or queued. A queue instance is however needed even for immediate operations. -
    • CLMem: base class for buffers and 2D and 3D images. -
    • -

      - -

      -JavaCL relies on OpenCL4Java, low-level bindings that closely match the OpenCL C API and use JNA+JNAerator for the native access interop. -

      - -

      -Here's a very simple vector addition JavaCL program : -

      package com.nativelibs4java.opencl.demos.vectoradd;
      -import com.nativelibs4java.opencl.*;
      -import java.nio.*;
      -
      -public class VectorAdd {
      -
      -    public static void main(String[] args) {
      -        try {
      -            FloatBuffer a = FloatBuffer.wrap(new float[] {  1,  2,  3,  4 });
      -            FloatBuffer b = FloatBuffer.wrap(new float[] { 10, 20, 30, 40 });
      -
      -            FloatBuffer sum = add(a, b);
      -            for (int i = 0, n = sum.capacity(); i < n; i++)
      -                System.out.println(sum.get(i));
      -        } catch (Exception ex) {
      -            ex.printStackTrace();
      -        }
      -    }
      -
      -    public static FloatBuffer add(FloatBuffer a, FloatBuffer b) throws CLBuildException {
      -        int n = a.capacity();
      -        
      -        CLContext context = JavaCL.createBestContext();
      -        CLQueue queue = context.createDefaultQueue();
      -        
      -        String source = 
      -            "__kernel void addFloats(__global const float* a, __global const float* b, __global float* output)     " +
      -            "{                                                                                                     " +
      -            "   int i = get_global_id(0);                                                                          " +
      -            "   output[i] = a[i] + b[i];                                                                           " +
      -            "}                                                                                                     ";
      -        
      -        CLKernel kernel = context.createProgram(source).createKernel("addFloats");
      -        CLFloatBuffer aBuf = context.createFloatBuffer(CLMem.Usage.Input, a, true);
      -        CLFloatBuffer bBuf = context.createFloatBuffer(CLMem.Usage.Input, b, true);
      -        CLFloatBuffer outBuf = context.createFloatBuffer(CLMem.Usage.Output, n);
      -        kernel.setArgs(aBuf, bBuf, outBuf);
      -        
      -        kernel.enqueueNDRange(queue, new int[]{n}, new int[] { 1 });
      -        queue.finish();
      -    
      -        return outBuf.read(queue);
      -    }
      -}
      -
      -
      - -

      - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/HardwareReport.jnlp b/libraries/OpenCL/Core/src/main/jnlp/HardwareReport.jnlp deleted file mode 100644 index 795dff741..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/HardwareReport.jnlp +++ /dev/null @@ -1,35 +0,0 @@ - - - - JavaCL-BridJ HardwareReport - Olivier Chafik - - JavaCL-BridJ HardwareReport - JavaCL-BridJ HardwareReport - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp b/libraries/OpenCL/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp deleted file mode 100644 index fc5047bcd..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/InteractiveImageTransformDemo.jnlp +++ /dev/null @@ -1,28 +0,0 @@ - - - - JavaCL-BridJ Interactive Image Transform Demo - Olivier Chafik - - Image Transform Kernel Editor + Demos for JavaCL-BridJ (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/JavaCL.jnlp b/libraries/OpenCL/Core/src/main/jnlp/JavaCL.jnlp deleted file mode 100644 index 4f73d549c..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/JavaCL.jnlp +++ /dev/null @@ -1,25 +0,0 @@ - - - - JavaCL-BridJ - Olivier Chafik - - Object-Oriented OpenCL-BridJ Library for Java - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/MandelbrotDemo.jnlp b/libraries/OpenCL/Core/src/main/jnlp/MandelbrotDemo.jnlp deleted file mode 100644 index b7f3aa965..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/MandelbrotDemo.jnlp +++ /dev/null @@ -1,33 +0,0 @@ - - - - JavaCL-BridJ Mandelbrot Demos - Olivier Chafik (demo adapted from Bob Boothby's) - - Mandelbrot Demo for JavaCL-BridJ (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/OpenCL4Java.jnlp b/libraries/OpenCL/Core/src/main/jnlp/OpenCL4Java.jnlp deleted file mode 100644 index d01b6a175..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/OpenCL4Java.jnlp +++ /dev/null @@ -1,24 +0,0 @@ - - - - OpenCL4Java-BridJ - Olivier Chafik - - OpenCL-BridJ bindings for Java - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/ParticlesDemo.jnlp b/libraries/OpenCL/Core/src/main/jnlp/ParticlesDemo.jnlp deleted file mode 100644 index f9f4a5208..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/ParticlesDemo.jnlp +++ /dev/null @@ -1,30 +0,0 @@ - - - - JavaCL-BridJ Particles Demos - Olivier Chafik - - Demos for JavaCL (Object-Oriented OpenCL Library for Java) - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/jnlp/ScalaCL.jnlp b/libraries/OpenCL/Core/src/main/jnlp/ScalaCL.jnlp deleted file mode 100644 index 20b7d9da5..000000000 --- a/libraries/OpenCL/Core/src/main/jnlp/ScalaCL.jnlp +++ /dev/null @@ -1,22 +0,0 @@ - - - - ScalaCL - Olivier Chafik - - OpenCL for Scala: natural DSL and Object-Oriented API - - - - - - - - - - - - diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ByteOrderHack.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ByteOrderHack.java deleted file mode 100644 index 57f3f98e7..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ByteOrderHack.java +++ /dev/null @@ -1,106 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; - -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import org.bridj.*; -import static org.bridj.Pointer.*; - -import java.io.IOException; -import java.nio.*; -import static com.nativelibs4java.opencl.JavaCL.*; -import static com.nativelibs4java.util.NIOUtils.*; -import java.util.*; -import static com.nativelibs4java.opencl.CLException.*; -import org.bridj.ValuedEnum; -import java.util.logging.Level; -import java.util.logging.Logger; - -class ByteOrderHack { - public static final boolean hackEnabled = - "1".equals(System.getenv("JAVACL_GUESS_ENDIANNESS")) || - "true".equals(System.getProperty("javacl.guessEndianness")); - public static ByteOrder guessByteOrderNeededForBuffers(CLDevice device) { - CLPlatform platform = device.getPlatform(); - PlatformUtils.PlatformKind knownPlatform = PlatformUtils.guessPlatformKind(platform); - if (!hackEnabled || knownPlatform != PlatformUtils.PlatformKind.AMDApp) - return device.getByteOrder(); - else - return checkByteOrderNeededForBuffers(device); - } - public static ByteOrder checkByteOrderNeededForBuffers(CLDevice device) { - CLContext context = JavaCL.createContext((Map)null, device); - CLQueue queue = context.createDefaultQueue(); - try { - int n = 16; - String testValueStr = "123456789f";//.101112f"; - float testValue = Float.parseFloat(testValueStr); - final int BIG_INDEX = 0, LITTLE_INDEX = 1; - - Pointer inPtr = Pointer.allocateFloats(n); - inPtr.order(ByteOrder.BIG_ENDIAN).set(BIG_INDEX, testValue); - inPtr.order(ByteOrder.LITTLE_ENDIAN).set(LITTLE_INDEX, testValue); - - CLBuffer inOut = context.createFloatBuffer(CLMem.Usage.InputOutput, inPtr); - CLBuffer success = context.createIntBuffer(CLMem.Usage.Output, n); - - String src = - "__kernel void compare_endiannesses(__global float *inout, __global int *success) {\n" + - "size_t i = get_global_id(0);\n" + - "success[i] = (inout[i] == " + testValueStr + ");\n" + - "inout[i] = " + testValueStr + ";\n" + - "}"; - - CLKernel test = context.createProgram(src).createKernel("compare_endiannesses"); - test.setArgs(inOut, success); - test.enqueueNDRange(queue, new int[] { n }, new int[] { 1 }); - - Pointer successPtr = Pointer.allocateInts(n); - success.read(queue, successPtr, true); - Pointer outPtr = Pointer.allocateFloats(n); - inOut.read(queue, outPtr, true); - - boolean bigOk = successPtr.get(BIG_INDEX) != 0; - boolean littleOk = successPtr.get(LITTLE_INDEX) != 0; - - int index, otherIndex; - ByteOrder order, otherOrder; - if (bigOk) { - order = ByteOrder.BIG_ENDIAN; - index = BIG_INDEX; - otherOrder = ByteOrder.LITTLE_ENDIAN; - otherIndex = LITTLE_INDEX; - } else { - order = ByteOrder.LITTLE_ENDIAN; - index = LITTLE_INDEX; - otherOrder = ByteOrder.BIG_ENDIAN; - otherIndex = BIG_INDEX; - } - float value = outPtr.order(order).get(index); - float otherValue = outPtr.order(otherOrder).get(otherIndex); - - if (JavaCL.debug) - System.out.println("[" + device + "] Endianness test: bigOk = " + bigOk + ", littleOk = " + littleOk + "; value = " + value + ", otherValue = " + otherValue); - - if (!(bigOk ^ littleOk)) - throw new RuntimeException("[" + device + "] Endianness check failed, kernel recognized both endiannesses..."); - - { - if (value != testValue || otherValue == testValue) - throw new RuntimeException("[" + device + "] Endianness double-check failed, expected " + testValue + " and found " + value + " instead for endianness " + order + " (otherValue = " + otherValue + " for " + otherOrder + ")"); - - return order; - } - } catch (Throwable ex) { - throw new RuntimeException("[" + device + "] Endianness check failed: " + ex, ex); - } finally { - queue.release(); - context.release(); - } - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractEntity.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractEntity.java deleted file mode 100644 index 39af06634..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractEntity.java +++ /dev/null @@ -1,124 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import org.bridj.*; -import static org.bridj.Pointer.*; - -abstract class CLAbstractEntity { - private long entityPeer; - private final boolean nullable; - - protected CLAbstractEntity(long entityPeer) { - this(entityPeer, false); - } - - protected CLAbstractEntity(long entityPeer, boolean nullable) { - this.nullable = nullable; - this.entityPeer = entityPeer; - checkNullity(entityPeer); - } - - private void checkNullity(long entityPeer) { - if (!nullable && entityPeer == 0) { - throw new IllegalArgumentException("Null OpenCL " + getClass().getSimpleName() + " !"); - } - } - - protected void setEntity(long entityPeer) { - checkNullity(entityPeer); - this.entityPeer = entityPeer; - } - - static Pointer copyNonNullEntities(CLAbstractEntity[] entities, int[] countOut, ReusablePointer tmp) { - int n; - if (entities == null || (n = entities.length) == 0) { - countOut[0] = 0; - return null; - } - Pointer out = null; - - int count = 0; - for (int i = 0; i < n; i++) { - CLAbstractEntity entity = entities[i]; - if (entity != null && entity != CLEvent.FIRE_AND_FORGET) { - long pointer = entity.getEntity(); - if (pointer != 0) { - if (out == null) - out = tmp.allocatedBytes(Pointer.SIZE * (n - i)); - - out.setSizeTAtOffset(Pointer.SIZE * count, pointer); - - count++; - } - } - } - countOut[0] = count; - return out; - } - - /** - * Manual release of the OpenCL resources represented by this object.
      - * Note that resources are automatically released by the garbage collector, so in general there's no need to call this method.
      - * In an environment with fast allocation/deallocation of large objects, it might be safer to call release() manually, though.
      - * Note that release() does not necessarily free the object immediately : OpenCL maintains a reference count for all its objects, and an object released on the Java side might still be pointed to by running kernels or queued operations. - */ - public synchronized void release() { - if (entityPeer == 0) { - if (!nullable) - throw new RuntimeException("This " + getClass().getSimpleName() + " has already been released ! Besides, keep in mind that manual release is not necessary, as it will automatically be done by the garbage collector."); - else - return; - } - - doRelease(); - } - - public static Pointer getEntities(A[] objects, Pointer out) { - for (int i = 0, len = objects.length; i < len; i++) - out.setSizeTAtOffset(i * Pointer.SIZE, objects[i].getEntity()); - return out; - } - private void checkNullity() { - if (entityPeer == 0 && !nullable) - throw new RuntimeException("This " + getClass().getSimpleName() + " has been manually released and can't be used anymore !"); - } - - synchronized long getEntity() { - checkNullity(); - return entityPeer; - } - - synchronized void doRelease() { - if (entityPeer != 0) { - clear(); - entityPeer = 0; - } - } - @Override - protected void finalize() throws Throwable { - doRelease(); - } - - protected abstract void clear(); - - /** - * Underyling implementation pointer-based hashCode computation - */ - @Override - public int hashCode() { - return entityPeer == 0 - ? 0 - : Long.valueOf(entityPeer).hashCode(); - } - - /** - * Underyling implementation pointer-based equality test - */ - @Override - public boolean equals(Object obj) { - if (!getClass().isInstance(obj)) - return false; - CLAbstractEntity e = (CLAbstractEntity)obj; - return getEntity() == e.getEntity(); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractUserProgram.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractUserProgram.java deleted file mode 100644 index f4138a62f..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLAbstractUserProgram.java +++ /dev/null @@ -1,97 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.nativelibs4java.util.IOUtils; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.lang.reflect.Array; - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -/** - * - * @author ochafik - */ -public abstract class CLAbstractUserProgram { - - final CLProgram program; - String rawSource; - Map velocityArgs; - - volatile boolean addedSources; - - protected Long getSourceChecksum() { - return null; - } - - public CLProgram getProgram() { - return program; - } - - protected void checkArrayLength(Object arr, int length, String argName) { - if (arr == null) - throw new IllegalArgumentException("Argument " + argName + " cannot be null. Expected array of size " + length); - - int len = Array.getLength(arr); - if (len != length) - throw new IllegalArgumentException("Argument " + argName + " must be an array of size " + length + ", but given array of size " + len); - } - protected static String readRawSourceForClass(Class c) throws IOException { - String simpleName = c.getSimpleName(); - - InputStream srcIn = c.getResourceAsStream(simpleName + ".cl"); - try { - if (srcIn == null) - srcIn = c.getResourceAsStream(simpleName + ".c"); - - if (srcIn == null) - throw new FileNotFoundException("OpenCL source code not found : '" + simpleName + "'"); - - return IOUtils.readText(srcIn); - } finally { - if (srcIn != null) - srcIn.close(); - } - } - protected CLAbstractUserProgram(CLProgram program, String rawSource) { - this.program = program; - this.rawSource = rawSource; - } - - protected CLAbstractUserProgram(CLContext context, String rawSource) { - this(context.createProgram(), rawSource); - } - - protected synchronized void addSources() { - if (addedSources) { - return; - } - - String src; - if (velocityArgs != null) { - src = rawSource;//veloTransform(rawSource, velocityArgs); - } else { - src = rawSource; - } - - program.addSource(src); - addedSources = true; - } - - protected void defineMacro(String name, String value) { - if (value == null) { - program.undefineMacro(name); - } else { - program.defineMacro(name, value); - } - } - - protected synchronized CLKernel createKernel(String name) throws CLBuildException { - addSources(); - return program.createKernel(name); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java deleted file mode 100644 index ccd45658c..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuffer.java +++ /dev/null @@ -1,411 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import com.nativelibs4java.util.Pair; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import static com.nativelibs4java.util.NIOUtils.directBytes; -import static com.nativelibs4java.util.NIOUtils.directCopy; - -import java.nio.ByteBuffer; - -import com.nativelibs4java.opencl.library.cl_buffer_region; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import org.bridj.*; -import java.nio.ByteOrder; -import java.nio.Buffer; -import com.nativelibs4java.util.NIOUtils; -import org.bridj.util.Utils; -import static org.bridj.Pointer.*; - - -/** - * OpenCL Memory Buffer Object.
      - * A buffer object stores a one-dimensional collection of elements.
      - * Elements of a buffer object can be a scalar data type (such as an int, float), vector data type, or a user-defined structure.
      - * @see CLContext - * @author Olivier Chafik - */ -public class CLBuffer extends CLMem { - final Object owner; - final PointerIO io; - - CLBuffer(CLContext context, long byteCount, long entityPeer, Object owner, PointerIO io) { - super(context, byteCount, entityPeer); - this.owner = owner; - this.io = io; - } - - public Class getElementClass() { - return Utils.getClass(io.getTargetType()); - } - public int getElementSize() { - return (int)io.getTargetSize(); - } - public long getElementCount() { - return getByteCount() / getElementSize(); - } - /** -#documentCallsFunction("clEnqueueMapBuffer") - */ - public Pointer map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, 0, getElementCount(), true, eventsToWaitFor).getFirst(); - } - /** -#documentCallsFunction("clEnqueueMapBuffer") - */ - public Pointer map(CLQueue queue, MapFlags flags, long offset, long length, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, offset, length, true, eventsToWaitFor).getFirst(); - } - - /** -#documentCallsFunction("clEnqueueMapBuffer") - */ - public Pair, CLEvent> mapLater(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, 0, getElementCount(), false, eventsToWaitFor); - } - /** -#documentCallsFunction("clEnqueueMapBuffer") - */ - public Pair, CLEvent> mapLater(CLQueue queue, MapFlags flags, long offset, long length, CLEvent... eventsToWaitFor) throws CLException.MapFailure { - return map(queue, flags, offset, length, false, eventsToWaitFor); - } - - /** - * Returns a pointer to native memory large enough for this buffer's data, and with a compatible byte ordering. - */ - public Pointer allocateCompatibleMemory(CLDevice device) { - return allocateArray(io, getElementCount()).order(device.getKernelsDefaultByteOrder()); - } - - public PointerIO getIO() { - return io; - } - - /** -#documentCallsFunction("clEnqueueReadBuffer") - */ - public Pointer read(CLQueue queue, CLEvent... eventsToWaitFor) { - Pointer out = allocateCompatibleMemory(queue.getDevice()); - read(queue, out, true, eventsToWaitFor); - return out; - } - /** -#documentCallsFunction("clEnqueueReadBuffer") - */ - public Pointer read(CLQueue queue, long offset, long length, CLEvent... eventsToWaitFor) { - Pointer out = allocateCompatibleMemory(queue.getDevice()); - read(queue, offset, length, out, true, eventsToWaitFor); - return out; - } - - protected void checkBounds(long offset, long length) { - if (offset + length * getElementSize() > getByteCount()) - throw new IndexOutOfBoundsException("Trying to map a region of memory object outside allocated range"); - } - - /** -#documentCallsFunction("clCreateSubBuffer") - * Can be used to create a new buffer object (referred to as a sub-buffer object) from an existing buffer object. - * @param usage is used to specify allocation and usage information about the image memory object being created and is described in table 5.3 of the OpenCL spec. - * @param offset - * @param length - * @since OpenCL 1.1 - * @return sub-buffer that is a "window" of this buffer starting at the provided offset, with the provided length - */ - public CLBuffer createSubBuffer(Usage usage, long offset, long length) { - try { - int s = getElementSize(); - cl_buffer_region region = new cl_buffer_region().origin(s * offset).size(s * length); - #declareReusablePtrsAndPErr() - long mem = CL.clCreateSubBuffer(getEntity(), usage.getIntFlags(), CL_BUFFER_CREATE_TYPE_REGION, getPeer(pointerTo(region)), getPeer(pErr)); - #checkPErr() - return mem == 0 ? null : new CLBuffer(context, length * s, mem, null, io); - } catch (Throwable th) { - // TODO check if supposed to handle OpenCL 1.1 - throw new UnsupportedOperationException("Cannot create sub-buffer (OpenCL 1.1 feature).", th); - } - } - - /** - * enqueues a command to copy a buffer object identified by src_buffer to another buffer object identified by destination. - * @param destination -#documentEventsToWaitForAndReturn() - */ - public CLEvent copyTo(CLQueue queue, CLMem destination, CLEvent... eventsToWaitFor) { - return copyTo(queue, 0, getElementCount(), destination, 0, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueCopyBuffer") - * enqueues a command to copy a buffer object identified by src_buffer to another buffer object identified by destination. - * @param queue - * @param srcOffset - * @param length - * @param destination - * @param destOffset -#documentEventsToWaitForAndReturn() - */ - public CLEvent copyTo(CLQueue queue, long srcOffset, long length, CLMem destination, long destOffset, CLEvent... eventsToWaitFor) { - long - byteCount = getByteCount(), - destByteCount = destination.getByteCount(), - eltSize = getElementSize(), - actualSrcOffset = srcOffset * eltSize, - actualDestOffset = destOffset * eltSize, - actualLength = length * eltSize; - - if ( actualSrcOffset < 0 || - actualSrcOffset >= byteCount || - actualSrcOffset + actualLength > byteCount || - actualDestOffset < 0 || - actualDestOffset >= destByteCount || - actualDestOffset + actualLength > destByteCount - ) - throw new IndexOutOfBoundsException("Invalid copy parameters : srcOffset = " + srcOffset + ", destOffset = " + destOffset + ", length = " + length + " (element size = " + eltSize + ", source byte count = " + byteCount + ", destination byte count = " + destByteCount + ")"); - - #declareReusablePtrsAndEventsInOut() - error(CL.clEnqueueCopyBuffer( - queue.getEntity(), - getEntity(), - destination.getEntity(), - actualSrcOffset, - actualDestOffset, - actualLength, - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueMapBuffer") - */ - protected Pair, CLEvent> map(CLQueue queue, MapFlags flags, long offset, long length, boolean blocking, CLEvent... eventsToWaitFor) { - checkBounds(offset, length); - #declareReusablePtrsAndEventsInOutBlockable() - #declarePErr() - long mappedPeer = CL.clEnqueueMapBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - flags.value(), - offset * getElementSize(), - length * getElementSize(), - #eventsInOutArgsRaw(), - getPeer(pErr) - ); - #checkPErr() - if (mappedPeer == 0) - return null; - return new Pair, CLEvent>( - pointerToAddress(mappedPeer, io).validElements(length).order(queue.getDevice().getKernelsDefaultByteOrder()), - #eventOutWrapper("queue") - ); - } - - /** -#documentCallsFunction("clEnqueueUnmapMemObject") - */ - public CLEvent unmap(CLQueue queue, Pointer buffer, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOut(); - error(CL.clEnqueueUnmapMemObject(queue.getEntity(), getEntity(), getPeer(buffer), #eventsInOutArgsRaw())); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueReadBuffer") - * @deprecated use {@link CLBuffer#read(CLQueue, Pointer, boolean, CLEvent[])} instead - */ - @Deprecated - public CLEvent read(CLQueue queue, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, 0, -1, out, blocking, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueReadBuffer") - */ - public CLEvent read(CLQueue queue, Pointer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, 0, -1, out, blocking, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueReadBuffer") - * @deprecated use {@link CLBuffer#read(CLQueue, long, long, Pointer, boolean, CLEvent[])} instead - */ - @Deprecated - public CLEvent read(CLQueue queue, long offset, long length, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - if (out == null) - throw new IllegalArgumentException("Null output buffer !"); - - if (out.isReadOnly()) - throw new IllegalArgumentException("Output buffer for read operation is read-only !"); - boolean indirect = !out.isDirect(); - Pointer ptr = null; - if (indirect) { - ptr = allocateArray(io, length).order(queue.getDevice().getKernelsDefaultByteOrder()); - blocking = true; - } else { - ptr = (Pointer)pointerToBuffer(out); - } - CLEvent ret = read(queue, offset, length, ptr, blocking, eventsToWaitFor); - if (indirect) - NIOUtils.put(ptr.getBuffer(), out); - - return ret; - } - - /** -#documentCallsFunction("clEnqueueReadBuffer") - */ - public CLEvent read(CLQueue queue, long offset, long length, Pointer out, boolean blocking, CLEvent... eventsToWaitFor) { - if (out == null) - throw new IllegalArgumentException("Null output pointer !"); - - if (length < 0) { - if (isGL) { - length = out.getValidElements(); - } - if (length < 0) { - length = getElementCount(); - long s = out.getValidElements(); - if (length > s && s >= 0) - length = s; - } - } - - #declareReusablePtrsAndEventsInOutBlockable() - error(CL.clEnqueueReadBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : 0, - offset * getElementSize(), - length * getElementSize(), - getPeer(out), - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueWriteBuffer") - * @deprecated use {@link CLBuffer#write(CLQueue, Pointer, boolean, CLEvent[])} instead - */ - @Deprecated - public CLEvent write(CLQueue queue, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, 0, -1, in, blocking, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueWriteBuffer") - */ - public CLEvent write(CLQueue queue, Pointer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, 0, -1, in, blocking, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueWriteBuffer") - * @deprecated use {@link CLBuffer#write(CLQueue, long, long, Pointer, boolean, CLEvent[])} instead - */ - @Deprecated - public CLEvent write(CLQueue queue, long offset, long length, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - if (in == null) - throw new IllegalArgumentException("Null input buffer !"); - - boolean indirect = !in.isDirect(); - Pointer ptr = null; - if (indirect) { - ptr = allocateArray(io, length).order(queue.getDevice().getKernelsDefaultByteOrder()); - ptr.setValues(in); - blocking = true; - } else { - ptr = (Pointer)pointerToBuffer(in); - } - return write(queue, offset, length, ptr, blocking, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueWriteBuffer") - */ - public CLEvent write(CLQueue queue, long offset, long length, Pointer in, boolean blocking, CLEvent... eventsToWaitFor) { - if (length == 0) - return null; - - if (in == null) - throw new IllegalArgumentException("Null input pointer !"); - - if (length < 0) { - if (isGL) - length = in.getValidElements(); - if (length < 0) { - length = getElementCount(); - long s = in.getValidElements(); - if (length > s && s >= 0) - length = s; - } - } - - #declareReusablePtrsAndEventsInOutBlockable() - error(CL.clEnqueueWriteBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - offset * getElementSize(), - length * getElementSize(), - getPeer(in), - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueWriteBuffer") - */ - public CLEvent writeBytes(CLQueue queue, long offset, long length, ByteBuffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return writeBytes(queue, offset, length, pointerToBuffer(in), blocking, eventsToWaitFor); - } - /** -#documentCallsFunction("clEnqueueWriteBuffer") - */ - public CLEvent writeBytes(CLQueue queue, long offset, long length, Pointer in, boolean blocking, CLEvent... eventsToWaitFor) { - if (in == null) - throw new IllegalArgumentException("Null input pointer !"); - - #declareReusablePtrsAndEventsInOutBlockable() - error(CL.clEnqueueWriteBuffer( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : 0, - offset, - length, - getPeer(in), - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - private T copyGLMark(T mem) { - mem.isGL = this.isGL; - return mem; - } - - public CLBuffer emptyClone(CLMem.Usage usage) { - return (CLBuffer)getContext().createBuffer(usage, io, getElementCount()); - } - - #foreach ($prim in $primitivesNoBool) - - public CLBuffer<${prim.WrapperName}> asCL${prim.BufferName}() { - return as(${prim.WrapperName}.class); - } - - #end - - public CLBuffer as(Class newTargetType) { - long mem = getEntity(); - error(CL.clRetainMemObject(mem)); - PointerIO newIO = PointerIO.getInstance(newTargetType); - return copyGLMark(new CLBuffer(context, getByteCount(), mem, owner, newIO)); - } - -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuildException.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuildException.java deleted file mode 100644 index 423ef2080..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLBuildException.java +++ /dev/null @@ -1,21 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.ochafik.util.string.StringUtils; -import java.util.Collection; - -/** - * OpenCL program build exception - * @author ochafik - */ -@SuppressWarnings("serial") -public class CLBuildException extends CLException { - final CLProgram program; - CLBuildException(CLProgram program, String string, Collection errors) { - super(string + "\n" + StringUtils.implode(errors, "\n"), -1); - this.program = program; - } - public CLProgram getProgram() { - return program; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java deleted file mode 100644 index b51302d3a..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLContext.java +++ /dev/null @@ -1,816 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import com.nativelibs4java.util.Pair; - -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.CLException.failedForLackOfMemory; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import static com.nativelibs4java.util.ImageUtils.getImageIntPixels; -import static com.nativelibs4java.util.NIOUtils.getSizeInBytes; - -import java.awt.Image; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicReference; -import java.util.List; -import java.util.logging.*; - -import com.nativelibs4java.opencl.CLDevice.QueueProperties; -import com.nativelibs4java.opencl.CLSampler.AddressingMode; -import com.nativelibs4java.opencl.CLSampler.FilterMode; -import com.nativelibs4java.opencl.ImageIOUtils.ImageInfo; -import com.nativelibs4java.opencl.library.OpenGLContextUtils; -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_context; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_sampler; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.util.NIOUtils; -import org.bridj.*; -import static org.bridj.Pointer.*; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Map; - - -/** - * OpenCL context.
      - * An OpenCL context is created with one or more devices.
      - * Contexts are used by the OpenCL runtime for managing objects such as command-queues, memory, program and kernel objects and for executing kernels on one or more devices specified in the context. - * @author Olivier Chafik - */ -public class CLContext extends CLAbstractEntity { - -#macro (docCreateBufferCopy $bufferType $details) - /** -#documentCallsFunction("clCreateBuffer") - * Create a $bufferType OpenCL buffer $details with the provided initial values.
      - * If copy is true (see CL_MEM_COPY_HOST_PTR), then the buffer will be hosted in OpenCL and will have the best performance, but any change done to the OpenCL buffer won't be propagated to the original data pointer.
      - * If copy is false (see CL_MEM_USE_HOST_PTR), then the provided data pointer will be used for storage of the OpenCL buffer. OpenCL might still cache the data in the OpenCL land, so careful use of {@link CLBuffer#map(CLQueue, CLMem.MapFlags, CLEvent...) CLBuffer#map(CLQueue, MapFlags, CLEvent...)} is then necessary to ensure the data is properly synchronized with the buffer. - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - * @param data Pointer to the initial values, must have known bounds (see {@link Pointer#getValidElements()}). - */ -#end -#macro (docCreateBuffer $bufferType $type $insertParam $exampleOfLength) - /** -#documentCallsFunction("clCreateBuffer") - * Create a $bufferType OpenCL buffer big enough to hold 'length' values of type $type. - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - $insertParam - * @param elementCount Length of the buffer expressed in elements $exampleOfLength - */ -#end -#macro (docCreateBufferPrim $bufferType $prim) -#docCreateBuffer($bufferType, $prim.Name, "", "(for instance, a $bufferType of length 10 will actually contain 10 * ${prim.Size} bytes, as ${prim.Name}s are ${prim.Size}-bytes-long)") -#end - - private final AtomicReference> propertiesMapRef = - new AtomicReference>(); - - public Object getClientProperty(Object key) { - ConcurrentHashMap propertiesMap = propertiesMapRef.get(); - return propertiesMap == null ? null : propertiesMap.get(key); - } - public Object putClientProperty(Object key, Object value) { - ConcurrentHashMap propertiesMap = propertiesMapRef.get(); - if (propertiesMap == null) { - propertiesMap = new ConcurrentHashMap(); - if (!propertiesMapRef.compareAndSet(null, propertiesMap)) - propertiesMap = propertiesMapRef.get(); - } - return propertiesMap.put(key, value); - } - - private volatile long maxMemAllocSize = -1; - - /** - * Max size of memory object allocation in bytes. The minimum value is max (1/4th of CL_DEVICE_GLOBAL_MEM_SIZE , 128*1024*1024) - */ - public long getMaxMemAllocSize() { - if (maxMemAllocSize < 0) { - long min = Long.MAX_VALUE; - for (CLDevice device : getDevices()) { - long m = device.getMaxMemAllocSize(); - if (m < min) - min = m; - } - maxMemAllocSize = min; - } - return maxMemAllocSize; - } - - volatile Boolean cacheBinaries; - - /** - * Change whether program binaries are automatically cached or not.
      - * By default it is true, it can be set to false with the "javacl.cacheBinaries" Java property or the "JAVACL_CACHE_BINARIES" environment variable (when set to "0").
      - * Each program can be set to be cached or not using {@link CLProgram#setCached(boolean) }.
      - * Caching of binaries might be disabled by default on some platforms (ATI Stream, for instance). - */ - public synchronized void setCacheBinaries(boolean cacheBinaries) { - this.cacheBinaries = cacheBinaries; - } - /** - * Says whether program binaries are automatically cached or not.
      - * By default it is true, it can be set to false with the "javacl.cacheBinaries" Java property, the "JAVACL_CACHE_BINARIES" environment variable (when set to "0") or the {@link CLContext#setCacheBinaries(boolean) } method.
      - * Each program can be set to be cached or not using {@link CLProgram#setCached(boolean) }.
      - * Caching of binaries might be disabled by default on some platforms (ATI Stream, for instance). - */ - public synchronized boolean getCacheBinaries() { - if (cacheBinaries == null) { - String prop = System.getProperty("javacl.cacheBinaries"), env = System.getenv("JAVACL_CACHE_BINARIES"); - if ("true".equals(prop) || "1".equals(env)) - cacheBinaries = true; - else if ("false".equals(prop) || "0".equals(env)) - cacheBinaries = false; - else { - cacheBinaries = !PlatformUtils.PlatformKind.AMDApp.equals(PlatformUtils.guessPlatformKind(getPlatform())); - } - //System.out.println("CACHE BINARIES = " + cacheBinaries); - } - return cacheBinaries; - } - - #declareInfosGetter("infos", "CL.clGetContextInfo") - - CLPlatform platform; - protected Pointer deviceIds; - - CLContext(CLPlatform platform, Pointer deviceIds, long context) { - super(context); - this.platform = platform; - this.deviceIds = deviceIds; - - if (getByteOrder() == null) { - JavaCL.log(Level.WARNING, "The devices in this context have mismatching byte orders. This mandates the use of __attribute__((endian(host))) in kernel sources or *very* careful use of buffers to avoid facing endianness issues"); - } - } - - /** - * Creates a user event object.
      - * User events allow applications to enqueue commands that wait on a user event to finish before the command is executed by the device. - * @since OpenCL 1.1 - */ - public CLUserEvent createUserEvent() { - try { - #declareReusablePtrsAndPErr() - long evt = CL.clCreateUserEvent(getEntity(), getPeer(pErr)); - #checkPErr() - return (CLUserEvent)CLEvent.createEvent(null, evt, true); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return null; - } - } - - /** - * Create an OpenCL queue on the first device of this context.
      - * Equivalent to calling getDevices()[0].createQueue(context) - * @return new OpenCL queue - */ - public CLQueue createDefaultQueue(QueueProperties... queueProperties) { - return new CLDevice(platform, deviceIds.getSizeT()).createQueue(this, queueProperties); - } - - /** - * Create an out-of-order OpenCL queue on the first device of this context.
      - * Equivalent to calling getDevices()[0].createOutOfOrderQueue(context) - * @return new out-of-order OpenCL queue - */ - public CLQueue createDefaultOutOfOrderQueue() { - return new CLDevice(platform, deviceIds.getSizeT()).createOutOfOrderQueue(this); - } - - - public String toString() { - StringBuilder b = new StringBuilder("CLContext(platform = ").append(getPlatform().getName()).append("; devices = "); - boolean first = true; - for (CLDevice d : getDevices()) { - if (first) - first = false; - else - b.append(", "); - b.append(d.getName()); - } - b.append(")"); - return b.toString(); - } - public CLQueue createDefaultOutOfOrderQueueIfPossible() { - try { - return createDefaultOutOfOrderQueue(); - } catch (Throwable th) {//CLException.InvalidQueueProperties ex) { - return createDefaultQueue(); - } - } - - /** - * Create an profiling-enabled OpenCL queue on the first device of this context.
      - * Equivalent to calling getDevices()[0].createProfilingQueue(context) - * @return new profiling-enabled OpenCL queue - */ - public CLQueue createDefaultProfilingQueue() { - return new CLDevice(platform, deviceIds.getSizeT()).createProfilingQueue(this); - } - - /** -#documentCallsFunction("clGetSupportedImageFormats") - */ - @SuppressWarnings("deprecation") - public CLImageFormat[] getSupportedImageFormats(CLBuffer.Flags flags, CLBuffer.ObjectType imageType) { - Pointer pCount = allocateInt(); - int memFlags = (int) flags.value(); - int imTyp = (int) imageType.value(); - CL.clGetSupportedImageFormats(getEntity(), memFlags, imTyp, 0, 0, getPeer(pCount)); - //cl_image_format ft = new cl_image_format(); - //int sz = ft.size(); - int n = pCount.getInt(); - if (n == 0) { - n = 30; // There HAS to be at least one format. the spec even says even more, but in fact on Mac OS X / CPU there's only one... - } - Pointer formats = allocateArray(cl_image_format.class, n); - CL.clGetSupportedImageFormats(getEntity(), memFlags, imTyp, n, getPeer(formats), 0); - List ret = new ArrayList(n); - for (cl_image_format ft : formats) { - if (ft.image_channel_data_type() == 0 && ft.image_channel_order() == 0) - break; - - ret.add(new CLImageFormat(ft)); - } - return ret.toArray(new CLImageFormat[ret.size()]); - } - - /** -#documentCallsFunction("clCreateSampler") - */ - @SuppressWarnings("deprecation") - public CLSampler createSampler(boolean normalized_coords, AddressingMode addressing_mode, FilterMode filter_mode) { - #declareReusablePtrsAndPErr() - long sampler = CL.clCreateSampler( - getEntity(), - normalized_coords ? CL_TRUE : CL_FALSE, - (int) addressing_mode.value(), - (int) filter_mode.value(), - getPeer(pErr) - ); - #checkPErr() - return new CLSampler(sampler); - } - - public int getDeviceCount() { - return infos.getOptionalFeatureInt(getEntity(), CL.CL_CONTEXT_NUM_DEVICES); - } - - /** - * Lists the devices of this context - * @return array of the devices that form this context - */ - public synchronized CLDevice[] getDevices() { - if (deviceIds == null) { - deviceIds = infos.getMemory(getEntity(), CL_CONTEXT_DEVICES).as(SizeT.class); - } - int n = (int)deviceIds.getValidElements(); - - CLDevice[] devices = new CLDevice[n]; - for (int i = n; i-- != 0;) { - devices[i] = new CLDevice(platform, deviceIds.getSizeTAtOffset(i * Pointer.SIZE)); - } - return devices; - } - - /** - * Create a program with all the C source code content provided as argument. - * @param srcs list of the content of source code for the program - * @return a program that needs to be built - */ - public CLProgram createProgram(String... srcs) { - return createProgram(null, srcs); - } - - public CLProgram createProgram(CLDevice[] devices, String... srcs) { - CLProgram program = new CLProgram(this, devices); - for (String src : srcs) - program.addSource(src); - return program; - } - - /** - * Restore a program previously saved with {@link CLProgram#store(java.io.OutputStream) } - * @param in will be closed - * @return a CLProgram object representing the previously saved program - * @throws IOException - */ - public CLProgram loadProgram(InputStream in) throws IOException { - Pair, String> binaries = CLProgram.readBinaries(Arrays.asList(getDevices()), null, in); - return createProgram(binaries.getFirst(), binaries.getSecond()); - } - - public CLProgram createProgram(Map binaries, String source) { - return new CLProgram(this, binaries, source); - } - - //cl_queue queue; - @Override - protected void clear() { - error(CL.clReleaseContext(getEntity())); - } - - - - @Deprecated - public CLDevice guessCurrentGLDevice() { - long[] props = CLPlatform.getContextProps(CLPlatform.getGLContextProperties(getPlatform())); - Pointer propsRef = pointerToSizeTs(props); - - Pointer pCount = allocateSizeT(); - Pointer> mem = allocatePointer(); - if (Platform.isMacOSX()) - error(CL.clGetGLContextInfoAPPLE( - getEntity(), - getPeer(OpenGLContextUtils.CGLGetCurrentContext()), - CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, - Pointer.SIZE, - getPeer(mem), - getPeer(pCount))); - else - error(CL.clGetGLContextInfoKHR( - getPeer(propsRef), - CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, - Pointer.SIZE, - getPeer(mem), - getPeer(pCount) - )); - - if (pCount.getSizeT() != Pointer.SIZE) - throw new RuntimeException("Not a device : len = " + pCount.get().intValue()); - - Pointer p = mem.getPointer(); - if (p.equals(Pointer.NULL)) - return null; - return new CLDevice(null, getPeer(p)); - } - - private static T markAsGL(T mem) { - mem.isGL = true; - return mem; - } - - /** -#documentCallsFunction("clCreateFromGLBuffer") - * Makes an OpenGL Vertex Buffer Object (VBO) visible to OpenCL as a buffer object.
      - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * see {@link CLMem#acquireGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLMem#releaseGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * @param usage flags - * @param openGLBufferObject Identifier of a VBO, as generated by glGenBuffers - */ - @SuppressWarnings("deprecation") - public CLBuffer createBufferFromGLBuffer(CLMem.Usage usage, int openGLBufferObject) { - #declareReusablePtrsAndPErr() - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLBuffer( - getEntity(), - usage.getIntFlags(), - openGLBufferObject, - getPeer(pErr) - ); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - return markAsGL(new CLBuffer(this, -1, mem, null, PointerIO.getByteInstance())); - } - - /** -#documentCallsFunction("clCreateFromGLRenderbuffer") - * Makes an OpenGL Render Buffer visible to OpenCL as a 2D image.
      - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * see {@link CLMem#acquireGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLMem#releaseGLObject(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLEvent[]) } - * @param openGLRenderBuffer Identifier of an OpenGL render buffer - */ - @SuppressWarnings("deprecation") - public CLImage2D createImage2DFromGLRenderBuffer(CLMem.Usage usage, int openGLRenderBuffer) { - #declareReusablePtrsAndPErr() - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLRenderbuffer( - getEntity(), - usage.getIntFlags(), - openGLRenderBuffer, - getPeer(pErr) - ); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - return markAsGL(new CLImage2D(this, mem, null)); - } - - /** -#documentCallsFunction("clCreateFromGLTexture2D") - * Creates an OpenCL 2D image object from an OpenGL 2D texture object, or a single face of an OpenGL cubemap texture object.
      - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * @param usage - * @param textureTarget Must be one of GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, or GL_TEXTURE_RECTANGLE47. texture_target is used only to define the image type of texture. No reference to a bound GL texture object is made or implied by this parameter. - * @param mipLevel Mipmap level to be used (Implementations may return CL_INVALID_OPERATION for miplevel values > 0) - * @param texture Name of a GL 2D, cubemap or rectangle texture object. The texture object must be a complete texture as per OpenGL rules on texture completeness. The texture format and dimensions defined by OpenGL for the specified miplevel of the texture will be used to create the 2D image object. Only GL texture objects with an internal format that maps to appropriate image channel order and data type specified in tables 5.4 and 5.5 may be used to create a 2D image object. - * @return valid OpenCL image object if the image object is created successfully - * @throws CLException.InvalidMipLevel if miplevel is less than the value of levelbase (for OpenGL implementations) or zero (for OpenGL ES implementations); or greater than the value of q (for both OpenGL and OpenGL ES). levelbase and q are defined for the texture in section 3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and section 3.7.10 of the OpenGL ES 2.0, or if miplevel is greather than zero and the OpenGL implementation does not support creating from non-zero mipmap levels. - * @throws CLException.InvalidGLObject if texture is not a GL texture object whose type matches texture_target, if the specified miplevel of texture is not defined, or if the width or height of the specified miplevel is zero. - * @throws CLException.InvalidImageFormatDescriptor if the OpenGL texture internal format does not map to a supported OpenCL image format. - */ - @SuppressWarnings("deprecation") - public CLImage2D createImage2DFromGLTexture2D(CLMem.Usage usage, GLTextureTarget textureTarget, int texture, int mipLevel) { - #declareReusablePtrsAndPErr() - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLTexture2D( - getEntity(), - usage.getIntFlags(), - (int)textureTarget.value(), - mipLevel, - texture, - getPeer(pErr) - ); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - return markAsGL(new CLImage2D(this, mem, null)); - } - - private static final int - GL_TEXTURE_2D = 0x0DE1, - GL_TEXTURE_3D = 0x806F, - GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515, - GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516, - GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517, - GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518, - GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519, - GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A, - GL_TEXTURE_RECTANGLE = 0x84F5; - - public CLPlatform getPlatform() { - return platform; - } - - - public enum GLTextureTarget implements com.nativelibs4java.util.ValuedEnum { - - Texture2D(GL_TEXTURE_2D), - //Texture3D(GL_TEXTURE_3D), - CubeMapPositiveX(GL_TEXTURE_CUBE_MAP_POSITIVE_X), - CubeMapNegativeX(GL_TEXTURE_CUBE_MAP_NEGATIVE_X), - CubeMapPositiveY(GL_TEXTURE_CUBE_MAP_POSITIVE_Y), - CubeMapNegativeY(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y), - CubeMapPositiveZ(GL_TEXTURE_CUBE_MAP_POSITIVE_Z), - CubeMapNegativeZ(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z), - Rectangle(GL_TEXTURE_RECTANGLE); - - GLTextureTarget(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static GLTextureTarget getEnum(int v) { return EnumValues.getEnum(v, GLTextureTarget.class); } - } - - /** -#documentCallsFunction("clCreateFromGLTexture3D") - * Creates an OpenCL 3D image object from an OpenGL 3D texture object
      - * Note that memory objects shared with OpenGL must be acquired / released before / after use from OpenCL. - * @param usage - * @param mipLevel Mipmap level to be used (Implementations may return CL_INVALID_OPERATION for miplevel values > 0) - * @param texture Name of a GL 3D texture object. The texture object must be a complete texture as per OpenGL rules on texture completeness. The texture format and dimensions defined by OpenGL for the specified miplevel of the texture will be used to create the 3D image object. Only GL texture objects with an internal format that maps to appropriate image channel order and data type specified in tables 5.4 and 5.5 can be used to create the 3D image object. - * @return valid OpenCL image object if the image object is created successfully - * @throws CLException.InvalidMipLevel if miplevel is less than the value of levelbase (for OpenGL implementations) or zero (for OpenGL ES implementations); or greater than the value of q (for both OpenGL and OpenGL ES). levelbase and q are defined for the texture in section 3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and section 3.7.10 of the OpenGL ES 2.0, or if miplevel is greather than zero and the OpenGL implementation does not support creating from non-zero mipmap levels. - * @throws CLException.InvalidGLObject if texture is not a GL texture object whose type matches texture_target, if the specified miplevel of texture is not defined, or if the width or height of the specified miplevel is zero. - * @throws CLException.InvalidImageFormatDescriptor if the OpenGL texture internal format does not map to a supported OpenCL image format. - */ - @SuppressWarnings("deprecation") - public CLImage3D createImage3DFromGLTexture3D(CLMem.Usage usage, int texture, int mipLevel) { - #declareReusablePtrsAndPErr() - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateFromGLTexture3D( - getEntity(), - usage.getIntFlags(), - GL_TEXTURE_3D, - mipLevel, - texture, - getPeer(pErr) - ); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - return markAsGL(new CLImage3D(this, mem, null)); - } - - /** - * Create an ARGB input 2D image with the content provided - * @param allowUnoptimizingDirectRead Some images expose their internal data for direct read, leading to performance increase during the creation of the OpenCL image. However, direct access to the image data disables some Java2D optimizations for this image, leading to degraded performance in subsequent uses with AWT/Swing. - */ - public CLImage2D createImage2D(CLMem.Usage usage, Image image, boolean allowUnoptimizingDirectRead) { - int width = image.getWidth(null), height = image.getHeight(null); - ImageInfo info = ImageIOUtils.getImageInfo(image); - return createImage2D( - usage, - info.clImageFormat, - width, height, - 0, - info.dataGetter.getData(image, null, true, allowUnoptimizingDirectRead, getByteOrder()), - true); - } - - /** -#documentCallsFunction("clCreateImage2D") - */ - @SuppressWarnings("deprecation") - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height, long rowPitch, Buffer buffer, boolean copy) { - long memFlags = usage.getIntFlags(); - if (buffer != null) { - memFlags |= copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR; - } - - #declareReusablePtrsAndPErr() - Pointer pImageFormat = pointerTo(format.to_cl_image_format()); - Pointer pBuffer = buffer == null ? null : pointerToBuffer(buffer); - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateImage2D( - getEntity(), - memFlags, - getPeer(pImageFormat), - width, - height, - rowPitch, - getPeer(pBuffer), - getPeer(pErr)); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - return new CLImage2D(this, mem, format); - } - - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height, long rowPitch) { - return createImage2D(usage, format, width, height, rowPitch, null, false); - } - - public CLImage2D createImage2D(CLMem.Usage usage, CLImageFormat format, long width, long height) { - return createImage2D(usage, format, width, height, 0, null, false); - } - - /** -#documentCallsFunction("clCreateImage3D") - */ - @SuppressWarnings("deprecation") - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth, long rowPitch, long slicePitch, Buffer buffer, boolean copy) { - long memFlags = usage.getIntFlags(); - if (buffer != null) { - memFlags |= copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR; - } - - #declareReusablePtrsAndPErr() - Pointer pImageFormat = pointerTo(format.to_cl_image_format()); - Pointer pBuffer = buffer == null ? null : pointerToBuffer(buffer); - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateImage3D( - getEntity(), - memFlags, - getPeer(pImageFormat), - width, - height, - depth, - rowPitch, - slicePitch, - getPeer(pBuffer), - getPeer(pErr)); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - - return new CLImage3D(this, mem, format); - } - - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth, long rowPitch, long slicePitch) { - return createImage3D(usage, format, width, height, depth, rowPitch, slicePitch, null, false); - } - - public CLImage3D createImage3D(CLMem.Usage usage, CLImageFormat format, long width, long height, long depth) { - return createImage3D(usage, format, width, height, depth, 0, 0, null, false); - } - -#foreach ($prim in $primitivesNoBool) - -#docCreateBufferCopy("CLBuffer<${prim.WrapperName}>", "") - public CLBuffer<${prim.WrapperName}> create${prim.BufferName}(CLMem.Usage kind, #if ($prim.Name == "byte") Buffer #else ${prim.BufferName} #end data, boolean copy) { -#if ($prim.Name == "byte") - return createBuffer(kind, Pointer.pointerToBuffer(data).as(Byte.class), copy); -#else - return createBuffer(kind, Pointer.pointerTo${prim.CapName}s(data), copy); -#end - } - -#docCreateBuffer("CLBuffer<${prim.WrapperName}>", "") - public CLBuffer<${prim.WrapperName}> create${prim.BufferName}(CLMem.Usage kind, Pointer<${prim.WrapperName}> data) { - return create${prim.BufferName}(kind, data, true); - } -#docCreateBufferCopy("CLBuffer<${prim.WrapperName}>", "") - public CLBuffer<${prim.WrapperName}> create${prim.BufferName}(CLMem.Usage kind, Pointer<${prim.WrapperName}> data, boolean copy) { - return createBuffer(kind, data, copy); - } - -#docCreateBufferPrim("CLBuffer<${prim.WrapperName}>", $prim) - public CLBuffer<${prim.WrapperName}> create${prim.BufferName}(CLMem.Usage kind, long elementCount) { - return createBuffer(kind, ${prim.WrapperName}.class, elementCount); - } - -#end - - /** -#documentCallsFunction("clCreateBuffer") - * Create an OpenCL buffer with the provided initial values, in copy mode (see CL_MEM_COPY_HOST_PTR). - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - * @param data Pointer to the initial values, must have known bounds (see {@link Pointer#getValidElements()}) - */ - public CLBuffer createBuffer(CLMem.Usage kind, Pointer data) { - return createBuffer(kind, data, true); - } - -#docCreateBufferCopy("CLBuffer<N>", "") - public CLBuffer createBuffer(CLMem.Usage kind, Pointer data, boolean copy) { - return createBuffer(data.getIO(), data, data.getValidBytes(), kind.getIntFlags() | (copy ? CL_MEM_COPY_HOST_PTR : CL_MEM_USE_HOST_PTR), copy); - } - -#docCreateBuffer("CLBuffer<N>", "T", "* @param elementClass Primitive type of the buffer. For instance a buffer of 'int' values can be created with elementClass being Integer.class or int.class indifferently.", "") - public CLBuffer createBuffer(CLMem.Usage kind, Class elementClass, long elementCount) { - PointerIO io = PointerIO.getInstance(elementClass); - if (io == null) - throw new IllegalArgumentException("Unknown target type : " + elementClass.getName()); - return createBuffer(kind, io, elementCount); - } - - /** -#documentCallsFunction("clCreateBuffer") - * Create an OpenCL buffer big enough to hold the provided amount of values of the specified type. - * @param kind Usage intended for the pointer in OpenCL kernels : a pointer created with {@link CLMem.Usage#Input} cannot be written to in a kernel. - * @param io Delegate responsible for reading and writing values. - * @param elementCount Length of the buffer expressed in elements (for instance, a CLBuffer of length 4 will actually contain 4 * 4 bytes, as ints are 4-bytes-long) - * @deprecated Intended for advanced uses in conjunction with BridJ. - */ - @Deprecated - public CLBuffer createBuffer(CLMem.Usage kind, PointerIO io, long elementCount) { - return createBuffer(io, null, io.getTargetSize() * elementCount, kind.getIntFlags(), false); - } - - /** -#documentCallsFunction("clCreateBuffer") - */ - @SuppressWarnings("deprecation") - private CLBuffer createBuffer(PointerIO io, Pointer data, long byteCount, final int CLBufferFlags, final boolean retainBufferReference) { - if (byteCount <= 0) - throw new IllegalArgumentException("Buffer size must be greater than zero (asked for size " + byteCount + ")"); - - if (byteCount > getMaxMemAllocSize()) - throw new OutOfMemoryError("Requested size for buffer allocation is more than the maximum for this context : " + byteCount + " > " + getMaxMemAllocSize()); - - if (data != null) { - ByteOrder contextOrder = getByteOrder(); - ByteOrder dataOrder = data.order(); - if (contextOrder != null && !dataOrder.equals(contextOrder) && data.getTargetSize() > 1) - throw new IllegalArgumentException("Byte order of this context is " + contextOrder + ", but was given pointer to data with order " + dataOrder + ". Please create a pointer with correct byte order (Pointer.order(CLContext.getByteOrder()))."); - } - - #declareReusablePtrsAndPErr() - long mem; - int previousAttempts = 0; - do { - mem = CL.clCreateBuffer( - getEntity(), - CLBufferFlags, - byteCount, - getPeer(data), - getPeer(pErr)); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - - return new CLBuffer(this, byteCount, mem, retainBufferReference ? data : null, io); - } - - public ByteOrder getKernelsDefaultByteOrder() { - if (kernelsDefaultByteOrder == null) { - ByteOrder order = null; - for (CLDevice device : getDevices()) { - ByteOrder devOrder = device.getKernelsDefaultByteOrder(); - if (order != null && devOrder != order) - return null; - order = devOrder; - } - kernelsDefaultByteOrder = order; - } - return kernelsDefaultByteOrder; - } - - private volatile ByteOrder byteOrder, kernelsDefaultByteOrder; - - /** - * Get the endianness common to all devices of this context, or null if the devices have mismatching endiannesses. - */ - public ByteOrder getByteOrder() { - if (byteOrder == null) { - ByteOrder order = null; - for (CLDevice device : getDevices()) { - ByteOrder devOrder = device.getByteOrder(); - if (order != null && devOrder != order) - return null; - order = devOrder; - } - byteOrder = order; - } - return byteOrder; - } - - private volatile int addressBits = -2; - - /** - * Return the number of bits used to represent a pointer on all of the context's devices, or -1 if not all devices use the same number of bits.
      - * Size of size_t type in OpenCL kernels can be obtained with getAddressBits() / 8. - * @return -1 if the address bits of the context's devices do not match, common address bits otherwise - */ - public int getAddressBits() { - if (addressBits == -2) { - synchronized (this) { - if (addressBits == -2) { - for (CLDevice device : getDevices()) { - int bits = device.getAddressBits(); - if (addressBits != -2 && bits != addressBits) { - addressBits = -1; - break; - } - addressBits = bits; - } - } - } - } - return addressBits; - } - - private volatile Boolean doubleSupported; - - /** - * Whether all the devices in this context support any double-precision numbers (see {@link CLDevice#isDoubleSupported()}). - */ - public boolean isDoubleSupported() { - if (doubleSupported == null) { - boolean supported = true; - for (CLDevice device : getDevices()) { - if (!device.isDoubleSupported()) { - supported = false; - break; - } - } - doubleSupported = supported; - } - return doubleSupported; - } - - private volatile Boolean halfSupported; - - /** - * Whether all the devices in this context support half-precision numbers (see {@link CLDevice#isHalfSupported()}). - */ - public boolean isHalfSupported() { - if (halfSupported == null) { - boolean supported = true; - for (CLDevice device : getDevices()) { - if (!device.isHalfSupported()) { - supported = false; - break; - } - } - halfSupported = supported; - } - return halfSupported; - } - - private volatile Boolean byteAddressableStoreSupported; - - public boolean isByteAddressableStoreSupported() { - if (byteAddressableStoreSupported == null) { - boolean supported = true; - for (CLDevice device : getDevices()) { - if (!device.isByteAddressableStoreSupported()) { - supported = false; - break; - } - } - byteAddressableStoreSupported = supported; - } - return byteAddressableStoreSupported; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLDevice.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLDevice.java deleted file mode 100644 index c81856c32..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLDevice.java +++ /dev/null @@ -1,915 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; - -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import org.bridj.*; -import static org.bridj.Pointer.*; - -import java.io.IOException; -import java.nio.*; -import static com.nativelibs4java.opencl.JavaCL.*; -import static com.nativelibs4java.util.NIOUtils.*; -import java.util.*; -import static com.nativelibs4java.opencl.CLException.*; -import org.bridj.ValuedEnum; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * OpenCL device (CPU, GPU...).
      - * Devices are retrieved from a CLPlatform through - * {@link CLPlatform#listDevices(java.util.EnumSet, boolean) }, - * {@link CLPlatform#listAllDevices(boolean) }, - * {@link CLPlatform#listCPUDevices(boolean) }, - * {@link CLPlatform#listGPUDevices(boolean) } - */ -@SuppressWarnings("unused") -public class CLDevice extends CLAbstractEntity { - - #declareInfosGetter("infos", "CL.clGetDeviceInfo") - - volatile CLPlatform platform; - - CLDevice(CLPlatform platform, long device) { - super(device); - this.platform = platform; - } - - public synchronized CLPlatform getPlatform() { - if (platform == null) { - Pointer pplat = infos.getPointer(getEntity(), CL_DEVICE_PLATFORM); - platform = new CLPlatform(getPeer(pplat)); - } - return platform; - } - - @Override - protected void clear() { - } - - public String createSignature() { - return getName() + "|" + getVendor() + "|" + getDriverVersion() + "|" + getProfile(); - } - public static Map> getDevicesBySignature(List devices) { - Map> ret = new HashMap>(); - for (CLDevice device : devices) { - String signature = device.createSignature(); - List list = ret.get(signature); - if (list == null) - ret.put(signature, list = new ArrayList()); - list.add(device); - } - return ret; - } - - private volatile ByteOrder byteOrder; - public ByteOrder getByteOrder() { - if (byteOrder == null) - byteOrder = isEndianLittle() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - return byteOrder; - } - - private volatile ByteOrder kernelsDefaultByteOrder; - /** - * @deprecated Use {@link CLDevice#getByteOrder()} - */ - @Deprecated - public synchronized ByteOrder getKernelsDefaultByteOrder() { - if (kernelsDefaultByteOrder == null) { - kernelsDefaultByteOrder = ByteOrderHack.guessByteOrderNeededForBuffers(this); - } - return kernelsDefaultByteOrder; - } - - /** Bit values for CL_DEVICE_EXECUTION_CAPABILITIES */ - public enum ExecutionCapability implements com.nativelibs4java.util.ValuedEnum { - - Kernel(CL_EXEC_KERNEL), - NativeKernel(CL_EXEC_NATIVE_KERNEL); - - ExecutionCapability(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, ExecutionCapability.class); - } - } - - /** - * Describes the execution capabilities of the device.
      - * The mandated minimum capability is: Kernel. - */ - @InfoName("CL_DEVICE_EXECUTION_CAPABILITIES") - public EnumSet getExecutionCapabilities() { - return ExecutionCapability.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_EXECUTION_CAPABILITIES)); - } - - /** Bit values for CL_DEVICE_TYPE */ - public enum Type implements com.nativelibs4java.util.ValuedEnum { - - CPU(CL_DEVICE_TYPE_CPU), - GPU(CL_DEVICE_TYPE_GPU), - Accelerator(CL_DEVICE_TYPE_ACCELERATOR), - Default(CL_DEVICE_TYPE_DEFAULT), - All(CL_DEVICE_TYPE_ALL); - - Type(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, Type.class); - } - } - - /** - * The OpenCL device type. - */ - @InfoName("CL_DEVICE_TYPE") - public EnumSet getType() { - return Type.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_TYPE)); - } - - /** - * A unique device vendor identifier.
      - * An example of a unique device identifier could be the PCIe ID. - */ - @InfoName("CL_DEVICE_VENDOR_ID") - public int getVendorId() { - return infos.getInt(getEntity(), CL_DEVICE_VENDOR_ID); - } - - /** - * The number of parallel compute cores on the OpenCL device.
      - * The minimum value is 1. - */ - @InfoName("CL_DEVICE_MAX_COMPUTE_UNITS") - public int getMaxComputeUnits() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_COMPUTE_UNITS); - } - - /** - * Maximum dimensions that specify the global and local work-item IDs used by the data parallel execution model.
      - * (Refer to clEnqueueNDRangeKernel). - *
      The minimum value is 3. - */ - @InfoName("CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS") - public int getMaxWorkItemDimensions() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS); - } - - /** - * Maximum number of work-items that can be specified in each dimension of the work-group to clEnqueueNDRangeKernel. - */ - @InfoName("CL_DEVICE_MAX_WORK_ITEM_SIZES") - public long[] getMaxWorkItemSizes() { - long sizes[] = infos.getNativeSizes(getEntity(), CL_DEVICE_MAX_WORK_ITEM_SIZES, getMaxWorkItemDimensions()); - for (int i = 0, n = sizes.length; i < n; i++) { - long size = sizes[i]; - if ((size & 0xffffffff00000000L) == 0xcccccccc00000000L) - sizes[i] = size & 0xffffffffL; - } - return sizes; - } - - /** - * Maximum number of work-items in a work-group executing a kernel using the data parallel execution model. - * (Refer to clEnqueueNDRangeKernel).
      - * The minimum value is 1. - */ - @InfoName("CL_DEVICE_MAX_WORK_GROUP_SIZE") - public long getMaxWorkGroupSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_WORK_GROUP_SIZE); - } - - /** - * Maximum configured clock frequency of the device in MHz. - */ - @InfoName("CL_DEVICE_MAX_CLOCK_FREQUENCY") - public int getMaxClockFrequency() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_CLOCK_FREQUENCY); - } - - /** - * The default compute device address space size specified as an unsigned integer value in bits. Currently supported values are 32 or 64 bits..
      - * Size of size_t type in OpenCL kernels can be obtained with getAddressBits() / 8. - */ - @InfoName("CL_DEVICE_ADDRESS_BITS") - public int getAddressBits() { - return infos.getInt(getEntity(), CL_DEVICE_ADDRESS_BITS); - } - - /** - * Max size of memory object allocation in bytes. The minimum value is max (1/4th of CL_DEVICE_GLOBAL_MEM_SIZE , 128*1024*1024) - */ - @InfoName("CL_DEVICE_MAX_MEM_ALLOC_SIZE") - public long getMaxMemAllocSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_MEM_ALLOC_SIZE); - } - - /** - * Is CL_TRUE if images are supported by the OpenCL device and CL_FALSE otherwise. - */ - @InfoName("CL_DEVICE_IMAGE_SUPPORT") - public boolean hasImageSupport() { - return infos.getBool(getEntity(), CL_DEVICE_IMAGE_SUPPORT); - } - - /** - * Max number of simultaneous image objects that can be read by a kernel.
      - * The minimum value is 128 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()). - */ - @InfoName("CL_DEVICE_MAX_READ_IMAGE_ARGS") - public int getMaxReadImageArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_READ_IMAGE_ARGS); - } - - /** - * Max number of simultaneous image objects that can be written to by a kernel.
      - * The minimum value is 8 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()). - */ - @InfoName("CL_DEVICE_MAX_WRITE_IMAGE_ARGS") - public int getMaxWriteImageArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_WRITE_IMAGE_ARGS); - } - - @Override - public String toString() { - return getName() + " (" + getPlatform().getName() + ")"; - } - - /** -#documentCallsFunction("clCreateCommandQueue") - * Create an OpenCL execution queue on this device for the specified context. - * @param context context of the queue to create - * @return new OpenCL queue object - */ - @SuppressWarnings("deprecation") - public CLQueue createQueue(CLContext context, QueueProperties... queueProperties) { - #declareReusablePtrsAndPErr() - long flags = 0; - for (QueueProperties prop : queueProperties) - flags |= prop.value(); - long queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), flags, getPeer(pErr)); - #checkPErr() - - return new CLQueue(context, queue, this); - } - - /** -#documentCallsFunction("clCreateCommandQueue") - */ - @Deprecated - public CLQueue createQueue(EnumSet queueProperties, CLContext context) { - #declareReusablePtrsAndPErr() - long queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), QueueProperties.getValue(queueProperties), getPeer(pErr)); - #checkPErr() - - return new CLQueue(context, queue, this); - } - - public CLQueue createOutOfOrderQueue(CLContext context) { - return createQueue(EnumSet.of(QueueProperties.OutOfOrderExecModeEnable), context); - } - - public CLQueue createProfilingQueue(CLContext context) { - return createQueue(EnumSet.of(QueueProperties.ProfilingEnable), context); - } - - /** - * Max width of 2D image in pixels.
      - * The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE2D_MAX_WIDTH") - public long getImage2DMaxWidth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_WIDTH); - } - - /** - * Max height of 2D image in pixels.
      - * The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE2D_MAX_HEIGHT") - public long getImage2DMaxHeight() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_HEIGHT); - } - - /** - * Max width of 3D image in pixels.
      - * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_WIDTH") - public long getImage3DMaxWidth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_WIDTH); - } - - /** - * Max height of 3D image in pixels.
      - * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_HEIGHT") - public long getImage3DMaxHeight() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_HEIGHT); - } - - /** - * Max depth of 3D image in pixels.
      - * The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_IMAGE3D_MAX_DEPTH") - public long getImage3DMaxDepth() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_DEPTH); - } - - /** - * Maximum number of samplers that can be used in a kernel.
      - * Refer to section 6.11.8 for a detailed description on samplers.
      - * The minimum value is 16 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE. - */ - @InfoName("CL_DEVICE_MAX_SAMPLERS") - public int getMaxSamplers() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_SAMPLERS); - } - - /** - * Max size in bytes of the arguments that can be passed to a kernel.
      - * The minimum value is 256. - */ - @InfoName("CL_DEVICE_MAX_PARAMETER_SIZE") - public long getMaxParameterSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_PARAMETER_SIZE); - } - - /** - * Describes the alignment in bits of the base address of any allocated memory object. - */ - @InfoName("CL_DEVICE_MEM_BASE_ADDR_ALIGN") - public int getMemBaseAddrAlign() { - return infos.getInt(getEntity(), CL_DEVICE_MEM_BASE_ADDR_ALIGN); - } - - /** - * The smallest alignment in bytes which can be used for any data type. - */ - @InfoName("CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE") - public int getMinDataTypeAlign() { - return infos.getInt(getEntity(), CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE); - } - - /** Bit values for CL_DEVICE_SINGLE_FP_CONFIG */ - public enum SingleFPConfig implements com.nativelibs4java.util.ValuedEnum { - - /** denorms are supported */ - Denorm(CL_FP_DENORM), - /** INF and quiet NaNs are supported. */ - InfNaN(CL_FP_INF_NAN), - /** round to nearest even rounding mode supported */ - RoundToNearest(CL_FP_ROUND_TO_NEAREST), - /** round to zero rounding mode supported */ - RoundToZero(CL_FP_ROUND_TO_ZERO), - /** round to +ve and -ve infinity rounding modes supported */ - RoundToInf(CL_FP_ROUND_TO_INF), - /** IEEE754-2008 fused multiply-add is supported. */ - FMA(CL_FP_FMA); - - SingleFPConfig(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, SingleFPConfig.class); - } - } - - /** - * Describes single precision floating- point capability of the device.
      - * The mandated minimum floating-point capability is: RoundToNearest and InfNaN. - */ - @InfoName("CL_DEVICE_SINGLE_FP_CONFIG") - public EnumSet getSingleFPConfig() { - return SingleFPConfig.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_SINGLE_FP_CONFIG)); - } - - /** Values for CL_DEVICE_GLOBAL_MEM_CACHE_TYPE */ - public enum GlobalMemCacheType implements com.nativelibs4java.util.ValuedEnum { - - None(CL_NONE), - ReadOnlyCache(CL_READ_ONLY_CACHE), - ReadWriteCache(CL_READ_WRITE_CACHE); - - GlobalMemCacheType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static GlobalMemCacheType getEnum(long v) { - return EnumValues.getEnum(v, GlobalMemCacheType.class); - } - } - - /** - * Type of global memory cache supported. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_TYPE") - public GlobalMemCacheType getGlobalMemCacheType() { - return GlobalMemCacheType.getEnum(infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_TYPE)); - } - - /** - * Size of global memory cache line in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE") - public int getGlobalMemCachelineSize() { - return infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE); - } - - /** - * Size of global memory cache in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_SIZE") - public long getGlobalMemCacheSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_SIZE); - } - - /** - * Size of global device memory in bytes. - */ - @InfoName("CL_DEVICE_GLOBAL_MEM_SIZE") - public long getGlobalMemSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_SIZE); - } - - /** - * Max size in bytes of a constant buffer allocation.
      - * The minimum value is 64 KB. - */ - @InfoName("CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE") - public long getMaxConstantBufferSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE); - } - - /** - * Max number of arguments declared with the __constant qualifier in a kernel.
      - * The minimum value is 8. - */ - @InfoName("CL_DEVICE_MAX_CONSTANT_ARGS") - public int getMaxConstantArgs() { - return infos.getInt(getEntity(), CL_DEVICE_MAX_CONSTANT_ARGS); - } - - /** Values for CL_DEVICE_LOCAL_MEM_TYPE */ - public enum LocalMemType implements com.nativelibs4java.util.ValuedEnum { - - /** implying dedicated local memory storage such as SRAM */ - Local(CL_LOCAL), - Global(CL_GLOBAL); - - LocalMemType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static LocalMemType getEnum(long v) { - return EnumValues.getEnum(v, LocalMemType.class); - } - } - - /** - * Type of local memory supported.
      - */ - @InfoName("CL_DEVICE_LOCAL_MEM_TYPE") - public LocalMemType getLocalMemType() { - return LocalMemType.getEnum(infos.getInt(getEntity(), CL_DEVICE_LOCAL_MEM_TYPE)); - } - - /** - * Size of local memory arena in bytes.
      - * The minimum value is 16 KB. - */ - @InfoName("CL_DEVICE_LOCAL_MEM_SIZE") - public long getLocalMemSize() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_LOCAL_MEM_SIZE); - } - - /** - * Is CL_TRUE if the device implements error correction for the memories, caches, registers etc. in the device.
      - * Is CL_FALSE if the device does not implement error correction.
      - * This can be a requirement for certain clients of OpenCL. - */ - @InfoName("CL_DEVICE_ERROR_CORRECTION_SUPPORT") - public boolean hasErrorCorrectionSupport() { - return infos.getBool(getEntity(), CL_DEVICE_ERROR_CORRECTION_SUPPORT); - } - - @InfoName("Out of order queues support") - public boolean hasOutOfOrderQueueSupport() { - CLContext context = getPlatform().createContext(null, this); - CLQueue queue = null; - try { - queue = createOutOfOrderQueue(context); - return true; - } catch (CLException.InvalidQueueProperties ex) { - return false; - } finally { - if (queue != null) - queue.release(); - context.release(); - } - } - - /** - * Describes the resolution of device timer.
      - * This is measured in nanoseconds.
      - * Refer to section 5.9 for details. - */ - @InfoName("CL_DEVICE_PROFILING_TIMER_RESOLUTION") - public long getProfilingTimerResolution() { - return infos.getIntOrLong(getEntity(), CL_DEVICE_PROFILING_TIMER_RESOLUTION); - } - - /** - * Is CL_TRUE if the OpenCL device is a little endian device and CL_FALSE otherwise. - */ - @InfoName("CL_DEVICE_ENDIAN_LITTLE") - public boolean isEndianLittle() { - return infos.getBool(getEntity(), CL_DEVICE_ENDIAN_LITTLE); - } - - /** - * Is CL_TRUE if the device is available and CL_FALSE if the device is not available. - */ - @InfoName("CL_DEVICE_AVAILABLE") - public boolean isAvailable() { - return infos.getBool(getEntity(), CL_DEVICE_AVAILABLE); - } - - /** - * Is CL_FALSE if the implementation does not have a compiler available to compile the program source.
      - * Is CL_TRUE if the compiler is available.
      - * This can be CL_FALSE for the embededed platform profile only. - */ - @InfoName("CL_DEVICE_COMPILER_AVAILABLE") - public boolean isCompilerAvailable() { - return infos.getBool(getEntity(), CL_DEVICE_COMPILER_AVAILABLE); - } - - /** - Device name string. - */ - @InfoName("CL_DEVICE_NAME") - public String getName() { - return infos.getString(getEntity(), CL_DEVICE_NAME); - } - - /** - * OpenCL C version string.
      - * Returns the highest OpenCL C version supported by the compiler for this device.
      - * This version string has the following format:
      - * OpenCL<space>C<space><major_version.minor_version><space><vendor-specific information>
      - * The major_version.minor_version value returned must be 1.1 if CL_DEVICE_VERSION is OpenCL 1.1.
      - * The major_version.minor_version value returned can be 1.0 or 1.1 if CL_DEVICE_VERSION is OpenCL 1.0.
      - * If OpenCL C 1.1 is returned, this implies that the language feature set defined in section 6 of the OpenCL 1.1 specification is supported by the OpenCL 1.0 device. - * @since OpenCL 1.1 - */ - @InfoName("CL_DEVICE_OPENCL_C_VERSION") - public String getOpenCLVersion() { - try { - return infos.getString(getEntity(), CL_DEVICE_OPENCL_C_VERSION); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return "OpenCL C 1.0"; - } - } - - /** - Vendor name string. - */ - @InfoName("CL_DEVICE_VENDOR") - public String getVendor() { - return infos.getString(getEntity(), CL_DEVICE_VENDOR); - } - - /** - OpenCL software driver version string in the form major_number.minor_number. - */ - @InfoName("CL_DRIVER_VERSION") - public String getDriverVersion() { - return infos.getString(getEntity(), CL_DRIVER_VERSION); - } - - /** - * OpenCL profile string.
      - * Returns the profile name supported by the device.
      - * The profile name returned can be one of the following strings: - *
        - *
      • FULL_PROFILE if the device supports the OpenCL specification (functionality defined as part of the core specification and does not require any extensions to be supported).
      • - *
      • EMBEDDED_PROFILE if the device supports the OpenCL embedded profile.
      • - *
      - */ - @InfoName("CL_DEVICE_PROFILE") - public String getProfile() { - return infos.getString(getEntity(), CL_DEVICE_PROFILE); - } - - /** - * Whether the device and the host have a unified memory subsystem. - * @since OpenCL 1.1 - */ - @InfoName("CL_DEVICE_HOST_UNIFIED_MEMORY") - public boolean isHostUnifiedMemory() { - try { - return infos.getBool(getEntity(), CL_DEVICE_HOST_UNIFIED_MEMORY); - } catch (Throwable th) { - // TODO throw if supposed to handle OpenCL 1.1 - return false; - } - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR") - public int getPreferredVectorWidthChar() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT") - public int getPreferredVectorWidthShort() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT") - public int getPreferredVectorWidthInt() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG") - public int getPreferredVectorWidthLong() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT") - public int getPreferredVectorWidthFloat() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT); - } - - /** - * Preferred native vector width size for built-in scalar types that can be put into vectors.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE") - public int getPreferredVectorWidthDouble() { - return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR") - public int getNativeVectorWidthChar() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT") - public int getNativeVectorWidthShort() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_INT") - public int getNativeVectorWidthInt() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_INT); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG") - public int getNativeVectorWidthLong() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT") - public int getNativeVectorWidthFloat() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT); - } - - /** - * Returns the native ISA vector width.
      - * The vector width is defined as the number of scalar elements that can be stored in the vector.
      - * If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0. - */ - @InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE") - public int getNativeVectorWidthDouble() { - return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE); - } - - /** - * OpenCL version string.
      - * Returns the OpenCL version supported by the device.
      - * This version string has the following format: - * - * OpenCL<space><major_version.min or_version><space><vendor-specific information> - * - * The major_version.minor_version value returned will be 1.0. - */ - @InfoName("CL_DEVICE_VERSION") - public String getVersion() { - return infos.getString(getEntity(), CL_DEVICE_VERSION); - } - - /** - Returns a space separated list of extension names (the extension names themselves do not contain any spaces). The list of extension names returned currently can include one or more of - */ - @InfoName("CL_DEVICE_EXTENSIONS") - public String[] getExtensions() { - if (extensions == null) { - extensions = infos.getString(getEntity(), CL_DEVICE_EXTENSIONS).split("\\s+"); - } - return extensions; - } - private String[] extensions; - - public boolean hasExtension(String name) { - name = name.trim(); - for (String x : getExtensions()) { - if (name.equals(x.trim())) { - return true; - } - } - return false; - } - - /** - * Whether this device support any double-precision number extension (cl_khr_fp64 or cl_amd_fp64) - */ - public boolean isDoubleSupported() { - return isDoubleSupportedKHR() || isDoubleSupportedAMD(); - } - - /** - * Whether this device support the cl_khr_fp64 double-precision number extension - */ - public boolean isDoubleSupportedKHR() { - return hasExtension("cl_khr_fp64"); - } - - /** - * Whether this device supports the cl_amd_fp64 double-precision number extension - */ - public boolean isDoubleSupportedAMD() { - return hasExtension("cl_amd_fp64"); - } - - /** - * If this device supports the extension cl_amd_fp64 but not cl_khr_fp64, replace any OpenCL source code pragma of the style #pragma OPENCL EXTENSION cl_khr_fp64 : enable by #pragma OPENCL EXTENSION cl_amd_fp64 : enable.
      - * Also works the other way around (if the KHR extension is available but the source code refers to the AMD extension).
      - * This method is called automatically by CLProgram unless the javacl.adjustDoubleExtension property is set to false or the JAVACL_ADJUST_DOUBLE_EXTENSION is set to 0. - */ - public String replaceDoubleExtensionByExtensionActuallyAvailable(String kernelSource) { - boolean hasKHR = isDoubleSupportedKHR(), hasAMD = isDoubleSupportedAMD(); - if (hasAMD && !hasKHR) - kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_khr_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_amd_fp64 : enable"); - else if (!hasAMD && hasKHR) - kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_amd_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_khr_fp64 : enable"); - return kernelSource; - } - - /** - * Whether this device supports the cl_khr_fp16 extension. - */ - public boolean isHalfSupported() { - return hasExtension("cl_khr_fp16"); - } - - /** - * Whether this device supports the cl_khr_byte_addressable_store extension. - */ - public boolean isByteAddressableStoreSupported() { - return hasExtension("cl_khr_byte_addressable_store"); - } - - /** - * Whether this device supports any OpenGL sharing extension (cl_khr_gl_sharing or cl_APPLE_gl_sharing) - */ - public boolean isGLSharingSupported() { - return hasExtension("cl_khr_gl_sharing") || hasExtension("cl_APPLE_gl_sharing"); - } - /** - * Whether this device supports the cl_khr_global_int32_base_atomics extension. - */ - public boolean isGlobalInt32BaseAtomicsSupported() { - return hasExtension("cl_khr_global_int32_base_atomics"); - } - /** - * Whether this device supports the cl_khr_global_int32_extended_atomics extension. - */ - public boolean isGlobalInt32ExtendedAtomicsSupported() { - return hasExtension("cl_khr_global_int32_extended_atomics"); - } - /** - * Whether this device supports the cl_khr_local_int32_base_atomics extension. - */ - public boolean isLocalInt32BaseAtomicsSupported() { - return hasExtension("cl_khr_local_int32_base_atomics"); - } - /** - * Whether this device supports the cl_khr_local_int32_extended_atomics extension. - */ - public boolean isLocalInt32ExtendedAtomicsSupported() { - return hasExtension("cl_khr_local_int32_extended_atomics"); - } - - /** Bit values for CL_DEVICE_QUEUE_PROPERTIES */ - public enum QueueProperties implements com.nativelibs4java.util.ValuedEnum { - - OutOfOrderExecModeEnable(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), - ProfilingEnable(CL_QUEUE_PROFILING_ENABLE); - - QueueProperties(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, QueueProperties.class); - } - } - - /** - * Describes the command-queue properties supported by the device.
      - * These properties are described in table 5.1.
      - * The mandated minimum capability is: ProfilingEnable. - */ - @InfoName("CL_DEVICE_QUEUE_PROPERTIES") - public EnumSet getQueueProperties() { - return QueueProperties.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_QUEUE_PROPERTIES)); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLEvent.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLEvent.java deleted file mode 100644 index 4c29fab73..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLEvent.java +++ /dev/null @@ -1,302 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import java.util.Arrays; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import org.bridj.*; -import org.bridj.ann.Ptr; -import static org.bridj.Pointer.*; - -/** - * OpenCL event object.
      - * Event objects can be used to refer to a kernel execution command (clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueNativeKernel), or read, write, map and copy commands on memory objects (clEnqueue{Read|Write|Map}{Buffer|Image}, clEnqueueCopy{Buffer|Image}, clEnqueueCopyBufferToImage, or clEnqueueCopyImageToBuffer).
      - * An event object can be used to track the execution status of a command.
      - * The API calls that enqueue commands to a command-queue create a new event object that is returned in the event argument.
      - * In case of an error enqueuing the command in the command-queue the event argument does not return an event object.
      - * The execution status of an enqueued command at any given point in time can be CL_QUEUED (command has been enqueued in the command-queue), CL_SUBMITTED (enqueued command has been submitted by the host to the device associated with the command-queue), CL_RUNNING (device is currently executing this command), CL_COMPLETE (command has successfully completed) or the appropriate error code if the command was abnormally terminated (this may be caused by a bad memory access etc.).
      - * The error code returned by a terminated command is a negative integer value.
      - * A command is considered to be complete if its execution status is CL_COMPLETE or is a negative integer value.
      - * If the execution of a command is terminated, the command-queue associated with this terminated command, and the associated context (and all other command-queues in this context) may no longer be available.
      - * The behavior of OpenCL API calls that use this context (and command-queues associated with this context) are now considered to be implementation- defined.
      - * The user registered callback function specified when context is created can be used to report appropriate error information.
      - * - * @author ochafik - */ -public class CLEvent extends CLAbstractEntity { - - /** - * Pass this to special value to any method that expects a variable number of events to wait for and that returns an event, to completely avoid returning the completion event (will return null instead of the event). - */ - public static final CLEvent FIRE_AND_FORGET = new CLEvent(null, -1); - - #declareInfosGetter("infos", "CL.clGetEventInfo") - - #declareInfosGetter("profilingInfos", "CL.clGetEventProfilingInfo") - - private final CLQueue queue; - - CLEvent(CLQueue queue, long evt) { - super(evt, false); - this.queue = queue; - } - - public CLQueue getQueue() { - return queue; - } - - public interface EventCallback { - public void callback(int executionStatus); - } - - /** - * Registers a user callback function for the completion execution status (CL_COMPLETE).
      - * @param callback - * @throws UnsupportedOperationException in OpenCL 1.0 - * @since OpenCL 1.1 - */ - public void setCompletionCallback(final EventCallback callback) { - setCallback(CL_COMPLETE, callback); - } - - private static final clSetEventCallback_arg1_callback eventCallback = new clSetEventCallback_arg1_callback() { - public void apply(@Ptr long evt, int executionStatus, @Ptr long callbackPeer) { - EventCallback callback = (EventCallback)JNI.refToObject(callbackPeer); - try { - callback.callback(executionStatus); - } finally { - JNI.deleteGlobalRef(callbackPeer); - } - } - }; - private static final long eventCallbackPeer = getPeer(pointerTo(eventCallback)); - - /** -#documentCallsFunction("clSetEventCallback") - * Registers a user callback function for a specific command execution status.
      - * The registered callback function will be called when the execution status of command associated with event changes to the execution status specified by command_exec_status. - * @param commandExecStatus specifies the command execution status for which the callback is registered. The command execution callback values for which a callback can be registered are: CL_COMPLETE. There is no guarantee that the callback functions registered for various execution status values for an event will be called in the exact order that the execution status of a command changes. - * @param callback - * @throws UnsupportedOperationException in OpenCL 1.0 - * @since OpenCL 1.1 - */ - public void setCallback(int commandExecStatus, final EventCallback callback) { - try { - error(CL.clSetEventCallback(getEntity(), commandExecStatus, eventCallbackPeer, JNI.newGlobalRef(callback))); - } catch (UnsatisfiedLinkError th) { - throw new UnsupportedOperationException("Cannot set event callback (OpenCL 1.1 feature): " + th, th); - } - } - - static CLEvent createEvent(final CLQueue queue, long evt) { - return createEvent(queue, evt, false); - } - - static CLEvent createEvent(final CLQueue queue, long evt, boolean isUserEvent) { - if (evt == 0) - return null; - - return isUserEvent ? - new CLUserEvent(queue, evt) : - new CLEvent(queue, evt); - } - - static CLEvent createEventFromPointer(CLQueue queue, Pointer evt1) { - if (evt1 == null) - return null; - - long peer = evt1.getSizeT(); - if (peer == 0) - return null; - - return new CLEvent(queue, peer); - } - - - /** - * Wait for this event, blocking the caller thread independently of any queue until all of the command associated with this events completes. - */ - public void waitFor() { - waitFor(this); - } - - /** -#documentCallsFunction("clWaitForEvents") - * Wait for events, blocking the caller thread independently of any queue until all of the commands associated with the events completed. - * @param eventsToWaitFor List of events which completion is to be waited for - */ - public static void waitFor(CLEvent... eventsToWaitFor) { - if (eventsToWaitFor.length == 0) - return; - - try { - #declareReusablePtrs() - #declareEventsIn() - if (eventsIn == null) - return; - error(CL.clWaitForEvents(#eventsInArgsRaw())); - } catch (Exception ex) { - throw new RuntimeException("Exception while waiting for events " + Arrays.asList(eventsToWaitFor), ex); - } - } - - /** - * Invoke an action in a separate thread only after completion of the command associated with this event.
      - * Returns immediately. - * @param action an action to be ran - * @throws IllegalArgumentException if action is null - */ - public void invokeUponCompletion(final Runnable action) { - invokeUponCompletion(action, this); - } - - /** - * Invoke an action in a separate thread only after completion of all of the commands associated with the specified events.
      - * Returns immediately. - * @param action an action to be ran - * @param eventsToWaitFor list of events which commands's completion should be waited for before the action is ran - * @throws IllegalArgumentException if action is null - */ - public static void invokeUponCompletion(final Runnable action, final CLEvent... eventsToWaitFor) { - if (action == null) - throw new IllegalArgumentException("Null action !"); - - new Thread() { - public void run() { - waitFor(eventsToWaitFor); - action.run(); - } - }.start(); - } - - static boolean containsFireAndForget(CLEvent[] eventsToWaitFor) { - for (int i = eventsToWaitFor.length; i-- != 0;) { - if (eventsToWaitFor[i] == FIRE_AND_FORGET) - return true; - } - return false; - } - - @Override - protected void clear() { - error(CL.clReleaseEvent(getEntity())); - } - - /** Values for CL_EVENT_COMMAND_EXECUTION_STATUS */ - public enum CommandExecutionStatus implements com.nativelibs4java.util.ValuedEnum { - /** command has been enqueued in the command-queue */ - Queued(CL_QUEUED), - /** enqueued command has been submitted by the host to the device associated with the command-queue */ - Submitted(CL_SUBMITTED), - /** device is currently executing this command */ - Running(CL_RUNNING), - /** the command has completed */ - Complete(CL_COMPLETE); - - CommandExecutionStatus(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static CommandExecutionStatus getEnum(long v) { return EnumValues.getEnum(v, CommandExecutionStatus.class); } - } - - /** - * Return the execution status of the command identified by event.
      - * @throws CLException is the execution status denotes an error - */ - public CommandExecutionStatus getCommandExecutionStatus() { - int v = infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); - CommandExecutionStatus status = CommandExecutionStatus.getEnum(v); - if (status == null) - error(v); - return status; - } - /** - * Return the execution status of the command identified by event.
      - * @throws CLException is the execution status denotes an error - */ - @InfoName("CL_EVENT_COMMAND_EXECUTION_STATUS") - public int getCommandExecutionStatusValue() { - return infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); - } - - /** Values for CL_EVENT_COMMAND_TYPE */ - public enum CommandType implements com.nativelibs4java.util.ValuedEnum { - NDRangeKernel(CL_COMMAND_NDRANGE_KERNEL), - Task(CL_COMMAND_TASK), - NativeKernel(CL_COMMAND_NATIVE_KERNEL), - ReadBuffer(CL_COMMAND_READ_BUFFER), - WriteBuffer(CL_COMMAND_WRITE_BUFFER), - CopyBuffer(CL_COMMAND_COPY_BUFFER), - ReadImage(CL_COMMAND_READ_IMAGE), - WriteImage(CL_COMMAND_WRITE_IMAGE), - CopyImage(CL_COMMAND_COPY_IMAGE), - CopyBufferToImage(CL_COMMAND_COPY_BUFFER_TO_IMAGE), - CopyImageToBuffer(CL_COMMAND_COPY_IMAGE_TO_BUFFER), - MapBuffer(CL_COMMAND_MAP_BUFFER), - CommandMapImage(CL_COMMAND_MAP_IMAGE), - UnmapMemObject(CL_COMMAND_UNMAP_MEM_OBJECT), - Marker(CL_COMMAND_MARKER), - AcquireGLObjects(CL_COMMAND_ACQUIRE_GL_OBJECTS), - ReleaseGLObjects(CL_COMMAND_RELEASE_GL_OBJECTS); - - CommandType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static CommandType getEnum(long v) { return EnumValues.getEnum(v, CommandType.class); } - } - - /** - * Return the command associated with event. - */ - @InfoName("CL_EVENT_COMMAND_TYPE") - public CommandType getCommandType() { - return CommandType.getEnum(infos.getInt(getEntity(), CL_EVENT_COMMAND_TYPE)); - } - - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event is enqueued in a command-queue by the host. - */ - @InfoName("CL_CL_PROFILING_COMMAND_QUEUED") - public long getProfilingCommandQueued() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_QUEUED); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event that has been enqueued is submitted by the host to the device associated with the command- queue. - */ - @InfoName("CL_CL_PROFILING_COMMAND_SUBMIT") - public long getProfilingCommandSubmit() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_SUBMIT); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event starts execution on the device. - */ - @InfoName("CL_CL_PROFILING_COMMAND_START") - public long getProfilingCommandStart() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_START); - } - - /** - * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event has finished execution on the device. - */ - @InfoName("CL_CL_PROFILING_COMMAND_END") - public long getProfilingCommandEnd() { - return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_END); - } - - - @Override - public String toString() { - return "Event {commandType: " + getCommandType() + "}"; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLException.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLException.java deleted file mode 100644 index e0a8e35c6..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLException.java +++ /dev/null @@ -1,225 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.ochafik.util.string.StringUtils; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.*; -import java.lang.reflect.*; -import static com.nativelibs4java.opencl.JavaCL.log; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * OpenCL error - * @author ochafik - */ -@SuppressWarnings("serial") -public class CLException extends RuntimeException { - protected int code; - CLException(String message, int code) { - super(message); - this.code = code; - } - public int getCode() { - return code; - } - - @Retention(RetentionPolicy.RUNTIME) - public @interface ErrorCode { - int value(); - } - - public static class CLTypedException extends CLException { - protected String message; - public CLTypedException() { - super("", 0); - ErrorCode code = getClass().getAnnotation(ErrorCode.class); - this.code = code.value(); - this.message = getClass().getSimpleName(); - } - - @Override - public String getMessage() { - return message + logSuffix; - } - - void setKernelArg(CLKernel kernel, int argIndex) { - message += " (kernel name = " + kernel.getFunctionName() + ", num args = " + kernel.getNumArgs() + ", arg index = " + argIndex; - CLProgram program = kernel.getProgram(); - if (program != null) - message += ", source = <<<\n\t" + program.getSource().replaceAll("\n", "\n\t"); - - message += "\n>>> )"; - } - - } - - @ErrorCode(CL_MISALIGNED_SUB_BUFFER_OFFSET) - public static class MisalignedSubBufferOffset extends CLTypedException {} - @ErrorCode(CL_OUT_OF_RESOURCES) - public static class OutOfResources extends CLTypedException {} - @ErrorCode(CL_COMPILER_NOT_AVAILABLE) - public static class CompilerNotAvailable extends CLTypedException {} - @ErrorCode(CL_INVALID_GLOBAL_WORK_SIZE) - public static class InvalidGlobalWorkSize extends CLTypedException {} - @ErrorCode(CL_MAP_FAILURE) - public static class MapFailure extends CLTypedException {} - @ErrorCode(CL_MEM_OBJECT_ALLOCATION_FAILURE) - public static class MemObjectAllocationFailure extends CLTypedException {} - @ErrorCode(CL_INVALID_EVENT_WAIT_LIST) - public static class InvalidEventWaitList extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_INDEX) - public static class InvalidArgIndex extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_SIZE) - public static class InvalidArgSize extends CLTypedException {} - @ErrorCode(CL_INVALID_ARG_VALUE) - public static class InvalidArgValue extends CLTypedException {} - @ErrorCode(CL_INVALID_BINARY) - public static class InvalidBinary extends CLTypedException {} - @ErrorCode(CL_INVALID_EVENT) - public static class InvalidEvent extends CLTypedException {} - @ErrorCode(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR) - public static class InvalidImageFormatDescriptor extends CLTypedException {} - @ErrorCode(CL_INVALID_IMAGE_SIZE) - public static class InvalidImageSize extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_DIMENSION) - public static class InvalidWorkDimension extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_GROUP_SIZE) - public static class InvalidWorkGroupSize extends CLTypedException {} - @ErrorCode(CL_INVALID_WORK_ITEM_SIZE) - public static class InvalidWorkItemSize extends CLTypedException {} - @ErrorCode(CL_INVALID_OPERATION) - public static class InvalidOperation extends CLTypedException {} - @ErrorCode(CL_INVALID_BUFFER_SIZE) - public static class InvalidBufferSize extends CLTypedException {} - @ErrorCode(CL_INVALID_GLOBAL_OFFSET) - public static class InvalidGlobalOffset extends CLTypedException {} - @ErrorCode(CL_OUT_OF_HOST_MEMORY) - public static class OutOfHostMemory extends CLTypedException {} - @ErrorCode(CL_INVALID_COMMAND_QUEUE) - public static class InvalidCommandQueue extends CLTypedException {} - @ErrorCode(CL_MEM_COPY_OVERLAP) - public static class MemCopyOverlap extends CLTypedException {} - @ErrorCode(CL_INVALID_CONTEXT) - public static class InvalidContext extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL) - public static class InvalidKernel extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_CONTEXT_APPLE) - public static class InvalidGLContextApple extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR) - public static class InvalidGLShareGroupReference extends CLTypedException {} - @ErrorCode(CL_INVALID_GL_OBJECT) - public static class InvalidGLObject extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_ARGS) - public static class InvalidKernelArgs extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_DEFINITION) - public static class InvalidKernelDefinition extends CLTypedException {} - @ErrorCode(CL_INVALID_KERNEL_NAME) - public static class InvalidKernelName extends CLTypedException {} - @ErrorCode(CL_INVALID_MEM_OBJECT) - public static class InvalidMemObject extends CLTypedException {} - @ErrorCode(CL_INVALID_MIP_LEVEL) - public static class InvalidMipLevel extends CLTypedException {} - @ErrorCode(CL_INVALID_PROGRAM) - public static class InvalidProgram extends CLTypedException {} - @ErrorCode(CL_INVALID_PROGRAM_EXECUTABLE) - public static class InvalidProgramExecutable extends CLTypedException {} - @ErrorCode(CL_INVALID_QUEUE_PROPERTIES) - public static class InvalidQueueProperties extends CLTypedException {} - @ErrorCode(CL_INVALID_VALUE) - public static class InvalidValue extends CLTypedException {} - @ErrorCode(CL_INVALID_SAMPLER) - public static class InvalidSampler extends CLTypedException {} - @ErrorCode(CL_INVALID_DEVICE_TYPE) - public static class InvalidDeviceType extends CLTypedException {} - @ErrorCode(CL_INVALID_BUILD_OPTIONS) - public static class InvalidBuildOptions extends CLTypedException {} - @ErrorCode(CL_BUILD_PROGRAM_FAILURE) - public static class BuildProgramFailure extends CLTypedException {} - - public static String errorString(int err) { - if (err == CL_SUCCESS) - return null; - - List candidates = new ArrayList(); - for (Field f : OpenCLLibrary.class.getDeclaredFields()) { - if (!Modifier.isStatic(f.getModifiers())) { - continue; - } - if (f.getType().equals(Integer.TYPE)) { - try { - int i = (Integer) f.get(null); - if (i == err) { - String name = f.getName(), lname = name.toLowerCase(); - if (lname.contains("invalid") || lname.contains("bad") || lname.contains("illegal") || lname.contains("wrong")) { - candidates.clear(); - candidates.add(name); - break; - } else - candidates.add(name); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return StringUtils.implode(candidates, " or "); - } - - static boolean failedForLackOfMemory(int err, int previousAttempts) { - switch (err) { - case CL_SUCCESS: - return false; - case CL_OUT_OF_HOST_MEMORY: - case CL_OUT_OF_RESOURCES: - case CL_MEM_OBJECT_ALLOCATION_FAILURE: - if (previousAttempts <= 1) { - System.gc(); - if (previousAttempts == 1) { - try { - Thread.sleep(100); - } catch (InterruptedException ex) {} - } - return true; - } - default: - error(err); - assert false; // won't reach - return false; - } - } - static final String logSuffix = System.getenv("CL_LOG_ERRORS") == null ? " (make sure to log all errors with environment variable CL_LOG_ERRORS=stdout)" : ""; - - static Map> typedErrorClassesByCode; - @SuppressWarnings("unchecked") - public static void error(int err) { - if (err == CL_SUCCESS) - return; - - if (typedErrorClassesByCode == null) { - typedErrorClassesByCode = new HashMap>(); - for (Class c : CLException.class.getDeclaredClasses()) { - if (c == CLTypedException.class || !CLTypedException.class.isAssignableFrom(c)) - continue; - typedErrorClassesByCode.put(c.getAnnotation(ErrorCode.class).value(), (Class)c); - } - } - CLException toThrow = null; - Class c = typedErrorClassesByCode.get(err); - if (c != null) { - try { - toThrow = c.newInstance(); - } catch (InstantiationException ex) { - assert log(Level.SEVERE, null, ex); - } catch (IllegalAccessException ex) { - assert log(Level.SEVERE, null, ex); - } - } - if (toThrow == null) - toThrow = new CLException("OpenCL Error : " + errorString(err) + logSuffix, err); - - throw toThrow; - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage.java deleted file mode 100644 index b14265d92..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage.java +++ /dev/null @@ -1,168 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FALSE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_ELEMENT_SIZE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_FORMAT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_TRUE; -import static com.nativelibs4java.util.NIOUtils.directCopy; - -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; - -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.NIOUtils; - -import com.nativelibs4java.util.Pair; -import org.bridj.*; -import static org.bridj.Pointer.*; - - -/** - * OpenCL Image Memory Object.
      - * An image object is used to store a two- or three- dimensional texture, frame-buffer or image
      - * An image object is used to represent a buffer that can be used as a texture or a frame-buffer. The elements of an image object are selected from a list of predefined image formats. - * @author Oliveir Chafik - */ -public abstract class CLImage extends CLMem { - - CLImageFormat format; - CLImage(CLContext context, long entityPeer, CLImageFormat format) { - super(context, -1, entityPeer); - this.format = format; - } - - - - /** - * Return image format descriptor specified when image is created with CLContext.create{Input|Output|InputOutput}{2D|3D}. - */ - @InfoName("CL_IMAGE_FORMAT") - public CLImageFormat getFormat() { - if (format == null) { - format = new CLImageFormat(new cl_image_format(infos.getMemory(getEntity(), CL_IMAGE_FORMAT))); - } - return format; - } - - /** - * Return size of each element of the image memory object given by image.
      - * An element is made up of n channels. The value of n is given in cl_image_format descriptor. - */ - @InfoName("CL_IMAGE_ELEMENT_SIZE") - public long getElementSize() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_ELEMENT_SIZE); - } - - /** -#documentCallsFunction("clEnqueueReadImage") - */ - protected CLEvent read(CLQueue queue, Pointer origin, Pointer region, long rowPitch, long slicePitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, origin, region, rowPitch, slicePitch, pointerToBuffer(out), blocking, eventsToWaitFor); - } - /** -#documentCallsFunction("clEnqueueReadImage") - */ - protected CLEvent read(CLQueue queue, Pointer origin, Pointer region, long rowPitch, long slicePitch, Pointer out, boolean blocking, CLEvent... eventsToWaitFor) { - /*if (!out.isDirect()) { - - }*/ - #declareReusablePtrsAndEventsInOutBlockable() - error(CL.clEnqueueReadImage( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - getPeer(origin), - getPeer(region), - rowPitch, - slicePitch, - getPeer(out), - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueWriteImage") - */ - protected CLEvent write(CLQueue queue, Pointer origin, Pointer region, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, origin, region, rowPitch, slicePitch, pointerToBuffer(in), blocking, eventsToWaitFor); - } - /** -#documentCallsFunction("clEnqueueWriteImage") - */ - protected CLEvent write(CLQueue queue, Pointer origin, Pointer region, long rowPitch, long slicePitch, Pointer in, boolean blocking, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOutBlockable() - error(CL.clEnqueueWriteImage( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - getPeer(origin), - getPeer(region), - rowPitch, - slicePitch, - getPeer(in), - #eventsInOutArgsRaw() - )); - CLEvent evt = #eventOutWrapper("queue"); - - if (!blocking) { - final Pointer toHold = in; - evt.invokeUponCompletion(new Runnable() { - public void run() { - // Make sure the GC held a reference to directData until the write was completed ! - toHold.order(); - } - }); - } - - return evt; - } - - protected Pair map(CLQueue queue, MapFlags flags, - Pointer offset3, Pointer length3, - Long imageRowPitch, - Long imageSlicePitch, - boolean blocking, CLEvent... eventsToWaitFor) - { - #declareReusablePtrsAndEventsInOutBlockable() - #declarePErr() - long mappedPeer = CL.clEnqueueMapImage( - queue.getEntity(), - getEntity(), - blocking ? CL_TRUE : CL_FALSE, - flags.value(), - getPeer(offset3), - getPeer(length3), - imageRowPitch == null ? 0 : getPeer(ptrs.sizeT3_1.pointerToSizeTs((long)imageRowPitch)), - imageSlicePitch == null ? 0 : getPeer(ptrs.sizeT3_1.pointerToSizeTs((long)imageSlicePitch)), - #eventsInOutArgsRaw(), - getPeer(pErr) - ); - #checkPErr() - return new Pair( - pointerToAddress(mappedPeer).getByteBuffer(getByteCount()), - #eventOutWrapper("queue") - ); - } - - /** -#documentCallsFunction("clEnqueueUnmapMemObject") - * see {@link CLImage2D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[]) } - * see {@link CLImage3D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[]) } - * @param queue - * @param buffer -#documentEventsToWaitForAndReturn() - */ - public CLEvent unmap(CLQueue queue, ByteBuffer buffer, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOut() - Pointer pBuffer = pointerToBuffer(buffer); - error(CL.clEnqueueUnmapMemObject(queue.getEntity(), getEntity(), getPeer(pBuffer), #eventsInOutArgsRaw())); - #returnEventOut("queue") - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage2D.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage2D.java deleted file mode 100644 index 8c83bfbaa..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage2D.java +++ /dev/null @@ -1,166 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import com.nativelibs4java.opencl.ImageIOUtils.ImageInfo; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_HEIGHT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_ROW_PITCH; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_WIDTH; - -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.Pair; - -/** - * OpenCL 2D Image Memory Object
      - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, java.awt.Image, boolean) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long) } - * see {@link CLContext#createImage2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, java.nio.Buffer, boolean) } - * see {@link CLContext#createImage2DFromGLRenderBuffer(com.nativelibs4java.opencl.CLMem.Usage, int) } - * see {@link CLContext#createImage2DFromGLTexture2D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLContext.GLTextureTarget, int, int) } - * @author Olivier Chafik - */ -public class CLImage2D extends CLImage { - CLImage2D(CLContext context, long entityPeer, CLImageFormat format) { - super(context, entityPeer, format); - } - - /** - * Return size in bytes of a row of elements of the image object given by image. - */ - @InfoName("CL_IMAGE_ROW_PITCH") - public long getRowPitch() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_ROW_PITCH); - } - - /** - * Return width of the image in pixels - */ - @InfoName("CL_IMAGE_WIDTH") - public long getWidth() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_WIDTH); - } - - /** - * Return height of the image in pixels - */ - @InfoName("CL_IMAGE_HEIGHT") - public long getHeight() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_HEIGHT); - } - - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent read(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - Pointer ptrOut = pointerToBuffer(out); - CLEvent evt = read(queue, minX, minY, width, height, rowPitch, ptrOut, blocking, eventsToWaitFor); - ptrOut.updateBuffer(out); // in case the buffer wasn't direct ! - return evt; - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent read(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Pointer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, pointerToSizeTs(minX, minY, 0), pointerToSizeTs(width, height, 1), rowPitch, 0, out, blocking, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, minX, minY, width, height, rowPitch, pointerToBuffer(in), blocking, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, long minX, long minY, long width, long height, long rowPitch, Pointer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, pointerToSizeTs(minX, minY, 0), pointerToSizeTs(width, height, 1), rowPitch, 0, in, blocking, eventsToWaitFor); - } - - /** - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - */ - public BufferedImage read(CLQueue queue, CLEvent... eventsToWaitFor) { - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - int imageType = info == null ? 0 : info.bufferedImageType; - if (imageType == 0) - throw new UnsupportedOperationException("Cannot convert image of format " + getFormat() + " to a BufferedImage."); - //imageType = BufferedImage.TYPE_INT_ARGB; - - BufferedImage im = new BufferedImage((int)getWidth(), (int)getHeight(), imageType); - read(queue, im, false, eventsToWaitFor); - return im; - } - /** - * @param eventsToWaitFor Events that need to complete before this particular command can be executed. - */ - public void read(CLQueue queue, BufferedImage imageOut, boolean allowDeoptimizingDirectWrite, CLEvent... eventsToWaitFor) { - //if (!getFormat().isIntBased()) - // throw new IllegalArgumentException("Image-read only supports int-based RGBA images"); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - int width = imageOut.getWidth(null), height = imageOut.getHeight(null); - - Pointer dataOut = allocateArray(info.bufferElementsClass, width * height * info.channelCount).order(getContext().getByteOrder()); - //Buffer dataOut = info.createBuffer(width, height, true); - //IntBuffer dataOut = directInts(width * height, getContext().getByteOrder()); - read(queue, 0, 0, width, height, 0, dataOut, true, eventsToWaitFor); - info.dataSetter.setData(imageOut, dataOut.getBuffer(), allowDeoptimizingDirectWrite); - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, Image image, CLEvent... eventsToWaitFor) { - return write(queue, image, 0, 0, image.getWidth(null), image.getHeight(null), false, false, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, Image image, boolean allowDeoptimizingDirectRead, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, image, 0, 0, image.getWidth(null), image.getHeight(null), allowDeoptimizingDirectRead, blocking, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, Image image, int destX, int destY, int width, int height, boolean allowDeoptimizingDirectRead, boolean blocking, CLEvent... eventsToWaitFor) { - //int imWidth = image.getWidth(null), height = image.getHeight(null); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - return write(queue, 0, 0, width, height, width * info.pixelByteSize, info.dataGetter.getData(image, null, false, allowDeoptimizingDirectRead, getContext().getByteOrder()), blocking, eventsToWaitFor); - } - public void write(CLQueue queue, BufferedImage imageIn, boolean allowDeoptimizingDirectRead, CLEvent... eventsToWaitFor) { - //if (!getFormat().isIntBased()) - // throw new IllegalArgumentException("Image read only supports int-based RGBA images"); - - int width = imageIn.getWidth(null), height = imageIn.getHeight(null); - ImageInfo info = ImageIOUtils.getBufferedImageInfo(getFormat()); - write(queue, 0, 0, width, height, 0, info.dataGetter.getData(imageIn, null, false, allowDeoptimizingDirectRead, getContext().getByteOrder()), true, eventsToWaitFor); - } - public void write(CLQueue queue, BufferedImage im) { - write(queue, im, false); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(0, 0), pointerToSizeTs(getWidth(), getHeight()), getWidth(), null, true, eventsToWaitFor).getFirst(); - } - public ByteBuffer map(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long lengthX, long lengthY, long rowPitch, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(offsetX, offsetY), pointerToSizeTs(lengthX, lengthY), rowPitch, null, true, eventsToWaitFor).getFirst(); - } - /** -#documentEventsToWaitForAndPairReturn("byte buffer") - */ - public Pair mapLater(CLQueue queue, MapFlags flags, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(0, 0), pointerToSizeTs(getWidth(), getHeight()), getWidth(), null, blocking, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndPairReturn("byte buffer") - */ - public Pair mapLater(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long lengthX, long lengthY, long rowPitch, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(offsetX, offsetY), pointerToSizeTs(lengthX, lengthY), rowPitch, null, blocking, eventsToWaitFor); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage3D.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage3D.java deleted file mode 100644 index 08f8fcc65..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImage3D.java +++ /dev/null @@ -1,76 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_DEPTH; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_IMAGE_SLICE_PITCH; - -import java.nio.Buffer; -import java.nio.ByteBuffer; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.Pair; - -import static org.bridj.Pointer.*; -/** - * OpenCL 3D Image Memory Object
      - * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long) } - * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, long, long) } - * see {@link CLContext#createImage3D(com.nativelibs4java.opencl.CLMem.Usage, com.nativelibs4java.opencl.CLImageFormat, long, long, long, long, long, java.nio.Buffer, boolean) } - * see {@link CLContext#createImage3DFromGLTexture3D(com.nativelibs4java.opencl.CLMem.Usage, int, int) } - * @author Olivier Chafik - */ -public class CLImage3D extends CLImage2D { - CLImage3D(CLContext context, long entityPeer, CLImageFormat format) { - super(context, entityPeer, format); - } - - /** - * Return size in bytes of a 2D slice for this 3D image object.
      - */ - @InfoName("CL_IMAGE_SLICE_PITCH") - public long getSlicePitch() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_SLICE_PITCH); - } - - /** - * Return depth of the image in pixels. - */ - @InfoName("CL_IMAGE_DEPTH") - public long getDepth() { - return infos.getIntOrLong(getEntity(), CL_IMAGE_DEPTH); - } - - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent read(CLQueue queue, long minX, long minY, long minZ, long width, long height, long depth, long rowPitch, long slicePitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) { - return read(queue, pointerToSizeTs(minX, minY, minZ), pointerToSizeTs(width, height, depth), rowPitch, slicePitch, out, blocking, eventsToWaitFor); - } - - /** -#documentEventsToWaitForAndReturn() - */ - public CLEvent write(CLQueue queue, long minX, long minY, long minZ, long width, long height, long depth, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) { - return write(queue, pointerToSizeTs(minX, minY, minZ), pointerToSizeTs(width, height, depth), rowPitch, slicePitch, in, blocking, eventsToWaitFor); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, 0, 0, 0, getWidth(), getHeight(), getDepth(), getWidth(), getHeight(), true, eventsToWaitFor); - } - /** -#documentEventsToWaitForAndPairReturn("mapped data") - */ - public Pair mapLater(CLQueue queue, MapFlags flags, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(0, 0, 0), pointerToSizeTs(getWidth(), getHeight(), getDepth()), getWidth(), getHeight(), true, eventsToWaitFor); - } - - public ByteBuffer map(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long offsetZ, long lengthX, long lengthY, long lengthZ, long rowPitch, long slicePitch, boolean blocking, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(offsetX, offsetY, offsetZ), pointerToSizeTs(lengthX, lengthY, lengthZ), rowPitch, slicePitch, true, eventsToWaitFor).getFirst(); - } - /** -#documentEventsToWaitForAndPairReturn("mapped data") - */ - public Pair mapLater(CLQueue queue, MapFlags flags, long offsetX, long offsetY, long offsetZ, long lengthX, long lengthY, long lengthZ, long rowPitch, long slicePitch, CLEvent... eventsToWaitFor) { - return map(queue, flags, pointerToSizeTs(offsetX, offsetY, offsetZ), pointerToSizeTs(lengthX, lengthY, lengthZ), rowPitch, slicePitch, true, eventsToWaitFor); - } - -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImageFormat.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImageFormat.java deleted file mode 100644 index 2144e70da..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLImageFormat.java +++ /dev/null @@ -1,256 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import com.nativelibs4java.opencl.library.cl_image_format; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * OpenCL Image Format - * see {@link CLContext#getSupportedImageFormats(com.nativelibs4java.opencl.CLMem.Flags, com.nativelibs4java.opencl.CLMem.ObjectType) } - * @author Olivier Chafik - */ -public class CLImageFormat { - - private final ChannelOrder channelOrder; - private final ChannelDataType channelDataType; - - CLImageFormat(cl_image_format fmt) { - this(ChannelOrder.getEnum(fmt.image_channel_order()), ChannelDataType.getEnum(fmt.image_channel_data_type())); - } - cl_image_format to_cl_image_format() { - return new cl_image_format().image_channel_order((int)channelOrder.value()).image_channel_data_type((int)channelDataType.value()); - } - public CLImageFormat(ChannelOrder channelOrder, ChannelDataType channelDataType) { - super(); - this.channelDataType = channelDataType; - this.channelOrder = channelOrder; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof CLImageFormat)) - return false; - CLImageFormat f = (CLImageFormat)obj; - if (channelOrder == null) { - if (f.channelOrder != null) - return false; - } else if (!channelOrder.equals(f.channelOrder)) - return false; - - - if (channelDataType == null) { - return f.channelDataType == null; - } else return channelDataType.equals(f.channelDataType); - } - - @Override - public int hashCode() { - int h = super.hashCode(); - if (channelOrder != null) - h ^= channelOrder.hashCode(); - if (channelDataType != null) - h ^= channelDataType.hashCode(); - return h; - } - - public boolean isIntBased() { - if (channelDataType == null || channelOrder == null) - return false; - switch (getChannelOrder()) { - case ARGB: - case BGRA: - case RGBA: - switch (getChannelDataType()) { - case SNormInt8: - case SignedInt8: - case UNormInt8: - case UnsignedInt8: - return true; - } - } - return false; - } - public final ChannelOrder getChannelOrder() { - return channelOrder; - } - public final ChannelDataType getChannelDataType() { - return channelDataType; - } - - @Override - public String toString() { - return "(" + channelOrder + ", " + channelDataType + ")"; - } - - - - public enum ChannelOrder implements com.nativelibs4java.util.ValuedEnum { - - /** - * components of channel data: (r, 0.0, 0.0, 1.0) - */ - R(CL_R), - /** - * components of channel data: (r, 0.0, 0.0, 1.0) - * @since OpenCL 1.1 - */ - Rx(CL_Rx), - /** - * components of channel data: (0.0, 0.0, 0.0, a) - */ - A(CL_A), - /** - * components of channel data: (I, I, I, I)
      - * This format can only be used if channel data type = CL_UNORM_INT8, CL_UNORM_INT16, CL_SNORM_INT8, CL_SNORM_INT16, CL_HALF_FLOAT or CL_FLOAT. - */ - INTENSITY(CL_INTENSITY), - /** - * components of channel data: (L, L, L, 1.0)
      - * This format can only be used if channel data type = CL_UNORM_INT8, CL_UNORM_INT16, CL_SNORM_INT8, CL_SNORM_INT16, CL_HALF_FLOAT or CL_FLOAT. - */ - LUMINANCE(CL_LUMINANCE), - /** - * components of channel data: (r, g, 0.0, 1.0) - */ - RG(CL_RG), - /** - * components of channel data: (r, g, 0.0, 1.0) - * @since OpenCL 1.1 - */ - RGx(CL_RGx), - /** - * components of channel data: (r, 0.0, 0.0, a) - */ - RA(CL_RA), - /** - * components of channel data: (r, g, b, 1.0)
      - * This format can only be used if channel data type = CL_UNORM_SHORT_565, CL_UNORM_SHORT_555 or CL_UNORM_INT101010. - */ - RGB(CL_RGB), - /** - * components of channel data: (r, g, b, 1.0)
      - * This format can only be used if channel data type = CL_UNORM_SHORT_565, CL_UNORM_SHORT_555 or CL_UNORM_INT101010. - * @since OpenCL 1.1 - */ - RGBx(CL_RGBx), - /** - * components of channel data: (r, g, b, a) - */ - RGBA(CL_RGBA), - /** - * components of channel data: (r, g, b, a) - */ - ARGB(CL_ARGB), - /** - * components of channel data: (r, g, b, a)
      - * This format can only be used if channel data type = CL_UNORM_INT8, CL_SNORM_INT8, CL_SIGNED_INT8 or CL_UNSIGNED_INT8. - */ - BGRA(CL_BGRA); - - - ChannelOrder(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static ChannelOrder getEnum(long v) { return EnumValues.getEnum(v, ChannelOrder.class); } - - } - - /** - * For example, to specify a normalized unsigned 8-bit / channel RGBA image, image_channel_order = CL_RGBA, and image_channel_data_type = CL_UNORM_INT8. The memory layout of this image format is described below: - */ - public enum ChannelDataType implements com.nativelibs4java.util.ValuedEnum { - /** - * Each channel component is a normalized signed 8-bit integer value - */ - SNormInt8(CL_SNORM_INT8, 8), - /** - * Each channel component is a normalized signed 16-bit integer value - */ - SNormInt16(CL_SNORM_INT16, 16), - /** - * Each channel component is a normalized unsigned 8-bit integer value - */ - UNormInt8(CL_UNORM_INT8, 8), - /** - * Each channel component is a normalized unsigned 16- bit integer value - */ - UNormInt16(CL_UNORM_INT16, 16), - /** - * Represents a normalized 5-6-5 3-channel RGB image.
      - * The channel order must be CL_RGB or CL_RGBx.
      - * CL_UNORM_SHORT_565 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
      - * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
      - * For CL_UNORM_SHORT_565, R is in bits 15:11, G is in bits 10:5 and B is in bits 4:0. - */ - UNormShort565(CL_UNORM_SHORT_565, 16/* ?? */), - /** - * Represents a normalized x-5-5-5 4-channel xRGB image.
      - * The channel order must be CL_RGB or CL_RGBx.
      - * CL_UNORM_SHORT_555 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
      - * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
      - * For CL_UNORM_SHORT_555, bit 15 is undefined, R is in bits 14:10, G in bits 9:5 and B in bits 4:0. - */ - UNormShort555(CL_UNORM_SHORT_555, 15/* ?? */), - /** - * Represents a normalized x-10-10-10 4-channel xRGB image.
      - * The channel order must be CL_RGB or CL_RGBx.
      - * CL_UNORM_INT_101010 is a special cases of packed image format where the channels of each element are packed into a single unsigned short or unsigned int.
      - * For this special packed image format, the channels are normally packed with the first channel in the most significant bits of the bitfield, and successive channels occupying progressively less significant locations.
      - * For CL_UNORM_INT_101010, bits 31:30 are undefined, R is in bits 29:20, G in bits 19:10 and B in bits 9:0. - */ - UNormInt101010(CL_UNORM_INT_101010, 30/* TODO ?? */), - /** - * Each channel component is an unnormalized signed 8- bit integer value - */ - SignedInt8(CL_SIGNED_INT8, 8), - /** - * Each channel component is an unnormalized signed 16- bit integer value - */ - SignedInt16(CL_SIGNED_INT16, 16), - /** - * Each channel component is an unnormalized signed 32- bit integer value - */ - SignedInt32(CL_SIGNED_INT32, 32), - /** - * Each channel component is an unnormalized unsigned 8-bit integer value - */ - UnsignedInt8(CL_UNSIGNED_INT8, 8), - /** - * Each channel component is an unnormalized unsigned 16-bit integer value - */ - UnsignedInt16(CL_UNSIGNED_INT16, 16), - /** - * Each channel component is an unnormalized unsigned 32-bit integer value - */ - UnsignedInt32(CL_UNSIGNED_INT32, 32), - /** - * Each channel component is a 16-bit half-float value - */ - HalfFloat(CL_HALF_FLOAT, 16), - /** - * Each channel component is a single precision floating- point value - */ - Float(CL_FLOAT, 32); - - ChannelDataType(long value, int bits) { - this.SIZE = bits; - this.value = value; - } - /** - * Size of this ChannelDataType, in bits - */ - public final int SIZE; - long value; - @Override - public long value() { return value; } - public static ChannelDataType getEnum(long v) { return EnumValues.getEnum(v, ChannelDataType.class); } - } - - static CLImageFormat INT_ARGB_FORMAT = new CLImageFormat(ChannelOrder.BGRA, ChannelDataType.UNormInt8); - //static CLImageFormat INT_ARGB_FORMAT = new CLImageFormat(ChannelOrder.RGBA, ChannelDataType.UNormInt8); -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLInfoGetter.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLInfoGetter.java deleted file mode 100644 index 326ed3d69..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLInfoGetter.java +++ /dev/null @@ -1,118 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLException.error; - -import org.bridj.*; -import static org.bridj.Pointer.*; - -import org.bridj.ann.Ptr; - -/** - * - * @author ochafik - */ -abstract class CLInfoGetter { - - protected abstract int getInfo(long entity, int infoTypeEnum, long size, Pointer out, Pointer sizeOut); - - public String getString(@Ptr long entity, int infoName) { - Pointer pLen = allocateSizeT(); - error(getInfo(entity, infoName, 0, null, pLen)); - - int len = (int)pLen.getSizeT(); - if (len == 0) { - return ""; - } - Pointer buffer = allocateBytes(len + 1); - error(getInfo(entity, infoName, len, buffer, null)); - - return buffer.getCString(); - } - - public Pointer getPointer(@Ptr long entity, int infoName) { - Pointer pLen = allocateSizeT(); - Pointer> mem = allocatePointer(); - error(getInfo(entity, infoName, Pointer.SIZE, mem, pLen)); - if (pLen.getSizeT() != Pointer.SIZE) { - throw new RuntimeException("Not a pointer : len = " + pLen.get()); - } - return mem.get(); - } - - public Pointer getMemory(@Ptr long entity, int infoName) { - Pointer pLen = allocateSizeT(); - error(getInfo(entity, infoName, 0, null, pLen)); - - int len = (int)pLen.getSizeT(); - Pointer buffer = allocateBytes(len); - error(getInfo(entity, infoName, len, buffer, null)); - - return buffer; - } - - public long[] getNativeSizes(@Ptr long entity, int infoName, int n) { - int nBytes = SizeT.SIZE * n; - Pointer pLen = pointerToSizeT(nBytes); - Pointer mem = allocateSizeTs(n); - error(getInfo(entity, infoName, nBytes, mem, pLen)); - - int actualLen = (int)pLen.getSizeT(); - if (actualLen != nBytes) { - throw new RuntimeException("Not a Size[" + n + "] : len = " + actualLen); - } - return mem.getSizeTs(n); - } - - public int getOptionalFeatureInt(@Ptr long entity, int infoName) { - try { - return getInt(entity, infoName); - } catch (CLException.InvalidValue ex) { - throw new UnsupportedOperationException("Cannot get value " + infoName, ex); - } catch (CLException.InvalidOperation ex) { - throw new UnsupportedOperationException("Cannot get value " + infoName, ex); - } - } - public int getInt(@Ptr long entity, int infoName) { - return (int)getIntOrLong(entity, infoName); - } - - public boolean getBool(@Ptr long entity, int infoName) { - Pointer pLen = allocateSizeT(); - Pointer mem = allocateBytes(8); - error(getInfo(entity, infoName, 8, mem, pLen)); - - long len = pLen.getSizeT(); - switch ((int)len) { - case 1: - return mem.getByte() != 0; - case 2: - return mem.getShort() != 0; - case 4: - return mem.getInt() != 0; - case 8: - return mem.getLong() != 0; - case 0: - // HACK to accommodate ATI Stream on Linux 32 bits (CLPlatform.isAvailable()) - //if (JNI.isLinux()) - return true; - default: - throw new RuntimeException("Not a BOOL : len = " + len); - } - } - - public long getIntOrLong(@Ptr long entity, int infoName) { - Pointer pLen = allocateSizeT(); - Pointer mem = allocateLong(); - error(getInfo(entity, infoName, 8, mem, pLen)); - - switch ((int)pLen.getSizeT()) { - case 4: - return mem.getInt(); - case 8: - return mem.getLong(); - default: - throw new RuntimeException("Not a native long : len = " + pLen.get()); - } - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLKernel.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLKernel.java deleted file mode 100755 index 347f46222..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLKernel.java +++ /dev/null @@ -1,470 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.*; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.util.HashMap; -import java.util.Map; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel; -import com.nativelibs4java.util.NIOUtils; - -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * OpenCL kernel.
      - * A kernel is a function declared in a program.
      - * A kernel is identified by the __kernel qualifier applied to any function in a program.
      - * A kernel object encapsulates the specific __kernel function declared in a program and the argument values to be used when executing this __kernel function.
      - *
      - * Kernels can be queued for execution in a CLQueue (see enqueueTask and enqueueNDRange) - * See {@link CLProgram#createKernel(java.lang.String, java.lang.Object[])} and {@link CLProgram#createKernels()} - * @author Olivier Chafik - */ -public class CLKernel extends CLAbstractEntity { - - protected final CLProgram program; - protected String name; - - #declareInfosGetter("infos", "CL.clGetKernelInfo") - - private volatile CLInfoGetter kernelInfos; - protected synchronized CLInfoGetter getKernelInfos() { - if (kernelInfos == null) - kernelInfos = new CLInfoGetter() { - - @Override - protected int getInfo(long entity, int infoTypeEnum, long size, Pointer out, Pointer sizeOut) { - return CL.clGetKernelWorkGroupInfo(getEntity(), entity, infoTypeEnum, size, getPeer(out), getPeer(sizeOut)); - } - }; - return kernelInfos; - } - - private final static int MAX_TMP_ITEMS = 16, MAX_TMP_ITEM_SIZE = 8; - - private final Pointer localPointer = Pointer.allocateBytes(MAX_TMP_ITEM_SIZE * MAX_TMP_ITEMS).withoutValidityInformation(); - - private final int contextAddressBits; - - CLKernel(CLProgram program, String name, long entity) { - super(entity); - this.program = program; - this.name = name; - this.contextAddressBits = getProgram().getContext().getAddressBits(); - } - - public CLProgram getProgram() { - return program; - } - - public String toString() { - return getFunctionName() + " {args: " + getNumArgs() + "}";//, workGroupSize = " + getWorkGroupSize() + ", localMemSize = " + getLocalMemSize() + "}"; - } - - /** - * Returns the preferred multiple of work- group size for launch.
      - * This is a performance hint.
      - * Specifying a work- group size that is not a multiple of the value returned by this query as the value of the local work size argument to clEnqueueNDRangeKernel will not fail to enqueue the kernel for execution unless the work-group size specified is larger than the device maximum. - * @since OpenCL 1.1 - */ - public Map getPreferredWorkGroupSizeMultiple() { - try { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE)); - return ret; - } catch (Throwable th) { - // TODO check if supposed to handle OpenCL 1.1 - throw new UnsupportedOperationException("Cannot get CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE (OpenCL 1.1 feature).", th); - } - } - - /** - * This provides a mechanism for the application to query the maximum work-group size that can be used to execute a kernel on a specific device given by device.
      - * The OpenCL implementation uses the resource requirements of the kernel (register usage etc.) to determine what this work- group size should be.
      - * See CL_KERNEL_WORK_GROUP_SIZE - */ - public Map getWorkGroupSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_WORK_GROUP_SIZE)); - return ret; - } - - /** - * Returns the work-group size specified by the __attribute__((reqd_work_gr oup_size(X, Y, Z))) qualifier.
      - * Refer to section 6.7.2.
      - * If the work-group size is not specified using the above attribute qualifier (0, 0, 0) is returned.
      - * See CL_KERNEL_COMPILE_WORK_GROUP_SIZE - * @return for each CLDevice, array of 3 longs - */ - public Map getCompileWorkGroupSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getNativeSizes(device.getEntity(), CL_KERNEL_COMPILE_WORK_GROUP_SIZE, 3)); - return ret; - } - - /** - * Returns the amount of local memory in bytes being used by a kernel.
      - * This includes local memory that may be needed by an implementation to execute the kernel, variables declared inside the kernel with the __local address qualifier and local memory to be allocated for arguments to the kernel declared as pointers with the __local address qualifier and whose size is specified with clSetKernelArg.
      - * If the local memory size, for any pointer argument to the kernel declared with the __local address qualifier, is not specified, its size is assumed to be 0.
      - * See CL_KERNEL_LOCAL_MEM_SIZE - */ - public Map getLocalMemSize() { - CLDevice[] devices = program.getDevices(); - Map ret = new HashMap(devices.length); - for (CLDevice device : devices) - ret.put(device, getKernelInfos().getIntOrLong(device.getEntity(), CL_KERNEL_LOCAL_MEM_SIZE)); - return ret; - } - - public void setArgs(Object... args) { - //assert getNumArgs() == args.length; - for (int i = 0, n = args.length; i < n; i++) { - setObjectArg(i, args[i]); - } - } - - public static final Object NULL_POINTER_KERNEL_ARGUMENT = new Object() {}; - - public void setObjectArg(int iArg, Object arg) { - boolean supported = true; - Class cls; - if (arg instanceof CLAbstractEntity) { - setArg(iArg, (CLAbstractEntity) arg); - } else if (arg instanceof Number) { - if (arg instanceof Integer) { - setArg(iArg, (Integer) arg); - } else if (arg instanceof Long) { - setArg(iArg, (Long) arg); - } else if (arg instanceof Short) { - setArg(iArg, (Short) arg); - } else if (arg instanceof Byte) { - setArg(iArg, (Byte) arg); - } else if (arg instanceof Float) { - setArg(iArg, (Float) arg); - } else if (arg instanceof Double) { - setArg(iArg, (Double) arg); - } else { - supported = false; - } - } else if (arg instanceof LocalSize) { - setArg(iArg, (LocalSize)arg); - } else if (arg instanceof Boolean) { - setArg(iArg, (Boolean)arg); - } else if (arg instanceof SizeT) { - setArg(iArg, (SizeT)arg); - } else if (arg == NULL_POINTER_KERNEL_ARGUMENT) { - setArg(iArg, SizeT.ZERO); - } else if ((cls = arg.getClass()).isArray()) { - if (arg instanceof int[]) { - setArg(iArg, (int[])arg); - } else if (arg instanceof long[]) { - setArg(iArg, (long[])arg); - } else if (arg instanceof short[]) { - setArg(iArg, (short[])arg); - } else if (arg instanceof double[]) { - setArg(iArg, (double[])arg); - } else if (arg instanceof float[]) { - setArg(iArg, (float[])arg); - } else if (arg instanceof byte[]) { - setArg(iArg, (byte[])arg); - } else if (arg instanceof boolean[]) { - setArg(iArg, (boolean[])arg); - } else { - supported = false; - } - } else if (arg instanceof Pointer) { - setArg(iArg, (Pointer)arg); - } else if (arg instanceof Buffer) { - setArg(iArg, pointerToBuffer((Buffer) arg)); - } else { - supported = false; - } - if (arg == null) - throw new IllegalArgumentException("Null arguments are not accepted. Please use CLKernel.NULL_POINTER_KERNEL_ARGUMENT instead."); - - if (!supported) { - throw new IllegalArgumentException("Cannot handle kernel arguments of type " + arg.getClass().getName() + ". Use CLKernel.get() and OpenCL4Java directly."); - } - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, LocalSize arg) { - setLocalArg(i, arg.size); - } - public void setLocalArg(int argIndex, long localArgByteLength) { - setKernelArg(argIndex, localArgByteLength, null); - } - - private void setKernelArg(int i, long size, Pointer ptr) { - if (size <= 0) - throw new IllegalArgumentException("Kernel args must have a known byte size, given " + size + " instead."); - try { - error(CL.clSetKernelArg(getEntity(), i, size, getPeer(ptr))); - } catch (CLTypedException ex) { - ex.setKernelArg(this, i); - throw ex; - } - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, Pointer ptr) { - setKernelArg(i, ptr.getValidBytes(), ptr); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, float[] arg) { - setKernelArg(i, arg.length * 4, arg.length <= MAX_TMP_ITEMS ? localPointer.setFloats(arg) : pointerToFloats(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, int[] arg) { - setKernelArg(i, arg.length * 4, arg.length <= MAX_TMP_ITEMS ? localPointer.setInts(arg) : pointerToInts(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, double[] arg) { - setKernelArg(i, arg.length * 8, arg.length <= MAX_TMP_ITEMS ? localPointer.setDoubles(arg) : pointerToDoubles(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, long[] arg) { - setKernelArg(i, arg.length * 8, arg.length <= MAX_TMP_ITEMS ? localPointer.setLongs(arg) : pointerToLongs(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, short[] arg) { - setKernelArg(i, arg.length * 2, arg.length <= MAX_TMP_ITEMS ? localPointer.setShorts(arg) : pointerToShorts(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, byte[] arg) { - setKernelArg(i, arg.length, arg.length <= MAX_TMP_ITEMS ? localPointer.setBytes(arg) : pointerToBytes(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, boolean[] arg) { - setKernelArg(i, arg.length, arg.length <= MAX_TMP_ITEMS ? localPointer.setBooleans(arg) : pointerToBooleans(arg)); - } - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, char[] arg) { - setKernelArg(i, arg.length * 2, arg.length <= MAX_TMP_ITEMS ? localPointer.setChars(arg) : pointerToChars(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, SizeT arg) { - switch (contextAddressBits) { - case 32: - setKernelArg(i, 4, localPointer.setInt(arg.intValue())); - break; - case 64: - setKernelArg(i, 8, localPointer.setLong(arg.longValue())); - break; - default: - setKernelArg(i, SizeT.SIZE, localPointer.setSizeT(arg.longValue())); - break; - } - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, int arg) { - setKernelArg(i, 4, localPointer.setInt(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, long arg) { - setKernelArg(i, 8, localPointer.setLong(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, short arg) { - setKernelArg(i, 2, localPointer.setShort(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, byte arg) { - setKernelArg(i, 1, localPointer.setByte(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, boolean arg) { - setKernelArg(i, 1, localPointer.setByte(arg ? (byte)1 : (byte)0)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, float arg) { - setKernelArg(i, 4, localPointer.setFloat(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, double arg) { - setKernelArg(i, 8, localPointer.setDouble(arg)); - } - - /** -#documentCallsFunction("clSetKernelArg") - */ - public void setArg(int i, CLAbstractEntity arg) { - setKernelArg(i, Pointer.SIZE, localPointer.setSizeT(arg.getEntity())); - } - - @Override - protected void clear() { - error(CL.clReleaseKernel(getEntity())); - } - - private static final Pointer oneNL = pointerToSizeT(1); - /** -#documentCallsFunction("clEnqueueTask") - * Enqueues a command to execute a kernel on a device.
      - * The kernel is executed using a single work-item. - * @param queue -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueTask(CLQueue queue, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOut() - error(CL.clEnqueueTask(queue.getEntity(), getEntity(), #eventsInOutArgsRaw())); - #returnEventOut("queue") - } - - /** -#documentCallsFunction("clEnqueueNDRangeKernel") - * Enqueues a command to execute a kernel on a device (see {@link CLKernel#enqueueNDRange(CLQueue, int[], int[], int[], CLEvent[])}) - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param localWorkSizes Each element describes the number of work-items that make up a work-group (also referred to as the size of the work-group) that will execute the kernel specified by kernel. The total number of work-items in a work-group is computed as localWorkSizes[0] * ... * localWorkSizes[localWorkSizes.length - 1]. The total number of work-items in the work-group must be less than or equal to the CL_DEVICE_MAX_WORK_GROUP_SIZE value specified in table 4.3 and the number of work- items specified in localWorkSizes[0], ... localWorkSizes[localWorkSizes.length - 1] must be less than or equal to the corresponding values specified by CLDevice.getMaxWorkItemSizes()[dimensionIndex]. The explicitly specified localWorkSize will be used to determine how to break the global work-items specified by global_work_size into appropriate work-group instances. If localWorkSize is specified, the values specified in globalWorkSize[dimensionIndex] must be evenly divisible by the corresponding values specified in localWorkSize[dimensionIndex]. This parameter can be left null, in which case the OpenCL implementation will choose good values. - * @param queue This kernel will be queued for execution on the device associated with that queue. -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueNDRange(CLQueue queue /*, int[] globalOffsets*/, int[] globalWorkSizes, int[] localWorkSizes, CLEvent... eventsToWaitFor) { - return enqueueNDRange(queue, null, globalWorkSizes, localWorkSizes, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueNDRangeKernel") - * Enqueues a command to execute a kernel on a device, using local work sizes chosen by the OpenCL implementation. - * See {@link CLKernel#enqueueNDRange(CLQueue, int[], int[], int[], CLEvent[])} - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param queue This kernel will be queued for execution on the device associated with that queue. -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueNDRange(CLQueue queue /*, int[] globalOffsets*/, int[] globalWorkSizes, CLEvent... eventsToWaitFor) { - return enqueueNDRange(queue, null, globalWorkSizes, null, eventsToWaitFor); - } - - /** -#documentCallsFunction("clEnqueueNDRangeKernel") - * Enqueues a command to execute a kernel on a device. - * @param globalOffsets Must be null in OpenCL 1.0. Each element describes the offset used to calculate the global ID of a work-item. If globalOffsets is null, the global IDs start at offset (0, 0, ... 0). - * @param globalWorkSizes Each element describes the number of global work-items in a dimension that will execute the kernel function. The total number of global work-items is computed as globalWorkSizes[0] * ... * globalWorkSizes[globalWorkSizes.length - 1]. - * @param localWorkSizes Each element describes the number of work-items that make up a work-group (also referred to as the size of the work-group) that will execute the kernel specified by kernel. The total number of work-items in a work-group is computed as localWorkSizes[0] * ... * localWorkSizes[localWorkSizes.length - 1]. The total number of work-items in the work-group must be less than or equal to the CL_DEVICE_MAX_WORK_GROUP_SIZE value specified in table 4.3 and the number of work- items specified in localWorkSizes[0], ... localWorkSizes[localWorkSizes.length - 1] must be less than or equal to the corresponding values specified by CLDevice.getMaxWorkItemSizes()[dimensionIndex]. The explicitly specified localWorkSize will be used to determine how to break the global work-items specified by global_work_size into appropriate work-group instances. If localWorkSize is specified, the values specified in globalWorkSize[dimensionIndex] must be evenly divisible by the corresponding values specified in localWorkSize[dimensionIndex]. This parameter can be left null, in which case the OpenCL implementation will choose good values. - * @param queue This kernel will be queued for execution on the device associated with that queue. -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueNDRange(CLQueue queue, long[] globalOffsets, long[] globalWorkSizes, long[] localWorkSizes, CLEvent... eventsToWaitFor) { - int nDims = globalWorkSizes.length; - if (localWorkSizes != null && localWorkSizes.length != nDims) { - throw new IllegalArgumentException("Global and local sizes must have same dimensions, given " + globalWorkSizes.length + " vs. " + localWorkSizes.length); - } - - #declareReusablePtrsAndEventsInOut() - error(CL.clEnqueueNDRangeKernel( - queue.getEntity(), - getEntity(), - nDims, - getPeer(ptrs.sizeT3_1.pointerToSizeTs(globalOffsets)), - getPeer(ptrs.sizeT3_2.pointerToSizeTs(globalWorkSizes)), - getPeer(ptrs.sizeT3_3.pointerToSizeTs(localWorkSizes)), - #eventsInOutArgsRaw() - )); - #returnEventOut("queue") - } - - /** - * @deprecated Use {@link CLKernel#enqueueNDRange(CLQueue, long[], long[], long[], CLEvent[])} instead. - */ - @Deprecated - public CLEvent enqueueNDRange(CLQueue queue, int[] globalOffsets, int[] globalWorkSizes, int[] localWorkSizes, CLEvent... eventsToWaitFor) { - int nDims = globalWorkSizes.length; - if (localWorkSizes != null && localWorkSizes.length != nDims) { - throw new IllegalArgumentException("Global and local sizes must have same dimensions, given " + globalWorkSizes.length + " vs. " + localWorkSizes.length); - } - #declareReusablePtrsAndEventsInOut() - error(CL.clEnqueueNDRangeKernel( - queue.getEntity(), - getEntity(), - nDims, - getPeer(ptrs.sizeT3_1.pointerToSizeTs(globalOffsets)), - getPeer(ptrs.sizeT3_2.pointerToSizeTs(globalWorkSizes)), - getPeer(ptrs.sizeT3_3.pointerToSizeTs(localWorkSizes)), - #eventsInOutArgsRaw())); - #returnEventOut("queue") - } - - /** - * Return the number of arguments to kernel. - */ - @InfoName("CL_KERNEL_NUM_ARGS") - public int getNumArgs() { - int numArgs = infos.getInt(getEntity(), CL_KERNEL_NUM_ARGS); - //System.out.println("numArgs = " + numArgs); - return numArgs; - } - - /** - * Return the kernel function name. - */ - @InfoName("CL_KERNEL_FUNCTION_NAME") - public String getFunctionName() { - if (name == null) - name = infos.getString(getEntity(), CL_KERNEL_FUNCTION_NAME); - return name; - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLMem.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLMem.java deleted file mode 100644 index 1c5ab5dcf..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLMem.java +++ /dev/null @@ -1,226 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import java.util.EnumSet; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import org.bridj.*; -import static org.bridj.Pointer.*; - - -/** - * OpenCL memory object.
      - * Memory objects are categorized into two types: buffer objects, and image objects.
      - * A buffer object stores a one-dimensional collection of elements whereas an image object is used to store a two- or three- dimensional texture, frame-buffer or image.
      - * Elements of a buffer object can be a scalar data type (such as an int, float), vector data type, or a user-defined structure. An image object is used to represent a buffer that can be used as a texture or a frame-buffer. The elements of an image object are selected from a list of predefined image formats.
      - * The minimum number of elements in a memory object is one.
      - * The fundamental differences between a buffer and an image object are: - *
        - *
      • Elements in a buffer are stored in sequential fashion and can be accessed using a pointer by a kernel executing on a device. Elements of an image are stored in a format that is opaque to the user and cannot be directly accessed using a pointer. Built-in functions are provided by the OpenCL C programming language to allow a kernel to read from or write to an image.
      • - *
      • For a buffer object, the data is stored in the same format as it is accessed by the kernel, but in the case of an image object the data format used to store the image elements may not be the same as the data format used inside the kernel. Image elements are always a 4- component vector (each component can be a float or signed/unsigned integer) in a kernel. The built-in function to read from an image converts image element from the format it is stored into a 4-component vector. Similarly, the built-in function to write to an image converts the image element from a 4-component vector to the appropriate image format specified such as 4 8-bit elements, for example.
      • - *
      - * - * Kernels take memory objects as input, and output to one or more memory objects. - * @author Olivier Chafik - */ -public abstract class CLMem extends CLAbstractEntity { - - protected final CLContext context; - protected long byteCount = -1; - boolean isGL; - - #declareInfosGetter("infos", "CL.clGetImageInfo") - - CLMem(CLContext context, long byteCount, long entityPeer) { - super(entityPeer); - this.byteCount = byteCount; - this.context = context; - } - - public CLContext getContext() { - return context; - } - - public interface DestructorCallback { - void callback(CLMem mem); - } - - /** -#documentCallsFunction("clSetMemObjectDestructorCallback") - * Registers a user callback function that will be called when the memory object is deleted and its resources freed.
      - * Each call to clSetMemObjectDestructorCallback registers the specified user callback function on a callback stack associated with memobj.
      - * The registered user callback functions are called in the reverse order in which they were registered.
      - * The user callback functions are called and then the memory object's resources are freed and the memory object is deleted.
      - * This provides a mechanism for the application (and libraries) using memobj to be notified when the memory referenced by host_ptr, specified when the memory object is created and used as the storage bits for the memory object, can be reused or freed. - * @since OpenCL 1.1 - * @param callback - */ - public void setDestructorCallback(final DestructorCallback callback) { - clSetMemObjectDestructorCallback_arg1_callback cb = new clSetMemObjectDestructorCallback_arg1_callback() { - /// @param cl_mem1 user_data - public void apply(OpenCLLibrary.cl_mem mem, Pointer userData) { - callback.callback(CLMem.this); - } - }; - BridJ.protectFromGC(cb); - error(CL.clSetMemObjectDestructorCallback(getEntity(), getPeer(pointerTo(cb)), 0)); - } - - public CLEvent acquireGLObject(CLQueue queue, CLEvent... eventsToWaitFor) { - return queue.enqueueAcquireGLObjects(new CLMem[] { this }, eventsToWaitFor); - } - - public CLEvent releaseGLObject(CLQueue queue, CLEvent... eventsToWaitFor) { - return queue.enqueueReleaseGLObjects(new CLMem[] { this }, eventsToWaitFor); - } - - /** - * Get the actual size of the memory object in bytes - * @return actual size of the memory object in bytes - */ - public long getByteCount() { - if (byteCount < 0) { - try { - byteCount = infos.getIntOrLong(getEntity(), CL_MEM_SIZE); - } catch (CLException.InvalidMemObject ex) { - if (isGL) - return -1; // GL objects are not (always?) considered as valid mem objects - else - throw ex; - } - } - return byteCount; - } - - /** - * Memory Object Usage enum - */ - public enum Usage { - Input(CL_MEM_READ_ONLY, Flags.ReadOnly), - Output(CL_MEM_WRITE_ONLY, Flags.WriteOnly), - InputOutput(CL_MEM_READ_WRITE, Flags.ReadWrite); - - private int intFlags; - private Flags flags; - Usage(int intFlags, Flags flags) { - this.intFlags = intFlags; - this.flags = flags; - } - public int getIntFlags() { - return intFlags; - } - public Flags getFlags() { - return flags; - } - } - - public enum Flags implements com.nativelibs4java.util.ValuedEnum { - /** - * This flag specifies that the memory object will be read and written by a kernel. This is the default. - */ - ReadWrite(CL_MEM_READ_WRITE), - /** - * This flags specifies that the memory object will be written but not read by a kernel.
      - * Reading from a buffer or image object created with CL_MEM_WRITE_ONLY inside a kernel is undefined. - */ - WriteOnly(CL_MEM_WRITE_ONLY), - /** - * This flag specifies that the memory object is a read-only memory object when used inside a kernel.
      - * Writing to a buffer or image object created with CL_MEM_READ_ONLY inside a kernel is undefined. - */ - ReadOnly(CL_MEM_READ_ONLY), - /** - * This flag is valid only if host_ptr is not NULL. If specified, it indicates that the application wants the OpenCL implementation to use memory referenced by host_ptr as the storage bits for the memory object.
      - * OpenCL implementations are allowed to cache the buffer contents pointed to by host_ptr in device memory. This cached copy can be used when kernels are executed on a device.
      - * The result of OpenCL commands that operate on multiple buffer objects created with the same host_ptr or overlapping host regions is considered to be undefined. - */ - UseHostPtr(CL_MEM_USE_HOST_PTR), - /** - * This flag specifies that the application wants the OpenCL implementation to allocate memory from host accessible memory.
      - * CL_MEM_ALLOC_HOST_PTR and CL_MEM_USE_HOST_PTR are mutually exclusive.
      - * CL_MEM_COPY_HOST_PTR: This flag is valid only if host_ptr is not NULL. If specified, it indicates that the application wants the OpenCL implementation to allocate memory for the memory object and copy the data from memory referenced by host_ptr.
      - * CL_MEM_COPY_HOST_PTR and CL_MEM_USE_HOST_PTR are mutually exclusive.
      - * CL_MEM_COPY_HOST_PTR can be used with CL_MEM_ALLOC_HOST_PTR to initialize the contents of the cl_mem object allocated using host-accessible (e.g. PCIe) memory. - */ - AllocHostPtr(CL_MEM_ALLOC_HOST_PTR), - CopyHostPtr(CL_MEM_COPY_HOST_PTR); - - Flags(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static long getValue(EnumSet set) { return EnumValues.getValue(set); } - public static EnumSet getEnumSet(long v) { return EnumValues.getEnumSet(v, Flags.class); } - } - public enum ObjectType implements com.nativelibs4java.util.ValuedEnum { - Buffer(CL_MEM_OBJECT_BUFFER), - Image2D(CL_MEM_OBJECT_IMAGE2D), - Image3D(CL_MEM_OBJECT_IMAGE3D); - - ObjectType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static ObjectType getEnum(long v) { return EnumValues.getEnum(v, ObjectType.class); } - } - - public enum GLObjectType implements com.nativelibs4java.util.ValuedEnum { - Buffer(CL_GL_OBJECT_BUFFER), - RenderBuffer(CL_GL_OBJECT_RENDERBUFFER), - Texture2D(CL_GL_OBJECT_TEXTURE2D), - Texture3D(CL_GL_OBJECT_TEXTURE3D); - - GLObjectType(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static GLObjectType getEnum(long v) { return EnumValues.getEnum(v, GLObjectType.class); } - } - - public static class GLObjectInfo { - final GLObjectType type; - final int name; - public GLObjectInfo(GLObjectType type, int name) { - this.type = type; - this.name = name; - } - public GLObjectType getType() { - return type; - } - public int getName() { - return name; - } - } - /** -#documentCallsFunction("clGetGLObjectInfo") - */ - @SuppressWarnings("deprecation") - public GLObjectInfo getGLObjectInfo() { - #declareReusablePtrs() - Pointer typeRef = ptrs.int1; - Pointer nameRef = ptrs.int2; - CL.clGetGLObjectInfo(getEntity(), getPeer(typeRef), getPeer(nameRef)); - return new GLObjectInfo(GLObjectType.getEnum(typeRef.getInt()), nameRef.getInt()); - } - public enum MapFlags implements com.nativelibs4java.util.ValuedEnum { - Read(CL_MAP_READ), - Write(CL_MAP_WRITE), - ReadWrite(CL_MAP_READ | CL_MAP_WRITE); - - MapFlags(long value) { this.value = value; } - long value; - public long value() { return value; } - public static MapFlags getEnum(long v) { return EnumValues.getEnum(v, MapFlags.class); } - } - - @Override - protected void clear() { - error(CL.clReleaseMemObject(getEntity())); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLPlatform.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLPlatform.java deleted file mode 100644 index 93c1df9c8..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLPlatform.java +++ /dev/null @@ -1,492 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.nativelibs4java.opencl.library.OpenGLContextUtils; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; - -import org.bridj.*; -import org.bridj.ann.*; -import static org.bridj.Pointer.*; - -import java.nio.ByteOrder; -import java.util.*; -import static com.nativelibs4java.opencl.JavaCL.*; -import static com.nativelibs4java.opencl.CLException.*; - -/** - * OpenCL implementation entry point. - * see {@link JavaCL#listPlatforms() } - * @author Olivier Chafik - */ -public class CLPlatform extends CLAbstractEntity { - - CLPlatform(long platform) { - super(platform, true); - } - - #declareInfosGetter("infos", "CL.clGetPlatformInfo") - - @Override - public String toString() { - return toString(new StringBuilder()).toString(); - } - StringBuilder toString(StringBuilder out) { - out. - append(getName()). - append(" {vendor: ").append(getVendor()). - append(", version: ").append(getVersion()). - append(", profile: ").append(getProfile()). - append(", extensions: ").append(Arrays.toString(getExtensions())). - append("}"); - return out; - } - - @Override - protected void clear() { - } - - /** - * Lists all the devices of the platform - * @param onlyAvailable if true, only returns devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listAllDevices(boolean onlyAvailable) { - return listDevices(CLDevice.Type.All, onlyAvailable); - } - - /** - * Lists all the GPU devices of the platform - * @param onlyAvailable if true, only returns GPU devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listGPUDevices(boolean onlyAvailable) { - try { - return listDevices(CLDevice.Type.GPU, onlyAvailable); - } catch (CLException ex) { - if (ex.getCode() == CL_DEVICE_NOT_FOUND) { - return new CLDevice[0]; - } - throw new RuntimeException("Unexpected OpenCL error", ex); - } - } - - /** - * Lists all the CPU devices of the platform - * @param onlyAvailable if true, only returns CPU devices that are available - * see {@link CLPlatform#listDevices(CLDevice.Type, boolean) } - */ - public CLDevice[] listCPUDevices(boolean onlyAvailable) { - try { - return listDevices(CLDevice.Type.CPU, onlyAvailable); - } catch (CLException ex) { - if (ex.getCode() == CL_DEVICE_NOT_FOUND) { - return new CLDevice[0]; - } - throw new RuntimeException("Unexpected OpenCL error", ex); - } - } - - private CLDevice[] getDevices(Pointer ids, boolean onlyAvailable) { - int nDevs = (int)ids.getValidElements(); - CLDevice[] devices; - if (onlyAvailable) { - List list = new ArrayList(nDevs); - for (int i = 0; i < nDevs; i++) { - CLDevice device = new CLDevice(this, ids.getSizeTAtOffset(i * Pointer.SIZE)); - if (device.isAvailable()) { - list.add(device); - } - } - devices = list.toArray(new CLDevice[list.size()]); - } else { - devices = new CLDevice[nDevs]; - for (int i = 0; i < nDevs; i++) { - devices[i] = new CLDevice(this, ids.getSizeTAtOffset(i * Pointer.SIZE)); - } - } - return devices; - } - - static long[] getContextProps(Map contextProperties) { - if (contextProperties == null) - return null; - final long[] properties = new long[contextProperties.size() * 2 + 1]; - int iProp = 0; - for (Map.Entry e : contextProperties.entrySet()) { - //if (!(v instanceof Number)) throw new IllegalArgumentException("Invalid context property value for '" + e.getKey() + ": " + v); - properties[iProp++] = e.getKey().value(); - Object v = e.getValue(); - if (v instanceof Number) - properties[iProp++] = ((Number)v).longValue(); - else if (v instanceof Pointer) - properties[iProp++] = ((Pointer)v).getPeer(); - else - throw new IllegalArgumentException("Cannot convert value " + v + " to a context property value !"); - } - //properties[iProp] = 0; - return properties; - } - - /** - * Enums used to indicate how to choose the best CLDevice. - */ - public enum DeviceFeature { - /** - * Prefer CPU devices (see {@link CLDevice#getType() }) - */ - CPU { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.CPU) ? 1 : 0; - } - }, - /** - * Prefer GPU devices (see {@link CLDevice#getType() }) - */ - GPU { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.GPU) ? 1 : 0; - } - }, - /** - * Prefer Accelerator devices (see {@link CLDevice#getType() }) - */ - Accelerator { - Comparable extractValue(CLDevice device) { - return device.getType().contains(CLDevice.Type.Accelerator) ? 1 : 0; - } - }, - /** - * Prefer devices with the most compute units (see {@link CLDevice#getMaxComputeUnits() }) - */ - MaxComputeUnits { - Comparable extractValue(CLDevice device) { - return device.getMaxComputeUnits(); - } - }, - /** - * Prefer devices with the same byte ordering as the hosting platform (see {@link CLDevice#getByteOrder() }) - */ - NativeEndianness { - Comparable extractValue(CLDevice device) { - return device.getKernelsDefaultByteOrder() == ByteOrder.nativeOrder() ? 1 : 0; - } - }, - /** - * Prefer devices that support double-precision float computations (see {@link CLDevice#isDoubleSupported() }) - */ - DoubleSupport { - Comparable extractValue(CLDevice device) { - return device.isDoubleSupported() ? 1 : 0; - } - }, - /** - * Prefer devices that support images and with the most supported image formats (see {@link CLDevice#hasImageSupport() }) - */ - ImageSupport { - Comparable extractValue(CLDevice device) { - return device.hasImageSupport() ? 1 : 0; - } - }, - /** - * Prefer devices that support out of order queues (see {@link CLDevice#hasOutOfOrderQueueSupport() }) - */ - OutOfOrderQueueSupport { - Comparable extractValue(CLDevice device) { - return device.hasOutOfOrderQueueSupport() ? 1 : 0; - } - }, - /** - * Prefer devices with the greatest variety of supported image formats (see {@link CLContext#getSupportedImageFormats(CLMem.Flags, CLMem.ObjectType) }) - */ - MostImageFormats { - Comparable extractValue(CLDevice device) { - if (!device.hasImageSupport()) - return 0; - // TODO: fix that ugly hack ? - CLContext context = JavaCL.createContext(null, device); - try { - return (Integer)context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image2D).length; - } finally { - context.release(); - } - } - }; - - Comparable extractValue(CLDevice device) { - throw new RuntimeException(); - } - } - - public static class DeviceComparator implements Comparator { - - private final List evals; - public DeviceComparator(List evals) { - this.evals = evals; - } - - @Override - public int compare(CLDevice a, CLDevice b) { - for (DeviceFeature eval : evals) { - if (eval == null) - continue; - - Comparable va = eval.extractValue(a), vb = eval.extractValue(b); - int c = va.compareTo(vb); - if (c != 0) - return c; - } - return 0; - } - - } - public static CLDevice getBestDevice(List evals, Collection devices) { - List list = new ArrayList(devices); - Collections.sort(list, new DeviceComparator(evals)); - return !list.isEmpty() ? list.get(list.size() - 1) : null; - } - - public CLDevice getBestDevice() { - return getBestDevice(Arrays.asList(DeviceFeature.MaxComputeUnits), Arrays.asList(listAllDevices(true))); - } - - /** Bit values for CL_CONTEXT_PROPERTIES */ - public enum ContextProperties implements com.nativelibs4java.util.ValuedEnum { - //D3D10Device(CL_CONTEXT_D3D10_DEVICE_KHR), - GLContext(CL_GL_CONTEXT_KHR), - EGLDisplay(CL_EGL_DISPLAY_KHR), - GLXDisplay(CL_GLX_DISPLAY_KHR), - WGLHDC(CL_WGL_HDC_KHR), - Platform(CL_CONTEXT_PLATFORM), - CGLShareGroupApple(CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE), - CGLShareGroup(CL_CGL_SHAREGROUP_KHR); - - ContextProperties(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - - public static long getValue(EnumSet set) { - return EnumValues.getValue(set); - } - - public static EnumSet getEnumSet(long v) { - return EnumValues.getEnumSet(v, ContextProperties.class); - } - } - - public CLContext createContextFromCurrentGL() { - return createGLCompatibleContext(listAllDevices(true)); - } - - static Map getGLContextProperties(CLPlatform platform) { - Map out = new LinkedHashMap(); - - if (Platform.isMacOSX()) { - Pointer context = OpenGLContextUtils.CGLGetCurrentContext(); - Pointer shareGroup = OpenGLContextUtils.CGLGetShareGroup(context); - out.put(ContextProperties.CGLShareGroupApple, shareGroup.getPeer()); - } else if (Platform.isWindows()) { - Pointer context = OpenGLContextUtils.wglGetCurrentContext(); - Pointer dc = OpenGLContextUtils.wglGetCurrentDC(); - out.put(ContextProperties.GLContext, context.getPeer()); - out.put(ContextProperties.WGLHDC, dc.getPeer()); - out.put(ContextProperties.Platform, platform.getEntity()); - } else if (Platform.isUnix()) { - Pointer context = OpenGLContextUtils.glXGetCurrentContext(); - Pointer dc = OpenGLContextUtils.glXGetCurrentDisplay(); - out.put(ContextProperties.GLContext, context.getPeer()); - out.put(ContextProperties.GLXDisplay, dc.getPeer()); - out.put(ContextProperties.Platform, platform.getEntity()); - } else - throw new UnsupportedOperationException("Current GL context retrieval not implemented on this platform !"); - - //out.put(ContextProperties.Platform, platform.getEntity().getPointer()); - - return out; - } - /** -#documentCallsFunction("clCreateContext") - */ - @Deprecated - public CLContext createGLCompatibleContext(CLDevice... devices) { - try { - return createContext(getGLContextProperties(this), devices); - } catch (Throwable th) {} - - for (CLDevice device : devices) { - if (!device.isGLSharingSupported()) - continue; - - try { - return createContext(getGLContextProperties(this), device); - } catch (Throwable th) {} - } - throw new UnsupportedOperationException("Failed to create an OpenGL-sharing-enabled OpenCL context out of devices " + Arrays.asList(devices)); - } - - /** -#documentCallsFunction("clCreateContext") - * Creates an OpenCL context formed of the provided devices.
      - * It is generally not a good idea to create a context with more than one device, - * because much data is shared between all the devices in the same context. - * @param devices devices that are to form the new context - * @return new OpenCL context - */ - public CLContext createContext(Map contextProperties, CLDevice... devices) { - int nDevs = devices.length; - if (nDevs == 0) { - throw new IllegalArgumentException("Cannot create a context with no associated device !"); - } - Pointer ids = allocateSizeTs(nDevs); - for (int i = 0; i < nDevs; i++) { - ids.setSizeTAtOffset(i * Pointer.SIZE, devices[i].getEntity()); - } - - #declareReusablePtrsAndPErr() - - long[] props = getContextProps(contextProperties); - Pointer propsRef = props == null ? null : pointerToSizeTs(props); - //System.out.println("ERROR CALLBACK " + Long.toHexString(errCb.getPeer())); - long context = CL.clCreateContext(getPeer(propsRef), nDevs, getPeer(ids), 0, 0, getPeer(pErr)); - #checkPErr(); - return new CLContext(this, ids, context); - } - /* - public static final clCreateContext_arg1_callback errorCallback = new clCreateContext_arg1_callback() { - public void apply(Pointer errInfo, Pointer private_info, @Ptr long cb, Pointer user_data) { - //new RuntimeException().printStackTrace(); - String log = errInfo.getCString(); - System.out.println("[JavaCL] " + log); - throw new CLException(log, -1); - } - };*/ - - /** -#documentCallsFunction("clGetDeviceIDs") - * List all the devices of the specified types, with only the ones declared as available if onlyAvailable is true. - */ - @SuppressWarnings("deprecation") - public CLDevice[] listDevices(CLDevice.Type type, boolean onlyAvailable) { - Pointer pCount = allocateInt(); - error(CL.clGetDeviceIDs(getEntity(), type.value(), 0, 0, getPeer(pCount))); - - int nDevs = pCount.getInt(); - if (nDevs <= 0) { - return new CLDevice[0]; - } - - Pointer ids = allocateSizeTs(nDevs); - - error(CL.clGetDeviceIDs(getEntity(), type.value(), nDevs, getPeer(ids), 0)); - return getDevices(ids, onlyAvailable); - } - - /* - public CLDevice[] listGLDevices(long openglContextId, boolean onlyAvailable) { - - Pointer errRef = allocateInt(); - long[] props = getContextProps(getGLContextProperties()); - Memory propsMem = toNSArray(props); - Pointer propsRef = allocateSizeT(); - propsRef.setPointer(propsMem); - - Pointer pCount = allocateSizeT(); - error(CL.clGetGLContextInfoKHR(propsRef, CL_DEVICES_FOR_GL_CONTEXT_KHR, 0, (Pointer) null, pCount)); - - int nDevs = pCount.getValue().intValue(); - if (nDevs == 0) - return new CLDevice[0]; - Memory idsMem = new Memory(nDevs * Pointer.SIZE); - error(CL.clGetGLContextInfoKHR(propsRef, CL_DEVICES_FOR_GL_CONTEXT_KHR, nDevs, idsMem, pCount)); - cl_device_id[] ids = new cl_device_id[nDevs]; - for (int i = 0; i < nDevs; i++) - ids[i] = new cl_device_id(idsMem.getPointer(i * Pointer.SIZE)); - return getDevices(ids, onlyAvailable); - }*/ - - /** - * OpenCL profile string. Returns the profile name supported by the implementation. The profile name returned can be one of the following strings: - *
        - *
      • FULL_PROFILE if the implementation supports the OpenCL specification (functionality defined as part of the core specification and does not require any extensions to be supported).
      • - *
      • EMBEDDED_PROFILE if the implementation supports the OpenCL embedded profile. The embedded profile is defined to be a subset for each version of OpenCL. The embedded profile for OpenCL 1.0 is described in section 10.
      • - *
      - */ - @InfoName("CL_PLATFORM_PROFILE") - public String getProfile() { - return infos.getString(getEntity(), CL_PLATFORM_PROFILE); - } - - /** - OpenCL version string. Returns the OpenCL version supported by the implementation. This version string has the following format: - OpenCL - Last Revision Date: 5/16/09 Page 30 - The major_version.minor_version value returned will be 1.0. - */ - @InfoName("CL_PLATFORM_VERSION") - public String getVersion() { - return infos.getString(getEntity(), CL_PLATFORM_VERSION); - } - - /** - * Platform name string. - */ - @InfoName("CL_PLATFORM_NAME") - public String getName() { - return infos.getString(getEntity(), CL_PLATFORM_NAME); - } - - /** - * Platform vendor string. - */ - @InfoName("CL_PLATFORM_VENDOR") - public String getVendor() { - return infos.getString(getEntity(), CL_PLATFORM_VENDOR); - } - - /** - * Returns a list of extension names
      - * Extensions defined here must be supported by all devices associated with this platform. - */ - @InfoName("CL_PLATFORM_EXTENSIONS") - public String[] getExtensions() { - if (extensions == null) { - extensions = infos.getString(getEntity(), CL_PLATFORM_EXTENSIONS).split("\\s+"); - } - return extensions; - } - - private String[] extensions; - - boolean hasExtension(String name) { - name = name.trim(); - for (String x : getExtensions()) { - if (name.equals(x.trim())) { - return true; - } - } - return false; - } - - @InfoName("cl_nv_device_attribute_query") - public boolean isNVDeviceAttributeQuerySupported() { - return hasExtension("cl_nv_device_attribute_query"); - } - - @InfoName("cl_nv_compiler_options") - public boolean isNVCompilerOptionsSupported() { - return hasExtension("cl_nv_compiler_options"); - } - - @InfoName("cl_khr_byte_addressable_store") - public boolean isByteAddressableStoreSupported() { - return hasExtension("cl_khr_byte_addressable_store"); - } - - @InfoName("cl_khr_gl_sharing") - public boolean isGLSharingSupported() { - return hasExtension("cl_khr_gl_sharing") || hasExtension("cl_APPLE_gl_sharing"); - } - -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLProgram.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLProgram.java deleted file mode 100644 index 5b8bbbeec..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLProgram.java +++ /dev/null @@ -1,852 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import java.util.Iterator; -import java.util.Arrays; -import com.nativelibs4java.util.Pair; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.CLException.errorString; -import static com.nativelibs4java.opencl.CLException.failedForLackOfMemory; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.JavaCL.log; -import java.util.logging.Level; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARIES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARY_SIZES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BUILD_LOG; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_SOURCE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SUCCESS; -import static org.bridj.util.DefaultParameterizedType.paramType; -import java.io.IOException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.net.MalformedURLException; -import java.net.URLConnection; -import java.net.URL; - -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Arrays; -import java.util.Map; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program; -import com.nativelibs4java.util.IOUtils; -import com.ochafik.util.string.StringUtils; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.Process; -import java.net.URL; -import java.util.Collection; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import java.util.zip.CRC32; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; -import java.util.zip.GZIPOutputStream; -import java.util.zip.GZIPInputStream; - -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * OpenCL program.
      - * An OpenCL program consists of a set of kernels that are identified as functions declared with the __kernel qualifier in the program source. OpenCL programs may also contain auxiliary functions and constant data that can be used by __kernel functions. The program executable can be generated online or offline by the OpenCL compiler for the appropriate target device(s).
      - * A program object encapsulates the following information: - *
        - *
      • An associated context.
      • - *
      • A program source or binary.
      • - *
      • The latest successfully built program executable
      • - *
      • The list of devices for which the program executable is built
      • - *
      • The build options used and a build log.
      • - *
      • The number of kernel objects currently attached.
      • - *
      - * - * A program can be compiled on the fly (costly) but its binaries can be stored and - * loaded back in subsequent executions to avoid recompilation.
      - * By default, program binaries are automatically cached on stable platforms (which currently exclude ATI Stream), - * but the caching can be forced on/off with * see {@link CLContext#setCacheBinaries(boolean) }.
      - * To create a program from sources, please use see {@link CLContext#createProgram(java.lang.String[]) } - * @author Olivier Chafik - */ -public class CLProgram extends CLAbstractEntity { - - protected final CLContext context; - - #declareInfosGetter("infos", "CL.clGetProgramInfo") - - CLDevice[] devices; - CLProgram(CLContext context, CLDevice... devices) { - super(0, true); - this.context = context; - this.devices = devices == null || devices.length == 0 ? context.getDevices() : devices; - } - CLProgram(CLContext context, Map binaries, String source) { - super(0, true); - this.context = context; - this.source = source; - - setBinaries(binaries); - } - - protected void setBinaries(Map binaries) { - if (this.devices == null) { - this.devices = new CLDevice[binaries.size()]; - int iDevice = 0; - for (CLDevice device : binaries.keySet()) - this.devices[iDevice++] = device; - } - int nDevices = this.devices.length; - if (binaries.size() != nDevices) - throw new IllegalArgumentException("Not enough binaries in provided map : expected " + nDevices + " (devices = " + Arrays.asList(devices) + "), got " + binaries.size() + " (" + binaries.keySet() + ")"); - Pointer lengths = allocateSizeTs(nDevices); - Pointer deviceIds = allocateSizeTs(nDevices); - Pointer> binariesArray = allocatePointers(nDevices); - Pointer[] binariesMems = new Pointer[nDevices]; - - int iDevice = 0; - for (CLDevice device : devices) { - byte[] binary = binaries.get(device); - if (binary == null) - throw new IllegalArgumentException("No binary for device " + device + " in provided binaries"); - - long offset = iDevice * Pointer.SIZE; - binariesArray.setPointerAtOffset(offset, binariesMems[iDevice] = pointerToBytes(binary)); - lengths.setSizeTAtOffset(offset, binary.length); - deviceIds.setSizeTAtOffset(offset, device.getEntity()); - - iDevice++; - } - nDevices = iDevice; - if (nDevices == 0) - return; - - #declareReusablePtrsAndPErr() - int previousAttempts = 0; - Pointer statuses = allocateInts(nDevices); - do { - setEntity(CL.clCreateProgramWithBinary(context.getEntity(), nDevices, getPeer(deviceIds), getPeer(lengths), getPeer(binariesArray), getPeer(statuses), getPeer(pErr))); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - } - - /** - * Write the compiled binaries of this program (for all devices it was compiled for), so that it can be restored later using {@link CLContext#loadProgram(java.io.InputStream) } - * @param out will be closed - * @throws CLBuildException - * @throws IOException - */ - public void store(OutputStream out) throws CLBuildException, IOException { - writeBinaries(getBinaries(), getSource(), null, out); - } - - private static final void addStoredEntry(ZipOutputStream zout, String name, byte[] data) throws IOException { - ZipEntry ze = new ZipEntry(name); - ze.setMethod(ZipEntry.STORED); - ze.setSize(data.length); - CRC32 crc = new CRC32(); - crc.update(data,0,data.length); - ze.setCrc(crc.getValue()); - zout.putNextEntry(ze); - zout.write(data); - zout.closeEntry(); - } - - private static final String BinariesSignatureZipEntryName = "SIGNATURE", SourceZipEntryName = "SOURCE", textEncoding = "utf-8"; - public static void writeBinaries(Map binaries, String source, String contentSignatureString, OutputStream out) throws IOException { - Map binaryBySignature = new HashMap(); - for (Map.Entry e : binaries.entrySet()) - binaryBySignature.put(e.getKey().createSignature(), e.getValue()); // Maybe multiple devices will have the same signature : too bad, we don't care and just write one binary per signature. - - ZipOutputStream zout = new ZipOutputStream(new GZIPOutputStream(new BufferedOutputStream(out))); - if (contentSignatureString != null) - addStoredEntry(zout, BinariesSignatureZipEntryName, contentSignatureString.getBytes(textEncoding)); - - if (source != null) - addStoredEntry(zout, SourceZipEntryName, source.getBytes(textEncoding)); - - for (Map.Entry e : binaryBySignature.entrySet()) - addStoredEntry(zout, e.getKey(), e.getValue()); - - zout.close(); - } - public static Pair, String> readBinaries(List allowedDevices, String expectedContentSignatureString, InputStream in) throws IOException { - Map ret = new HashMap(); - Map> devicesBySignature = CLDevice.getDevicesBySignature(allowedDevices); - - ZipInputStream zin = new ZipInputStream(new GZIPInputStream(new BufferedInputStream(in))); - ZipEntry ze; - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - String source = null; - - boolean first = true; - byte[] b = new byte[65536]; - while ((ze = zin.getNextEntry()) != null) { - String signature = ze.getName(); - boolean isSignature = signature.equals(BinariesSignatureZipEntryName); - if (first && !isSignature && expectedContentSignatureString != null || - !first && isSignature) - throw new IOException("Expected signature to be the first zip entry, got '" + signature + "' instead !"); - - first = false; - bout.reset(); - int len; - while ((len = zin.read(b)) > 0) - bout.write(b, 0, len); - - byte[] data = bout.toByteArray(); - if (isSignature) { - if (expectedContentSignatureString != null) { - String contentSignatureString = new String(data, textEncoding); - if (!expectedContentSignatureString.equals(contentSignatureString)) - throw new IOException("Content signature does not match expected one :\nExpected '" + expectedContentSignatureString + "',\nGot '" + contentSignatureString + "'"); - } - } else if (signature.equals(SourceZipEntryName)) { - source = new String(data, textEncoding); - } else { - List devices = devicesBySignature.get(signature); - for (CLDevice device : devices) - ret.put(device, data); - } - } - zin.close(); - return new Pair, String>(ret, source); - } - - List sources = new ArrayList(); - Map programByDevice = new HashMap(); - - public CLDevice[] getDevices() { - return devices.clone(); - } - - /// Workaround to avoid crash of ATI Stream 2.0.0 final (beta 3 & 4 worked fine) - public static boolean passMacrosAsSources = true; - - public synchronized void allocate() { - if (isAllocated()) - throw new IllegalThreadStateException("Program was already allocated !"); - - if (passMacrosAsSources) { - if (macros != null && !macros.isEmpty()) { - StringBuilder b = new StringBuilder(); - for (Map.Entry m : macros.entrySet()) - b.append("#define " + m.getKey() + " " + m.getValue() + "\n"); - this.sources.add(0, b.toString()); - } - } - - if (!"false".equals(System.getProperty("javacl.adjustDoubleExtension")) && !"0".equals(System.getenv("JAVACL_ADJUST_DOUBLE_EXTENSION"))) { - for (int i = 0, len = sources.size(); i < len; i++) { - String source = sources.get(i); - for (CLDevice device : getDevices()) - source = device.replaceDoubleExtensionByExtensionActuallyAvailable(source); - sources.set(i, source); - // TODO keep different sources for each device !!! - } - } - - String[] sources = this.sources.toArray(new String[this.sources.size()]); - Pointer pLengths = allocateSizeTs(sources.length); - long[] lengths = new long[sources.length]; - for (int i = 0; i < sources.length; i++) { - pLengths.setSizeTAtOffset(i * Pointer.SIZE, sources[i].length()); - } - - #declareReusablePtrsAndPErr() - long program; - int previousAttempts = 0; - Pointer> pSources = pointerToCStrings(sources); - do { - program = CL.clCreateProgramWithSource( - context.getEntity(), - sources.length, - getPeer(pSources), - getPeer(pLengths), - getPeer(pErr) - ); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - setEntity(program); - } - - private boolean isAllocated() { - return super.getEntity() != 0; - } - /* - @Override - protected synchronized cl_program getEntity() { - if (!isAllocated()) - allocate(); - - return super.getEntity(); - }*/ - - @Override - protected synchronized long getEntity() { - if (!isAllocated()) - allocate(); - - return super.getEntity(); - } - - List includes; - - /** - * Add a path (file or URL) to the list of paths searched for included files.
      - * OpenCL kernels may contain \#include "subpath/file.cl" statements.
      - * This automatically adds a "-Ipath" argument to the compilator's command line options.
      - * Note that it's not necessary to add include paths for files that are in the classpath. - * @param path A file or URL that points to the root path from which includes can be resolved. - */ - public synchronized void addInclude(String path) { - if (includes == null) - includes = new ArrayList(); - includes.add(path); - resolvedInclusions = null; - } - public synchronized void addSource(String src) { - if (isAllocated()) - throw new IllegalThreadStateException("Program was already allocated : cannot add sources anymore."); - sources.add(src); - resolvedInclusions = null; - } - - Map resolvedInclusions; - - protected Runnable copyIncludesToTemporaryDirectory() throws IOException { - Map inclusions = resolveInclusions(); - File includesDir = JavaCL.createTempDirectory("includes", "", "includes"); - final List filesToDelete = new ArrayList(); - for (Map.Entry e : inclusions.entrySet()) { - assert log(Level.INFO, "Copying include '" + e.getKey() + "' from '" + e.getValue() + "' to '" + includesDir + "'"); - File f = new File(includesDir, e.getKey().replace('/', File.separatorChar)); - File p = f.getParentFile(); - filesToDelete.add(f); - if (p != null) { - p.mkdirs(); - filesToDelete.add(p); - } - InputStream in = e.getValue().openStream(); - OutputStream out = new FileOutputStream(f); - IOUtils.readWrite(in, out); - in.close(); - out.close(); - f.deleteOnExit(); - } - filesToDelete.add(includesDir); - addInclude(includesDir.toString()); - return new Runnable() { public void run() { - for (File f : filesToDelete) - f.delete(); - }}; - } - public Map resolveInclusions() throws IOException { - if (resolvedInclusions == null) { - resolvedInclusions = new HashMap(); - for (String source : sources) - resolveInclusions(source, resolvedInclusions); - } - return resolvedInclusions; - } - - static Pattern includePattern = Pattern.compile("#\\s*include\\s*\"([^\"]+)\""); - private void resolveInclusions(String source, Map ret) throws IOException { - List includedPaths = new ArrayList(); - Matcher m = includePattern.matcher(source); - while (m.find()) { - includedPaths.add(m.group(1)); - } - for (String includedPath : includedPaths) { - if (ret.containsKey(includedPath)) - continue; - URL url = getIncludedSourceURL(includedPath); - if (url == null) { - assert log(Level.SEVERE, "Failed to resolve include '" + includedPath + "'"); - } else { - String s = IOUtils.readText(url); - ret.put(includedPath, url); - resolveInclusions(s, ret); - } - } - } - - public String getIncludedSourceContent(String path) throws IOException { - URL url = getIncludedSourceURL(path); - if (url == null) - return null; - - String src = IOUtils.readText(url); - return src; - } - - public URL getIncludedSourceURL(String path) throws MalformedURLException { - File f = new File(path); - if (f.exists()) - return f.toURI().toURL(); - URL url = Platform.getClassLoader(getClass()).getResource(path); - if (url != null) - return url; - - if (includes != null) - for (String include : includes) { - f = new File(new File(include), path); - if (f.exists()) - return f.toURI().toURL(); - - url = Platform.getClassLoader(getClass()).getResource(f.toString()); - if (url != null) - return url; - - try { - url = new URL(include + (include.endsWith("/") ? "" : "/") + path); - url.openStream().close(); - return url; - } catch (IOException ex) { - // Bad URL or impossible to read from the URL - } - - } - - return null; - } - - String source; - /** - * Get the source code of this program - */ - public synchronized String getSource() { - if (source == null) - source = infos.getString(getEntity(), CL_PROGRAM_SOURCE); - - return source; - } - - /** - * Get the binaries of the program (one for each device, in order) - * @return map from each device the program was compiled for to the corresponding binary data - */ - public Map getBinaries() throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - - Pointer s = infos.getMemory(getEntity(), CL_PROGRAM_BINARY_SIZES); - int n = (int)s.getValidBytes() / Platform.SIZE_T_SIZE; - long[] sizes = s.getSizeTs(n); - //int[] sizes = new int[n]; - //for (int i = 0; i < n; i++) { - // sizes[i] = s.getNativeLong(i * Native.LONG_SIZE).intValue(); - //} - - Pointer[] binMems = (Pointer[])new Pointer[n]; - Pointer> ptrs = allocatePointers(n); - for (int i = 0; i < n; i++) { - ptrs.set(i, binMems[i] = allocateBytes(sizes[i])); - } - error(infos.getInfo(getEntity(), CL_PROGRAM_BINARIES, ptrs.getValidBytes(), ptrs, null)); - - Map ret = new HashMap(devices.length); - int iBin = n == devices.length + 1 ? 1 : 0; - for (int i = 0; i < devices.length; i++) { - CLDevice device = devices[i]; - Pointer bytes = binMems[iBin + i]; - if (bytes != null) - ret.put(device, bytes.getBytes((int)sizes[iBin + i])); - } - return ret; - } - - /** - * Returns the context of this program - */ - public CLContext getContext() { - return context; - } - Map macros; - public CLProgram defineMacro(String name, Object value) { - createMacros(); - macros.put(name, value); - return this; - } - public CLProgram undefineMacro(String name) { - if (macros != null) - macros.remove(name); - return this; - } - - private void createMacros() { - if (macros == null) - macros = new LinkedHashMap(); - } - public void defineMacros(Map macros) { - createMacros(); - this.macros.putAll(macros); - } - List extraBuildOptions; - - /** - * Add the -cl-fast-relaxed-math compile option.
      - * Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations. - * This allows optimizations for floating-point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5. - * This option causes the preprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.
      - * Also see : Khronos' documentation for clBuildProgram. - */ - public void setFastRelaxedMath() { - addBuildOption("-cl-fast-relaxed-math"); - } - - /** - * Add the -cl-no-signed-zero compile option.
      - * Allow optimizations for floating-point arithmetic that ignore the signedness of zero. - * IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -clfinite-math only). - * This option implies that the sign of a zero result isn't significant.
      - * Also see : Khronos' documentation for clBuildProgram. - */ - public void setNoSignedZero() { - addBuildOption("-cl-no-signed-zero"); - } - - /** - * Add the -cl-mad-enable compile option.
      - * Allow a * b + c to be replaced by a mad. The mad computes a * b + c with reduced accuracy. For example, some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
      - * Also see : Khronos' documentation for clBuildProgram. - */ - public void setMadEnable() { - addBuildOption("-cl-mad-enable"); - } - /** - * Add the -cl-finite-math-only compile option.
      - * Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or infinites. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5.
      - * Also see : Khronos' documentation for clBuildProgram. - */ - public void setFiniteMathOnly() { - addBuildOption("-cl-finite-math-only"); - } - /** - * Add the -cl-unsafe-math-optimizations option.
      - * Allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid, (b) may violate IEEE 754 standard and (c) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single-precision floating-point, section 9.3.9 for double-precision floating-point, and edge case behavior in section 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable options.
      - * Also see : Khronos' documentation for clBuildProgram. - */ - public void setUnsafeMathOptimizations() { - addBuildOption("-cl-unsafe-math-optimizations"); - } - /** - * Add the -cl-nv-verbose compilation option (NVIDIA GPUs only)
      - * Enable verbose mode. Output will be reported in JavaCL's log at the INFO level - */ - public void setNVVerbose() { - addBuildOption("-cl-nv-verbose"); - } - /** - * Add the -cl-nv-maxrregcount=N compilation option (NVIDIA GPUs only)
      - * Specify the maximum number of registers that GPU functions can use. - * Until a function-specific limit, a higher value will generally increase - * the performance of individual GPU threads that execute this function. - * However, because thread registers are allocated from a global register - * pool on each GPU, a higher value of this option will also reduce the - * maximum thread block size, thereby reducing the amount of thread - * parallelism. Hence, a good maxrregcount value is the result of a - * trade-off. - * If this option is not specified, then no maximum is assumed. Otherwise - * the specified value will be rounded to the next multiple of 4 registers - * until the GPU specific maximum of 128 registers. - * @param N positive integer - */ - public void setNVMaximumRegistryCount(int N) { - addBuildOption("-cl-nv-maxrregcount=" + N); - } - /** - * Add the -cl-nv-opt-level compilation option (NVIDIA GPUs only)
      - * Specify optimization level (default value: 3) - * @param N positive integer, or 0 (no optimization). - */ - public void setNVOptimizationLevel(int N) { - addBuildOption("-cl-nv-opt-level=" + N); - } - - /** - * Please see OpenCL's clBuildProgram documentation for details on supported build options. - */ - public synchronized void addBuildOption(String option) { - if (option.startsWith("-I")) { - addInclude(option.substring(2)); - return; - } - if (extraBuildOptions == null) - extraBuildOptions = new ArrayList(); - - extraBuildOptions.add(option); - } - - protected String getOptionsString() { - StringBuilder b = new StringBuilder("-DJAVACL=1 "); - - if (extraBuildOptions != null) { - if (JavaCL.debug) { - boolean isCPUOnly = true; - for (CLDevice device : getDevices()) { - if (!device.getType().contains(CLDevice.Type.CPU)) { - isCPUOnly = false; - break; - } - } - if (!isCPUOnly) - log(Level.WARNING, "Debug mode : cannot only compile with debug flags on a CPU-only context"); - else { - for (Iterator it = extraBuildOptions.iterator(); it.hasNext();) { - String opt = it.next(); - if ((opt.startsWith("-O") || opt.startsWith("-g:")) && !JavaCL.DEBUG_COMPILER_FLAGS.contains(opt)) { - log(Level.WARNING, "Debug mode : removed argument \"" + opt + "\" from OpenCL compiler command-line arguments"); - it.remove(); - } - } - extraBuildOptions.addAll(JavaCL.DEBUG_COMPILER_FLAGS); - log(Level.ALL, "Debug mode : added OpenCL compiler command-line arguments \"" + StringUtils.implode(JavaCL.DEBUG_COMPILER_FLAGS, " ") + "\""); - } - } - for (String option : extraBuildOptions) - b.append(option.contains(" ") || option.contains("\"") ? "\"" + option.replaceAll("\"", "\\\"") + "\"" : option).append(' '); - - } - - // http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clBuildProgram.html - //b.append("-O2 -cl-no-signed-zeros -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math -cl-strict-aliasing "); - - if (!passMacrosAsSources && macros != null && !macros.isEmpty()) - for (Map.Entry m : macros.entrySet()) - b.append("-D" + m.getKey() + "=" + m.getValue() + " "); - - if (includes != null) - for (String path : includes) - if (new File(path).exists()) // path can be an URL as well, in which case it's copied to a local file copyIncludesToTemporaryDirectory() - b.append("-I").append(path).append(' '); - - return b.toString(); - } - - private volatile Boolean cached; - public synchronized void setCached(boolean cached) { - this.cached = cached; - } - public synchronized boolean isCached() { - if (cached == null) - cached = context.getCacheBinaries(); - return cached; - } - - protected String computeCacheSignature() throws IOException { - StringBuilder b = new StringBuilder(16 * 1024); - getContext().getPlatform().toString(b); - b.append('\n'); - for (CLDevice device : getDevices()) - b.append(device).append('\n'); - - b.append(getOptionsString()).append('\n'); - if (macros != null && !macros.isEmpty()) - for (Map.Entry m : macros.entrySet()) - b.append("-D").append(m.getKey()).append('=').append(m.getValue()).append('\n'); - - if (includes != null && !includes.isEmpty()) - for (String path : includes) - b.append("-I").append(path).append('\n'); - - if (sources != null && !sources.isEmpty()) - for (String source : sources) - b.append(source).append('\n'); - - Map inclusions = resolveInclusions(); - if (inclusions != null && !inclusions.isEmpty()) - for (Map.Entry e : inclusions.entrySet()) { - URLConnection con = e.getValue().openConnection(); - InputStream in = con.getInputStream(); - b.append('#').append(e.getKey()).append(con.getLastModified()).append('\n'); - in.close(); - } - - for (String name : propsToIncludeInSignature) - b.append(name).append('=').append(System.getProperty(name)).append('\n'); - - return b.toString(); - } - private final String[] propsToIncludeInSignature = new String[] { - //"java.vm.version", // probably superfluous... - "os.version", - "os.name" - }; - - protected Set getProgramBuildInfo(long pgm, Pointer deviceIds) { - Pointer len = allocateSizeT(); - int bufLen = 2048 * 32; //TODO find proper size - Pointer buffer = allocateBytes(bufLen); - - Set errs = new HashSet(); - if (deviceIds == null) { - error(CL.clGetProgramBuildInfo(pgm, 0, CL_PROGRAM_BUILD_LOG, bufLen, getPeer(buffer), getPeer(len))); - String s = buffer.getCString(); - if (s.length() > 0) - errs.add(s); - } else { - for (SizeT device : deviceIds) { - error(CL.clGetProgramBuildInfo(pgm, device.longValue(), CL_PROGRAM_BUILD_LOG, bufLen, getPeer(buffer), getPeer(len))); - String s = buffer.getCString(); - if (s.length() > 0) - errs.add(s); - } - } - return errs; - } - boolean built; - /** - * Returns the context of this program - */ - public synchronized CLProgram build() throws CLBuildException { - if (built) - throw new IllegalThreadStateException("Program was already built !"); - - String contentSignature = null; - File cacheFile = null; - boolean readBinaries = false; - if (isCached()) { - try { - contentSignature = computeCacheSignature(); - byte[] sha = java.security.MessageDigest.getInstance("MD5").digest(contentSignature.getBytes(textEncoding)); - StringBuilder shab = new StringBuilder(); - for (byte b : sha) - shab.append(Integer.toHexString(b & 0xff)); - String hash = shab.toString(); - cacheFile = new File(JavaCL.userCacheDir, hash); - if (cacheFile.exists()) { - Pair, String> bins = readBinaries(Arrays.asList(getDevices()), contentSignature, new FileInputStream(cacheFile)); - setBinaries(bins.getFirst()); - this.source = bins.getSecond(); - assert log(Level.INFO, "Read binaries cache from '" + cacheFile + "'"); - readBinaries = true; - } - } catch (Throwable ex) { - assert log(Level.WARNING, "Failed to load cached program : " + ex.getMessage()); - setEntity(0); - } - } - - if (!isAllocated()) - allocate(); - - Runnable deleteTempFiles = null; - if (!readBinaries) - try { - deleteTempFiles = copyIncludesToTemporaryDirectory(); - } catch (IOException ex) { - throw new CLBuildException(this, ex.toString(), Collections.EMPTY_LIST); - } - - int nDevices = devices.length; - Pointer deviceIds = null; - if (nDevices != 0) { - deviceIds = allocateSizeTs(nDevices); - for (int i = 0; i < nDevices; i++) - deviceIds.setSizeTAtOffset(i * Pointer.SIZE, devices[i].getEntity()); - } - Pointer pOptions = pointerToCString(getOptionsString()); - int err = CL.clBuildProgram( - getEntity(), - nDevices, - getPeer(deviceIds), - getPeer(pOptions), - 0, - 0 - ); - Set errors = getProgramBuildInfo(getEntity(), deviceIds); - - if (err != CL_SUCCESS) { - throw new CLBuildException(this, "Compilation failure : " + errorString(err) + " (devices: " + Arrays.asList(getDevices()) + ")", errors); - } else { - if (!errors.isEmpty()) - JavaCL.log(Level.INFO, "Build info :\n\t" + StringUtils.implode(errors, "\n\t")); - } - built = true; - if (deleteTempFiles != null) - deleteTempFiles.run(); - - if (isCached() && !readBinaries) { - JavaCL.userCacheDir.mkdirs(); - try { - Map binaries = getBinaries(); - if (!binaries.isEmpty()) { - writeBinaries(getBinaries(), getSource(), contentSignature, new FileOutputStream(cacheFile)); - assert log(Level.INFO, "Wrote binaries cache to '" + cacheFile + "'"); - } - } catch (Exception ex) { - new IOException("[JavaCL] Failed to cache program", ex).printStackTrace(); - } - } - - return this; - } - - @Override - protected void clear() { - error(CL.clReleaseProgram(getEntity())); - } - - /** -#documentCallsFunction("clCreateKernelsInProgram") - * Return all the kernels found in the program. - */ - public CLKernel[] createKernels() throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - Pointer pCount = allocateInt(); - int previousAttempts = 0; - while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), 0, 0, getPeer(pCount)), previousAttempts++)) {} - - int count = pCount.getInt(); - Pointer kerns = allocateSizeTs(count); - previousAttempts = 0; - while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), count, getPeer(kerns), getPeer(pCount)), previousAttempts++)) {} - - CLKernel[] kernels = new CLKernel[count]; - for (int i = 0; i < count; i++) - kernels[i] = new CLKernel(this, null, kerns.getSizeTAtOffset(i * Pointer.SIZE)); - - return kernels; - } - - /** -#documentCallsFunction("clCreateKernel") - * Find a kernel by its functionName, and optionally bind some arguments to it. - */ - public CLKernel createKernel(String name, Object... args) throws CLBuildException { - synchronized (this) { - if (!built) - build(); - } - #declareReusablePtrsAndPErr() - Pointer pName = pointerToCString(name); - long kernel; - int previousAttempts = 0; - do { - kernel = CL.clCreateKernel(getEntity(), getPeer(pName), getPeer(pErr)); - } while (failedForLackOfMemory(pErr.getInt(), previousAttempts++)); - - CLKernel kn = new CLKernel(this, name, kernel); - if (args.length != 0) - kn.setArgs(args); - return kn; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLQueue.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLQueue.java deleted file mode 100644 index 317b32e9d..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLQueue.java +++ /dev/null @@ -1,176 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FALSE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_QUEUE_PROPERTIES; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_TRUE; - -import java.util.EnumSet; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_command_queue; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_mem; -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * OpenCL command queue.
      - * OpenCL objects such as memory, program and kernel objects are created using a context.
      - * Operations on these objects are performed using a command-queue.
      - * The command-queue can be used to queue a set of operations (referred to as commands) in order.
      - * Having multiple command-queues allows applications to queue multiple independent commands without requiring synchronization.
      - * Note that this should work as long as these objects are not being shared.
      - * Sharing of objects across multiple command-queues will require the application to perform appropriate synchronization.
      - *
      - * A queue is bound to a single device. - * see {@link CLDevice#createQueue(com.nativelibs4java.opencl.CLContext, com.nativelibs4java.opencl.CLDevice.QueueProperties[]) } - * see {@link CLDevice#createOutOfOrderQueue(com.nativelibs4java.opencl.CLContext) } - * see {@link CLDevice#createProfilingQueue(com.nativelibs4java.opencl.CLContext) } - * see {@link CLContext#createDefaultQueue(com.nativelibs4java.opencl.CLDevice.QueueProperties[]) } - * see {@link CLContext#createDefaultOutOfOrderQueue() } - * see {@link CLContext#createDefaultProfilingQueue() } - * @author Olivier Chafik - * - */ -public class CLQueue extends CLAbstractEntity { - - #declareInfosGetter("infos", "CL.clGetCommandQueueInfo") - - final CLContext context; - final CLDevice device; - - CLQueue(CLContext context, long entity, CLDevice device) { - super(entity); - this.context = context; - this.device = device; - } - - public CLContext getContext() { - return context; - } - public CLDevice getDevice() { - return device; - } - - volatile Boolean outOfOrder; - public synchronized boolean isOutOfOrder() { - if (outOfOrder == null) - outOfOrder = getProperties().contains(CLDevice.QueueProperties.OutOfOrderExecModeEnable); - return outOfOrder; - } - - @InfoName("CL_QUEUE_PROPERTIES") - public EnumSet getProperties() { - return CLDevice.QueueProperties.getEnumSet(infos.getIntOrLong(getEntity(), CL_QUEUE_PROPERTIES)); - } - - @SuppressWarnings("deprecation") - public void setProperty(CLDevice.QueueProperties property, boolean enabled) { - error(CL.clSetCommandQueueProperty(getEntity(), property.value(), enabled ? CL_TRUE : CL_FALSE, 0)); - } - - - @Override - protected void clear() { - error(CL.clReleaseCommandQueue(getEntity())); - } - - /** -#documentCallsFunction("clFinish") - * Blocks until all previously queued OpenCL commands in this queue are issued to the associated device and have completed.
      - * finish() does not return until all queued commands in this queue have been processed and completed.
      - * finish() is also a synchronization point. - */ - public void finish() { - error(CL.clFinish(getEntity())); - } - - /** -#documentCallsFunction("clFlush") - * Issues all previously queued OpenCL commands in this queue to the device associated with this queue.
      - * flush() only guarantees that all queued commands in this queue get issued to the appropriate device.
      - * There is no guarantee that they will be complete after flush() returns. - */ - public void flush() { - error(CL.clFlush(getEntity())); - } - - /** -#documentCallsFunction("clEnqueueWaitForEvents") - * Enqueues a wait for a specific event or a list of events to complete before any future commands queued in the this queue are executed. - */ - public void enqueueWaitForEvents(CLEvent... eventsToWaitFor) { - #declareReusablePtrs() - #declareEventsIn() - if (eventsIn == null) - return; - error(CL.clEnqueueWaitForEvents(getEntity(), #eventsInArgsRaw())); - } - - /** -#documentCallsFunction("clEnqueueBarrier") - * Enqueue a barrier operation.
      - * The enqueueBarrier() command ensures that all queued commands in command_queue have finished execution before the next batch of commands can begin execution.
      - * enqueueBarrier() is a synchronization point. - */ - public void enqueueBarrier() { - error(CL.clEnqueueBarrier(getEntity())); - } - - /** -#documentCallsFunction("clEnqueueMarker") - * Enqueue a marker command to command_queue.
      - * The marker command returns an event which can be used by to queue a wait on this marker event i.e. wait for all commands queued before the marker command to complete. - * @return Event object that identifies this command and can be used to query or queue a wait for the command to complete. - */ - public CLEvent enqueueMarker() { - #declareReusablePtrs() - Pointer eventOut = ptrs.event_out; - error(CL.clEnqueueMarker(getEntity(), getPeer(eventOut))); - #returnEventOut("this") - } - - /** -#documentCallsFunction("clEnqueueAcquireGLObjects") - * Used to acquire OpenCL memory objects that have been created from OpenGL objects.
      - * These objects need to be acquired before they can be used by any OpenCL commands queued to a command-queue.
      - * The OpenGL objects are acquired by the OpenCL context associated with this queue and can therefore be used by all command-queues associated with the OpenCL context. - * @param objects CL memory objects that correspond to GL objects. -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueAcquireGLObjects(CLMem[] objects, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOut() - Pointer mems = allocateSizeTs(objects.length); - for (int i = 0; i < objects.length; i++) { - mems.setSizeTAtOffset(i * Pointer.SIZE, objects[i].getEntity()); - } - error(CL.clEnqueueAcquireGLObjects( - getEntity(), - objects.length, - getPeer(mems), - #eventsInOutArgsRaw() - )); - #returnEventOut("this") - } - - /** -#documentCallsFunction("clEnqueueReleaseGLObjects") - * Used to release OpenCL memory objects that have been created from OpenGL objects.
      - * These objects need to be released before they can be used by OpenGL.
      - * The OpenGL objects are released by the OpenCL context associated with this queue. - * @param objects CL memory objects that correpond to GL objects. -#documentEventsToWaitForAndReturn() - */ - public CLEvent enqueueReleaseGLObjects(CLMem[] objects, CLEvent... eventsToWaitFor) { - #declareReusablePtrsAndEventsInOut() - Pointer mems = getEntities(objects, (Pointer)allocateSizeTs(objects.length)); - error(CL.clEnqueueReleaseGLObjects( - getEntity(), - objects.length, - getPeer(mems), - #eventsInOutArgsRaw() - )); - #returnEventOut("this") - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLSampler.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLSampler.java deleted file mode 100644 index fe36aea15..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLSampler.java +++ /dev/null @@ -1,100 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_CLAMP; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_CLAMP_TO_EDGE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_NONE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_ADDRESS_REPEAT; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FILTER_LINEAR; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_FILTER_NEAREST; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_ADDRESSING_MODE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_FILTER_MODE; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SAMPLER_NORMALIZED_COORDS; - -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_sampler; -import com.nativelibs4java.util.EnumValue; -import com.nativelibs4java.util.EnumValues; -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * OpenCL sampler object.
      - * A sampler object describes how to sample an image when the image is read in the kernel.
      - * The built-in functions to read from an image in a kernel take a sampler as an argument.
      - * The sampler arguments to the image read function can be sampler objects created using OpenCL functions and passed as argument values to the kernel or can be samplers declared inside a kernel. - *
      - * see {@link CLContext#createSampler(boolean, com.nativelibs4java.opencl.CLSampler.AddressingMode, com.nativelibs4java.opencl.CLSampler.FilterMode) } - * @author Olivier Chafik - */ -public class CLSampler extends CLAbstractEntity { - - #declareInfosGetter("infos", "CL.clGetSamplerInfo") - - CLSampler(long entity) { - super(entity); - } - - @Override - protected void clear() { - error(CL.clReleaseSampler(getEntity())); - } - - /** - * Values for CL_SAMPLER_ADDRESSING_MODE
      - * How out-of-range image coordinates are handled when reading from an image - */ - public enum AddressingMode implements com.nativelibs4java.util.ValuedEnum { - Repeat(CL_ADDRESS_REPEAT), - ClampToEdge(CL_ADDRESS_CLAMP_TO_EDGE), - Clamp(CL_ADDRESS_CLAMP), - None(CL_ADDRESS_NONE); - - AddressingMode(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static AddressingMode getEnum(long v) { return EnumValues.getEnum(v, AddressingMode.class); } - } - - /** - * Return the value specified by addressing_mode argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_ADDRESSING_MODE") - public AddressingMode getAddressingMode() { - return AddressingMode.getEnum(infos.getInt(getEntity(), CL_SAMPLER_ADDRESSING_MODE)); - } - - /** - * Values for CL_SAMPLER_FILTER_MODE
      - * Type of filter that must be applied when reading an image - */ - public enum FilterMode implements com.nativelibs4java.util.ValuedEnum { - Nearest(CL_FILTER_NEAREST), - Linear(CL_FILTER_LINEAR); - - FilterMode(long value) { this.value = value; } - long value; - @Override - public long value() { return value; } - public static FilterMode getEnum(int v) { return EnumValues.getEnum(v, FilterMode.class); } - } - /** - * Return the value specified by filter_mode argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_FILTER_MODE") - public FilterMode getFilterMode() { - return FilterMode.getEnum(infos.getInt(getEntity(), CL_SAMPLER_FILTER_MODE)); - } - - /** - * Return the value specified by normalized_coords argument to CLContext.createSampler. - */ - @InfoName("CL_SAMPLER_NORMALIZED_COORDS") - public boolean getNormalizedCoords() { - return infos.getBool(getEntity(), CL_SAMPLER_NORMALIZED_COORDS); - } - - - -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLUserEvent.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLUserEvent.java deleted file mode 100644 index 15c19ad92..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/CLUserEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - - -import static com.nativelibs4java.opencl.JavaCL.CL; -import static com.nativelibs4java.opencl.CLException.error; -import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; - -public class CLUserEvent extends CLEvent { - CLUserEvent(CLQueue queue, long evt) { - super(queue, evt); - } - /** -#documentCallsFunction("clSetUserEventStatus") - * Sets the execution status of a this event object. - * NOTE: Enqueued commands that specify user events in the event_wait_list argument of clEnqueue*** commands must ensure that the status of these user events being waited on are set using clSetUserEventStatus before any OpenCL APIs that release OpenCL objects except for event objects are called; otherwise the behavior is undefined. More details in the OpenCL specifications at section 5.9. - * @param executionStatus specifies the new execution status to be set and can be CL_COMPLETE or a negative integer value to indicate an error. A negative integer value causes all enqueued commands that wait on this user event to be terminated. setStatus can only be called once to change the execution status of event. - */ - public void setStatus(int executionStatus) { - error(CL.clSetUserEventStatus(getEntity(), executionStatus)); - } - - /** - * Calls setStatus(CL_COMPLETE) - */ - public void setComplete() { - setStatus(CL_COMPLETE); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ImageIOUtils.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ImageIOUtils.java deleted file mode 100644 index 097154c80..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ImageIOUtils.java +++ /dev/null @@ -1,488 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import com.nativelibs4java.opencl.CLImageFormat.ChannelOrder; -import com.nativelibs4java.opencl.CLImageFormat.ChannelDataType; -import com.nativelibs4java.util.NIOUtils; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.image.*; -import java.nio.*; -import static com.nativelibs4java.opencl.ImageIOUtils.ImageInfo.*; - -/** - * No apparent correspondance with any OpenCL image type for the following BufferedImage types : - * TYPE_3BYTE_BGR - * TYPE_4BYTE_ABGR (support only argb or bgra : need to see if endian-magic can help...) - * TYPE_4BYTE_ABGR_PRE (no support for pre-multiplied channels) - * TYPE_BYTE_BINARY - * TYPE_BYTE_INDEXED - * TYPE_CUSTOM - * TYPE_INT_ARGB_PRE (no support for pre-multiplied channels) - * TYPE_INT_BGR - * TYPE_INT_RGB (no support for UnsignedInt8 channel data type) - * TYPE_USHORT_555_RGB - * TYPE_USHORT_565_RGB - */ -class ImageIOUtils { - - public static class ImageInfo { - public final int bufferedImageType; - public final CLImageFormat clImageFormat; - //public final int width, height; - public final ImageDataGetter dataGetter; - public final ImageDataSetter dataSetter; - public final Class bufferClass; - public final Class bufferElementsClass; - public final int channelCount; - public final int pixelByteSize; - public ImageInfo( - int bufferedImageType, - CLImageFormat clImageFormat, - ImageDataGetter dataGetter, - ImageDataSetter dataSetter, - Class bufferClass, - Class bufferElementsClass, - int channelCount, - int pixelByteSize) - { - this.bufferedImageType = bufferedImageType; - this.clImageFormat = clImageFormat; - this.dataGetter = dataGetter; - this.dataSetter = dataSetter; - this.bufferClass = bufferClass; - this.bufferElementsClass = bufferElementsClass; - this.channelCount = channelCount; - this.pixelByteSize = pixelByteSize; - } - - public interface ImageDataGetter { - Buffer getData(I image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder); - } - public interface ImageDataSetter { - void setData(I image, Buffer data, boolean allowDeoptimizingDirectWrite); - } - } - - public static ImageInfo getGenericImageInfo() { - return new ImageInfo( - 0, - CLImageFormat.INT_ARGB_FORMAT, - new ImageDataGetter() { - public Buffer getData(Image image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int[] intData = null; - int width = image.getWidth(null), height = image.getHeight(null); - PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, true); - try { - grabber.grabPixels(); - intData = (int[])grabber.getPixels(); - } catch (InterruptedException ex) { - throw new RuntimeException("Pixel read operation was interrupted", ex); - } - IntBuffer output = IntBuffer.wrap(intData); - if (directBuffer) - return NIOUtils.directCopy(output, byteOrder); - else - return output; - } - }, - new ImageDataSetter() { - public void setData(Image image, Buffer data, boolean allowDeoptimizingDirectWrite) { - if (!(image instanceof BufferedImage)) - throw new UnsupportedOperationException("Image must be a BufferedImage"); - - BufferedImage bufferedImage = (BufferedImage)image; - int width = bufferedImage.getWidth(), height = bufferedImage.getHeight(); - WritableRaster raster = checkWritableRaster(bufferedImage); - - IntBuffer input = checkBuffer(data, IntBuffer.class); - int[] intData = input.array(); - if (intData == null) { - intData = new int[width * height]; - input.get(intData); - } - raster.setPixels(0, 0, width, height, intData); - } - }, - IntBuffer.class, - Integer.class, - 1, - 4 - ); - } - - static void checkSinglePixelPackedSampleModel(Raster raster) { - if (raster.getNumDataElements() != 1) - throw new IllegalArgumentException("Raster has " + raster.getNumBands() + " data elements, should have only 1 !"); - - //SampleModel sampleModel = raster.getSampleModel(); - //if (!(sampleModel instanceof SinglePixelPackedSampleModel)) - // throw new IllegalArgumentException("Expected SinglePixelPackedSampleModel, got " + sampleModel.getClass().getName()); - - //return (SinglePixelPackedSampleModel)sampleModel; - } - static DB checkDataBuffer(Raster raster, Class dbType) { - DataBuffer dataBuffer = raster.getDataBuffer(); - if (!dbType.isInstance(dataBuffer)) - throw new IllegalArgumentException("Expected " + dbType.getName() + ", got " + (dataBuffer == null ? null : dataBuffer.getClass().getName())); - - return (DB)dataBuffer; - } - static B checkBuffer(Buffer buffer, Class bType) { - if (!bType.isInstance(buffer)) - throw new IllegalArgumentException("Expected " + bType.getName() + ", got " + (buffer == null ? null : buffer.getClass().getName())); - - return (B)buffer; - } - static WritableRaster checkWritableRaster(BufferedImage image) { - Raster raster = image.getRaster(); - if (!(raster instanceof WritableRaster)) - throw new UnsupportedOperationException("Image data is not writable"); - - return (WritableRaster)raster; - } - public static ImageInfo getShortGrayImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_USHORT_GRAY, - new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.UNormInt16), - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - short[] existingArray = getIndirectArray(optionalExistingOutput, width * height, short[].class); - short[] array; - ShortBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (short[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferShort.class).getData(); - if (optionalExistingOutput instanceof ShortBuffer) { - output = (ShortBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (!output.isDirect()) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = ShortBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); - short[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - short[] outputArray = checkDataBuffer(raster, DataBufferShort.class).getData(); - ShortBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new short[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - ShortBuffer.class, - Short.class, - 1, - 2 - ); - } - - /** - * Image stored in TYPE_USHORT_GRAY BufferedImages but in ChannelOrder.RGBA/BGRA + ChannelDataType.short - */ - public static ImageInfo getARGBShortGrayImageInfo(CLImageFormat format) { - return new ImageInfo( - BufferedImage.TYPE_USHORT_GRAY, - format, - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - int length = width * height; - short[] existingArray = getIndirectArray(optionalExistingOutput, length, short[].class); - short[] array = (short[])raster.getDataElements(0, 0, width, height, existingArray); - - ShortBuffer output = null; - if (optionalExistingOutput instanceof ShortBuffer) { - output = (ShortBuffer)optionalExistingOutput; - if (output.capacity() != length * 4) - output = null; - } - if (output == null) - output = NIOUtils.directShorts(length * 4, byteOrder); - - for (int i = 0; i < length; i++) { - int offset = i * 4; - short value = array[i]; - output.put(offset, value); - output.put(offset + 1, value); - output.put(offset + 2, value); - output.put(offset + 3, (short)0xffff); - } - - return output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); - int length = width * height; - short[] data = new short[length]; - short[] four = new short[4]; - for (int i = 0; i < length; i++) { - int offset = i * 4; - int a = input.get(offset); - int b = input.get(offset + 1); - int c = input.get(offset + 2); - int alpha = input.get(offset + 3); // TODO multiply by ALPHA ??? - data[i] = (short)((a + b + c) / 3); - } - raster.setDataElements(0, 0, width, height, data); - } - }, - ShortBuffer.class, - Short.class, - 4, - 4 * 2 - ); - } - - public static ImageInfo getByteGrayImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_BYTE_GRAY, - new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.SignedInt8), - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - - byte[] existingArray = getIndirectArray(optionalExistingOutput, width * height, byte[].class); - byte[] array; - ByteBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (byte[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferByte.class).getData(); - if (optionalExistingOutput instanceof ByteBuffer) { - output = (ByteBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (!output.isDirect()) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = ByteBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - ByteBuffer input = checkBuffer(inputBuffer, ByteBuffer.class); - byte[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - byte[] outputArray = checkDataBuffer(raster, DataBufferByte.class).getData(); - ByteBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new byte[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - ByteBuffer.class, - Byte.class, - 1, - 1 - ); - } - static A getIndirectArray(Buffer buffer, int length, Class arrayClass) { - if (buffer instanceof IntBuffer && arrayClass == int[].class) - return (A)((IntBuffer)buffer).array(); - if (buffer instanceof ShortBuffer && arrayClass == short[].class) - return (A)((ShortBuffer)buffer).array(); - if (buffer instanceof ByteBuffer && arrayClass == byte[].class) - return (A)((ByteBuffer)buffer).array(); - if (buffer instanceof FloatBuffer && arrayClass == float[].class) - return (A)((FloatBuffer)buffer).array(); - if (buffer instanceof LongBuffer && arrayClass == long[].class) - return (A)((LongBuffer)buffer).array(); - if (buffer instanceof DoubleBuffer && arrayClass == double[].class) - return (A)((DoubleBuffer)buffer).array(); - if (buffer instanceof CharBuffer && arrayClass == char[].class) - return (A)((CharBuffer)buffer).array(); - return null; - } - public static boolean isSubRaster(Raster raster) { - Rectangle bounds = raster.getBounds(); - return raster.getParent() != null || bounds.x != 0 || bounds.y != 0; - } - public static ImageInfo getIntARGBImageInfo() { - return new ImageInfo( - BufferedImage.TYPE_INT_ARGB, - CLImageFormat.INT_ARGB_FORMAT, - new ImageDataGetter() { - public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - int[] existingArray = getIndirectArray(optionalExistingOutput, width * height, int[].class); - int[] array; - IntBuffer output = null; - if (!allowDeoptimizingDirectRead || isSubRaster(raster)) - array = (int[])raster.getDataElements(0, 0, width, height, existingArray); - else { - array = checkDataBuffer(raster, DataBufferInt.class).getData(); - if (optionalExistingOutput instanceof IntBuffer) { - output = (IntBuffer)optionalExistingOutput; - if (output != null && output.capacity() == width * height) { - if (output.array() != null) - System.arraycopy(array, 0, output.array(), 0, width * height); - else { - output.duplicate().put(array); - } - } - } - } - if (output == null) - output = IntBuffer.wrap(array); - return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; - } - }, - new ImageDataSetter() { - public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { - int width = image.getWidth(), height = image.getHeight(); - WritableRaster raster = checkWritableRaster(image); - checkSinglePixelPackedSampleModel(raster); - IntBuffer input = checkBuffer(inputBuffer, IntBuffer.class); - int[] inputArray = input.isDirect() ? null : input.array(); - if (allowDeoptimizingDirectWrite) { - if (input.isDirect()) { - int[] outputArray = checkDataBuffer(raster, DataBufferInt.class).getData(); - IntBuffer.wrap(outputArray).put(input.duplicate()); - return; - } - } - if (inputArray == null) { - inputArray = new int[width * height]; - input.duplicate().get(inputArray); - } - raster.setDataElements(0, 0, width, height, inputArray); - } - }, - IntBuffer.class, - Integer.class, - 1, - 4 - ); - } - - public static ImageInfo getImageInfo(Image image) { - if (image instanceof BufferedImage) - return getBufferedImageInfo(((BufferedImage)image).getType()); - return getGenericImageInfo(); - } - public static ImageInfo getBufferedImageInfo(int bufferedImageType) { - switch (bufferedImageType) { - case BufferedImage.TYPE_INT_ARGB: - return getIntARGBImageInfo(); - case BufferedImage.TYPE_BYTE_GRAY: - return getByteGrayImageInfo(); - case BufferedImage.TYPE_USHORT_GRAY: - return getShortGrayImageInfo(); - default: - return (ImageInfo)getGenericImageInfo(); - } - } - public static ImageInfo getBufferedImageInfo(CLImageFormat imageFormat) { - if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) - return null; - - switch (imageFormat.getChannelOrder()) { - case BGRA: - case RGBA: - switch (imageFormat.getChannelDataType()) { - case UNormInt16: - case UnsignedInt16: - case SignedInt16: - return getARGBShortGrayImageInfo(imageFormat); - } - } - return getBufferedImageInfo(getBufferedImageType(imageFormat)); - } - static int getBufferedImageType(CLImageFormat imageFormat) { - if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) - return 0; - - switch (imageFormat.getChannelOrder()) { - case INTENSITY: - case LUMINANCE: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_BYTE_GRAY; - case UnsignedInt16: - case UNormInt16: - case SignedInt16: - return BufferedImage.TYPE_USHORT_GRAY; - default: - return 0; - } - case ARGB: - case BGRA: - case RGBA: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_INT_ARGB; - default: - return 0; - } - case RGB: - switch (imageFormat.getChannelDataType()) { - case UNormInt8: - case UnsignedInt8: - case SignedInt8: - return BufferedImage.TYPE_INT_BGR; - default: - return 0; - } - case RGBx: - default: - return 0; - } - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/InfoName.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/InfoName.java deleted file mode 100644 index 9044aead9..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/InfoName.java +++ /dev/null @@ -1,17 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Tagging annotation to indicate the name of an OpenCL information in the OpenCL specifications. - * @author ochafik - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface InfoName { - String value(); -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/JavaCL.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/JavaCL.java deleted file mode 100644 index 522d2e63c..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/JavaCL.java +++ /dev/null @@ -1,324 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLException.error; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.*; - -import com.nativelibs4java.opencl.library.OpenCLLibrary; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id; -import org.bridj.*; -import org.bridj.ann.Ptr; - -import org.bridj.util.ProcessUtils; -import org.bridj.util.StringUtils; -import static org.bridj.Pointer.*; - -/** - * Entry point class for the OpenCL4Java Object-oriented wrappers around the OpenCL API.
      - * @author Olivier Chafik - */ -public class JavaCL { - - static final boolean debug = "true".equals(System.getProperty("javacl.debug")) || "1".equals(System.getenv("JAVACL_DEBUG")); - static final boolean verbose = debug || "true".equals(System.getProperty("javacl.verbose")) || "1".equals(System.getenv("JAVACL_VERBOSE")); - static final int minLogLevel = Level.WARNING.intValue(); - - static final String JAVACL_DEBUG_COMPILER_FLAGS_PROP = "JAVACL_DEBUG_COMPILER_FLAGS"; - static List DEBUG_COMPILER_FLAGS; - - static boolean shouldLog(Level level) { - return verbose || level.intValue() >= minLogLevel; - } - static boolean log(Level level, String message, Throwable ex) { - if (!shouldLog(level)) - return true; - Logger.getLogger(JavaCL.class.getSimpleName()).log(level, message, ex); - return true; - } - - static boolean log(Level level, String message) { - log(level, message, null); - return true; - } - - private static int getPlatformIDs(int count, Pointer out, Pointer pCount) { - try { - return CL.clIcdGetPlatformIDsKHR(count, getPeer(out), getPeer(pCount)); - } catch (Throwable th) { - return CL.clGetPlatformIDs(count, getPeer(out), getPeer(pCount)); - } - } - - @org.bridj.ann.Library("OpenCLProbe") - @org.bridj.ann.Convention(org.bridj.ann.Convention.Style.StdCall) - public static class OpenCLProbeLibrary { - @org.bridj.ann.Optional - public native static synchronized int clGetPlatformIDs(int cl_uint1, Pointer cl_platform_idPtr1, Pointer cl_uintPtr1); - @org.bridj.ann.Optional - public native static synchronized int clIcdGetPlatformIDsKHR(int cl_uint1, Pointer cl_platform_idPtr1, Pointer cl_uintPtr1); - @org.bridj.ann.Optional - public native static int clGetPlatformInfo(@Ptr long cl_platform_id1, int cl_platform_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - - #declareInfosGetter("infos", "clGetPlatformInfo") - - private static int getPlatformIDs(int count, Pointer out, Pointer pCount) { - try { - return clIcdGetPlatformIDsKHR(count, out, pCount); - } catch (Throwable th) { - return clGetPlatformIDs(count, out, pCount); - } - } - private static Pointer getPlatformIDs() { - Pointer pCount = allocateInt(); - error(getPlatformIDs(0, null, pCount)); - - int nPlats = pCount.getInt(); - if (nPlats == 0) - return null; - - Pointer ids = allocateTypedPointers(cl_platform_id.class, nPlats); - error(getPlatformIDs(nPlats, ids, null)); - return ids; - } - public static boolean hasOpenCL1_0() { - Pointer ids = getPlatformIDs(); - if (ids == null) - return false; - - for (cl_platform_id id : ids) - if (isOpenCL1_0(id)) - return true; - return false; - } - public static boolean isOpenCL1_0(cl_platform_id platform) { - String version = infos.getString(getPeer(platform), OpenCLLibrary.CL_PLATFORM_VERSION); - return version.matches("OpenCL 1\\.0.*"); - } - public static boolean isValid() { - try { - Pointer ids = getPlatformIDs(); - return ids != null; - } catch (Throwable th) { - return false; - } - } - } - - static final OpenCLLibrary CL; - static { - if (Platform.isLinux()) { - String amdAppBase = "/opt/AMDAPP/lib"; - BridJ.addLibraryPath(amdAppBase + "/" + (Platform.is64Bits() ? "x86_64" : "x86")); - BridJ.addLibraryPath(amdAppBase); - } - boolean needsAdditionalSynchronization = false; - { - OpenCLProbeLibrary probe = null; - try { - try { - BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL"); - BridJ.register(); - } catch (Throwable th) {} - - probe = new OpenCLProbeLibrary(); - - if (!probe.isValid()) { - BridJ.unregister(OpenCLProbeLibrary.class); - //BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL"); - String alt; - if (Platform.is64Bits() && (BridJ.getNativeLibraryFile(alt = "atiocl64") != null || BridJ.getNativeLibraryFile(alt = "amdocl64") != null) || - BridJ.getNativeLibraryFile(alt = "atiocl32") != null || - BridJ.getNativeLibraryFile(alt = "atiocl") != null || - BridJ.getNativeLibraryFile(alt = "amdocl32") != null || - BridJ.getNativeLibraryFile(alt = "amdocl") != null) - { - log(Level.INFO, "Hacking around ATI's weird driver bugs (using atiocl/amdocl library instead of OpenCL)", null); - BridJ.setNativeLibraryActualName("OpenCL", alt); - } - BridJ.register(OpenCLProbeLibrary.class); - } - - - if (probe.hasOpenCL1_0()) { - needsAdditionalSynchronization = true; - log(Level.WARNING, "At least one OpenCL platform uses OpenCL 1.0, which is not thread-safe: will use (slower) synchronized low-level bindings."); - } - } finally { - if (probe != null) - BridJ.unregister(OpenCLProbeLibrary.class); - probe = null; - } - } - - if (debug) { - String debugArgs = System.getenv(JAVACL_DEBUG_COMPILER_FLAGS_PROP); - if (debugArgs != null) - DEBUG_COMPILER_FLAGS = Arrays.asList(debugArgs.split(" ")); - else if (Platform.isMacOSX()) - DEBUG_COMPILER_FLAGS = Arrays.asList("-g"); - else - DEBUG_COMPILER_FLAGS = Arrays.asList("-O0", "-g"); - - int pid = ProcessUtils.getCurrentProcessId(); - log(Level.INFO, "Debug mode enabled with compiler flags \"" + StringUtils.implode(DEBUG_COMPILER_FLAGS, " ") + "\" (can be overridden with env. var. JAVACL_DEBUG_COMPILER_FLAGS_PROP)"); - log(Level.INFO, "You can debug your kernels with GDB using one of the following commands :\n" - + "\tsudo gdb --tui --pid=" + pid + "\n" - + "\tsudo ddd --debugger \"gdb --pid=" + pid + "\"\n" - + "More info here :\n" - + "\thttp://code.google.com/p/javacl/wiki/DebuggingKernels"); - - - } - Class libraryClass = OpenCLLibrary.class; - if (needsAdditionalSynchronization) { - try { - libraryClass = BridJ.subclassWithSynchronizedNativeMethods(libraryClass); - } catch (Throwable ex) { - throw new RuntimeException("Failed to create a synchronized version of the OpenCL API bindings: " + ex, ex); - } - } - BridJ.register(libraryClass); - try { - CL = libraryClass.newInstance(); - } catch (Throwable ex) { - throw new RuntimeException("Failed to instantiate library " + libraryClass.getName() + ": " + ex, ex); - } - } - - /** - * List the OpenCL implementations that contain at least one GPU device. - */ - public static CLPlatform[] listGPUPoweredPlatforms() { - CLPlatform[] platforms = listPlatforms(); - List out = new ArrayList(platforms.length); - for (CLPlatform platform : platforms) { - if (platform.listGPUDevices(true).length > 0) - out.add(platform); - } - return out.toArray(new CLPlatform[out.size()]); - } - /** - * Lists all available OpenCL implementations. - */ - public static CLPlatform[] listPlatforms() { - Pointer pCount = allocateInt(); - error(getPlatformIDs(0, null, pCount)); - - int nPlats = pCount.getInt(); - if (nPlats == 0) - return new CLPlatform[0]; - - Pointer ids = allocateTypedPointers(cl_platform_id.class, nPlats); - - error(getPlatformIDs(nPlats, ids, null)); - CLPlatform[] platforms = new CLPlatform[nPlats]; - - for (int i = 0; i < nPlats; i++) { - platforms[i] = new CLPlatform(ids.getSizeTAtOffset(i * Pointer.SIZE)); - } - return platforms; - } - - /** - * Creates an OpenCL context formed of the provided devices.
      - * It is generally not a good idea to create a context with more than one device, - * because much data is shared between all the devices in the same context. - * @param devices devices that are to form the new context - * @return new OpenCL context - */ - public static CLContext createContext(Map contextProperties, CLDevice... devices) { - return devices[0].getPlatform().createContext(contextProperties, devices); - } - - /** - * Allows the implementation to release the resources allocated by the OpenCL compiler.
      - * This is a hint from the application and does not guarantee that the compiler will not be used in the future or that the compiler will actually be unloaded by the implementation.
      - * Calls to Program.build() after unloadCompiler() will reload the compiler, if necessary, to build the appropriate program executable. - */ - public static void unloadCompiler() { - error(CL.clUnloadCompiler()); - } - - /** - * Returns the "best" OpenCL device (currently, the one that has the largest amount of compute units).
      - * For more control on what is to be considered a better device, please use the {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature[]) } variant.
      - * This is currently equivalent to getBestDevice(MaxComputeUnits) - */ - public static CLDevice getBestDevice() { - return getBestDevice(CLPlatform.DeviceFeature.MaxComputeUnits); - } - /** - * Returns the "best" OpenCL device based on the comparison of the provided prioritized device feature.
      - * The returned device does not necessarily exhibit the features listed in preferredFeatures, but it has the best ordered composition of them.
      - * For instance on a system with a GPU and a CPU device, JavaCL.getBestDevice(CPU, MaxComputeUnits) will return the CPU device, but on another system with two GPUs and no CPU device it will return the GPU that has the most compute units. - */ - public static CLDevice getBestDevice(CLPlatform.DeviceFeature... preferredFeatures) { - List devices = new ArrayList(); - for (CLPlatform platform : listPlatforms()) - devices.addAll(Arrays.asList(platform.listAllDevices(true))); - return CLPlatform.getBestDevice(Arrays.asList(preferredFeatures), devices); - } - /** - * Creates an OpenCL context with the "best" device (see {@link JavaCL#getBestDevice() }) - */ - public static CLContext createBestContext() { - return createBestContext(DeviceFeature.MaxComputeUnits); - } - - /** - * Creates an OpenCL context with the "best" device based on the comparison of the provided - * prioritized device feature (see {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature...) }) - */ - public static CLContext createBestContext(CLPlatform.DeviceFeature... preferredFeatures) { - CLDevice device = getBestDevice(preferredFeatures); - return device.getPlatform().createContext(null, device); - } - - /** - * Creates an OpenCL context able to share entities with the current OpenGL context. - * @throws RuntimeException if JavaCL is unable to create an OpenGL-shared OpenCL context. - */ - public static CLContext createContextFromCurrentGL() { - RuntimeException first = null; - for (CLPlatform platform : listPlatforms()) { - try { - CLContext ctx = platform.createContextFromCurrentGL(); - if (ctx != null) - return ctx; - } catch (RuntimeException ex) { - if (first == null) - first = ex; - - } - } - throw new RuntimeException("Failed to create an OpenCL context based on the current OpenGL context", first); - } - - static File userJavaCLDir = new File(new File(System.getProperty("user.home")), ".javacl"); - static File userCacheDir = new File(userJavaCLDir, "cache"); - - static synchronized File createTempFile(String prefix, String suffix, String category) { - File dir = new File(userJavaCLDir, category); - dir.mkdirs(); - try { - return File.createTempFile(prefix, suffix, dir); - } catch (IOException ex) { - throw new RuntimeException("Failed to create a temporary directory for category '" + category + "' in " + userJavaCLDir + ": " + ex.getMessage(), ex); - } - } - static synchronized File createTempDirectory(String prefix, String suffix, String category) { - File file = createTempFile(prefix, suffix, category); - file.delete(); - file.mkdir(); - return file; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/LocalSize.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/LocalSize.java deleted file mode 100644 index 263f2be27..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/LocalSize.java +++ /dev/null @@ -1,36 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import org.bridj.*; -import org.bridj.util.*; -import java.lang.reflect.Type; -/** - * Size in bytes of a __local argument. - */ -public class LocalSize { - long size; - public LocalSize(long size) { - this.size = size; - } - - #foreach ($prim in $primitivesNoBool) - - /** - * Returns the size in bytes of an array of ${prim.Name} values of the specified length.
      - * @return arrayLength * sizeof(${prim.Name}) = arrayLength * ${prim.Size}
      - */ - public static LocalSize of${prim.CapName}Array(long arrayLength) { - return new LocalSize(arrayLength * ${prim.Size}); - } - - #end - - /** - * Returns the size in bytes of an array of T values of the specified length.
      - */ - public static LocalSize ofArray(long arrayLength, Type componentType) { - PointerIO io = PointerIO.getInstance(componentType); - if (io == null) - throw new RuntimeException("Unsupported type : " + Utils.toString(componentType)); - return new LocalSize(arrayLength * io.getTargetSize()); - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/PlatformUtils.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/PlatformUtils.java deleted file mode 100644 index 17512b1b7..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/PlatformUtils.java +++ /dev/null @@ -1,26 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; - -class PlatformUtils { - public enum PlatformKind { - AMDApp, - NVIDIA, - Apple, - Intel - } - public static PlatformKind guessPlatformKind(CLPlatform p) { - String name = p.getName(); - if (name != null) { - if (name.equals("Apple")) - return PlatformKind.Apple; - else if (name.equals("ATI Stream") || name.equals("AMD Accelerated Parallel Processing")) - return PlatformKind.AMDApp; - else { - String vendor = p.getVendor().toLowerCase(); - if (vendor.contains("nvidia")) - return PlatformKind.NVIDIA; - } - } - return null; - } -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointer.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointer.java deleted file mode 100644 index 8d5774260..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointer.java +++ /dev/null @@ -1,56 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import org.bridj.*; - -/** - * - * @author ochafik - */ -final class ReusablePointer { - private final Pointer pointer; - private final long bytesCapacity; - - public ReusablePointer(long bytesCapacity) { - this.bytesCapacity = bytesCapacity; - this.pointer = Pointer.allocateBytes(bytesCapacity).withoutValidityInformation(); - } - public Pointer pointerToInts(int... values) { - if (values == null) - return null; - long needed = 4 * values.length; - if (needed > bytesCapacity) { - return Pointer.pointerToInts(values); - } else { - return (Pointer)pointer.setInts(values); - } - } - public Pointer pointerToSizeTs(long... values) { - if (values == null) - return null; - long needed = SizeT.SIZE * values.length; - if (needed > bytesCapacity) { - return Pointer.pointerToSizeTs(values); - } else { - return (Pointer)pointer.setSizeTs(values); - } - } - public Pointer pointerToSizeTs(int... values) { - if (values == null) - return null; - long needed = SizeT.SIZE * values.length; - if (needed > bytesCapacity) { - return Pointer.pointerToSizeTs(values); - } else { - return (Pointer)pointer.setSizeTs(values); - } - } - public Pointer allocatedBytes(int needed) { - if (needed == 0) - return null; - if (needed > bytesCapacity) { - return (Pointer)Pointer.allocateBytes(needed); - } else { - return (Pointer)pointer; - } - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointers.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointers.java deleted file mode 100644 index fb777cf75..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/ReusablePointers.java +++ /dev/null @@ -1,44 +0,0 @@ -#parse("main/Header.vm") -package com.nativelibs4java.opencl; -import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; -import org.bridj.*; -import static org.bridj.Pointer.*; -/** - * - * @author ochafik - */ -final class ReusablePointers { - public final ReusablePointer - sizeT3_1 = new ReusablePointer(3 * SizeT.SIZE), - sizeT3_2 = new ReusablePointer(3 * SizeT.SIZE), - sizeT3_3 = new ReusablePointer(3 * SizeT.SIZE); - - public final Pointer - int1 = allocateInt().withoutValidityInformation(), - int2 = allocateInt().withoutValidityInformation(); - - public final ReusablePointer - kernelArg = new ReusablePointer(8 * 16); // double16 arguments ! - - public final Pointer event_out = allocateTypedPointer(cl_event.class).withoutValidityInformation(); - - public final Pointer pErr = allocateInt().withoutValidityInformation(); - - public final int[] event_count = new int[1]; - public final ReusablePointer events_in = new ReusablePointer(Pointer.SIZE * 10); - - private ReusablePointers() {} - - public static ReusablePointers get() { - return local.get(); - } - private static final ThreadLocal local = new ThreadLocal() { - - @Override - protected ReusablePointers initialValue() { - return new ReusablePointers(); - } - - }; - -} diff --git a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/package-info.java b/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/package-info.java deleted file mode 100644 index 8794d52cc..000000000 --- a/libraries/OpenCL/Core/src/main/velocity/com/nativelibs4java/opencl/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -#parse("main/Header.vm") -/** - * Object-oriented wrappers around the OpenCL API ({@link com.nativelibs4java.opencl.JavaCL}, {@link com.nativelibs4java.opencl.CLPlatform}, {@link com.nativelibs4java.opencl.CLContext}, {@link com.nativelibs4java.opencl.CLProgram}, {@link com.nativelibs4java.opencl.CLKernel}, {@link com.nativelibs4java.opencl.CLBuffer}...)
      - * Also see the low-level bindings : {@link com.nativelibs4java.opencl.library.OpenCL4Java} - */ -package com.nativelibs4java.opencl; diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java deleted file mode 100644 index c2ec33c95..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/AbstractCommon.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import org.junit.Before; -import org.junit.BeforeClass; - -import com.nativelibs4java.test.MiscTestUtils; -import java.util.ArrayList; -import java.util.List; -import org.junit.After; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -/** - * - * @author ochafik - */ -@RunWith(Parameterized.class) -public abstract class AbstractCommon { - - CLPlatform platform; - CLContext context; - CLQueue queue; - CLDevice device; - CLImageFormat[] formatsRead2D, formatsRead3D, formatsWrite2D, formatsWrite3D, formatsReadWrite2D, formatsReadWrite3D; - /* - @BeforeClass - public static void setup() { - MiscTestUtils.protectJNI(); - } - */ - - static boolean listedPlatforms; - - AbstractCommon(CLDevice device) { - this.device = device; - platform = device.getPlatform(); - context = platform.createContext(null, device); - queue = context.createDefaultQueue(); - device = context.getDevices()[0]; - formatsRead2D = context.getSupportedImageFormats(CLMem.Flags.ReadOnly, CLMem.ObjectType.Image2D); - formatsWrite2D = context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image2D); - formatsRead3D = context.getSupportedImageFormats(CLMem.Flags.ReadOnly, CLMem.ObjectType.Image3D); - formatsWrite3D = context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image3D); - formatsReadWrite2D = context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image2D); - formatsReadWrite3D = context.getSupportedImageFormats(CLMem.Flags.ReadWrite, CLMem.ObjectType.Image3D); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - List ret = new ArrayList(); - for (CLPlatform platform : JavaCL.listPlatforms()) - for (CLDevice device : platform.listAllDevices(true)) - ret.add(new Object[] { device }); - return ret; - } - /* - @After - public void cleanup() { - queue.finish(); - queue.release(); - context.release(); - device.release(); - platform.release(); - } - */ -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java deleted file mode 100644 index 0f147e865..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BinaryKernelTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.nativelibs4java.opencl; - -import java.util.Map; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import com.nativelibs4java.test.MiscTestUtils; -import java.util.List; -import org.junit.runners.Parameterized; - -/** - * - * @author Kazo Csaba - */ -@SuppressWarnings("unchecked") -public class BinaryKernelTest extends AbstractCommon { - public BinaryKernelTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - - @Test - public void simpleTest() throws CLBuildException { - if (!context.getCacheBinaries()) { - System.out.println("Skipping binaries caching test"); - return; - } - CLProgram program = context.createProgram( - "__kernel void copy(__global int* a, __global int* b) {\n" + - " int i = get_global_id(0);\n" + - " b[i]=a[i];\n" + - "} "); - program.build(); - Map binaries = program.getBinaries(); - program.release(); - - CLProgram binaryProgram = context.createProgram(binaries, null); - CLKernel kernel = binaryProgram.createKernel("copy"); - - CLBuffer a=context.createBuffer(CLMem.Usage.Input, Integer.class, 4); - CLBuffer b=context.createBuffer(CLMem.Usage.Output, Integer.class, 4); - - Pointer source = allocateInts(4).order(context.getByteOrder()); - for (int i=0; i<4; i++) - source.set(i, 3*i+10); - - a.write(queue, source, true); - - kernel.setArgs(a, b); - kernel.enqueueNDRange(queue, new int[]{4}).waitFor(); - - Pointer target = b.read(queue); - - assertEquals(target.getValidElements(), source.getValidElements()); - for (int i=0; i<4; i++) - assertEquals(source.get(i), target.get(i)); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java deleted file mode 100644 index df4ed5abc..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferReadTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.nativelibs4java.opencl; - -import java.nio.LongBuffer; -import java.util.Random; - -import junit.framework.TestCase; - -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.NIOUtils; - -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLDevice; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import org.bridj.Pointer; - -public class BufferReadTest extends TestCase { - - private CLProgram program; - private CLContext context; - private CLQueue q; - private Random r; - @Override - protected void setUp() throws Exception { - super.setUp(); - r = new Random(2011); - initializeCLStuff(); - compileProgram(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if(context != null) - context.release(); - if(q != null) - q.release(); - if(program != null) - program.release(); - context = null; - q = null; - program = null; - } - - public void testBufferRead() throws Exception { - int size = 50; - CLKernel kernel = program.createKernel("testLongRead"); - CLBuffer clInBuff = context.createLongBuffer(CLMem.Usage.Input, size); - CLBuffer clOutBuff = context.createLongBuffer(CLMem.Usage.Output, size); - long[] longArray = new long[size]; - for(int i = 0; i < longArray.length ; i ++) { - longArray[i] = i; - } - clInBuff.write(q, Pointer.pointerToLongs(longArray), true); - kernel.setArg(0, clInBuff); - kernel.setArg(1, clOutBuff); - CLEvent completion = kernel.enqueueNDRange(q, new int[] {size}); - completion.waitFor(); - - - /////////////////////////////////////////////////// - //we tried to make a buffer before the clOutBuff.read() so that it isn't creating new ones - //this way when we're on a loop we won't have to waste memory creating more buffers - //we thought that the read would simply read everything into the LongBuffer, - //and since the LongBuffer is wrapped around the outPrim, it would update the values as soon as it is read. - long[] outPrim = new long[size]; - if (false) { - Pointer outBuffJava = Pointer.pointerToLongs(outPrim); - clOutBuff.read(q, 0, size,outBuffJava, true); - } else { - Pointer outBuffJava = Pointer.allocateLongs(size).order(context.getByteOrder()); - clOutBuff.read(q, 0, size,outBuffJava, true); - //LongBuffer outBuffJava = clOutBuff.read(q, 0, size); - outBuffJava.getLongs(outPrim); - } - System.out.println("test1:\nThese should read 1, 2, 3, 4, 5"); - for(int i = 0 ; i < 5 ; i ++) { - System.out.print(outPrim[i] + ", "); - - } - System.out.println(); - - - //////////////////////////////////////////////////// - //this is the way that we know works, but it creates a new LongBuffer every read, and we also have to do a - //outBuffJava2.get(), which forces us to separate the outPrim2 from the java LongBuffer, and require us to create a new array. - Pointer outBuffJava2 = clOutBuff.read(q); - long[] outPrim2 = new long[size]; - outBuffJava2.getLongs(outPrim2); - System.out.println("test2:\nThese should read 1, 2, 3, 4, 5"); - for(int i = 0 ; i < 5 ; i ++) { - System.out.print(outPrim2[i] + ", "); - - } - System.out.println(); - - } - - private void initializeCLStuff() { - initializeCLContextAndQueueOrNothing(0, 0); - } - private void compileProgram() throws Exception{ - String sources = IOUtils.readText(BufferReadTest.class.getResourceAsStream("BufferReadTest.c")); - program = context.createProgram(sources).build(); - - } - private synchronized void initializeCLContextAndQueueOrNothing(int platformNumber, int deviceNumber) { - //should check for index out of bounds later. need to figure out how I should throw the errors - if(context==null || q == null) { - CLDevice device = JavaCL.listPlatforms()[platformNumber].listAllDevices(false)[deviceNumber]; - System.out.println("Device = " + device); - context = (JavaCL.createContext(null, device)); - q = (context.createDefaultQueue()); - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java deleted file mode 100644 index c67d05e43..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/BufferTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.util.NIOUtils.directBuffer; -import static com.nativelibs4java.util.NIOUtils.get; -import static com.nativelibs4java.util.NIOUtils.put; -import static org.junit.Assert.assertEquals; - -import java.nio.*; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.NIOUtils; -import org.bridj.*; -import java.nio.ByteOrder; -import static org.bridj.Pointer.*; -import java.nio.ByteOrder; -import java.util.List; -import org.junit.runners.Parameterized; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unchecked") -public class BufferTest extends AbstractCommon { - public BufferTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - - static ByteOrder otherOrder(ByteOrder o) { - return o.equals(ByteOrder.BIG_ENDIAN) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - } - - @Test(expected = IllegalArgumentException.class) - public void testMismatchingOrder() { - context.createBuffer(CLMem.Usage.InputOutput, allocateFloats(10).order(otherOrder(context.getByteOrder()))); - } - @Test - public void testMismatchingByteOrder() { - context.createBuffer(CLMem.Usage.InputOutput, allocateBytes(10).order(otherOrder(context.getByteOrder()))); - } - - @Test - public void testReadWrite() { - for (Class bufferClass : bufferClasses) - testReadWrite(bufferClass, 10, 3, 3); - } - public void testReadWrite(Class bufferClass, int n, int zeroOffset, int zeroLength) { - CLBuffer buf = context.createBuffer(CLMem.Usage.InputOutput, bufferClass, n); - assertEquals(n, buf.getElementCount()); - - Pointer initial = allocateArray(bufferClass, n).order(context.getByteOrder()); - Pointer zeroes = allocateArray(bufferClass, n).order(context.getByteOrder()); - for (int i = 0; i < n; i++) { - int v = i + 1; - Object value = null; - if (bufferClass == Integer.class) - value = (Object)v; - else if (bufferClass == Long.class) - value = (Object)(long)v; - else if (bufferClass == Short.class) - value = (Object)(short)v; - else if (bufferClass == Byte.class) - value = (Object)(byte)v; - else if (bufferClass == Double.class) - value = (Object)(double)v; - else if (bufferClass == Float.class) - value = (Object)(float)v; - else if (bufferClass == Boolean.class) - value = (Object)(v != 0); - else if (bufferClass == Character.class) - value = (Object)(char)v; - else - throw new RuntimeException(); - initial.set(i, (B)value); - } - - buf.write(queue, initial, true); - - Pointer retrieved = buf.read(queue); - assertEquals(buf.getElementCount(), retrieved.getValidElements()); - - for (int i = 0; i < n; i++) - assertEquals(bufferClass.getName(), initial.get(i), retrieved.get(i)); - - buf.write(queue, zeroOffset, zeroLength, zeroes, true); - - boolean direct = true; - String type = direct ? "read to direct buffer" : "read to indirect buffer"; - Pointer readBuffer; - //if (direct) - readBuffer = retrieved; - //else - // readBuffer = NIOUtils.indirectBuffer(n, bufferClass); - buf.read(queue, readBuffer, true); - - for (int i = 0; i < n; i++) { - if (i >= zeroOffset && i < (zeroOffset + zeroLength)) - assertEquals(bufferClass.getName(), zeroes.get(i), readBuffer.get(i)); - else - assertEquals(bufferClass.getName(), initial.get(i), readBuffer.get(i)); - } - } - - Class[] bufferClasses = new Class[] { - Integer.class, - Long.class, - Short.class, - Byte.class, - Double.class, - Float.class - }; - Class[] primClasses = new Class[] { - Integer.class, - Long.class, - Short.class, - Byte.class, - Double.class, - Character.class, - Float.class - }; - @Test - public void testMap() { - for (Class bufferClass : bufferClasses) - testMap(bufferClass); - } - public void testMap(Class bufferClass) { - int size = 10; - Pointer data = allocateBytes(size).order(context.getByteOrder()); - CLBuffer buf = context.createBuffer(CLMem.Usage.Input, data, false).as(bufferClass); - Pointer mapped = buf.map(queue, CLMem.MapFlags.Read); - - assertEquals(data, mapped); - } - -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ByteOrderHackTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ByteOrderHackTest.java deleted file mode 100644 index d356b71fb..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ByteOrderHackTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.nativelibs4java.opencl; - -import java.util.Map; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import com.nativelibs4java.test.MiscTestUtils; -import java.util.List; -import org.junit.runners.Parameterized; - -@SuppressWarnings("unchecked") -public class ByteOrderHackTest extends AbstractCommon { - public ByteOrderHackTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - - @Test - public void test() { - if (!ByteOrderHack.hackEnabled) - return; - for (CLPlatform platform : JavaCL.listPlatforms()) { - for (CLDevice device : platform.listAllDevices(true)) { - assertEquals(device.getByteOrder(), ByteOrderHack.checkByteOrderNeededForBuffers(device)); - } - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLPlatformTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLPlatformTest.java deleted file mode 100644 index cb7590574..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLPlatformTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.JavaCL.*; - -import java.util.*; - -import static org.junit.Assert.*; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class CLPlatformTest { - final CLPlatform platform; - - public CLPlatformTest(CLPlatform platform) { - this.platform = platform; - } - @Test - public void ensureHasDevices() { - CLDevice[] devices = platform.listAllDevices(false); - assertTrue("No device in platform " + platform, devices.length > 0); - } - @Parameters - public static List readParameters() { - List data = new ArrayList(); - - for (CLPlatform platform : JavaCL.listPlatforms()) { - data.add(new Object[] { platform }); - } - - return data; - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java deleted file mode 100644 index 48bfff522..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/CLTestUtils.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.nativelibs4java.opencl; -import static com.nativelibs4java.opencl.JavaCL.listPlatforms; - -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; - - -import org.bridj.*; -import static org.bridj.Pointer.*; -/** - * @author ochafik - */ -public class CLTestUtils { - public enum Target { - CPU, GPU, CPU_GPU; - - } - public static interface Action1 { - void call(X x); - } - public static interface Action2 { - void call(X x, Y y); - } - public static interface Action3 { - void call(X x, Y y, Z z); - } - /// Calculate the average relative error of operations between two result buffers - public static double avgError(FloatBuffer a, Pointer b, int dataSize) { - double tot = 0; - for (int i = 0; i < dataSize; i++) { - float va = a.get(i), vb = b.get(i); - float d = va - vb; - if (Float.isNaN(d)) - d = d + 0; - if (d < 0) - d = -d; - float m = (va + vb) / 2; - if (m == 0) - continue; - double r = d / (double)m; - tot += r; - } - return tot / dataSize; - } - public static double avgError(DoubleBuffer a, Pointer b, int dataSize) { - double tot = 0; - for (int i = 0; i < dataSize; i++) { - double va = a.get(i), vb = b.get(i); - double d = va - vb; - if (Double.isNaN(d)) - d = d + 0; - if (d < 0) - d = -d; - double m = (va + vb) / 2; - if (m == 0) - continue; - double r = d / (double)m; - tot += r; - } - return tot / dataSize; - } - - public static void fillBuffersWithSomeDataf(FloatBuffer a, FloatBuffer b) { - fillBuffersWithSomeDataf((Pointer)pointerToBuffer(a), (Pointer)pointerToBuffer(b)); - } - public static void fillBuffersWithSomeDatad(DoubleBuffer a, DoubleBuffer b) { - fillBuffersWithSomeDatad((Pointer)pointerToBuffer(a), (Pointer)pointerToBuffer(b)); - } - public static void fillBuffersWithSomeDataf(Pointer a, Pointer b) { - int s = (int)a.getValidElements(); - for (int i = 0; i < s; i++) { - float v = i; - a.set(i, v); - b.set(i, v); - } - } - public static void fillBuffersWithSomeDatad(Pointer a, Pointer b) { - int s = (int)a.getValidElements(); - for (int i = 0; i < s; i++) { - double v = i; - a.set(i, v); - b.set(i, v); - } - } - - public static CLDevice[] getDevices(Target target) { - CLPlatform platform = listPlatforms()[0]; - switch (target) { - case CPU: - return platform.listCPUDevices(true); - case GPU: - return platform.listGPUDevices(true); - case CPU_GPU: - return platform.listAllDevices(true); - default: - throw new IllegalArgumentException("Unknown target : " + target); - } - } - public static class ExecResult { - public B buffer; - public double unitTimeNano; - public ExecResult(B buffer, double unitTimeNano) { - this.buffer = buffer; - this.unitTimeNano = unitTimeNano; - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/EventTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/EventTest.java deleted file mode 100644 index acfe8a20f..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/EventTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.nativelibs4java.opencl; - -import java.util.Map; -import static org.junit.Assert.*; - -import org.junit.BeforeClass; -import org.junit.Test; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import com.nativelibs4java.test.MiscTestUtils; -import java.util.List; -import org.junit.runners.Parameterized; - -@SuppressWarnings("unchecked") -public class EventTest extends AbstractCommon { - public EventTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - - @Test - public void simpleTest() throws CLBuildException { - CLKernel kernel = context.createProgram( - "__kernel void copy(__global int* a, __global int* b) {\n" + - " int i = get_global_id(0);\n" + - " b[i]=a[i];\n" + - "} " - ).createKernel("copy"); - - CLBuffer - a = context.createBuffer(CLMem.Usage.Input, Integer.class, 4), - b = context.createBuffer(CLMem.Usage.Output, Integer.class, 4); - - kernel.setArgs(a, b); - - int[] globalSizes = new int[]{4}; - CLEvent e = kernel.enqueueNDRange(queue, globalSizes); - assertNotNull(e); - e.waitFor(); - assertNull(kernel.enqueueNDRange(queue, globalSizes, CLEvent.FIRE_AND_FORGET)); - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java deleted file mode 100644 index 5bb998122..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/ImageTest.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl; - -import org.bridj.Pointer; -import com.nativelibs4java.opencl.CLImageFormat.ChannelDataType; -import com.nativelibs4java.opencl.CLImageFormat.ChannelOrder; -import static org.junit.Assert.*; - -import java.awt.image.BufferedImage; -import java.nio.IntBuffer; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.ImageUtils; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; -import java.util.Arrays; -import java.util.List; -import org.junit.runners.Parameterized; - -/** - * - * @author ochafik - */ -public class ImageTest extends AbstractCommon { - public ImageTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - - public boolean supportsImages() { - for (CLDevice device : context.getDevices()) - if (device.hasImageSupport()) - return true; - return false; - } - @Test - public void simpleImage2d() { - if (!supportsImages()) - return; - long width = 100, height = 200; - CLImageFormat format = formatsRead2D[0]; - CLImage2D im = context.createImage2D(CLMem.Usage.InputOutput, format, width, height); - assertEquals(width, im.getWidth()); - assertEquals(height, im.getHeight()); - assertEquals(format, im.getFormat()); - } - - int someARGBPixelValue = 0xff123456; - int someARGBGrayPixelValue = 0xffababab; - int someShortGrayPixelValue = 0xf1f1; - - - @Test - public void testCreateARGBFromImage() { - int width = 2, height = 2; - BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - im.setRGB(1, 0, someARGBPixelValue); - - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, im, true); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - assertEquals(CLImageFormat.INT_ARGB_FORMAT, clim.getFormat()); - assertSameImage(im, clim.read(queue)); - } - - static void assertSameImage(BufferedImage expected, BufferedImage real) { - int width = expected.getWidth(), height = expected.getHeight(); - assertEquals("Bad width", width, real.getWidth()); - assertEquals("Bad height", height, real.getHeight()); - - for (int x = 0; x < width; x++) - for (int y = 0; y < height; y++) - assertEquals("Different value for pixel x = " + x + ", y = " + y, Integer.toHexString(expected.getRGB(x, y)), Integer.toHexString(real.getRGB(x, y))); - } - - @Test - public void testARGBReadWrite() { - int width = 2, height = 2; - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, CLImageFormat.INT_ARGB_FORMAT, width, height); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - - BufferedImage im = clim.read(queue); - assertEquals(BufferedImage.TYPE_INT_ARGB, im.getType()); - int x = 0, y = 1; - im.setRGB(x, y, someARGBPixelValue); - clim.write(queue, im, false, true); - - assertSameImage(im, clim.read(queue)); - } - - @Test - public void testARGBShortGrayReadWrite() { - int width = 2, height = 2; - CLImage2D clim = context.createImage2D(CLMem.Usage.InputOutput, new CLImageFormat(ChannelOrder.RGBA, ChannelDataType.UnsignedInt16), width, height); - assertEquals(width, clim.getWidth()); - assertEquals(height, clim.getHeight()); - - BufferedImage im = clim.read(queue); - assertEquals(BufferedImage.TYPE_USHORT_GRAY, im.getType()); - int x = 0, y = 1; - im.setRGB(x, y, someARGBGrayPixelValue); - clim.write(queue, im, false, true); - - assertSameImage(im, clim.read(queue)); - } - - - - @Test - public void testMaxWidth() { - if (!supportsImages()) - return; - context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], device.getImage2DMaxWidth() - 1, 1); - //long d = device.getImage3DMaxDepth(); - //TODO FAILING !!! context.createInput3D(formatsRead3D[0], device.getImage3DMaxWidth() - 1, 1, 1); - } - @Test - public void testMaxHeight() { - if (!supportsImages()) - return; - context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], 1, device.getImage2DMaxHeight() - 1); - //long d = device.getImage3DMaxDepth(); - //TODO FAILING !!! context.createInput3D(formatsRead3D[0], 1, device.getImage3DMaxHeight(), 1); - } - @Test - public void testMaxDepth() { - if (!supportsImages()) - return; - context.createImage3D(CLMem.Usage.Input, formatsRead3D[0], 1, 1, device.getImage3DMaxDepth() - 1); - } - - /*@Test(expected=CLException.InvalidImageSize.class) - public void testInvalidImageSize() { - CLImage2D im = context.createImage2D(CLMem.Usage.Input, formatsRead2D[0], device.getImage2DMaxWidth() + 10, 1); - }*/ - public void simpleImage3d() { - long width = 100, height = 200, depth = 50;//device.getImage3DMaxDepth(); - CLImageFormat format = formatsRead3D[0]; - CLImage3D im = context.createImage3D(CLMem.Usage.Input, format, width, height, depth); - assertEquals(width, im.getWidth()); - assertEquals(height, im.getHeight()); - assertEquals(depth, im.getDepth()); - assertEquals(format, im.getFormat()); - //im.blockingMap(queue, CLMem.MapFlags.Read); - } - - @Test - public void testRGBAImageSource() { - if (!supportsImages()) - return; - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - String src = "\n" + - "const sampler_t sampler = \n" + - " CLK_NORMALIZED_COORDS_FALSE | \n" + - " CLK_FILTER_NEAREST | \n" + - " CLK_ADDRESS_CLAMP_TO_EDGE; \n" + - " \n" + - "__kernel void test( \n" + - " __read_only image2d_t src_image, \n" + - " int width, \n" + - " int height, \n" + - " __global float* output) \n" + - "{ \n" + - " int x = get_global_id(0); \n" + - " int y = get_global_id(1); \n" + - " int2 coord = (int2)(x, y); \n" + - " float4 pixel = read_imagef(src_image, sampler, coord); \n" + - " int offset = (y * width + x) * 4; \n" + - " output[offset] = pixel.x; \n" + - " output[offset + 1] = pixel.y; \n" + - " output[offset + 2] = pixel.z; \n" + - " output[offset + 3] = pixel.w; \n" + - "} \n"; - - int width = 16, height = 16; - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - for (int x = 0; x < width; x++) - for (int y = 0; y < height; y++) { - int red = (x + y); - int green = 2 * (x + y); - int blue = (x + 2 * y); - int alpha = (2 * x + y); - - int p = (alpha << 24) | (blue << 16) | (green << 8) | red; - image.setRGB(x, y, p); - } - //image.setRGB(i, 0, i); - //image.setRGB(i, height - 1, i); - - CLProgram program = context.createProgram(src).build(); - //CLBuffer cloutput = context.createBuffer(CLMem.Usage.Output, Integer.class, width * height * 4); - CLBuffer cloutput = context.createBuffer(CLMem.Usage.Output, Float.class, width * height * 4); - CLKernel kernel = program.createKernel("test"); - - ChannelDataType channelDataType = CLImageFormat.INT_ARGB_FORMAT.getChannelDataType(); - for (ChannelOrder channelOrder : Arrays.asList(ChannelOrder.BGRA, ChannelOrder.RGBA)) { - CLImageFormat imageFormat = new CLImageFormat(channelOrder, channelDataType); - - //CLImage2D climage = context.createImage2D(CLMem.Usage.Input, image, true); - CLImage2D climage = context.createImage2D(CLMem.Usage.Input, imageFormat, width, height); - climage.write(queue, image); - kernel.setArgs( - climage, - width, height, - cloutput - ); - - kernel.enqueueNDRange(queue, new int[] {width, height}).waitFor(); - - //IntBuffer output = cloutput.read(queue); - //IntBuffer output = cloutput.readBytes(queue, 0, width * height * 4 * 4).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); - Pointer output = cloutput.read(queue); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - int expected = image.getRGB(x, y); - float expectedRed = (x + y) / (float)0xff; - float expectedGreen = (2 * (x + y)) / (float)0xff; - float expectedBlue = (x + 2 * y) / (float)0xff; - float expectedAlpha = (2 * x + y) / (float)0xff; - - int offset = (y * width + x) * 4; - /*int r = output.get(offset); - int g = output.get(offset + 1); - int b = output.get(offset + 2); - int a = output.get(offset + 3); - System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + Integer.toHexString(expected) + ", r = " + Integer.toHexString(r) + ", g = " + Integer.toHexString(g) + ", b = " + Integer.toHexString(b) + ", a = " + Integer.toHexString(a)); - System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + (expectedChannel / (double)0xff) + ", r = " + (r / (double)Integer.MAX_VALUE) + ", g = " + (g / (double)Integer.MAX_VALUE) + ", b = " + (b / (double)Integer.MAX_VALUE) + ", a = " + (a / (double)Integer.MAX_VALUE));*/ - float px = output.get(offset); - float py = output.get(offset + 1); - float pz = output.get(offset + 2); - float pw = output.get(offset + 3); - - float red, green, blue, alpha; - switch (climage.getFormat().getChannelOrder()) { - case RGBA: - red = px; - green = py; - blue = pz; - alpha = pw; - break; - case ARGB: - alpha = px; - red = py; - green = pz; - blue = pw; - break; - case BGRA: - blue = px; - green = py; - red = pz; - alpha = pw; - break; - default: - assertTrue("Channel order not handled in this test : " + climage.getFormat(), false); - return; - } - float tolerance = 0.00001f; - String rgba = "(r = " + red + ", green = " + green + ", blue = " + blue + ", alpha = " + alpha + ")"; - String expectedRgba = "(r = " + expectedRed + ", green = " + expectedGreen + ", blue = " + expectedBlue + ", alpha = " + expectedAlpha + ")"; - assertEquals("[" + imageFormat + " format] bad red value for (x, y) = (" + x + ", " + y + ") : \n\t Got " + rgba + ", \n\tExpected " + expectedRgba, expectedRed, red, tolerance); - assertEquals("[" + imageFormat + " format] bad green value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedGreen, green, tolerance); - assertEquals("[" + imageFormat + " format] bad blue value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedBlue, blue, tolerance); - assertEquals("[" + imageFormat + " format] bad alpha value for (x, y) = (" + x + ", " + y + ") : " + rgba + " expected " + expectedRgba, expectedAlpha, alpha, tolerance); - //System.out.println("(x, y) = (" + x + ", "+ y + ") : expected " + (expectedChannel / (double)0xff) + ", r = " + (r) + ", g = " + (g) + ", b = " + (b) + ", a = " + (a)); - - } - } - } - - /* - for (int i = 0; i < width; i++) { - int value = output.get(i); - //System.out.println(value); - Assert.assertEquals(i, value); - } - * - */ - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - - @Test - public void testShortGrayImageSource() { - if (!supportsImages()) - return; - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - String src = "\n" + - "const sampler_t sampler = \n" + - " CLK_NORMALIZED_COORDS_FALSE | \n" + - " CLK_FILTER_NEAREST | \n" + - " CLK_ADDRESS_CLAMP_TO_EDGE; \n" + - " \n" + - "__kernel void test( \n" + - " __read_only image2d_t src_image, \n" + - " int width, \n" + - " int height, \n" + - " __global float* output) \n" + - "{ \n" + - " int x = get_global_id(0); \n" + - " int y = get_global_id(1); \n" + - " int2 coord = (int2)(x, y); \n" + - " float4 pixel = read_imagef(src_image, sampler, coord); \n" + - " int offset = (y * width + x) * 4; \n" + - " output[offset] = pixel.x; \n" + - " output[offset + 1] = pixel.y; \n" + - " output[offset + 2] = pixel.z; \n" + - " output[offset + 3] = pixel.w; \n" + - "} \n"; - - int width = 16, height = 16; - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY); - short[] data = new short[width * height]; - for (short x = 0; x < width; x++) - for (short y = 0; y < height; y++) { - short value = (short) (10 * (x + y)); - data[y * height + x] = value; - } - - image.getRaster().setDataElements(0, 0, width, height, data); - - CLProgram program = context.createProgram(src).build(); - CLBuffer cloutput = context.createBuffer(CLMem.Usage.Output, Float.class, width * height * 4); - - CLKernel kernel = program.createKernel("test"); - - List formats = Arrays.asList(context.getSupportedImageFormats(CLMem.Flags.WriteOnly, CLMem.ObjectType.Image2D)); - //System.out.println("Supported formats = " + formats); - ChannelDataType channelDataType = ChannelDataType.UNormInt16; - for (ChannelOrder channelOrder : Arrays.asList(ChannelOrder.RGBA)) { - CLImageFormat imageFormat = new CLImageFormat(channelOrder, channelDataType); - - //CLImage2D climage = context.createImage2D(CLMem.Usage.Input, image, true); - CLImage2D climage = context.createImage2D(CLMem.Usage.Input, imageFormat, width, height); - climage.write(queue, image); - kernel.setArgs( - climage, - width, height, - cloutput - ); - - kernel.enqueueNDRange(queue, new int[] {width, height}).waitFor(); - - //IntBuffer output = cloutput.read(queue); - //IntBuffer output = cloutput.readBytes(queue, 0, width * height * 4 * 4).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); - Pointer output = cloutput.read(queue); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - float expected = 10f * (x + y) / (float)0xffff; - int offset = (y * width + x) * 4; - float px = output.get(offset); - float py = output.get(offset + 1); - float pz = output.get(offset + 2); - float pw = output.get(offset + 3); - - float tolerance = 0.00001f; - - assertEquals("[" + imageFormat + " format] different RGB components for gray image", px, py, tolerance); - assertEquals("[" + imageFormat + " format] different RGB components for gray image", px, pz, tolerance); - assertEquals("[" + imageFormat + " format] alpha not solid for gray image", 1f, pw, tolerance); - - float actual = px; - assertEquals("[" + imageFormat + " format] bad value for (x, y) = (" + x + ", " + y + ") : \n\t Got " + actual + ", \n\tExpected " + expected, expected, actual, tolerance); - } - } - } - - /* - for (int i = 0; i < width; i++) { - int value = output.get(i); - //System.out.println(value); - Assert.assertEquals(i, value); - } - * - */ - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java deleted file mode 100644 index 1adff649f..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/InfoGettersTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.test.MiscTestUtils.testGetters; -import static org.junit.Assert.assertFalse; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.BeforeClass; - -import com.nativelibs4java.test.MiscTestUtils; - -/** - * - * @author ochafik - */ -public class InfoGettersTest { - @Before - public void gc() { - System.gc(); - try { - Thread.sleep(100); - } catch (InterruptedException ex) { - Logger.getLogger(InfoGettersTest.class.getName()).log(Level.SEVERE, null, ex); - } - System.gc(); - } - - CLProgram createProgram() { - CLProgram pg = createContext().createProgram("__kernel void f(__global int* a) {}"); - try { - pg.build(); - } catch (CLBuildException ex) { - assertFalse(ex.toString(), true); - } - return pg; - } - - CLPlatform createPlatform() { - return JavaCL.listPlatforms()[0]; - } - - CLDevice createDevice() { - return createPlatform().listAllDevices(true)[0]; - } - - CLContext ctx; - CLContext createContext() { - if (ctx == null) - ctx = createPlatform().createContext(null, createDevice()); - return ctx; - } - - CLKernel createKernel() { - try { - return createProgram().createKernels()[0]; - } catch (CLBuildException ex) { - throw new RuntimeException("Failed to create kernel", ex); - } - } - - CLEvent createEvent() { - CLContext c = createContext(); - return c.createBuffer(CLMem.Usage.Input, Integer.class, 10).mapLater(c.createDefaultQueue(), CLMem.MapFlags.Read).getSecond(); - } - - CLSampler createSampler() { - return createContext().createSampler(true, CLSampler.AddressingMode.ClampToEdge, CLSampler.FilterMode.Linear); - } - - CLQueue createQueue() { - CLContext c = createContext(); - CLDevice d = c.getDevices()[0]; - return d.createQueue(c); - } - - @org.junit.Test - public void CLProgramGetters() { - testGetters(createProgram()); - } - - @org.junit.Test - public void CLKernelGetters() { - testGetters(createKernel()); - } - - @org.junit.Test - public void CLMemGetters() { - testGetters(createContext().createBuffer(CLMem.Usage.Input, Byte.class, 10)); - testGetters(createContext().createBuffer(CLMem.Usage.Output, Byte.class, 10)); - } - - @org.junit.Test - public void CLQueueGetters() { - testGetters(createQueue()); - } - - @org.junit.Test - public void CLDeviceGetters() { - testGetters(createDevice()); - } - - @org.junit.Test - public void CLPlatformGetters() { - testGetters(createPlatform()); - } - - @org.junit.Test - public void CLContextGetters() { - testGetters(createContext()); - } - - @org.junit.Test - public void CLEventGetters() { - testGetters(createEvent()); - } - - @org.junit.Test - public void CLSamplerGetters() { - testGetters(createSampler()); - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java deleted file mode 100644 index cf4f6f3dd..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/JOGLTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl; - -import com.jogamp.opengl.util.FPSAnimator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.nio.ByteBuffer; -import java.nio.FloatBuffer; -import java.util.concurrent.Semaphore; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JFrame; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.CLMem.GLObjectInfo; -import com.nativelibs4java.util.NIOUtils; - -import javax.media.opengl.*; -import javax.media.opengl.awt.*; -import static javax.media.opengl.GL.*; -import static javax.media.opengl.GL2.*; - -import com.jogamp.opengl.util.*; -import com.jogamp.common.nio.*; - -import java.nio.ByteOrder; - -public class JOGLTest { - - @BeforeClass - public static void initialise() { - //if (Platform.isWindows()) - System.setProperty("sun.java2d.noddraw","true"); - } - - public GLCanvas createGLCanvas(int width, int height) { - //GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - caps.setHardwareAccelerated(true); - caps.setDoubleBuffered(true); - GLCanvas glCanvas = new GLCanvas(caps);//new GLCapabilities(GLProfile.get(GLProfile.GL))); - //GLCapabilitiesImmutable icaps = glCanvas.getChosenGLCapabilities(); - //boolean hwa = icaps.getHardwareAccelerated(); - glCanvas.setSize( width, height ); - glCanvas.setIgnoreRepaint( true ); - - return glCanvas; - } - - @Test - public void testBuffer() { - if (JavaCL.listGPUPoweredPlatforms().length == 0) { - System.out.println("#\n# Warning: There is no GPU-powered OpenCL platform available. Skipping test.\n#"); - return; - } - - try { - final Semaphore sem = new Semaphore(0); - JFrame f = new JFrame(); - GLCanvas canvas = createGLCanvas(100, 100); - f.getContentPane().add("Center", canvas); - final AssertionError[] err = new AssertionError[1]; - final Throwable[] exx = new Throwable[1]; - canvas.addGLEventListener(new GLEventListener() { - - @Override - public void init(GLAutoDrawable drawable) { - try { - CLContext context = JavaCL.createContextFromCurrentGL(); - assertNotNull(context); - if (context != null) { - //int glcontext = gl.glGet.getContext().CONTEXT_CURRENT; - CLQueue queue = context.createDefaultQueue(); - - System.err.println("Initializing with OpenCL context = " + context + "..."); - int bufferSize = 1024; - FloatBuffer buffer; - int[] VBO = new int[1]; - int[] Texture = new int[1]; - GL2 gl = (GL2)drawable.getGL(); - buffer = NIOUtils.directFloats(bufferSize, ByteOrder.nativeOrder()); - gl.glGenBuffers(1, VBO, 0); // Get A Valid Name - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO[0]); // Bind The Buffer - gl.glBufferData(GL.GL_ARRAY_BUFFER, bufferSize * 4 /*SIZEOF_FLOAT*/, buffer, GL2.GL_DYNAMIC_READ); - - gl.glGenTextures(1, Texture, 0); - gl.glBindTexture(GL2.GL_TEXTURE_2D, Texture[0]); - //gl.glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - - int width = 2, height = 2, border = 0; - //int width = 4, height = 4, border = 0; - byte bZero = (byte)0, bMin1 = (byte)0xFF; - ByteBuffer texData = NIOUtils.directCopy(ByteBuffer.wrap(new byte[] { - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1, - bMin1,bMin1,bMin1,bMin1, bMin1,bMin1,bMin1,bMin1 - }), queue.getDevice().getByteOrder()); - gl.glTexImage2D ( - GL2.GL_TEXTURE_2D, - 0, // no mipmap - 4, // 4 colours - width, - height, - border, - GL.GL_LUMINANCE, GL2.GL_UNSIGNED_BYTE, - //GL.GL_RGBA, GL2.GL_UNSIGNED_INT_8_8_8_8, - texData - ); - - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); - gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); - - gl.glFlush(); - //gl.glFinish(); - - CLBuffer clbuf = context.createBufferFromGLBuffer(CLMem.Usage.Input, VBO[0]).as(Float.class); - CLImage2D climg = context.createImage2DFromGLTexture2D(CLMem.Usage.InputOutput, CLContext.GLTextureTarget.Texture2D, Texture[0], 0); - - assertNotNull(clbuf); - assertNotNull(climg); - - queue.enqueueAcquireGLObjects(new CLMem[] { clbuf }); - queue.enqueueAcquireGLObjects(new CLMem[] { climg }); - queue.finish(); - - { - GLObjectInfo info = clbuf.getGLObjectInfo(); - assertNotNull(info); - assertEquals(CLMem.GLObjectType.Buffer, info.getType()); - assertEquals(VBO[0], info.getName()); - } - { - GLObjectInfo info = climg.getGLObjectInfo(); - assertNotNull(info); - assertEquals(CLMem.GLObjectType.Texture2D, info.getType()); - assertEquals(Texture[0], info.getName()); - } - - float expected = 10; - try { - CLKernel kernel = context.createProgram("__kernel void fill(__global float* out) { out[get_global_id(0)] = (float)" + expected + ";}").build().createKernel("fill", clbuf); - kernel.enqueueNDRange(queue, new int[]{bufferSize}).waitFor(); - } catch (CLException.InvalidKernelArgs ex) { - assertTrue("GL-converted buffer was refused as kernel argument", false); - } catch (Throwable ex) { - assertTrue("Unexpected error : " + ex, false); - } - - //inbuf.put(0, expected); - //clbuf.write(queue, 0, 4 * bufferSize, inbuf, true).waitFor(); - - queue.enqueueReleaseGLObjects(new CLMem[] { clbuf }); - queue.finish(); - - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO[0]); // Bind The Buffer - ByteBuffer mb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2.GL_READ_ONLY); - if (mb != null) { - buffer = mb.asFloatBuffer(); - float val = buffer.get(0); - assertEquals(expected, val, 0); - } - } - - } catch (AssertionError ex) { - ex.printStackTrace(); - err[0] = ex; - } catch (Throwable ex) { - ex.printStackTrace(); - exx[0] = ex; - } finally { - System.out.println("Releasing..."); - sem.release(); - } - } - - public void dispose(GLAutoDrawable glad) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @SuppressWarnings("unused") - public void displayChanged(GLAutoDrawable glad, boolean bln, boolean bln1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void display(GLAutoDrawable drawable) { - } - - @Override - public void reshape(GLAutoDrawable drawable, int i, int i1, int i2, int i3) { - } - }); - f.pack(); - f.setVisible(true); - - FPSAnimator animator = new FPSAnimator(canvas, 60); - //animator.setRunAsFastAsPossible(true); - animator.start(); - - System.out.println("Acquiring..."); - sem.acquire(); - System.out.println("Acquired !"); - - f.setVisible(false); - if (err[0] != null) { - throw err[0]; - } - if (exx[0] != null) { - throw exx[0]; - } - } catch (AssertionError ex) { - throw ex; - } catch (Throwable ex) { - Logger.getLogger(JOGLTest.class.getName()).log(Level.SEVERE, null, ex); - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java deleted file mode 100644 index 91420c1e8..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBasicTest.java +++ /dev/null @@ -1,96 +0,0 @@ - -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.JavaCL.createBestContext; -import static com.nativelibs4java.util.NIOUtils.directFloats; -import static org.junit.Assert.assertEquals; -import org.bridj.*; -import static org.bridj.Pointer.*; - -import java.nio.FloatBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.test.MiscTestUtils; -import com.nativelibs4java.util.NIOUtils; - -public class OpenCL4JavaBasicTest { - - public static final double ABSOLUTE_FLOAT_ERROR_TOLERANCE = 1e-4; - public static final double RELATIVE_FLOAT_ERROR_TOLERANCE = 1e-8; - - @Test - public void simpleTest() { - try { - CLContext context = createBestContext(); - - int dataSize = 10000; - String src = "\n" + - "__kernel void aSinB( \n" + - " __global const float* a, \n" + - " __global const float* b, \n" + - " __global float* output) \n" + - "{ \n" + - " int i = get_global_id(0); \n" + - " output[i] = a[i] * sin(b[i]) + 1; \n" + - "} \n"; - - CLProgram program = context.createProgram(src).build(); - CLKernel kernel = program.createKernel("aSinB"); - CLQueue queue = context.createDefaultQueue(); - - /// Create direct NIO buffers and fill them with data in the correct byte order - Pointer a = allocateFloats(dataSize).order(context.getKernelsDefaultByteOrder()); - Pointer b = allocateFloats(dataSize).order(context.getKernelsDefaultByteOrder()); - for (int i = 0; i < dataSize; i++) { - float value = (float)i; - a.set(i, value); - b.set(i, value); - } - - // Allocate OpenCL-hosted memory for inputs and output, - // with inputs initialized as copies of the NIO buffers - CLBuffer memIn1 = context.createBuffer(CLMem.Usage.Input, a, true); // 'true' : copy provided data - CLBuffer memIn2 = context.createBuffer(CLMem.Usage.Input, b, true); - CLBuffer memOut = context.createBuffer(CLMem.Usage.Output, Float.class, dataSize); - - // Bind these memory objects to the arguments of the kernel - kernel.setArgs(memIn1, memIn2, memOut); - - // Ask for execution of the kernel with global size = dataSize - // and workgroup size = 1 - kernel.enqueueNDRange(queue, new int[]{dataSize}); - - // Wait for all operations to be performed - queue.finish(); - - // Copy the OpenCL-hosted array back to RAM - Pointer output = memOut.read(queue); - - // Compute absolute and relative average errors wrt Java implem - double totalAbsoluteError = 0, totalRelativeError = 0; - for (int i = 0; i < dataSize; i++) { - float expected = i * (float) Math.sin(i) + 1; - float result = output.get(i); - - double d = result - expected; - if (expected != 0) { - totalRelativeError += d / expected; - } - - totalAbsoluteError += d < 0 ? -d : d; - } - double avgAbsoluteError = totalAbsoluteError / dataSize; - double avgRelativeError = totalRelativeError / dataSize; - System.out.println("Average absolute error = " + avgAbsoluteError); - System.out.println("Average relative error = " + avgRelativeError); - - assertEquals("Bad relative error", 0, avgRelativeError, RELATIVE_FLOAT_ERROR_TOLERANCE); - assertEquals("Bad absolute error", 0, avgAbsoluteError, ABSOLUTE_FLOAT_ERROR_TOLERANCE); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java deleted file mode 100644 index 749fc744c..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OpenCL4JavaBenchmarkTest.java +++ /dev/null @@ -1,313 +0,0 @@ -package com.nativelibs4java.opencl; - -import static com.nativelibs4java.opencl.CLTestUtils.avgError; -import static com.nativelibs4java.opencl.CLTestUtils.fillBuffersWithSomeDatad; -import static com.nativelibs4java.opencl.CLTestUtils.fillBuffersWithSomeDataf; -import static com.nativelibs4java.test.BenchmarkUtils.gc; -import static com.nativelibs4java.util.NIOUtils.directBytes; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import java.util.Arrays; - -import java.nio.FloatBuffer; -import java.nio.DoubleBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.CLTestUtils.Action2; -import com.nativelibs4java.opencl.CLTestUtils.ExecResult; -import com.nativelibs4java.test.MiscTestUtils; - -//import com.nativelibs4java.scalacl.*; -/// @see http://ati.amd.com/technology/streamcomputing/intro_opencl.html#simple -public class OpenCL4JavaBenchmarkTest { - static final boolean warmup = true; - - static ExecResult testJava_float_aSinB(int loops, int dataSize) throws CLBuildException { - - FloatBuffer aBuffer = FloatBuffer.allocate(dataSize); - FloatBuffer bBuffer = FloatBuffer.allocate(dataSize); - FloatBuffer outputBuffer = FloatBuffer.allocate(dataSize); - float[] a = aBuffer.array(), b = bBuffer.array(), output = outputBuffer.array(); - - if (warmup) { - System.out.print("Warming up Java operations..."); - for (int i = 0; i < 3000; i++) { - java_aSinB(a, b, output, 100); - } - System.out.println(); - } - - fillBuffersWithSomeDataf(aBuffer, bBuffer); - gc(); - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - java_aSinB(a, b, output, dataSize); - } - long time = System.nanoTime() - start; - System.out.println("Java operations : " + time + "ns"); - return new ExecResult(outputBuffer, time / (loops * (double) dataSize)); - } - - static ExecResult testJava_double_aSinB(int loops, int dataSize) throws CLBuildException { - - DoubleBuffer aBuffer = DoubleBuffer.allocate(dataSize); - DoubleBuffer bBuffer = DoubleBuffer.allocate(dataSize); - DoubleBuffer outputBuffer = DoubleBuffer.allocate(dataSize); - double[] a = aBuffer.array(), b = bBuffer.array(), output = outputBuffer.array(); - - if (warmup) { - System.out.print("Warming up Java operations..."); - for (int i = 0; i < 3000; i++) { - java_aSinB(a, b, output, 100); - } - System.out.println(); - } - - fillBuffersWithSomeDatad(aBuffer, bBuffer); - gc(); - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - java_aSinB(a, b, output, dataSize); - } - long time = System.nanoTime() - start; - System.out.println("Java operations : " + time + "ns"); - return new ExecResult(outputBuffer, time / (loops * (double) dataSize)); - } - - static ExecResult> testOpenCL_float_aSinB(CLContext context, int loops, int dataSize, boolean hostInOpenCL) throws CLBuildException { - - ExecResult> er = testOpenCL_aSinB(context, Prim.Float, loops, dataSize, hostInOpenCL, new Action2, Pointer>() { - - public void call(Pointer a, Pointer b) { - fillBuffersWithSomeDataf(a.as(Float.class), b.as(Float.class)); - } - }); - return new ExecResult>(er.buffer.as(Float.class), er.unitTimeNano); - } - - static ExecResult> testOpenCL_double_aSinB(CLContext context, int loops, int dataSize, boolean hostInOpenCL) throws CLBuildException { - - ExecResult> er = testOpenCL_aSinB(context, Prim.Double, loops, dataSize, hostInOpenCL, new Action2, Pointer>() { - - public void call(Pointer a, Pointer b) { - fillBuffersWithSomeDatad(a.as(Double.class), b.as(Double.class)); - } - }); - return new ExecResult>(er.buffer.as(Double.class), er.unitTimeNano); - } - - static ExecResult> testOpenCL_aSinB(CLContext context, Prim nativePrim, int loops, int dataSize, boolean hostInOpenCL, Action2, Pointer> fillBuffersWithSomeData) throws CLBuildException { - - CLKernel kernel = setupASinB(nativePrim, context); - CLQueue queue = context.createDefaultQueue(); - - Pointer input1 = null, input2 = null, output = null; - CLBuffer memIn1, memIn2, memOut; - if (hostInOpenCL) { - memIn1 = kernel.program.context.createBuffer(CLMem.Usage.Input, Byte.class, dataSize * nativePrim.sizeof()); - memIn2 = kernel.program.context.createBuffer(CLMem.Usage.Input, Byte.class, dataSize * nativePrim.sizeof()); - memOut = kernel.program.context.createBuffer(CLMem.Usage.Output, Byte.class, dataSize * nativePrim.sizeof()); - } else { - input1 = allocateBytes(dataSize * nativePrim.sizeof()).order(context.getByteOrder()); - input2 = allocateBytes(dataSize * nativePrim.sizeof()).order(context.getByteOrder()); - output = allocateBytes(dataSize * nativePrim.sizeof()).order(context.getByteOrder()); - - memIn1 = kernel.program.context.createBuffer(CLMem.Usage.Input, input1, false); - memIn2 = kernel.program.context.createBuffer(CLMem.Usage.Input, input2, false); - memOut = kernel.program.context.createBuffer(CLMem.Usage.Output, output, false); - } - kernel.setArgs(memIn1, memIn2, memOut); - - if (warmup) { - for (int i = 0; i < 3000; i++) { - kernel.enqueueNDRange(queue, new int[]{dataSize}); - } - queue.finish(); - } - - if (hostInOpenCL) { - input1 = memIn1.map(queue, CLMem.MapFlags.Write); - input2 = memIn2.map(queue, CLMem.MapFlags.Write); - } - fillBuffersWithSomeData.call(input1, input2); - if (hostInOpenCL) { - memIn1.unmap(queue, input1); - memIn2.unmap(queue, input2); - } - queue.finish(); - gc(); - - //if (dataSize < workItemSize) { - // System.err.println("dataSize = " + dataSize + " is lower than max workItemSize for first dim = " + workItemSize + " !!!"); - // workItemSize = 1; - //} - - long start = System.nanoTime(); - for (int i = 0; i < loops; i++) { - kernel.enqueueNDRange(queue, new int[]{dataSize});//, new int[]{workItemSize}); - } - queue.finish(); - long time = System.nanoTime() - start; - - //System.out.println("OpenCL operations(" + target + ") : " + time + "ns"); - if (hostInOpenCL) { - // Copy the OpenCL-hosted array back to RAM - output = memOut.map(queue, CLMem.MapFlags.Read); - System.out.println("memOut.map = " + Long.toHexString(output.getPeer())); - //queue.finish(); - Pointer b = allocateBytes(dataSize * nativePrim.sizeof()).order(context.getByteOrder()); - output.copyTo(b, dataSize); - memOut.unmap(queue, output); - output = b; - } - return new ExecResult>(output, time / (loops * (double) dataSize)); - } - - static CLKernel setupASinB(Prim nativeType, CLContext context) throws CLBuildException { - String src = "\n" - //+ "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n" - + "#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable\n" - + (nativeType == Prim.Double ? "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" : "") - + "__kernel void aSinB( \n" - + " __global const " + nativeType + "* a, \n" - + " __global const " + nativeType + "* b, \n" - + " __global " + nativeType + "* output) \n" - + "{ \n" - + " int i = get_global_id(0); \n" - + " float ai = a[i], bi = b[i]; \n" - + " output[i] = ai * sin(bi);// + atan2(ai, bi); \n" - + "} \n"; - - CLProgram program = context.createProgram(src).build(); - CLKernel kernel = program.createKernel("aSinB"); - - return kernel; - } - - public static void java_aSinB(float[] a, float[] b, float[] output, int dataSize) throws CLBuildException { - for (int i = 0; i < dataSize; i++) { - float ai = a[i], bi = b[i]; - output[i] = ai * (float) Math.sin(bi);// + (float)Math.atan2(ai, bi); - } - } - - public static void java_aSinB(double[] a, double[] b, double[] output, int dataSize) throws CLBuildException { - for (int i = 0; i < dataSize; i++) { - double ai = a[i], bi = b[i]; - output[i] = ai * Math.sin(bi);// + Math.atan2(ai, bi); - } - } - - enum Prim { - - Float(4), Double(8), Int(4), Short(2), Half(2); - final int sizeof; - - Prim(int sizeof) { - this.sizeof = sizeof; - } - - public int sizeof() { - return sizeof; - } - - public String toString() { - return name().toLowerCase(); - } - } - - @Test - public void testBenchmark() { - /*for (String s : new String[] { - "C:\\Program Files (x86)\\ATI Stream\\bin\\x86_64\\OpenCL.dll", - "C:\\Program Files (x86)\\ATI Stream\\bin\\x86\\OpenCL.dll", - "C:\\Program Files\\ATI Stream\\bin\\x86\\OpenCL.dll" - }) - if ((f = new File(s)).exists()) - break; - - if (f.exists()) - System.setProperty("OpenCL.library", f.toString()); - //sss */ - try { - System.out.println("#\n# " + OpenCL4JavaBenchmarkTest.class.getName() + "\n#"); - System.out.println("java.vm.name = " + System.getProperty("java.vm.name")); - System.out.println("java.vm.version = " + System.getProperty("java.runtime.version")); - System.out.println("Found platforms : " + Arrays.asList(JavaCL.listPlatforms())); - CLPlatform platform = JavaCL.listPlatforms()[0]; - String v = platform.getVendor(); - System.out.println("Platform Vendor: " + v); - boolean isAMD = v.equals("Advanced Micro Devices, Inc."); - int loops = 10; - int dataSize = isAMD ? 1024 : 1024 * 1024; - - CLContext context = JavaCL.createBestContext(); - boolean hasDoubleSupport = context.isDoubleSupported(); - - if (!hasDoubleSupport) { - System.out.println("OpenCL context does not support double precision computations : skipping second part of the test"); - } else { - System.out.println("#\n# [Double Operations]\n#"); - ExecResult nsByJavaOp = testJava_double_aSinB(loops, dataSize); - ExecResult> nsByCLHostedOp = testOpenCL_double_aSinB(context, loops, dataSize, true); - ExecResult> nsByNativeHostedCLOp = testOpenCL_double_aSinB(context, loops, dataSize, false); - double errCLHosted = avgError(nsByJavaOp.buffer, nsByCLHostedOp.buffer, dataSize); - double errNativeHosted = avgError(nsByJavaOp.buffer, nsByNativeHostedCLOp.buffer, dataSize); - - System.out.println(" Avg relative error (hosted in CL) = " + errCLHosted); - System.out.println("Avg relative error (hosted in RAM) = " + errNativeHosted); - System.out.println(); - - System.out.println(" java op\t= " + nsByJavaOp.unitTimeNano + " ns"); - System.out.println(); - System.out.println(" opencl (hosted in CL) op\t= " + nsByCLHostedOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByCLHostedOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByCLHostedOp.unitTimeNano)); - System.out.println(); - System.out.println("opencl (hosted in RAM) op\t= " + nsByNativeHostedCLOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByNativeHostedCLOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByNativeHostedCLOp.unitTimeNano)); - } - - if (true) { - System.out.println("#\n# [Float Operations]\n#"); - ExecResult nsByJavaOp = testJava_float_aSinB(loops, dataSize); - ExecResult> nsByCLHostedOp = testOpenCL_float_aSinB(context, loops, dataSize, true); - ExecResult> nsByNativeHostedCLOp = testOpenCL_float_aSinB(context, loops, dataSize, false); - double errCLHosted = avgError(nsByJavaOp.buffer, nsByCLHostedOp.buffer, dataSize); - double errNativeHosted = avgError(nsByJavaOp.buffer, nsByNativeHostedCLOp.buffer, dataSize); - - /*for (int i = 0; i < 10; i++) { - System.out.print("i\t = " + i + ",\t"); - System.out.print("buf \t=" + nsByJavaOp.buffer.get(i) +",\t"); - System.out.print("nat \t=" + nsByNativeHostedCLOp.buffer.get(i) +",\t"); - System.out.print("ocl \t=" + nsByCLHostedOp.buffer.get(i) +",\t"); - System.out.println(); - }*/ - System.out.println(" Avg relative error (hosted in CL) = " + errCLHosted); - System.out.println("Avg relative error (hosted in RAM) = " + errNativeHosted); - System.out.println(); - - System.out.println(" java op\t= " + nsByJavaOp.unitTimeNano + " ns"); - System.out.println(); - System.out.println(" opencl (hosted in CL) op\t= " + nsByCLHostedOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByCLHostedOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByCLHostedOp.unitTimeNano)); - System.out.println(); - System.out.println("opencl (hosted in RAM) op\t= " + nsByNativeHostedCLOp.unitTimeNano + " ns"); - System.out.println(" times slower than Java = " + (nsByNativeHostedCLOp.unitTimeNano / nsByJavaOp.unitTimeNano)); - System.out.println(" times faster than Java = " + (nsByJavaOp.unitTimeNano / nsByNativeHostedCLOp.unitTimeNano)); - } - - - - } catch (CLBuildException e) { - e.printStackTrace(); - } - } -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OverheadTest.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OverheadTest.java deleted file mode 100644 index 4398f4d4d..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/opencl/OverheadTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl; - -import com.nativelibs4java.opencl.library.*; -import java.util.Map; -import static org.junit.Assert.*; - -import org.junit.BeforeClass; -import org.junit.Test; - -import org.bridj.Pointer; -import org.bridj.Platform; -import static org.bridj.Pointer.*; -import com.nativelibs4java.test.MiscTestUtils; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.nio.ByteBuffer; -import java.util.List; -import org.junit.runners.Parameterized; -/** - * - * @author Kazo Csaba - */ -@SuppressWarnings("unchecked") -public class OverheadTest extends AbstractCommon { - public OverheadTest(CLDevice device) { - super(device); - } - - @Parameterized.Parameters - public static List getDeviceParameters() { - return AbstractCommon.getDeviceParameters(); - } - static void gc() { - try { - System.gc(); - Thread.sleep(100); - System.gc(); - Thread.sleep(100); - } catch (InterruptedException ex) {} - } - static long time(String title, int n, Runnable payload, Runnable finalizer) { - gc(); - - long start = System.nanoTime(); - for (int i = 0; i < n; i++) { - payload.run(); - } - if (finalizer != null) - finalizer.run(); - long timeMillis = (System.nanoTime() - start) / 1000000; - - if (title != null) - System.out.println("Time[ " + title + " ; n = " + n + "] = " + timeMillis + " ms"); - return timeMillis; - } - @Test - public void compareVariousSetArgsPerformance() throws CLBuildException { - if (!context.getCacheBinaries()) { - System.out.println("Skipping binaries caching test"); - return; - } - CLProgram program = context.createProgram( - "__kernel void copy(__global int* a, __global int* b, short s, int i, char c, float f) {\n" + - " int idx = get_global_id(0);\n" + - " b[idx] = a[idx];\n" + - "} "); - - - program.build(); - final CLKernel kernel = program.createKernel("copy"); - - final CLBuffer a=context.createBuffer(CLMem.Usage.Input, Integer.class, 4); - final CLBuffer b=context.createBuffer(CLMem.Usage.Output, Integer.class, 4); - - int nArgs = kernel.getNumArgs(); - - Runnable setWithSetArgs = new Runnable() { public void run() { - kernel.setArgs(a, b, (short)1, 1, (byte)1, 1.0f); - }}; - Runnable setWithSpecializedSetArg = new Runnable() { public void run() { - kernel.setArg(0, a); - kernel.setArg(1, b); - kernel.setArg(2, (short)1); - kernel.setArg(3, 1); - kernel.setArg(4, (byte)1); - kernel.setArg(5, 1.0f); - }}; - /* - Runnable setWithCLAPI = new Runnable() { - private final OpenCLLibrary CL = new OpenCLLibrary(); - private final Pointer tmp = allocateBytes(8); - public void run() { - CL.clSetKernelArg(kernel.getEntity(), 0, Pointer.SIZE, a.getEntity()); - CL.clSetKernelArg(kernel.getEntity(), 1, Pointer.SIZE, b.getEntity()); - CL.clSetKernelArg(kernel.getEntity(), 2, 2L, tmp.setShort((short)1)); - CL.clSetKernelArg(kernel.getEntity(), 3, 4L, tmp.setInt(1)); - CL.clSetKernelArg(kernel.getEntity(), 4, 1L, tmp.setByte((byte)1)); - CL.clSetKernelArg(kernel.getEntity(), 5, 4L, tmp.setFloat(1)); - } - }; - */ - Runnable setWithRawCLAPI = new Runnable() { - private final long aPeer = a.getEntity(); - private final long bPeer = b.getEntity(); - private final long kEntity = kernel.getEntity(); - private final Pointer tmp = allocateBytes(8);//.withoutValidityInformation(); - private final ByteBuffer tmpBuf = tmp.getByteBuffer(); - private final long tPeer = getPeer(tmp); - private final long pointerSize = Pointer.SIZE; - private final OpenCLLibrary CL = new OpenCLLibrary(); - public void run() { - CL.clSetKernelArg(kEntity, 0, pointerSize, aPeer); - CL.clSetKernelArg(kEntity, 1, pointerSize, bPeer); - tmpBuf.putShort(0, (short)1); - CL.clSetKernelArg(kEntity, 2, 2L, tPeer); - tmpBuf.putInt(0, 1); - CL.clSetKernelArg(kEntity, 3, 4L, tPeer); - tmpBuf.put(0, (byte)1); - CL.clSetKernelArg(kEntity, 4, 1L, tPeer); - tmpBuf.putFloat(0, 1); - CL.clSetKernelArg(kEntity, 5, 4L, tPeer); - } - }; - - int nWarmup = 8000, nTest = 50000; - //time(null, nWarmup, setWithCLAPI, null); - time(null, nWarmup, setWithSetArgs, null); - time(null, nWarmup, setWithSpecializedSetArg, null); - time(null, nWarmup, setWithRawCLAPI, null); - - int nSamples = 10; - double totSetArgs = 0, totCLSetKernelArg = 0, totSetArg = 0, totCLSetKernelArgRaw = 0; - for (int i = 0; i < nSamples; i++) { - //totCLSetKernelArg += time("clSetKernelArg pointers", nTest, setWithCLAPI, null); - totSetArgs += time("CLKernel.setArgs", nTest, setWithSetArgs, null); - totSetArg += time("CLKernel.setArg", nTest, setWithSpecializedSetArg, null); - totCLSetKernelArgRaw += time("clSetKernelArg raw", nTest, setWithRawCLAPI, null); - System.out.println(); - } - - final double maxSlower = 1.4; - double slowerSetArg = totSetArg / totCLSetKernelArgRaw; - double slowerSetArgs = totSetArgs / totCLSetKernelArgRaw; - - System.out.println("CLKernel.setArg is " + slowerSetArg + "x slower than hand-optimized."); - System.out.println("CLKernel.setArgs is " + slowerSetArgs + "x slower than hand-optimized."); - final double maxMilliSecondsPerCall = Platform.is64Bits() ? 0.0025 : 0.007; - double setArgAvg = (totSetArg / (double)nTest) / nArgs; - System.out.println("CLKernel.setArg took " + setArgAvg + " ms per call in average."); - - assertTrue("CLKernel.setArg was supposed to last at most " + maxMilliSecondsPerCall + " ms in average, but was " + setArgAvg + " ms", setArgAvg < maxMilliSecondsPerCall); - assertTrue("CLKernel.setArg was supposed not to be more than " + maxSlower + "x slower than hand-optimized version, was " + slowerSetArg + "x slower.", slowerSetArg <= maxSlower); - assertTrue("CLKernel.setArgs was supposed not to be more than " + maxSlower + "x slower than hand-optimized version, was " + slowerSetArgs + "x slower.", slowerSetArgs <= maxSlower); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java deleted file mode 100644 index e1d2f264c..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/BenchmarkUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.test; - -/** - * - * @author ochafik - */ -public class BenchmarkUtils { - public static void gc() { - try { - System.gc(); - Thread.sleep(200); - System.gc(); - Thread.sleep(200); - } catch (InterruptedException ex) {} - } - -} diff --git a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java b/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java deleted file mode 100644 index 470e7f12a..000000000 --- a/libraries/OpenCL/Core/src/test/java/com/nativelibs4java/test/MiscTestUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.test; - -import static org.junit.Assert.assertFalse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -public class MiscTestUtils { - public static void protectJNI() { - //Native.setProtected(true); - } - public static void testGetters(Object instance) { - if (instance == null) - return; - Logger log = Logger.getLogger(instance.getClass().getName()); - for (Method m : instance.getClass().getDeclaredMethods()) { - if (Modifier.isStatic(m.getModifiers())) - continue; - if (!Modifier.isPublic(m.getModifiers())) - continue; - if (m.getParameterTypes().length != 0) - continue; - - String name = m.getName(); - if (name.contains("ProfilingCommand")) - continue; - - boolean isToString = name.equals("toString"); - if (name.startsWith("get") && name.length() > 3 || - name.startsWith("has") && name.length() > 3 || - name.startsWith("is") && name.length() > 2 || - isToString && !Modifier.isPublic(m.getDeclaringClass().getModifiers())) - { - String msg = "Failed to call " + m; - try { - m.invoke(instance); - } catch (IllegalAccessException ex) { - if (!isToString) - log.log(Level.WARNING, msg, ex); - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (!(cause instanceof UnsupportedOperationException)) { - log.log(Level.SEVERE, msg, ex.getCause()); - assertFalse(msg, true); - } - } catch (Exception ex) { - log.log(Level.SEVERE, msg, ex); - } - } - } - } -} diff --git a/libraries/OpenCL/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c b/libraries/OpenCL/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c deleted file mode 100644 index 0e19e18fc..000000000 --- a/libraries/OpenCL/Core/src/test/resources/com/nativelibs4java/opencl/BufferReadTest.c +++ /dev/null @@ -1,6 +0,0 @@ -__kernel void testLongRead( __global const long* input, - __global long* output) { - int i = get_global_id(0); - - output[i] = input[i] + 1; -} diff --git a/libraries/OpenCL/Demos/.classpath b/libraries/OpenCL/Demos/.classpath deleted file mode 100644 index 63fc74ae6..000000000 --- a/libraries/OpenCL/Demos/.classpath +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Demos/.gitignore b/libraries/OpenCL/Demos/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Demos/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Demos/.project b/libraries/OpenCL/Demos/.project deleted file mode 100644 index 778f92065..000000000 --- a/libraries/OpenCL/Demos/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Demos - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL/Demos/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/Demos/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 575a63fe0..000000000 --- a/libraries/OpenCL/Demos/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:20 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/Demos/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/Demos/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL/Demos/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/Demos/javacl-demos-bridj.iml b/libraries/OpenCL/Demos/javacl-demos-bridj.iml deleted file mode 100644 index baf0eab7b..000000000 --- a/libraries/OpenCL/Demos/javacl-demos-bridj.iml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Demos/javacl-demos.iml b/libraries/OpenCL/Demos/javacl-demos.iml deleted file mode 100644 index 78c89b1d6..000000000 --- a/libraries/OpenCL/Demos/javacl-demos.iml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Demos/pom.xml b/libraries/OpenCL/Demos/pom.xml deleted file mode 100644 index 2b5ed029d..000000000 --- a/libraries/OpenCL/Demos/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-demos - JavaCL Demos / BridJ - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - true - com.nativelibs4java.opencl.HardwareReport - - - - - - com.nativelibs4java - javacl - - - - org.swinglabs - swing-layout - 1.0.3 - - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - - - - diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java deleted file mode 100644 index 030b8e92a..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.demos; - -import java.net.MalformedURLException; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bridj.BridJ; -import org.bridj.JNI; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.nativelibs4java.opencl.JavaCL; -import org.bridj.Platform; - -/** - * - * @author ochafik - */ -public class SetupUtils { - - public enum DownloadURL { - ATI("http://developer.amd.com/tools/hc/AMDAPPSDK/Pages/default.aspx"), - NVidia("http://www.nvidia.com/Download/Find.aspx"); - - public final URL url; - DownloadURL(String s) { - URL url; - try { - url = new URL(s); - } catch (MalformedURLException ex) { - Logger.getLogger(SetupUtils.class.getName()).log(Level.SEVERE, null, ex); - url = null; - } - this.url = url; - } - } - public static void failWithDownloadProposalsIfOpenCLNotAvailable() { - ///* - try { - JavaCL.listPlatforms(); - return; - } catch (Throwable ex) { - ex.printStackTrace(); - } //*/ - String title = "JavaCL Error: OpenCL library not found"; - if (Platform.isMacOSX()) { - JOptionPane.showMessageDialog(null, "Please upgrade Mac OS X to Snow Leopard (10.6) to be able to use OpenCL.", title, JOptionPane.ERROR_MESSAGE); - return; - } - Object[] options = new Object[] { - "NVIDIA graphic card", - "ATI graphic card", - "CPU only", - "Cancel" - }; - //for (;;) { - int option = JOptionPane.showOptionDialog(null, - "You don't appear to have an OpenCL implementation properly configured.\n" + - "Please choose one of the following options to proceed to the download of an appropriate OpenCL implementation :", title, JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[2]); - if (option >= 0 && option != 3) { - DownloadURL url; - if (option == 0) { - /*String nvidiaVersion = "260.99"; - boolean appendPlatform = true; - String sys; - - if (JNI.isWindows()) { - if (System.getProperty("os.name").toLowerCase().contains("xp")) { - sys = "winxp"; - appendPlatform = false; - } else { - sys = "win7_vista"; - } - urlString = "http://www.nvidia.fr/object/" + sys + "_" + nvidiaVersion + (appendPlatform ? "_" + (JNI.is64Bits() ? "64" : "32") + "bit" : "") + "_whql.html"; - } else - urlString = "http://developer.nvidia.com/object/opencl-download.html"; - */ - url = DownloadURL.NVidia; - } else - url = DownloadURL.ATI; - - try { - Platform.open(url.url); - } catch (Exception ex1) { - exception(ex1); - } - } - System.exit(1); - } - - public static void exception(Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "Error in JavaCL Demo", JOptionPane.ERROR_MESSAGE); - } - - static Border etchedBorder; - static synchronized Border getEtchedBorder() { - if (etchedBorder == null) { - etchedBorder = UIManager.getBorder( "TitledBorder.aquaVariant" ); - if (etchedBorder == null) - etchedBorder = BorderFactory.createCompoundBorder(new EtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)); - } - return etchedBorder; - } - public static void setEtchedTitledBorder(JComponent comp, String title) { - comp.setBorder(new TitledBorder(getEtchedBorder(), title)); - } -} diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java deleted file mode 100644 index cbd4d50d6..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/hardware/HardwareReport.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos.hardware; -import org.bridj.BridJ; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.demos.SetupUtils; -import org.bridj.Platform; - -import java.awt.BorderLayout; -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.UIManager; - -/** - * Small program that outputs html reports about the information returned by OpenCL for each device. - * @author ochafik - */ -public class HardwareReport { - - public static Map infoMethods(Class c) { - Map mets = new TreeMap(); - for (Method met : c.getMethods()) { - InfoName name = met.getAnnotation(InfoName.class); - if (name == null) { - continue; - } - mets.put(name.value(), met); - } - return mets; - } - - public static List> listInfos(CLPlatform platform) { - try { - List> ret = new ArrayList>(); - Map platMets = infoMethods(CLPlatform.class); - Map devMets = infoMethods(CLDevice.class); - //for (CLPlatform platform : JavaCL.listPlatforms()) { - Map platInfos = new TreeMap(); - for (Map.Entry platMet : platMets.entrySet()) { - try { - platInfos.put(platMet.getKey(), platMet.getValue().invoke(platform)); - } catch (InvocationTargetException ex) { - if (ex.getCause() instanceof UnsupportedOperationException) - platInfos.put(platMet.getKey(), "n/a"); - else - throw ex; - } - } - for (CLDevice device : platform.listAllDevices(false)) { - Map devInfos = new TreeMap(platInfos); - for (Map.Entry devMet : devMets.entrySet()) { - try { - devInfos.put(devMet.getKey(), devMet.getValue().invoke(device)); - } catch (InvocationTargetException ex) { - if (ex.getCause() instanceof UnsupportedOperationException) - devInfos.put(devMet.getKey(), "n/a"); - else - throw ex; - } - } - ret.add(devInfos); - } - //} - return ret; - } catch (Throwable ex) { - throw new RuntimeException(ex); - } - } - - public static String toString(Object value) { - if (value == null) { - return "null"; - } - Class c = value.getClass(); - try { - if (c.isArray()) { - if (!c.getComponentType().isPrimitive()) { - c = Object[].class; - } - value = Arrays.class.getMethod("toString", c).invoke(null, value); - } - } catch (Exception ex) { - throw new RuntimeException(ex); - } - String s = value.toString(); - if (s.startsWith("[") && s.endsWith("]")) { - s = s.substring(1, s.length() - 1); - s = s.replaceAll(", ", "
      "); - } - return s; - } - - public static String toTable(List> list) { - StringBuilder b = new StringBuilder(); - - b.append("\n"); - if (!list.isEmpty()) { - Set keys = list.get(0).keySet(); - - b.append("\t\n"); - b.append("\t\t"); - for (Map device : list) { - Object value = device.get("CL_DEVICE_NAME"); - b.append("\n"); - } - b.append("\n"); - b.append("\t\n"); - - for (String key : keys) { - b.append("\t\n"); - b.append("\t\t"); - for (Map device : list) { - Object value = device.get(key); - b.append(""); - } - b.append("\n"); - b.append("\t\n"); - } - } - - b.append("
      [" + toString(value) + "]
      " + key + "" + toString(value) + "
      \n"); - return b.toString(); - } - - public static String toHTML(List> list) { - return //"\n" + - "\n" - + "\n" - + toTable(list) - + ""; - } - - public static JComponent getHardwareReportComponent(CLPlatform platform) { - List> list = listInfos(platform); - final String html = toHTML(list); - - JEditorPane ed = new JEditorPane(); - ed.setContentType("text/html"); - ed.setText(html); - ed.setEditable(false); - - JPanel ret = new JPanel(new BorderLayout()); - ret.add("Center", new JScrollPane(ed)); - - final String fileName = "HardwareReport.html"; - JButton bWrite = new JButton("Save " + fileName + "..."); - bWrite.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - FileDialog fd = new FileDialog((Frame)null, "Save " + fileName, FileDialog.SAVE); - fd.setFile(fileName); - fd.setVisible(true); - if (fd.getFile() == null) - return; - - try { - File file = new File(new File(fd.getDirectory()), fd.getFile()); - file.getParentFile().mkdirs(); - Writer w = new OutputStreamWriter(new FileOutputStream(file), "utf-8"); - w.write(html); - w.close(); - - Platform.show(file); - } catch (Throwable ex) { - SetupUtils.exception(ex); - } - } - - }); - - ret.add("South", bWrite); - return ret; - } - public static void main(String[] args) { - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - try { - JTabbedPane pane = new JTabbedPane(); - for (CLPlatform platform : JavaCL.listPlatforms()) - pane.addTab(platform.toString(), getHardwareReportComponent(platform)); - - JFrame f = new JFrame("OpenCL4Java: Hardware Characteristics"); - f.getContentPane().add("Center", pane); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.pack(); - f.setSize(f.getWidth() + 15, 700); - f.setVisible(true); - - } catch (Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "[Error] OpenCL4Java HardwareReport", JOptionPane.ERROR_MESSAGE); - } - } -} diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java deleted file mode 100644 index c94563b7d..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/mandelbrot/MandelbrotDemo.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.nativelibs4java.opencl.demos.mandelbrot; - -import static com.nativelibs4java.opencl.JavaCL.createBestContext; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import org.bridj.Pointer; - -import javax.imageio.ImageIO; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.UIManager; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.nativelibs4java.util.IOUtils; - - -/** - * Copied and adapted from Bob Boothby's code : - * http://bbboblog.blogspot.com/2009/10/gpgpu-mandelbrot-with-opencl-and-java.html - */ -public class MandelbrotDemo { - //boundary of view on mandelbrot set - - public static void main(String[] args) throws IOException, CLBuildException { - - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - //Setup variables for parameters - - //Boundaries - float realMin = -2.25f; //-0.19920f; // -2.25 - float realMax = 0.75f; //-0.12954f; // 0.75 - float imaginaryMin = -1.5f; //1.01480f; // -1.5 - float imaginaryMax = 1.5f; //1.06707f; // 1.5 - - //Resolution - int realResolution = 1640; // TODO validate against device capabilities - int imaginaryResolution = 1640; - - //The maximum iterations to perform before returning and assigning 0 to a pixel (infinity) - int maxIter = 64; - - //TODO describe what this number means... - int magicNumber = 4; - - //Derive the distance in imaginary / real coordinates between adjacent pixels of the image. - float deltaReal = (realMax - realMin) / (realResolution-1); - float deltaImaginary = (imaginaryMax - imaginaryMin) / (imaginaryResolution-1); - - //Create a context and program using the devices discovered. - CLContext context = createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - //Setup output buffer - int size = realResolution * imaginaryResolution; - Pointer results = Pointer.allocateInts(size).order(context.getByteOrder()); - - //TODO use an image object directly. - //CL.clCreateImage2D(context.get(), 0, OpenCLLibrary); - //TODO set up a Float4 array in order to be able to provide a colour map. - //This depends on whether we will be able to pass in a Float4 array as an argument in the future. - - //Read the source file. - String src = IOUtils.readTextClose(MandelbrotDemo.class.getResourceAsStream("Mandelbrot.cl")); - - long time = buildAndExecuteKernel(queue, realMin, imaginaryMin, realResolution, imaginaryResolution, maxIter, magicNumber, - deltaReal, deltaImaginary, results, src); - - int nPixels = imaginaryResolution * realResolution; - long timePerPixel = time / nPixels; - String label = "Computed in " + ((time / 1000)) + " microseconds\n(" + ((timePerPixel)) + " nanoseconds per pixel)"; - - BufferedImage image = getImage(realResolution, imaginaryResolution, results); - outputImage(image); - - JFrame f = new JFrame("JavaCL Mandelbrot Demo"); - f.getContentPane().add("Center", new JScrollPane(new JLabel(new ImageIcon(image)))); - f.getContentPane().add("North", new JLabel(label)); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.pack(); - f.setVisible(true); - } - - private static BufferedImage getImage(int realResolution, int imaginaryResolution, - Pointer results) { - int[] outputResults = results.getInts(realResolution * imaginaryResolution); - int max = Integer.MIN_VALUE; - for (int i = outputResults.length; i-- != 0;) { - int v = outputResults[i]; - if (v > max) - max = v; - } - - for (int i = outputResults.length; i-- != 0;) { - int v = outputResults[i]; - float f = v / (float)max; - outputResults[i] = Color.HSBtoRGB(1 - f, 0.5f, 0.3f + f * 0.7f); - } - - BufferedImage image = new BufferedImage(realResolution, imaginaryResolution, BufferedImage.TYPE_INT_RGB); - image.setRGB(0, 0, realResolution, imaginaryResolution, outputResults, 0, realResolution); - return image; - } - private static void outputImage(BufferedImage image) { - try { - ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next(); - ImageOutputStream stream = ImageIO.createImageOutputStream(new File("test.gif")); - writer.setOutput(stream); - writer.write(image); - } catch (IOException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - static boolean useAutoGenWrapper = true; - private static long buildAndExecuteKernel(CLQueue queue, float realMin, float imaginaryMin, int realResolution, - int imaginaryResolution, int maxIter, int magicNumber, float deltaReal, - float deltaImaginary, Pointer results, String src) throws CLBuildException, IOException { - - CLContext context = queue.getContext(); - long startTime = System.nanoTime(); - if (useAutoGenWrapper) { - Mandelbrot mandelbrot = new Mandelbrot(context); - mandelbrot.mandelbrot( - queue, - new float[] { deltaReal, deltaImaginary }, - new float[] { realMin, imaginaryMin }, - - maxIter, - magicNumber, - realResolution, - context.createBuffer(CLMem.Usage.Output, results, false), - - new int[]{realResolution, imaginaryResolution}, - new int[]{1,1} - ); - } else { - CLProgram program = context.createProgram(src).build(); - - //Create a kernel instance from the mandelbrot kernel, passing in parameters. - CLKernel kernel = program.createKernel( - "mandelbrot", - new float[] { deltaReal, deltaImaginary }, - new float[] { realMin, imaginaryMin }, - - maxIter, - magicNumber, - realResolution, - context.createBuffer(CLMem.Usage.Output, results, false) - ); - - //Enqueue and complete work using a 2D range of work groups corrsponding to individual pizels in the set. - //The work groups are 1x1 in size and their range is defined by the desired resolution. This corresponds - //to one device thread per pixel. - - kernel.enqueueNDRange(queue, new int[]{realResolution, imaginaryResolution}, new int[]{1,1}); - } - queue.finish(); - long time = System.nanoTime() - startTime; - return time; - - } -} diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java deleted file mode 100644 index 8d095d7b8..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.demos.random; - -import com.nativelibs4java.opencl.util.ParallelRandom; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLMem.MapFlags; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import java.io.IOException; -import java.nio.ByteOrder; -import org.bridj.Pointer; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -public class ParallelRandomDemo { - - private static void println(Pointer b) { - for (int i = 0, n = (int)b.getValidElements(); i < n; i++) { - if (i > 0) - System.out.print(", "); - System.out.print(b.get(i)); - - if (i > 32) - System.out.print("..."); - } - System.out.println(); - } - - static class Stat { - long total; - long times; - boolean skippedFirst; - void add(long value) { - if (!skippedFirst) { - skippedFirst = true; - return; - } - - total += value; - times++; - } - long average() { - return times == 0 ? 0 : total / times; - } - } - public static void main(String[] args) { - try { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - int warmupSize = 16; - ParallelRandom demo = new ParallelRandom(queue, warmupSize, System.currentTimeMillis()); - - println(demo.getSeeds().read(queue)); - Pointer b = demo.next(); - println(b); - b = demo.next(); - println(b); - b = demo.next(); - println(b); - - gc(); - - long start = System.nanoTime(); - int loops = 2800; - Random random = new Random(); - int res = 0; - for (int i = loops; i-- != 0;) { - //demo.next(b); - //demo.next(); - demo.doNext(); - res |= random.nextInt(); - } - demo.getQueue().finish(); - long time = System.nanoTime() - start; - - System.err.println("Warmup took " + time + " ns"); - - - Stat stat; - - - int testSize = 1024 * 1024;//1024 * 1024; - int testLoops = 10; - - System.err.println("n = " + testSize); - demo = new ParallelRandom(queue, testSize, System.currentTimeMillis()); - b = demo.next(); - - gc(); - - stat = new Stat(); - for (int iTest = 0; iTest < testLoops; iTest++) { - start = System.nanoTime(); - //b = demo.next();//b); - demo.doNext(); - demo.getQueue().finish(); - time = System.nanoTime() - start; - stat.add(time); - //System.err.println("[OpenCL] Cost per random number = " + (time / (double)testSize) + " ns"); - - } - long avgCL = stat.average(); - System.err.println("[OpenCL] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); - System.err.println(); - - gc(); - - stat = new Stat(); - for (int iTest = 0; iTest < testLoops; iTest++) { - start = System.nanoTime(); - for (int i = testSize; i-- != 0;) - res |= random.nextInt(); - time = System.nanoTime() - start; - stat.add(time); - //System.err.println("[Random.nextInt()] Cost per random number = " + (time / (double)testSize) + " ns"); - } - long avgJava = stat.average(); - System.err.println("[Random.nextInt()] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); - System.err.println(); - - double timesCLFasterThanJava = avgJava / (double)avgCL; - System.err.println("Java / CL (avg) = " + timesCLFasterThanJava); - System.err.println(res); // make sure no brutal optimization happens - System.err.println(b.get(0)); // make sure no brutal optimization happens - //println(b); - - } catch (IOException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - } - } - static void gc() { - try { - System.gc(); - Thread.sleep(200); - System.gc(); - Thread.sleep(200); - } catch (InterruptedException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - } - } -} diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java deleted file mode 100644 index fa5159f3f..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos.sobelfilter; - -import org.bridj.JNI; -import javax.swing.*; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.*; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.nativelibs4java.util.Pair; -import java.awt.image.*; -import java.io.*; - -import org.bridj.Platform; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import java.awt.FileDialog; -public class SobelFilterDemo { - - static File chooseFile() { - if (Platform.isMacOSX()) { - FileDialog d = new FileDialog((java.awt.Frame)null); - d.setMode(FileDialog.LOAD); - d.show(); - String f = d.getFile(); - if (f != null) - return new File(new File(d.getDirectory()), d.getFile()); - } else { - JFileChooser chooser = new JFileChooser(); - if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) - return chooser.getSelectedFile(); - } - return null; - } - public static void main(String[] args) { - try { - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - File imageFile = chooseFile(); - if (imageFile == null) - return; - - BufferedImage image = ImageIO.read(imageFile); - int width = image.getWidth(), height = image.getHeight(); - //int step = 32; - // image = image.getSubimage(0, 0, (width / step) * step, (height / step) * step); - //image = image.getSubimage(0, 0, 512, 512);//(width / step) * step, (height / step) * step); - - - JFrame f = new JFrame("JavaCL Sobel Filter Demo"); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - SobelFilterDemo demo = new SobelFilterDemo(); - Pair imgs = demo.computeSobel(image); - f.getContentPane().add("Center", - //new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, - // new JScrollPane(new JLabel(new ImageIcon(image))), - new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, - new JScrollPane(new JLabel(new ImageIcon(imgs.getFirst()))), - new JScrollPane(new JLabel(new ImageIcon(imgs.getSecond()))) - ) {/** - * - */ - private static final long serialVersionUID = 8267014922143370639L; - - { - setResizeWeight(0.5); - }} - //) - ); - - f.pack(); - f.setVisible(true); - } catch (Throwable th) { - th.printStackTrace(); - SetupUtils.exception(th); - } - } - - CLContext context; - CLQueue queue; - SimpleSobel sobel; - ReductionUtils.Reductor floatMinReductor; - - - public SobelFilterDemo() throws IOException, CLBuildException { - context = JavaCL.createBestContext(); - queue = context.createDefaultQueue(); - sobel = new SimpleSobel(context); - floatMinReductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Max, OpenCLType.Float, 1); - - } - - public static int roundUp(int group_size, int global_size) - { - int r = global_size % group_size; - return r == 0 ? global_size : global_size + group_size - r; - } - public Pair computeSobel(BufferedImage img) throws IOException, CLBuildException { - int width = img.getWidth(), height = img.getHeight(); - - int dataSize = height * width; - Pointer pixels = Pointer.pointerToInts(img.getRGB(0, 0, width, height, null, 0, width)); - CLImage2D inputImage = context.createImage2D(CLMem.Usage.Input, new CLImageFormat(CLImageFormat.ChannelOrder.ARGB, CLImageFormat.ChannelDataType.UnsignedInt8), width, height, width * 4, pixels.getBuffer(), true); - //CLImage2D inputImage = context.createImage2D(CLMem.Usage.Input, img, false); - - CLBuffer - gradients = context.createBuffer(CLMem.Usage.InputOutput, Float.class, dataSize), - directions = context.createBuffer(CLMem.Usage.InputOutput, Float.class, dataSize); - - CLEvent evt = sobel.simpleSobel(queue, - inputImage, - width, - height, - gradients, - directions, - new int[] { width, height }, - null//new int[] { 1, 1 } - ); - - //queue.finish(); - - //float[] test = new float[1000]; - //gradients.read(queue).get(test); - - float gradientMax = floatMinReductor.reduce(queue, gradients, dataSize, 32, evt).get(); - float dirMax = floatMinReductor.reduce(queue, directions, dataSize, 32, evt).get(); - - //CLEvent.waitFor(evtGradMax, evtDirMax); - - CLBuffer gradientPixels = context.createBuffer(CLMem.Usage.Output, Integer.class, dataSize); - CLBuffer directionPixels = context.createBuffer(CLMem.Usage.Output, Integer.class, dataSize); - - //CLEvent evtGrad = - sobel.normalizeImage(queue, gradients, gradientMax, (CLBuffer)gradientPixels, new int[] { dataSize }, null); - //CLEvent evtDir = - sobel.normalizeImage(queue, directions, dirMax, (CLBuffer)directionPixels, new int[] { dataSize }, null); - - queue.finish(); - - BufferedImage gradientsImage = getRowsOrderImage(queue, gradientPixels, width, height);//, evtGrad); - BufferedImage directionsImage = getRowsOrderImage(queue, directionPixels, width, height);//, evtDir); - - return new Pair(gradientsImage, directionsImage); - } - static BufferedImage getRowsOrderImage(CLQueue queue, CLBuffer buffer, int width, int height, CLEvent... eventsToWaitFor) { - queue.finish(); - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - int[] pixels = buffer.read(queue, eventsToWaitFor).getInts(width * height); - img.setRGB(0, 0, width,height, pixels, 0, width); - return img; - } -} - diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java deleted file mode 100644 index a90feee5b..000000000 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/vectoradd/VectorAdd.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.nativelibs4java.opencl.demos.vectoradd; -import com.nativelibs4java.opencl.*; -import java.nio.*; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - - -/** - * This is about the simplest possible JavaCL program.
      - * It adds two vectors of floats in parallel.
      - * This program can be written more easily with the JavaCL BLAS Library : - * - * LinearAlgebraUtils la = new LinearAlgebraUtils(); - * CLKernel kernel = new LinearAlgebraUtils().getKernel(LinearAlgebraUtils.Fun2.add, LinearAlgebraUtils.Primitive.Float); - * - * @author ochafik - */ -public class VectorAdd { - - public static void main(String[] args) { - try { - Pointer a = pointerToFloats(1, 2, 3, 4 ); - Pointer b = pointerToFloats(10, 20, 30, 40); - - Pointer sum = add(a, b); - for (long i = 0, n = sum.getValidElements(); i < n; i++) - System.out.println(sum.get(i)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Pointer add(Pointer a, Pointer b) throws CLBuildException { - int n = (int)a.getValidElements(); - - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - String source = - "__kernel void addFloats(__global const float* a, __global const float* b, __global float* output) " + - "{ " + - " int i = get_global_id(0); " + - " output[i] = a[i] + b[i]; " + - "} "; - - CLKernel kernel = context.createProgram(source).createKernel("addFloats"); - CLBuffer aBuf = context.createBuffer(CLMem.Usage.Input, a, true); - CLBuffer bBuf = context.createBuffer(CLMem.Usage.Input, b, true); - CLBuffer outBuf = context.createBuffer(CLMem.Usage.Output, Float.class, n); - kernel.setArgs(aBuf, bBuf, outBuf); - - kernel.enqueueNDRange(queue, new int[]{n}); - queue.finish(); - - return outBuf.read(queue); - } -} - diff --git a/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl b/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl deleted file mode 100644 index 3d8b544d0..000000000 --- a/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/mandelbrot/Mandelbrot.cl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copied and adapted from Bob Boothby's code : - * http://bbboblog.blogspot.com/2009/10/gpgpu-mandelbrot-with-opencl-and-java.html - */ -__kernel void mandelbrot( - const float2 delta, - const float2 minimum, - const unsigned int maxIter, - const unsigned int magicNumber, - const unsigned int hRes, - __global int* outputi -) -{ - int2 id = (int2)(get_global_id(0), get_global_id(1)); - - float2 pos = minimum + delta * (float2)(id.x, id.y); - float2 squared = pos * pos; - float2 val = pos; - - int iter = 0; - while ( (iter < maxIter) && ((squared.x + squared.y) < magicNumber) ) - { - val.y = (2 * (val.x * val.y)); - val.x = squared.x - squared.y; - val += pos; - squared = val * val; - - iter++; - } - if(iter >= maxIter) - iter = 0; - - outputi[id.y * hRes + id.x] = iter; -} \ No newline at end of file diff --git a/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl b/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl deleted file mode 100644 index 763cd0bc2..000000000 --- a/libraries/OpenCL/Demos/src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl +++ /dev/null @@ -1,75 +0,0 @@ - -sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; - -#define MX_NW 1 -#define MX_N 2 -#define MX_NE 1 -#define MX_W 0 -#define MX_C 0 -#define MX_E 0 -#define MX_SW -1 -#define MX_S -2 -#define MX_SE -1 - -#define MY_NW 1 -#define MY_N 0 -#define MY_NE -1 -#define MY_W 2 -#define MY_C 0 -#define MY_E -2 -#define MY_SW 1 -#define MY_S 0 -#define MY_SE -1 - -#define PIXEL_TO_INTENSITIES(pixel, coefX, coefY) (uint2)(coefX, coefY) * (uint2)((pixel.x + pixel.y + pixel.z) * pixel.w / 255 / 3) - -__kernel void simpleSobel( - __read_only image2d_t input, - uint width, uint height, - __global float* gradientOutput, - __global float* directionOutput -) { - int x = get_global_id(0), y = get_global_id(1); - if (x >= width || y >= height) - return; - - int i = y * width + x; - - uint2 total = (uint2)0; - - //total += PIXEL_TO_INTENSITIES(input[i], 1, 1); - - int in = i - width, is = i + width; - bool allowEast = x < width - 1, allowSouth = y < height - 1, allowNorth = y, allowWest = x; - if (allowNorth) { - if (allowWest) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x-1, y-1)), MX_NW, MY_NW); - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x, y-1)), MX_N, MY_N); - if (allowEast) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x+1, y-1)), MX_NE, MY_NE); - } - - if (allowWest) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x-1, y)), MX_W, MY_W); - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x, y)), MX_C, MY_C); - if (allowEast) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x+1, y)), MX_E, MY_E); - - if (allowSouth) { - if (allowWest) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x-1, y+1)), MX_SW, MY_SW); - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x, y+1)), MX_S, MY_S); - if (allowEast) - total += PIXEL_TO_INTENSITIES(read_imageui(input, sampler, (int2)(x+1, y+1)), MX_SE, MY_SE); - } - - uint2 square = total * total; - gradientOutput[i] = sqrt((float)(square.x + square.y)); - directionOutput[i] = atan2((float)total.y, (float)total.x); -} - -__kernel void normalizeImage(__global const float* input, float maxValue, __global uchar4* output) { - int i = get_global_id(0); - uchar v = input[i] / maxValue * 255; - output[i] = (uchar4)(v, v, v, 255); -} diff --git a/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/SetupUtilsTest.java b/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/SetupUtilsTest.java deleted file mode 100644 index 24603c40d..000000000 --- a/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/SetupUtilsTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.demos; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URLConnection; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class SetupUtilsTest { - @Test - public void checkValidDownloadLinks() throws IOException { - for (SetupUtils.DownloadURL url : SetupUtils.DownloadURL.values()) { - HttpURLConnection con = (HttpURLConnection) url.url.openConnection(); - assertEquals("Bad url for " + url + " : " + url.url, 200, con.getResponseCode()); - con.disconnect(); - } - } -} diff --git a/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java b/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java deleted file mode 100644 index 3184c4804..000000000 --- a/libraries/OpenCL/Demos/src/test/java/com/nativelibs4java/opencl/demos/TestReport.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.nativelibs4java.opencl.demos; -import com.nativelibs4java.opencl.*; - -import com.nativelibs4java.opencl.demos.hardware.HardwareReport; -import java.util.List; -import java.util.Map; -import org.junit.Test; - -/** - * Test that HardwareReport runs without exception - * @author ochafik - */ -public class TestReport { - - @Test - public void runReport() { - for (CLPlatform platform : JavaCL.listPlatforms()) { - List> list = HardwareReport.listInfos(platform); - HardwareReport.toHTML(list); - } - } -} diff --git a/libraries/OpenCL/Generator/.classpath b/libraries/OpenCL/Generator/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/OpenCL/Generator/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/OpenCL/Generator/.gitignore b/libraries/OpenCL/Generator/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Generator/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Generator/.project b/libraries/OpenCL/Generator/.project deleted file mode 100644 index 7dbd9de12..000000000 --- a/libraries/OpenCL/Generator/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - Generator - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL/Generator/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/Generator/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 45a45b3f0..000000000 --- a/libraries/OpenCL/Generator/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:18 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/Generator/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/Generator/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL/Generator/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/Generator/pom.xml b/libraries/OpenCL/Generator/pom.xml deleted file mode 100644 index 10ed5c40d..000000000 --- a/libraries/OpenCL/Generator/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-generator - JavaCL Generator / BridJ - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - jnaerator - - - - com.nativelibs4java - javacl-core - - - - - - diff --git a/libraries/OpenCL/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java b/libraries/OpenCL/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java deleted file mode 100644 index fdd2c2c9b..000000000 --- a/libraries/OpenCL/Generator/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGenerator.java +++ /dev/null @@ -1,527 +0,0 @@ -package com.nativelibs4java.opencl.generator; - -import com.nativelibs4java.opencl.*; -import com.ochafik.io.IOUtils; -import com.ochafik.lang.jnaerator.*; -import com.ochafik.lang.jnaerator.PreprocessorUtils.MacroUseCallback; -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrimitive; -import com.ochafik.lang.jnaerator.TypeConversion.TypeConversionMode; -import com.ochafik.lang.jnaerator.UniversalReconciliator; -import com.ochafik.lang.jnaerator.UnsupportedConversionException; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import java.io.PrintStream; - -import java.util.regex.Pattern; -import org.anarres.cpp.LexerException; - -public class JavaCLGenerator extends JNAerator { - - static Pattern nameExtPatt = Pattern.compile("(.*?)\\.(\\w+)"); - - public JavaCLGenerator(JNAeratorConfig config) { - super(config); - - config.forceOverwrite = true; - config.outputMode = JNAeratorConfig.OutputMode.Directory; - config.noCPlusPlus = true; - config.genCPlusPlus = false; - config.gccLong = true; - config.putTopStructsInSeparateFiles = false; - config.runtime = JNAeratorConfig.Runtime.JNAerator;//NL4JStructs; - config.fileToLibrary = new Adapter() { - @Override - public String adapt(File value) { - String[] m = RegexUtils.match(value.getName(), nameExtPatt); - return m == null ? null : m[1]; - } - }; - - config.functionsAccepter = new Adapter() { - @Override - public Boolean adapt(Function value) { - List mods = value.getModifiers(); - if (ModifierType.__kernel.isContainedBy(mods)) - return true; - if (value.getValueType() == null) - return null; - mods = value.getValueType().getModifiers(); - return ModifierType.__kernel.isContainedBy(mods); - } - }; - } - - Map> macrosByFile = new HashMap>(); - - @Override - protected JNAeratorParser createJNAeratorParser() { - return new JNAeratorParser() { - - @Override - protected com.ochafik.lang.jnaerator.parser.ObjCppParser newObjCppParser(TypeConversion typeConverter, String s, boolean verbose, PrintStream errorOut) throws IOException { - com.ochafik.lang.jnaerator.parser.ObjCppParser parser = super.newObjCppParser(typeConverter, s, verbose, errorOut); - parser.allowKinds(ModifierKind.OpenCL); - return parser; - } - - }; - } - - static Set openclPrimitives = new HashSet(); - static { - openclPrimitives.add("half"); - openclPrimitives.add("image2d_t"); - openclPrimitives.add("image3d_t"); - openclPrimitives.add("sampler_t"); - openclPrimitives.add("event_t"); - } - - @Override - public Result createResult(final ClassOutputter outputter, Feedback feedback) { - return new Result(config, outputter, feedback) { - - @Override - public void init() { - typeConverter = new BridJTypeConversion(this) { - - @Override - public void initTypes() { - super.initTypes(); - - } - - - @Override - public boolean isObjCppPrimitive(String s) { - int len; - if (s == null || (len = s.length()) == 0) - return false; - - if (super.isObjCppPrimitive(s)) - return true; - - // handle case of "(int|long|short|byte|double|float)\\d" - if (len > 1 && Character.isDigit(s.charAt(len - 1))) { - String ss = s.substring(0, len - 1); - if (ss.charAt(0) == 'u') - ss = ss.substring(1); - - if (super.isObjCppPrimitive(ss)) - return true; - } - - return openclPrimitives.contains(s); - } - - }; - declarationsConverter = new BridJDeclarationsConverter(this) { - - @Override - public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, int iConstructor) { - if (isCallback) - return; - - if (!result.config.functionsAccepter.adapt(function)) - return; - - List args = function.getArgs(); - List convArgs = new ArrayList(args.size()); - String queueName = "commandQueue"; - convArgs.add(new Arg(queueName, typeRef(CLQueue.class))); - List convArgExpr = new ArrayList(args.size()); - List extraStatements = new ArrayList(); - - int iArg = 1; - for (Arg arg : args) { - TypeRef tr = arg.createMutatedType(); - if (tr == null) - return; - - try { - tr = result.typeConverter.resolveTypeDef(tr, libraryClassName, true, false); - List mods = arg.harvestModifiers(); - - TypeRef convTr; - String argName = arg.getName() == null ? "arg" + iArg : arg.getName(); - Expression argExpr; - - if (ModifierType.__local.isContainedBy(mods)) { - argName += "LocalByteSize"; - //convTr = typeRef(Long.TYPE); - //argExpr = new Expression.New(typeRef(LocalSize.class), varRef(argName)); - convTr = typeRef(LocalSize.class); - argExpr = varRef(argName);//new Expression.New(typeRef(LocalSize.class), varRef(argName)); - } else { - Conversion conv = convertTypeToJavaCL(result, argName, tr, TypeConversion.TypeConversionMode.PrimitiveOrBufferParameter, null); - convTr = conv.outerJavaTypeRef; - argExpr = conv.convertedExpr; - extraStatements.addAll(conv.extraStatements); - //String convTrStr = convTr.toString(); - /*if (convTrStr.equals(NativeSize.class.getName()) || convTrStr.equals(NativeLong.class.getName())) - argExpr = new Expression.New(tr, varRef(conv.argName)); - else - argExpr = varRef(ident(argName));*/ - } - - convArgs.add(new Arg(argName, convTr)); - - convArgExpr.add(argExpr);//varRef(argName)); - - } catch (UnsupportedConversionException ex) { - out.addDeclaration(skipDeclaration(function, ex.toString())); - } - iArg++; - } - - String globalWSName = "globalWorkSizes", localWSName = "localWorkSizes", eventsName = "eventsToWaitFor"; - convArgs.add(new Arg(globalWSName, typeRef(int[].class))); - convArgs.add(new Arg(localWSName, typeRef(int[].class))); - convArgs.add(new Arg(eventsName, typeRef(CLEvent.class)).setVarArg(true)); - - String functionName = function.getName().toString(); - String kernelVarName = functionName + "_kernel"; - if (signatures.addVariable(kernelVarName)) - out.addDeclaration(new VariablesDeclaration(typeRef(CLKernel.class), new Declarator.DirectDeclarator(kernelVarName))); - Function method = new Function(Function.Type.JavaMethod, ident(functionName), typeRef(CLEvent.class)); - method.addModifiers(ModifierType.Public, ModifierType.Synchronized); - method.addThrown(typeRef(CLBuildException.class)); - - method.setArgs(convArgs); - List statements = new ArrayList(); - statements.add( - new Statement.If( - expr(varRef(kernelVarName), Expression.BinaryOperator.IsEqual, new Expression.NullExpression()), - stat( - expr( - varRef(kernelVarName), Expression.AssignmentOperator.Equal, - methodCall( - "createKernel", - new Expression.Constant(Expression.Constant.Type.String, functionName, null) - ) - ) - ), - null - ) - ); - statements.addAll(extraStatements); - statements.add( - stat(methodCall( - varRef(kernelVarName), - Expression.MemberRefStyle.Dot, - "setArgs", - convArgExpr.toArray(new Expression[convArgExpr.size()]) - )) - ); - statements.add( - new Statement.Return(methodCall( - varRef(kernelVarName), - Expression.MemberRefStyle.Dot, - "enqueueNDRange", - varRef(queueName), - varRef(globalWSName), - varRef(localWSName), - varRef(eventsName) - )) - ); - method.setBody(block(statements.toArray(new Statement[statements.size()]))); - if (signatures.addMethod(method)) - out.addDeclaration(method); - } - }; - globalsGenerator = new BridJGlobalsGenerator(this); - objectiveCGenerator = new ObjectiveCGenerator(this); - universalReconciliator = new UniversalReconciliator(); - } - - }; - } - - static class CLPrim { - TypeConversion.JavaPrimitive javaPrim; - int arity; - boolean isLong, isShort; - Expression assertExpr; - Statement checkStatement; - Expression convertStatement; - Class argClass; - - public CLPrim(JavaPrimitive javaPrim, int arity) { - this.javaPrim = javaPrim; - this.arity = arity; - } - - static Pattern patt = Pattern.compile("(?:(long|short)\\s+)?(float|double|u?(?:char|long|short|int))(\\d)"); - public static CLPrim parse(Result result, TypeRef tr) { - String s = tr.toString(); - if (s == null || s.length() == 0) - return null; - char c = s.charAt(s.length() - 1); - if (!Character.isDigit(c)) { - //JavaPrim prim = result.typeConverter.getPrimitive( - return null; - } - String[] m = RegexUtils.match(tr.toString(), patt); - if (m == null) - return null; - - - //boolean isShort = false, - //result.typeConverter - return null; - } - } - - static class Conversion { - TypeRef outerJavaTypeRef; - Expression convertedExpr; - String argName; - List extraStatements = new ArrayList(); - } - static Map>> buffersAndArityByType = new HashMap>>(); - static Map>> arraysAndArityByType = new HashMap>>(); - static { - Object[] data = new Object[] { - "char", Byte.TYPE, byte[].class, Byte.class, - "long", Long.TYPE, long[].class, Long.class, - "int", Integer.TYPE, int[].class, Integer.class, - "short", Short.TYPE, short[].class, Short.class, - "wchar_t", Character.TYPE, char[].class, Short.class, - "double", Double.TYPE, double[].class, Double.class, - "float", Float.TYPE, float[].class, Float.class, - "bool", Boolean.TYPE, boolean[].class, Boolean.class - }; - for (int arity : new int[] { 1, 2, 4, 8, 16 }) { - String suffix = arity == 1 ? "" : arity +""; - for (int i = 0; i < data.length; i += 4) { - String rawType = (String)data[i]; - Class scalClass = (Class)data[i + 1]; - Class arrClass = (Class)data[i + 2]; - Class buffClass = (Class)data[i + 3]; - - Pair> - buffPair = new Pair>(arity, buffClass), - arrPair = new Pair>(arity, arity == 1 ? scalClass : arrClass); - - for (String type : new String[] { rawType + suffix, "u" + rawType + suffix}) { - buffersAndArityByType.put(type, buffPair); - arraysAndArityByType.put(type, arrPair); - } - } - } - data = new Object[] { - "image2d_t", CLImage2D.class, - "image3d_t", CLImage3D.class - }; - for (int i = 0; i < data.length; i+=2) { - String type = (String) data[i]; - Class scalClass = (Class)data[i + 1]; - Pair> arrPair = new Pair>(1, scalClass); - arraysAndArityByType.put(type, arrPair); - } - } - private Conversion convertTypeToJavaCL(Result result, String argName, TypeRef valueType, TypeConversionMode typeConversionMode, Identifier libraryClassName) throws UnsupportedConversionException { - Conversion ret = new Conversion(); - ret.argName = argName; - ret.convertedExpr = varRef(argName); - - if (valueType instanceof TypeRef.Pointer) { - TypeRef target = ((TypeRef.Pointer)valueType).getTarget(); - if (target instanceof TypeRef.SimpleTypeRef) { - TypeRef.SimpleTypeRef starget = (TypeRef.SimpleTypeRef)target; - - Pair> pair = buffersAndArityByType.get((starget + "").equals("long") ? "long" : starget.getName() + ""); - if (pair != null) { - ret.outerJavaTypeRef = typeRef(ident(CLBuffer.class, expr(typeRef(pair.getSecond())))); - return ret; - } - } - } else if (valueType instanceof TypeRef.SimpleTypeRef) { - TypeRef.SimpleTypeRef sr = (TypeRef.SimpleTypeRef)valueType; - String name = sr.getName() == null ? sr.toString() : sr.getName().toString(); - if (name.equals("size_t")) { - ret.outerJavaTypeRef = typeRef(Long.TYPE); - ret.convertedExpr = new Expression.New(typeRef(NativeSize.class), ret.convertedExpr); - return ret; - } else { - Pair> pair = arraysAndArityByType.get(name); - if (pair != null) { - ret.outerJavaTypeRef = typeRef(pair.getSecond()); - if (pair.getFirst().intValue() != 1) { - ret.extraStatements.add( - stat( - methodCall( - "checkArrayLength", - varRef(ret.argName), - expr( - Expression.Constant.Type.Int, - pair.getFirst() - ), - expr( - Expression.Constant.Type.String, - ret.argName - ) - ) - ) - ); - } - return ret; - } - } - } - throw new UnsupportedConversionException(valueType, "Unhandled type : " + valueType); - } - - @Override - protected void generateLibraryFiles(SourceFiles sourceFiles, Result result) throws IOException { - //super.generateLibraryFiles(sourceFiles, result); - for (SourceFile sourceFile : sourceFiles.getSourceFiles()) { - String rawSrcFilePath = new File(sourceFile.getElementFile()).getCanonicalPath(); - String srcFilePath = result.config.relativizeFileForSourceComments(rawSrcFilePath); - File srcFile = new File(srcFilePath); - String srcParent = srcFile.getParent(); - String srcFileName = srcFile.getName(); - String[] nameExt = RegexUtils.match(srcFileName, nameExtPatt); - if (nameExt == null) - continue; - String name = nameExt[1], ext = nameExt[2]; - if (!ext.equals("c") && !ext.equals("cl")) - continue; - - String packageName = srcParent == null || srcParent.length() == 0 ? null : srcParent.replace('/', '.').replace('\\', '.'); - Identifier packageIdent = ident(packageName); - String className = (packageName == null ? "" : packageName + ".") + name; - - - Struct interf = new Struct(); - interf.addToCommentBefore("Wrapper around the OpenCL program " + name); - interf.addModifiers(ModifierType.Public); - interf.setTag(ident(name)); - interf.addParent(ident(CLAbstractUserProgram.class)); - interf.setType(Struct.Type.JavaClass); - - String[] constrArgNames = new String[] { "context", "program" }; - Class[] constrArgTypes = new Class[] { CLContext.class, CLProgram.class }; - for (int i = 0; i < constrArgNames.length; i++) { - String argName = constrArgNames[i]; - - Function constr = new Function(Function.Type.JavaMethod, ident(name), null, new Arg(argName, typeRef(constrArgTypes[i]))); - constr.addModifiers(ModifierType.Public); - constr.addThrown(typeRef(IOException.class)); - constr.setBody( - block( - stat( - methodCall( - "super", - varRef(argName), - methodCall( - "readRawSourceForClass", - result.typeConverter.typeLiteral(typeRef(name)) - ) - ) - ) - ) - ); - interf.addDeclaration(constr); - } - - //result.declarationsConverter.convertStructs(null, null, interf, null) - Signatures signatures = new Signatures();//result.getSignaturesForOutputClass(fullLibraryClassName); - result.typeConverter.allowFakePointers = true; - String library = name; - Identifier fullLibraryClassName = ident(className); - result.declarationsConverter.convertStructs(result.structsByLibrary.get(library), signatures, interf, fullLibraryClassName, library); - //result.declarationsConverter.convertCallbacks(result.callbacksByLibrary.get(library), signatures, interf, fullLibraryClassName); - - int declCount = interf.getDeclarations().size(); - result.declarationsConverter.convertFunctions(result.functionsByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertEnums(result.enumsByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertConstants(library, result.definesByLibrary.get(library), sourceFiles, signatures, interf, fullLibraryClassName); - - boolean hasKernels = interf.getDeclarations().size() > declCount; - if (!hasKernels) - continue; - - //for () - - /* - public SampleUserProgram(CLContext context) throws IOException { - super(context, readRawSourceForClass(SampleUserProgram.class)); - }*/ - - - for (Set set : macrosByFile.values()) { - for (String macroName : set) { - if (macroName.equals("__LINE__") || - macroName.equals("__FILE__") || - macroName.equals("__COUNTER__") || - config.preprocessorConfig.macros.containsKey(macroName)) - continue; - - String[] parts = macroName.split("_+"); - List newParts = new ArrayList(parts.length); - for (String part : parts) { - if (part == null || (part = part.trim()).length() == 0) - continue; - newParts.add(StringUtils.capitalize(part)); - } - String functionName = "define" + StringUtils.implode(newParts, ""); - Function macroDef = new Function(Function.Type.JavaMethod, ident(functionName), typeRef("void")); - String valueName = "value"; - macroDef.addArg(new Arg(valueName, typeRef(String.class))); - macroDef.setBody(block(stat(methodCall("defineMacro", expr(Expression.Constant.Type.String, macroName), varRef(valueName))))); - interf.addDeclaration(macroDef); - } - } - - PrintWriter out = result.classOutputter.getClassSourceWriter(className); - result.printJavaClass(packageIdent, interf, out); - //if (packageName != null) - // out.println("package " + packageName + ";"); - //out.println(interf); - out.close(); - } - } - - - @Override - protected void autoConfigure() { - super.autoConfigure(); - - /* - __OPENCL_VERSION__ - __ENDIAN_LITTLE__ - - __IMAGE_SUPPORT__ - __FAST_RELAXED_MATH__ - */ - - } - - public static void main(String[] args) { - JNAerator.main(new JavaCLGenerator(new JNAeratorConfig()), - new String[] { - "-o", "target/generated-sources/main/java", - //"-o", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/generated-sources/main/java", - "-noJar", - "-noComp", - "-v", - "-addRootDir", "src/main/opencl", - "src/main/opencl", - //"-addRootDir", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Blas/target/../src/main/opencl", - //"/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Blas/src/main/opencl/com/nativelibs4java/opencl/blas/LinearAlgebraKernels.c" - //"-addRootDir", "/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/../src/main/opencl", - //"/Users/ochafik/Prog/Java/versionedSources/nativelibs4java/trunk/libraries/OpenCL/Demos/target/../src/main/opencl/com/nativelibs4java/opencl/demos/sobelfilter/SimpleSobel.cl" - } - ); - } -} - diff --git a/libraries/OpenCL/InteractiveImageDemo/.gitignore b/libraries/OpenCL/InteractiveImageDemo/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo-bridj.iml b/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo-bridj.iml deleted file mode 100644 index 9e0916384..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo-bridj.iml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo.iml b/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo.iml deleted file mode 100644 index acf5a8b2f..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/javacl-interactive-image-demo.iml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/InteractiveImageDemo/pom.xml b/libraries/OpenCL/InteractiveImageDemo/pom.xml deleted file mode 100644 index fdd9d7f60..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-interactive-image-demo - JavaCL Interactive Image Demo / BridJ - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - com.nativelibs4java.opencl.demos.interactiveimage.InteractiveImageDemo - true - - - - - - com.nativelibs4java - javacl-core - - - com.nativelibs4java - javacl-demos - - - com.nativelibs4java - libcl - - - com.nativelibs4java - ochafik-swing - ${jnaerator.version} - - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - - - - diff --git a/libraries/OpenCL/InteractiveImageDemo/project/build.properties b/libraries/OpenCL/InteractiveImageDemo/project/build.properties deleted file mode 100644 index faa423a6d..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/project/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -#Project properties -#Fri Dec 17 13:30:54 CET 2010 -project.organization=com.nativelibs4java -project.name=javacl-interactive-image-demo -sbt.version=0.7.4 -project.version=1.0-SNAPSHOT -build.scala.versions=2.8.1 -project.initialize=false diff --git a/libraries/OpenCL/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala b/libraries/OpenCL/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala deleted file mode 100644 index f127dd3fe..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/project/build/InteractiveImageDemoProject.scala +++ /dev/null @@ -1,12 +0,0 @@ -import sbt._ - -class InteractiveImageDemoProject(info: ProjectInfo) extends DefaultProject(info) with AutoCompilerPlugins -{ - val nativelibs4javaRepo = "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - - val jnaeratorVersion = "0.9.6-SNAPSHOT" - val javaclVersion = "1.0-SNAPSHOT" - - val javacl = "com.nativelibs4java" % "javacl" % javaclVersion - val ochafikSwing = "com.ochafik" % "ochafik-swing" % jnaeratorVersion -} diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java b/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java deleted file mode 100644 index 0303e46ff..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/InteractiveImageDemo.java +++ /dev/null @@ -1,555 +0,0 @@ -package com.nativelibs4java.opencl.demos.interactiveimage; - -import com.nativelibs4java.opencl.demos.SetupUtils; -import java.awt.dnd.DropTarget; -import java.net.MalformedURLException; -import java.awt.datatransfer.DataFlavor; -import java.awt.Image; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.dnd.DropTargetEvent; -import java.awt.dnd.DnDConstants; -import java.awt.datatransfer.Transferable; -import java.awt.dnd.DropTargetDragEvent; -import java.awt.dnd.DropTargetListener; -import java.awt.Dimension; -import java.awt.Point; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.nativelibs4java.opencl.*; -import com.ochafik.io.ReadText; -import com.ochafik.io.WriteText; -import javax.swing.*; -import java.awt.event.*; -import javax.imageio.*; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.image.*; -import java.io.*; -import java.awt.FileDialog; -import java.util.*; - -import com.ochafik.swing.UndoRedoUtils; -import com.ochafik.swing.syntaxcoloring.TokenMarker; -import com.ochafik.swing.syntaxcoloring.CCTokenMarker; -import com.ochafik.swing.syntaxcoloring.JEditTextArea; -import com.ochafik.util.SystemUtils; -import org.bridj.Platform; - -import static com.nativelibs4java.opencl.demos.interactiveimage.Utils.*; - -/** -mvn compile exec:java -Dexec.mainClass=com.nativelibs4java.opencl.demos.interactiveimage.InteractiveImageDemo -*/ -public class InteractiveImageDemo extends JPanel { - JSplitPane imgSrcSplitPane, imgsSplitPane; - JLabel origImgLab, resultImgLab, instructionsLabel, timeLabel, progressLabel; - JScrollPane origImgScroll, resultImgScroll; - - JEditTextArea sourceTextArea; - JComboBox devicesCombo, examplesCombo; - //JTextArea sourceTextArea; - - JButton runButton; - BufferedImage image, result; - JProgressBar progressBar; - - JComponent[] toDisable; - File lastOpenedFile; - - static final String RUN_ACTION = "run", SAVE_ACTION = "save"; - File persistentFile = new File(new File(new File(System.getProperty("user.home"), ".javacl"), getClass().getSimpleName()), "Test.cl"); - - boolean load() { - if (!persistentFile.exists()) - return false; - - sourceTextArea.setText(ReadText.readText(persistentFile)); - return true; - } - void save() { - try { - WriteText.writeText(sourceTextArea.getText(), persistentFile); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(this, traceToHTML(ex), "Failed to save file", JOptionPane.ERROR_MESSAGE); - } - } - class SaveAction extends AbstractAction { - public void actionPerformed(ActionEvent e) { - save(); - } - } - void run() { - save(); - try { - final BufferedImage bufferedImage = getImage(); - if (bufferedImage == null) - return; - - // Could just be this : final CLContext context = JavaCL.createBestContext(); - final CLContext context = getContext(); - if (context == null) - return; - - final Point initialViewPosition = origImgScroll.getViewport().getViewPosition(); - - for (JComponent c : toDisable) - c.setEnabled(false); - resultImgLab.setText(null); - resultIcon(null); - resultImgLab.setToolTipText(null); - result = null; - timeLabel.setVisible(false); - progressBar.setIndeterminate(true); - progressBar.setVisible(true); - setProgress("Initializing..."); - - final long[] elapsedTimeNanos = new long[] { -1L }; - new Thread() { public void run() { - try { - setProgress("Creating OpenCL queue..."); - CLQueue queue = context.createDefaultQueue(); - setProgress("Compiling program..."); - CLProgram program = context.createProgram(sourceTextArea.getText()); - CLKernel[] kernels = program.createKernels(); - if (kernels.length == 0) - throw new RuntimeException("No kernels found in the source code ! (please mark a function with __kernel)"); - - setProgress("Creating OpenCL images..."); - int width = bufferedImage.getWidth(), height = bufferedImage.getHeight(); - CLImage2D imageIn = context.createImage2D(CLMem.Usage.InputOutput, bufferedImage, false); - CLImage2D imageOut = context.createImage2D(CLMem.Usage.InputOutput, imageIn.getFormat(), width, height); - - long startTimeNanos = System.nanoTime(); - CLEvent lastEvent = null; - CLImage2D finalImageOut = null; - for (CLKernel kernel : kernels) { - setProgress("Running kernel '" + kernel.getFunctionName() + "'..."); - try { - kernel.setArgs(imageIn, imageOut); - finalImageOut = imageOut; - imageOut = imageIn; - imageIn = finalImageOut; - lastEvent = kernel.enqueueNDRange(queue, new int[] { width, height }, lastEvent); - } catch (CLException ex) { - throw new RuntimeException("Error occurred while running kernel '" + kernel.getFunctionName() + "': " + ex, ex); - } - } - lastEvent.waitFor(); - elapsedTimeNanos[0] = System.nanoTime() - startTimeNanos; - - setProgress("Reading the image output..."); - result = finalImageOut.read(queue); - - imageIn.release(); - imageOut.release(); - for (CLKernel kernel : kernels) - kernel.release(); - program.release(); - queue.release(); - - SwingUtilities.invokeLater(new Runnable() { public void run() { - resultIcon(result == null ? null : new ImageIcon(result)); - resultImgLab.setToolTipText(result == null ? null : "Click to save this image"); - - SwingUtilities.invokeLater(new Runnable() { public void run() { - origImgScroll.getViewport().setViewPosition(initialViewPosition); - }}); - }}); - } catch (Exception ex) { - ex.printStackTrace(); - resultError(ex); - } finally { - SwingUtilities.invokeLater(new Runnable() { public void run() { - setProgress(null); - - for (JComponent c : toDisable) - c.setEnabled(true); - progressBar.setIndeterminate(false); - progressBar.setVisible(false); - if (elapsedTimeNanos[0] >= 0) { - timeLabel.setText("Completed in " + (elapsedTimeNanos[0] / 1000000.0) + " msecs"); - timeLabel.setVisible(true); - } - }}); - } - }}.start(); - } catch (Exception ex) { - ex.printStackTrace(); - resultError(ex); - } - } - class RunAction extends AbstractAction { - public void actionPerformed(ActionEvent e) { - run(); - } - } - - String runKeyStroke = "F5"; - - int spacing = 10; - - class Example { - public Example(String caption, String fileName) { - this.fileName = fileName; - this.caption = caption; - } - public final String fileName, caption; - @Override - public String toString() { - return caption; - } - - } - public InteractiveImageDemo() { - super(new BorderLayout()); - - devicesCombo = new JComboBox(); - List devices = new ArrayList(); - try { - for (CLPlatform platform : JavaCL.listPlatforms()) { - for (CLDevice device : platform.listAllDevices(true)) { - devicesCombo.addItem(device); - devices.add(device); - } - } - if (!devices.isEmpty()) - devicesCombo.setSelectedItem(CLPlatform.getBestDevice(Arrays.asList(CLPlatform.DeviceFeature.MaxComputeUnits), devices)); - } catch (Exception ex) { - ex.printStackTrace(); - devicesCombo.setToolTipText(traceToHTML(ex)); - } - if (devices.isEmpty()) { - devicesCombo.addItem("No OpenCL Device detected"); - } - - examplesCombo = new JComboBox(); - examplesCombo.addItem("Examples..."); - { - final String signature = "__kernel void transform(__global read_only image2d inputImage, __global write_only image2d outputImage)"; - - examplesCombo.setToolTipText("Kernel samples in the form of :\n'" + signature + "'"); - for (Example example : new Example[] { - //"Blur", - new Example("Convolution", "Convolution"), - new Example("Sobel Operator", "SobelFilter"), - new Example("Desaturate Colors", "DesaturateColors"), - new Example("Richardson-Lucy Deconvolution", "RichardsonLucyDeconvolution"), - new Example("Luminance Threshold", "LuminanceThreshold"), - new Example("Naive Denoising", "NaiveDenoising"), - new Example("Identity", "Identity"), - new Example("Image Info", "QueryFormat") - }) { - examplesCombo.addItem(example); - } - examplesCombo.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - String t = sourceTextArea.getText(); - if (t.trim().length() > 0) - t = t + "\n"; - sourceTextArea.setText(t + "__kernel " + signature + " {\n\tint x = get_global_id(0), y = get_global_id(1);\n\t// write here\n}"); - }}); - examplesCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { - Object selection = examplesCombo.getSelectedItem(); - if (selection instanceof Example) { - loadExample(((Example)selection).fileName); - examplesCombo.setSelectedIndex(0); - } - }}); - } - - JPanel srcPanel = new JPanel(new BorderLayout()); - sourceTextArea = textArea(new CCTokenMarker()); - srcPanel.add("Center", withTitle("Image transformation kernel source code", sourceTextArea)); - - runButton = new JButton("Run (" + runKeyStroke + ")"); - { - Box toolbar = Box.createHorizontalBox(); - for (JComponent c : new JComponent[] { examplesCombo, runButton, devicesCombo }) - c.setMaximumSize(c.getPreferredSize()); - - runButton.putClientProperty("JButton.buttonType", "bevel"); - examplesCombo.putClientProperty("JComboBox.isPopDown", Boolean.TRUE); - devicesCombo.putClientProperty("JComboBox.isPopDown", Boolean.TRUE); - - toolbar.add(examplesCombo); - toolbar.add(runButton); - toolbar.add(devicesCombo); - toolbar.add(createLinkLabel("Khronos OpenCL Documentation", "http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/")); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(createLinkLabel("JavaCL FAQ", "http://code.google.com/p/javacl/wiki/FAQ")); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(Box.createHorizontalGlue()); - toolbar.add(progressLabel = new JLabel()); - toolbar.add(Box.createHorizontalStrut(spacing)); - toolbar.add(progressBar = new JProgressBar()); - progressBar.putClientProperty("JProgressBar.style", "circular"); - toolbar.add(timeLabel = new JLabel()); - progressBar.setMaximumSize(progressBar.getPreferredSize()); - progressLabel.setVisible(false); - progressBar.setVisible(false); - timeLabel.setVisible(false); - srcPanel.add("South", toolbar); - } - origImgScroll = new JScrollPane(origImgLab = new JLabel()); - resultImgScroll = new JScrollPane(resultImgLab = new JLabel()); - for (JScrollPane sp : Arrays.asList(origImgScroll, resultImgScroll)) { - sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - } - resultVertScrollModel = resultImgScroll.getVerticalScrollBar().getModel(); - resultHorzScrollModel = resultImgScroll.getHorizontalScrollBar().getModel(); - - origImgLab.setDropTarget(new DropTarget(origImgLab, DnDConstants.ACTION_COPY, imgDropTargetListener)); - - add("Center", imgSrcSplitPane = new JSplitPane( - JSplitPane.VERTICAL_SPLIT, - imgsSplitPane = new JSplitPane( - JSplitPane.HORIZONTAL_SPLIT, - withTitle("Input", origImgScroll), - withTitle("Output", resultImgScroll) - ), - srcPanel - )); - imgSrcSplitPane.setResizeWeight(0.5); - imgsSplitPane.setResizeWeight(0.5); - - origImgLab.setToolTipText("Click to load a different image"); - origImgLab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - chooseImage(); - }}); - resultImgLab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - saveResult(); - }}); - - runButton.addActionListener(new RunAction()); - - toDisable = new JComponent[] { - examplesCombo, - runButton, - devicesCombo, - sourceTextArea, - //origImgLab, - resultImgLab - }; - - UndoRedoUtils.registerNewUndoManager(sourceTextArea, sourceTextArea.getDocument()); - for (JComponent focusable : Arrays.asList(sourceTextArea, examplesCombo, devicesCombo, runButton)) { - InputMap im = focusable.getInputMap(); - ActionMap am = focusable.getActionMap(); - im.put(KeyStroke.getKeyStroke(runKeyStroke), RUN_ACTION); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, isMac() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK), SAVE_ACTION); - am.put(RUN_ACTION, new RunAction()); - am.put(SAVE_ACTION, new SaveAction()); - } - } - - protected DropTargetListener imgDropTargetListener = new DropTargetListener() { - - public void dragEnter(DropTargetDragEvent dtde) { - try { - if ( - dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || - dtde.isDataFlavorSupported(DataFlavor.stringFlavor) || - dtde.isDataFlavorSupported(DataFlavor.imageFlavor)) - dtde.acceptDrag(DnDConstants.ACTION_COPY); - else - dtde.rejectDrag(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - dtde.acceptDrag(DnDConstants.ACTION_COPY); - } - public void dragExit(DropTargetEvent dte) {} - public void dragOver(DropTargetDragEvent dtde) {} - public void dropActionChanged(DropTargetDragEvent dtde) {} - public void drop(DropTargetDropEvent dtde) { - try { - if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - java.util.List files = (java.util.List)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); - if (files != null && !files.isEmpty()) { - readImage(files.get(0).toURI().toURL()); - } - dtde.dropComplete(true); - } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) { - try { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - readImage(new URL((String)dtde.getTransferable().getTransferData(DataFlavor.stringFlavor))); - dtde.dropComplete(true); - return ; - } catch (MalformedURLException ex) {} - } else if (dtde.isDataFlavorSupported(DataFlavor.imageFlavor)) { - dtde.acceptDrop(DnDConstants.ACTION_COPY); - Image image = (Image)dtde.getTransferable().getTransferData(DataFlavor.imageFlavor); - if (image instanceof BufferedImage) - setImage((BufferedImage)image); - dtde.dropComplete(true); - return; - } - dtde.rejectDrop(); - } catch (Exception ex) { - origImgLab.setToolTipText(traceToHTML(ex)); - } - } - }; - BufferedImage getImage() { - if (image == null) - chooseImage(); - return image; - } - void readImage(URL url) { - try { - setImage(null); - - InputStream in = url.openStream(); - if (in == null) - return; - - lastOpenedFile = new File(url.getFile()); - setImage(ImageIO.read(in)); - - in.close(); - } catch (Exception ex) { - ex.printStackTrace(); - origImgLab.setText(traceToHTML(ex)); - } - } - void setImage(BufferedImage image) { - this.image = image; - origImgLab.setText(null); - origIcon(image == null ? null : new ImageIcon(image)); - } - void readImageResource(String name) { - readImage(Platform.getClassLoader(getClass()).getResource("images/" + name)); - } - - void chooseImage() { - try { - File f = chooseFile(lastOpenedFile, true); - if (f == null) - return; - - readImage(f.toURI().toURL()); - } catch (Exception ex) { - ex.printStackTrace(); - origImgLab.setText(traceToHTML(ex)); - } - } - String getOutputFormat(File file) { - if (file != null) { - String s = file.getName().toLowerCase(); - if (s.matches(".*?\\.jpe?g")) - return "jpeg"; - for (String ex : new String[] { "png", "gif", "tiff", "pnm", "pbm" }) - if (s.matches(".*?\\." + ex)) - return ex; - } - return "png"; - } - static Pattern fileExtRx = Pattern.compile("(.*?)(\\.[^.]+)?"); - void saveResult() { - if (result == null) - return; - - try { - File f = null; - if (lastOpenedFile != null) { - Matcher matcher = fileExtRx.matcher(lastOpenedFile.getName()); - if (matcher.matches()) { - String body = matcher.group(1); - String ext = matcher.group(2); - f = new File(lastOpenedFile.getParentFile(), body + ".transformed" + (ext == null ? ".png" : ext)); - } - } - - f = chooseFile(f, false); - if (f == null) - return; - - ImageIO.write(result, getOutputFormat(f), f); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(this, traceToHTML(ex), "Failed to write image", JOptionPane.ERROR_MESSAGE); - } - } - CLContext getContext() { - Object selection = devicesCombo.getSelectedItem(); - if (!(selection instanceof CLDevice)) - return null; - - CLDevice device = (CLDevice)selection; - CLContext context = JavaCL.createContext(null, device); - return context; - } - void setProgress(final String caption) { - System.out.println(caption); - SwingUtilities.invokeLater(new Runnable() { public void run() { - //progressLabel.setVisible(caption != null); - //progressLabel.setText(caption); - if (!isMac()) { - progressBar.setStringPainted(caption != null); - progressBar.setString(caption); - } - progressBar.setToolTipText(caption); - }}); - } - BoundedRangeModel resultVertScrollModel, resultHorzScrollModel; - void resultIcon(Icon icon) { - if (icon == null) { - resultImgScroll.getVerticalScrollBar().setModel(resultVertScrollModel); - resultImgScroll.getHorizontalScrollBar().setModel(resultHorzScrollModel); - } else { - resultImgScroll.getVerticalScrollBar().setModel(origImgScroll.getVerticalScrollBar().getModel()); - resultImgScroll.getHorizontalScrollBar().setModel(origImgScroll.getHorizontalScrollBar().getModel()); - } - resultImgLab.setIcon(icon); - } - void origIcon(Icon icon) { - origImgLab.setIcon(icon); - SwingUtilities.invokeLater(new Runnable() { public void run() { - JScrollBar bar; - BoundedRangeModel model; - model = (bar = origImgScroll.getVerticalScrollBar()).getModel(); - model.setValue((model.getMinimum() + model.getMaximum()) / 2); - model = (bar = origImgScroll.getHorizontalScrollBar()).getModel(); - model.setValue((model.getMinimum() + model.getMaximum()) / 2); - - }}); - } - void resultError(Exception ex) { - String html = traceToHTML(ex); - resultIcon(null); - resultImgLab.setText(html); - resultImgLab.setToolTipText(html); - } - void loadExample(String fileName) { - try { - String s = readTextResource("examples/" + fileName + ".cl"); - sourceTextArea.setText(s); - sourceTextArea.setCaretPosition(0); - } catch (Exception ex) { - ex.printStackTrace(); - sourceTextArea.setText("Failed to load example '" + fileName + "' :\n" + traceToString(ex)); - } - } - public static void main(String[] args) { - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - JFrame f = new JFrame("JavaCL's Interactive Image Transform Demo"); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - InteractiveImageDemo demo = new InteractiveImageDemo(); - f.getContentPane().add("Center", demo); - f.setSize(1200, 800); - f.setVisible(true); - - demo.getContext(); - demo.readImageResource("lena.jpg"); - if (!demo.load()) - demo.loadExample("Convolution"); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java b/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java deleted file mode 100644 index 51bdb7b92..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/java/com/nativelibs4java/opencl/demos/interactiveimage/Utils.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.nativelibs4java.opencl.demos.interactiveimage; - -import com.nativelibs4java.opencl.*; -import javax.swing.*; -import java.awt.event.*; -import javax.imageio.*; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.image.*; -import java.io.*; -import java.awt.FileDialog; -import java.util.*; -import org.bridj.Platform; - -import com.ochafik.swing.UndoRedoUtils; -import com.ochafik.swing.syntaxcoloring.TokenMarker; -import com.ochafik.swing.syntaxcoloring.CCTokenMarker; -import com.ochafik.swing.syntaxcoloring.JEditTextArea; -import com.ochafik.util.SystemUtils; -import java.net.URL; - -class Utils { - public static C withTitle(String title, C c) { - c.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title), BorderFactory.createLoweredBevelBorder())); - return c; - } - public static JLabel createLinkLabel(String caption, final String urlString) { - final JLabel[] lab = new JLabel[1]; - JLabel ret = lab[0] = createLinkLabel(caption, new Runnable() { public void run() { - try { - SystemUtils.runSystemOpenURL(new URL(urlString)); - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(lab[0], traceToHTML(ex), "Failed to open URL", JOptionPane.ERROR_MESSAGE); - } - }}); - ret.setToolTipText(urlString); - return ret; - } - public static JLabel createLinkLabel(String caption, final Runnable action) { - JLabel lab = new JLabel("
      " + caption + ""); - lab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - lab.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { - action.run(); - }}); - lab.setMaximumSize(lab.getPreferredSize()); - return lab; - } - - public static boolean isMac() { - return System.getProperty("os.name").startsWith("Mac"); - } - public static File chooseFile(File initialFile, boolean load) { - if (isMac()) { - FileDialog d = new FileDialog((java.awt.Frame)null); - d.setMode(load ? FileDialog.LOAD : FileDialog.SAVE); - if (initialFile != null) { - d.setDirectory(initialFile.getParent()); - d.setFile(initialFile.getName()); - } - d.show(); - String f = d.getFile(); - if (f != null) - return new File(new File(d.getDirectory()), d.getFile()); - } else { - JFileChooser chooser = new JFileChooser(); - if (initialFile != null) - chooser.setSelectedFile(initialFile); - if ((load ? chooser.showOpenDialog(null) : chooser.showSaveDialog(null)) == JFileChooser.APPROVE_OPTION) - return chooser.getSelectedFile(); - } - return null; - } - - public static JEditTextArea textArea(TokenMarker marker) { - JEditTextArea ta = new JEditTextArea() { - private static final long serialVersionUID = 1L; -// int lastCode, lastLocation; -// char lastChar = 0; - - @Override - public void processKeyEvent(KeyEvent evt) { - if (isMac()) { - int m = evt.getModifiers(); - if ((m & InputEvent.META_MASK) != 0) { - m = (m & ~InputEvent.META_MASK) | InputEvent.CTRL_MASK; - evt = new KeyEvent(evt.getComponent(), evt.getID(), evt.getWhen(), m, evt.getKeyCode(), evt.getKeyChar(), evt.getKeyLocation()); - if (evt.getID() == KeyEvent.KEY_TYPED) - return; - } - } - - super.processKeyEvent(evt); - } - @Override - public Dimension getMinimumSize() { - return new Dimension(100, 100); - } - }; - ta.setBorder(BorderFactory.createLoweredBevelBorder()); - ta.setFocusTraversalKeysEnabled(false); - ta.addMouseWheelListener(mouseWheelListener); - ta.setPreferredSize(new Dimension(200, 300)); - ta.setTokenMarker(marker); - return ta; - } - static MouseWheelListener mouseWheelListener = new MouseWheelListener() { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - if (!(e.getSource() instanceof JEditTextArea)) - return; - - JEditTextArea ta = (JEditTextArea)e.getSource(); - - int line = ta.getFirstLine(); - if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { - int u = e.getUnitsToScroll(); - line += u > 0 ? 1 : -1; - if (line < 0) - line = 0; - else if (line >= ta.getLineCount()) - line = ta.getLineCount() - 1; - - ta.setFirstLine(line); - } - } - - }; - public static String traceToHTML(Exception ex) { - return "
      " + traceToString(ex).replaceAll("\n", "
      ") + "
      "; - } - - public static String traceToString(Exception ex) { - StringWriter sout = new StringWriter(); - PrintWriter pout = new PrintWriter(sout); - ex.printStackTrace(pout); - pout.close(); - return sout.toString(); - } - public static String readTextResource(String path) throws IOException { - InputStream in = Platform.getClassLoader(Utils.class).getResourceAsStream(path); - if (in == null) - throw new FileNotFoundException(path); - - BufferedReader rin = new BufferedReader(new InputStreamReader(in)); - String line; - StringBuilder b = new StringBuilder(); - while ((line = rin.readLine()) != null) { - b.append(line); - b.append("\n"); - } - return b.toString(); - } -} diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Blur.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Blur.cl deleted file mode 100644 index fd1dfdb73..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Blur.cl +++ /dev/null @@ -1,65 +0,0 @@ -/** - Blur example : naive square blur. - This example also demonstrates the chaining of multiple kernels (see commented code at the end). - Written by Olivier Chafik, no right reserved :-) */ - -void performBlur( - int blurSize, - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - float4 transformedPixel = (float4)0; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - int minDiff = -(blurSize - 1); - for (int dx = minDiff; dx < blurSize; dx++) { - for (int dy = minDiff; dy < blurSize; dy++) { - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx, y + dy)); - transformedPixel += pixel; - } - } - - int n = (2 * blurSize - 1); - n *= n; - - transformedPixel /= (float)n; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - const float matrix[] = { - 3.f, 0.f, -3.f, - 10.f, 0.f, -10.f, - 3.f, 0.f, -3.f, - }; - convolveImage(inputImage, matrix, 3, outputImage); -} - -// Perform a blur -__kernel void pass1(read_only image2d_t inputImage, write_only image2d_t outputImage) { - performBlur(10, inputImage, outputImage); -} - -/** - You can chain as many kernel calls as you want : - each new kernel takes the output of the previous one as input image. -*/ -/* -__kernel void pass2(read_only image2d_t inputImage, write_only image2d_t outputImage) { - performBlur(10, inputImage, outputImage); -} -*/ diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Convolution.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Convolution.cl deleted file mode 100644 index 6cb51dab3..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Convolution.cl +++ /dev/null @@ -1,45 +0,0 @@ -/** - Generic Convolution example with a 5x5 gaussian blur matrix. - This sample also shows how to chain two kernels, with a color to b&w conversion pass ready to be uncommented (see below). - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL's image convolution functions -// See sources here : http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" - -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float gaussian7x7Matrix[] = { - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00038771f, 0.01330373f, 0.11098164f, 0.22508352f, 0.11098164f, 0.01330373f, 0.00038771f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f -}; - - -__kernel void convolve( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - convolveFloatImage(inputImage, gaussian7x7Matrix, 7 /* matrixSize */, outputImage); -} - -// Uncomment this kernel to add a pass that transforms the image from color to gray levels : -/* -__kernel void toGray( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - float luminance = dot(pixel, (float4)(1, 1, 1, 0)) / 3; - write_imagef(outputImage, (int2)(x, y), (float4)(luminance, luminance, luminance, 1)); -} -*/ - diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl deleted file mode 100644 index dde70d526..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DesaturateColors.cl +++ /dev/null @@ -1,44 +0,0 @@ -/** - Color Desaturation example : make an image look more gray - Written by Olivier Chafik, no right reserved :-) */ - -void desaturate( - float greyFactor, - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // If the image is of type BGRA, UNormInt8, the pixel is in the form : - // (float4)(red, green, blue, alpha) with each component beinge [0.0f; 1.0f] interval. - - // Compute pixel luminance using a dot product, equivalent to the following two lines : - // float red = pixel.x, green = pixel.y, blue = pixel.z, alpha = pixel.w; - // float luminance = (red + green + blue) / 3; - float luminance = dot((float4)(1/3.f, 1/3.f, 1/3.f, 0), pixel); - - // Lower color saturation of pixel : - const float colorFactor = 1.f - greyFactor; - float4 transformedPixel = colorFactor * pixel + greyFactor * ((float4)(luminance, luminance, luminance, 1.f)); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - -__kernel void pass( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - desaturate(0.5f, inputImage, outputImage); -} - diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DummySample.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DummySample.cl deleted file mode 100644 index 2fb843052..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/DummySample.cl +++ /dev/null @@ -1,33 +0,0 @@ -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = - CLK_NORMALIZED_COORDS_FALSE | - CLK_FILTER_NEAREST | - CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - __read_only image2d_t inputImage, - __write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_data_type.html - int channelDataType = get_image_channel_data_type(inputImage); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_order.html - int channelOrder = get_image_channel_order(inputImage); - - int x = get_global_id(0); - int y = get_global_id(1); - int2 coordinates = (int2)(x, y); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, coordinates); - - float4 transformedPixel = (float4)(0);//pixel; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, coordinates, transformedPixel); -} - diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Identity.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Identity.cl deleted file mode 100644 index 295769ccb..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/Identity.cl +++ /dev/null @@ -1,32 +0,0 @@ -/** - Identity example : simply copy the input image into the output image. - Written by Olivier Chafik, no right reserved :-) */ - -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // If the image is of type BGRA / UNormInt8, each component is in the [0.0f; 1.0f] interval : - float red = pixel.x, green = pixel.y, blue = pixel.z, alpha = pixel.w; - - // Perform no transformation : - // float4 transformedPixel = pixel; - float4 transformedPixel = (float4)(red, green, blue, alpha); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, (int2)(x, y), transformedPixel); -} - - diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl deleted file mode 100644 index 4e417b294..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/LuminanceThreshold.cl +++ /dev/null @@ -1,33 +0,0 @@ -/** - Image luminance threshold example : hide pixels that are not bright enough (with gaussian smoothing) - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" -#include "LibCL/SobelOperator.cl" -#include "LibCL/Gaussian7x7.cl" - -__kernel void imageThreshold( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - // Get smoothed luminance (averaged from neighborhood with a gaussian) : - float luminance = convolveFloatImagePixelGray(inputImage, x, y, gaussian7x7Matrix, 7); - // Get exact local luminance : - // float luminance = dot((float4)(1/3.f, 1/3.f, 1/3.f, 0), pixel); - - float2 sobel = sobelOperatorRGBFloat(inputImage, x, y); - - float threshold = 0.3f; - if (luminance < threshold && (luminance * sobel.x) < threshold) - pixel.w = 0; // make these pixels transparent - - write_imagef(outputImage, (int2)(x, y), pixel); -} diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl deleted file mode 100644 index ff9087bfe..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/NaiveDenoising.cl +++ /dev/null @@ -1,52 +0,0 @@ -/** - Naive denoising sample : - Transform RGB to HSL, replace L channel by local average if the sobel operator's value is not too high and the pixel L value is not too different. - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" -#include "LibCL/SobelOperator.cl" -#include "LibCL/rgba2hsla.cl" -#include "LibCL/hsla2rgba.cl" - -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float gaussian7x7Matrix[] = { - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00038771f, 0.01330373f, 0.11098164f, 0.22508352f, 0.11098164f, 0.01330373f, 0.00038771f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f -}; - -__kernel void imageThreshold( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - float4 pixel = read_imagef(inputImage, sampler, (int2)(x, y)); - - float sobel = fabs(sobelOperatorRGBFloat(inputImage, x, y).x); - float sobelThreshold = 0.05f; - float averageThreshold = 0.07f; - - if (sobel < sobelThreshold) { - // Get smoothed pixel (averaged from neighborhood with a gaussian) : - float4 averagePixelHSLA = rgba2hsla(convolveFloatImagePixel(inputImage, x, y, gaussian7x7Matrix, 7)); - float4 pixelHSLA = rgba2hsla(pixel); - - pixelHSLA.x = averagePixelHSLA.x; // avoid chromatic aberrations : unconditionally replace Hue channel - - float4 d = fabs(pixelHSLA - averagePixelHSLA); - if (d.x < averageThreshold && d.y < averageThreshold && d.z < averageThreshold) - pixelHSLA.z = averagePixelHSLA.z; // replace Luminance channel by average if it's not too far away - - pixel = hsla2rgba(pixelHSLA); - } - - write_imagef(outputImage, (int2)(x, y), pixel); -} diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl deleted file mode 100644 index e70b9b8ae..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/QueryFormat.cl +++ /dev/null @@ -1,35 +0,0 @@ -/** - QueryFormat example : query image format dynamically inside the kernel - Written by Olivier Chafik, no right reserved :-) */ - -// See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/sampler_t.html -const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_dim.html - int2 dimensions = get_image_dim(inputImage); - int width = dimensions.x, height = dimensions.y; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_data_type.html - int channelDataType = get_image_channel_data_type(inputImage); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/get_image_channel_order.html - int channelOrder = get_image_channel_order(inputImage); - - int x = get_global_id(0), y = get_global_id(1); - int2 coordinates = (int2)(x, y); - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/read_imagef2d.html - //float4 pixel = read_imagef(inputImage, sampler, coordinates); - float4 pixel = read_imagef(inputImage, sampler, coordinates); - float4 transformedPixel = pixel; - //float4 transformedPixel = (float4)(0);//pixel; - - // See http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/write_image.html - write_imagef(outputImage, coordinates, transformedPixel); -} - - diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl deleted file mode 100644 index 1cac8ef3e..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/RichardsonLucyDeconvolution.cl +++ /dev/null @@ -1,40 +0,0 @@ -/** - Deconvolution sample that uses the Richardson-Lucy algorithm. - Knowing the exact "point-spread function" that made an image blurry, this algorithm tries to restore - the original image. - If the point-spread function is not well known, the results aren't good ! - - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/RichardsonLucyImageDeconvolution.cl" - -// Gaussian point-spread function : -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float pointSpreadFunction7x7[] = { - 0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067, - 0.00002292, 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292, - 0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117, - 0.00038771, 0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373, 0.00038771, - 0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117, - 0.00002292, 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292, - 0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067 -}; - -// Blur the initial image -/* -__kernel void blur(read_only image2d_t inputImage, write_only image2d_t outputImage) { - convolveFloatImage(inputImage, pointSpreadFunction7x7, 7, outputImage); -} -*/ - -RICHARDSON_LUCY_DECONVOLUTION_PRE(pointSpreadFunction7x7, 7); - -// Chain a few deconvolution passes : -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 1); -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 2); -RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 3); -//RICHARDSON_LUCY_DECONVOLUTION_PASS(pointSpreadFunction7x7, 7, 4); - -RICHARDSON_LUCY_DECONVOLUTION_POST(); diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl deleted file mode 100644 index aac5facd5..000000000 --- a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/examples/SobelFilter.cl +++ /dev/null @@ -1,45 +0,0 @@ -/** - Sobel filter example : naive edge detection - This sample includes Sobel and Scharr operators, please see below. - See http://en.wikipedia.org/wiki/Sobel_operator - Written by Olivier Chafik, no right reserved :-) */ - -// Import LibCL functions, which sources can be browsed here : -// http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/OpenCL/LibCL/src/main/resources#resources%2FLibCL -#include "LibCL/ImageConvolution.cl" - -__constant float2 sobel3x3MatrixXY[] = { - (float2)(-1, -1), (float2)(0, -2), (float2)(1, -1), - (float2)(-2, 0), (float2)(0, 0), (float2)(2, 0), - (float2)(-1, 1), (float2)(0, 2), (float2)(1, 1) -}; -__constant float2 scharr3x3MatrixXY[] = { - (float2)(3, 3), (float2)(0, 10), (float2)(-3, 3), - (float2)(10, 0), (float2)(0, 0), (float2)(-10, 0), - (float2)(3, -3), (float2)(0, -10), (float2)(-3, -3) -}; - -__kernel void test( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - float scaling = 0.3f; // you can adjust this - - // Sobel operator - float2 total = scaling * convolveFloatImagePixelGray2(inputImage, x, y, sobel3x3MatrixXY, 3); - - // Scharr operator (better rotational symmetry) : - // float2 total = scaling * convolveFloatImagePixelGray2(inputImage, x, y, scharr3x3MatrixXY, 3); - -#if 1 - float gradient = fast_length(total); - float value = gradient; -#else - float direction = atan2(total.y, total.x); - float value = direction; -#endif - - write_imagef(outputImage, (int2)(x, y), (float4)(value, value, value, 1.f)); -} diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/lena.jpg b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/lena.jpg deleted file mode 100644 index edac58885..000000000 Binary files a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/lena.jpg and /dev/null differ diff --git a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/mandrill.jpg b/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/mandrill.jpg deleted file mode 100644 index bf756e743..000000000 Binary files a/libraries/OpenCL/InteractiveImageDemo/src/main/resources/images/mandrill.jpg and /dev/null differ diff --git a/libraries/OpenCL/JavaCL-OSGi/pom.xml b/libraries/OpenCL/JavaCL-OSGi/pom.xml deleted file mode 100644 index 6029b9987..000000000 --- a/libraries/OpenCL/JavaCL-OSGi/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-osgi - JavaCL OSGi Bundle - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - bundle - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - ../.. - - - - - com.nativelibs4java - javacl-shaded - 1.0-SNAPSHOT - - - - org.osgi - org.osgi.core - 4.3.0 - provided - - - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - ${pom.groupId}.${pom.artifactId} - ${pom.name} - ${pom.version} - - com.nativelibs4java.opencl.OSGiBundleActivator - - - org.bridj.relocated.* - - - org.osgi.framework - - - com.nativelibs4java.opencl, - com.nativelibs4java.opencl.library, - com.nativelibs4java.opencl.util, - com.nativelibs4java.opencl.util.fft, - com.nativelibs4java.util, - com.ochafik.util.string, - - org.bridj, - org.bridj.ann, - org.bridj.cpp, - org.bridj.cpp.com, - org.bridj.cpp.com.shell, - org.bridj.demangling, - org.bridj.jawt, - org.bridj.objc, - org.bridj.dyncall, - org.bridj.util, - - org.bridj.lib.darwin_universal, - org.bridj.lib.linux_x64, - org.bridj.lib.linux_x86, - org.bridj.lib.sunos_x86, - org.bridj.lib.win32, - org.bridj.lib.win64 - - - - - - - - - - - - diff --git a/libraries/OpenCL/JavaCL-OSGi/src/main/java/com/nativelibs4java/opencl/OSGiBundleActivator.java b/libraries/OpenCL/JavaCL-OSGi/src/main/java/com/nativelibs4java/opencl/OSGiBundleActivator.java deleted file mode 100644 index 8125666db..000000000 --- a/libraries/OpenCL/JavaCL-OSGi/src/main/java/com/nativelibs4java/opencl/OSGiBundleActivator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.nativelibs4java.opencl; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -public class OSGiBundleActivator implements BundleActivator { - - public void start(BundleContext bundleContext) { - System.out.println("Starting JavaCL"); - } - - public void stop(BundleContext bundleContext) { - System.out.println("Stopping JavaCL"); - } -} diff --git a/libraries/OpenCL/JavaCL-Shaded/pom.xml b/libraries/OpenCL/JavaCL-Shaded/pom.xml deleted file mode 100644 index ea27e3464..000000000 --- a/libraries/OpenCL/JavaCL-Shaded/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-shaded - JavaCL Shaded - http://code.google.com/p/javacl/ - 1.0-SNAPSHOT - jar - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - ../.. - - - - false - - - - - com.nativelibs4java - javacl - 1.0-SNAPSHOT - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - diff --git a/libraries/OpenCL/JavaCL/.gitignore b/libraries/OpenCL/JavaCL/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/JavaCL/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/JavaCL/javacl-bridj.iml b/libraries/OpenCL/JavaCL/javacl-bridj.iml deleted file mode 100644 index 5977dbce3..000000000 --- a/libraries/OpenCL/JavaCL/javacl-bridj.iml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/JavaCL/javacl.iml b/libraries/OpenCL/JavaCL/javacl.iml deleted file mode 100644 index ccf617034..000000000 --- a/libraries/OpenCL/JavaCL/javacl.iml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/JavaCL/pom.xml b/libraries/OpenCL/JavaCL/pom.xml deleted file mode 100644 index 3d1404f39..000000000 --- a/libraries/OpenCL/JavaCL/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl - JavaCL / BridJ - http://code.google.com/p/javacl/ - jar - - - -JavaCL is an Object-Oriented API that makes the C OpenCL API available to Java in a very natural way. -It hides away the complexity of cross-platform C bindings, has a clean OO design (with generics, Java enums, NIO buffers, fully typed exceptions...), provides high-level features (OpenGL-interop, array reductions) and comes with samples and demos. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl-core - - - org.apache.commons - commons-math - 2.2 - test - - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun1.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun1.java deleted file mode 100644 index c7ea7947c..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun1.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - - -public enum Fun1 { - not("!"), - complement("~"), - abs, - log, - exp, - sqrt, - sin, - cos, - tan, - atan, - asin, - acos, - sinh, - cosh, - tanh, - asinh, - acosh, - atanh; - - final String prefixOp; - Fun1(String op) { - this.prefixOp = op; - } - Fun1() { - this(null); - } - void expr(String a, StringBuilder out) { - if (prefixOp != null) - out.append('(').append(prefixOp).append(a).append(')'); - out.append(name()).append('(').append(a).append(')'); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun2.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun2.java deleted file mode 100644 index 05db8c0e1..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Fun2.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - - -public enum Fun2 { - min, - max, - atan2, - dist, - modulo("%"), - rshift(">>"), - lshift("<<"), - xor("^"), - bitOr("|"), - bitAnd("&"), - add("+"), - substract("-"), - multiply("*"), - divide("/"); - - String infixOp; - Fun2() {} - Fun2(String infixOp) { - this.infixOp = infixOp; - } - void expr(String a, String b, StringBuilder out) { - if (infixOp == null) - out.append(name()).append('(').append(a).append(", ").append(b).append(")"); - else - out.append(a).append(' ').append(infixOp).append(' ').append(b); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java deleted file mode 100644 index a0afd2bbb..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/LinearAlgebraUtils.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.ReductionUtils; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.Pair; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unused") -public class LinearAlgebraUtils { - - final LinearAlgebraKernels kernels; - final CLQueue queue; - public LinearAlgebraUtils(boolean doubleCapable) throws IOException, CLBuildException { - this(JavaCL.createBestContext(doubleCapable ? DeviceFeature.DoubleSupport : null).createDefaultQueue()); - } - - public LinearAlgebraUtils(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - kernels = new LinearAlgebraKernels(queue.getContext()); - } - - public CLContext getContext() { - return getQueue().getContext(); - } - - public CLQueue getQueue() { - return queue; - } - - public synchronized CLEvent multiply( - CLBuffer a, int aRows, int aColumns, - CLBuffer b, int bRows, int bColumns, - CLBuffer out, //long outRows, long outColumns, - CLEvent... eventsToWaitFor) throws CLBuildException - { - if (a.getElementClass() == Double.class) - return multiplyDoubles((CLBuffer)a, aRows, aColumns, (CLBuffer)b, bRows, bColumns, (CLBuffer)out, eventsToWaitFor); - if (a.getElementClass() == Float.class) - return multiplyFloats((CLBuffer)a, aRows, aColumns, (CLBuffer)b, bRows, bColumns, (CLBuffer)out, eventsToWaitFor); - - throw new UnsupportedOperationException(); - } - public synchronized CLEvent multiplyDoubles( - CLBuffer a, int aRows, int aColumns, - CLBuffer b, int bRows, int bColumns, - CLBuffer out, //long outRows, long outColumns, - CLEvent... eventsToWaitFor) throws CLBuildException - { - if (a == null || b == null || out == null) - throw new IllegalArgumentException("Null matrix"); - - if (aColumns != bRows || out.getElementCount() != (aRows * bColumns)) - throw new IllegalArgumentException("Invalid matrix sizes : multiplying matrices of sizes (A, B) and (B, C) requires output of size (A, C)"); - - long outRows = aRows; - long outColumns = bColumns; - return kernels.mulMatDouble(queue, - a, (int)aColumns, - b, (int)bColumns, - out, - new int[] { (int)outRows, (int)outColumns }, - null, - eventsToWaitFor - ); - } - public synchronized CLEvent multiplyFloats( - CLBuffer a, long aRows, long aColumns, - CLBuffer b, long bRows, long bColumns, - CLBuffer out, //long outRows, long outColumns, - CLEvent... eventsToWaitFor) throws CLBuildException - { - long outRows = aRows; - long outColumns = bColumns; - return kernels.mulMatFloat(queue, - a, (int)aColumns, - b, (int)bColumns, - out, - new int[] { (int)outRows, (int)outColumns }, - null, - eventsToWaitFor - ); - } - Reductor addReductorDouble; - synchronized Reductor getAddReductorDouble() { - if (addReductorDouble == null) { - try { - addReductorDouble = ReductionUtils.createReductor(getContext(), ReductionUtils.Operation.Add, OpenCLType.Double, 1); - } catch (CLBuildException ex) { - Logger.getLogger(LinearAlgebraUtils.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to create an addition reductor !", ex); - } - } - return addReductorDouble; - } - - public synchronized CLEvent transposeDouble(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - return kernels.transposeDouble(queue, - a, aRows, aColumns, - out, - new int[] { (int)aColumns, (int)aRows }, - null, - eventsToWaitFor - ); - } - Reductor addReductorFloat; - synchronized Reductor getAddReductorFloat() { - if (addReductorFloat == null) { - try { - addReductorFloat = ReductionUtils.createReductor(getContext(), ReductionUtils.Operation.Add, OpenCLType.Float, 1); - } catch (CLBuildException ex) { - Logger.getLogger(LinearAlgebraUtils.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to create an addition reductor !", ex); - } - } - return addReductorFloat; - } - - public synchronized CLEvent transpose(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - if (a.getElementClass() == Double.class) - return transposeDoubles((CLBuffer)a, aRows, aColumns, (CLBuffer)out, eventsToWaitFor); - if (a.getElementClass() == Float.class) - return transposeFloats((CLBuffer)a, aRows, aColumns, (CLBuffer)out, eventsToWaitFor); - - throw new UnsupportedOperationException(); - } - - public synchronized CLEvent transposeFloats(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - return kernels.transposeFloat(queue, - a, aRows, aColumns, - out, - new int[] { (int)aColumns, (int)aRows }, - null, - eventsToWaitFor - ); - } - - - public synchronized CLEvent transposeDoubles(CLBuffer a, int aRows, int aColumns, CLBuffer out, CLEvent... eventsToWaitFor) throws CLBuildException { - return kernels.transposeDouble(queue, - a, aRows, aColumns, - out, - new int[] { (int)aColumns, (int)aRows }, - null, - eventsToWaitFor - ); - } - - -} diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java deleted file mode 100644 index 8d0faca23..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/OpenCLType.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -public enum OpenCLType { - Int(Integer.class), Char(Character.class), Long(Long.class), Short(Short.class), Byte(Byte.class), Double(Double.class), Float(Float.class), Half(null); - - OpenCLType(Class type) { - this.type = type; - } - public final Class type; - - public String toCType() { - if (this == Byte) - return "char"; - if (this == Char) - return "short"; - return name().toLowerCase(); - } - public static OpenCLType fromClass(Class valueType) { - if (valueType == Integer.TYPE || valueType == Integer.class) - return Int; - if (valueType == java.lang.Long.TYPE || valueType == Long.class) - return Long; - if (valueType == java.lang.Short.TYPE || valueType == Short.class) - return Short; - if (valueType == java.lang.Double.TYPE || valueType == Double.class) - return Double; - if (valueType == java.lang.Float.TYPE || valueType == Float.class) - return Float; - if (valueType == java.lang.Byte.TYPE || valueType == Byte.class) - return Byte; - - if (!valueType.isPrimitive()) - throw new IllegalArgumentException("Value type is not a primitive: '" + valueType.getName() + "' !"); - - throw new IllegalArgumentException("Primitive type not handled: '" + valueType.getName() + "' !"); - } -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java deleted file mode 100644 index f1a754e12..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelMath.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLKernel; -import com.nativelibs4java.opencl.CLProgram; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.util.ReductionUtils; -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.Pair; -import static com.nativelibs4java.util.NIOUtils.*; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author ochafik - */ -@SuppressWarnings("unused") -public class ParallelMath { - - protected CLContext context; - protected CLQueue queue; - - public ParallelMath() { - this(JavaCL.createBestContext().createDefaultQueue()); - } - - public ParallelMath(CLQueue queue) { - this.queue = queue; - CLContext context = queue.getContext(); - } - - public CLQueue getQueue() { - return queue; - } - - public CLContext getContext() { - return getQueue().getContext(); - } - - protected String createVectFun1Source(Fun1 function, Primitive type, StringBuilder out) { - String t = type.clTypeName(); - String kernelName = "vect_" + function.name() + "_" + t;// + (inPlace ? "_inplace" : ""); - out.append("__kernel void " + kernelName + "(\n"); - out.append("\t__global const " + t + "* in,\n"); - out.append("\t__global " + t + "* out,\n"); - out.append("\tlong length\n"); - out.append(") {\n"); - out.append("\tint i = get_global_id(0);\n"); - out.append("\tif (i >= length) return;\n"); - out.append("\tout[i] = "); - function.expr("in[i]", out); - out.append(";\n"); - out.append("}\n"); - return kernelName; - } - - - protected String createVectFun2Source(Fun2 function, Primitive type1, Primitive type2, Primitive typeOut, StringBuilder out, boolean secondOperandIsScalar) { - String t1 = type1.clTypeName(), t2 = type2.clTypeName(), to = typeOut.clTypeName(); - String kernelName = "vect_" + function.name() + "_" + t1 + "_" + t2 + "_" + to; - out.append("__kernel void " + kernelName + "(\n"); - out.append("\t__global const " + t1 + "* in1,\n"); - if (secondOperandIsScalar) - out.append("\t" + t2 + " in2,\n"); - else - out.append("\t__global const " + t2 + "* in2,\n"); - out.append("\t__global " + to + "* out,\n"); - out.append("\tlong length\n"); - out.append(") {\n"); - out.append("\tint i = get_global_id(0);\n"); - out.append("\tif (i >= length) return;\n"); - out.append("\tout[i] = (" + to + ")"); - function.expr("in1[i]", (secondOperandIsScalar ? "in2" : "in2[i]"), out); - out.append(";\n"); - out.append("}\n"); - return kernelName; - } - - - private EnumMap> fun1Kernels = new EnumMap>(Fun1.class); - - - public synchronized CLKernel getKernel(Fun1 op, Primitive prim) throws CLBuildException { - EnumMap m = fun1Kernels.get(op); - if (m == null) - fun1Kernels.put(op, m = new EnumMap(Primitive.class)); - - CLKernel kers = m.get(prim); - if (kers == null) { - StringBuilder out = new StringBuilder(300); - String name = createVectFun1Source(op, prim, out); - CLProgram prog = getContext().createProgram(out.toString()).build(); - kers = prog.createKernel(name); - m.put(prim, kers); - } - return kers; - } - - static class PrimitiveTrio extends Pair, Pair> { - public PrimitiveTrio(Primitive a, Primitive b, Primitive c, boolean secondOperandIsScalar) { - super(new Pair(a, b), new Pair(c, secondOperandIsScalar)); - } - } - private EnumMap> fun2Kernels = new EnumMap>(Fun2.class); - public synchronized CLKernel getKernel(Fun2 op, Primitive prim, boolean secondOperandIsScalar) throws CLBuildException { - return getKernel(op, prim, prim, prim, secondOperandIsScalar); - } - - public synchronized CLKernel getKernel(Fun2 op, Primitive prim1, Primitive prim2, Primitive primOut, boolean secondOperandIsScalar) throws CLBuildException { - Map m = fun2Kernels.get(op); - if (m == null) - fun2Kernels.put(op, m = new HashMap()); - - PrimitiveTrio key = new PrimitiveTrio(prim1, prim2, primOut, secondOperandIsScalar); - CLKernel ker = m.get(key); - if (ker == null) { - StringBuilder out = new StringBuilder(300); - String name = createVectFun2Source(op, prim1, prim2, primOut, out, secondOperandIsScalar); - CLProgram prog = getContext().createProgram(out.toString()).build(); - ker = prog.createKernel(name); - m.put(key, ker); - } - return ker; - } - -} diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java deleted file mode 100644 index ffd884688..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ParallelRandom.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import java.io.IOException; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.opencl.CLMem.Usage; - -/** - * Parallel Random numbers generator (Xorshift adapted to work in parallel).
      - * This class was designed as a drop-in replacement for java.util.Random (albeit with a more limited API) : - *
      {@code
      - * ParallelRandom r = new ParallelRandom();
      - * r.setPreload(true); // faster
      - * while (true) {
      - *     System.out.println(r.nextDouble());
      - * }
      - * }
      - *
      - * It is also possible to get entire batches of random integers with {@link ParallelRandom#next()} or {@link ParallelRandom#next(Pointer)}.
      - * The preload feature precomputes a new batch in background as soon as one starts to consume numbers from the current batch. - * @author ochafik - */ -public class ParallelRandom { - - protected final XORShiftRandom randomProgram; - //private final IntBuffer outputBuffer; - //private IntBuffer mappedOutputBuffer; - protected final CLQueue queue; - protected final CLContext context; - protected final int parallelSize; - protected final int[] globalWorkSizes; - - protected int consumedInts = 0; - - boolean preload; - CLEvent preloadEvent; - protected CLBuffer seeds, output; - Pointer lastData; - boolean isDataFresh; - - public ParallelRandom() throws IOException { - this(JavaCL.createBestContext().createDefaultQueue(), 32 * 1024, System.currentTimeMillis()); - } - public ParallelRandom(CLQueue queue, int parallelSize, final long seed) throws IOException { - try { - this.queue = queue; - this.context = queue.getContext(); - randomProgram = new XORShiftRandom(context); - this.parallelSize = parallelSize; - - int seedsNeededByWorkItem = 4; - //int generatedNumbersByWorkItemIteration = 1; - int maxUnits = queue.getDevice().getMaxComputeUnits(); - int unitsFactor = maxUnits < 10 ? 1 : 16; - int scheduledWorkItems = maxUnits * unitsFactor; - //int countByWorkItem = parallelSize / scheduledWorkItems; - if (scheduledWorkItems > parallelSize / seedsNeededByWorkItem) { - scheduledWorkItems = parallelSize / seedsNeededByWorkItem; - scheduledWorkItems += parallelSize % seedsNeededByWorkItem; - } - //int iterationsByWorkItem = parallelCount / (generatedNumbersByWorkItemIteration * scheduledWorkItems); - globalWorkSizes = new int[] { scheduledWorkItems }; - - //int lws = 1;//(int)queue.getDevice().getMaxWorkGroupSize(); - //if (lws > 32) - // lws = 32; - //localWorkSizes = new int[] { lws }; - - randomProgram.getProgram().defineMacro("NUMBERS_COUNT", parallelSize); - randomProgram.getProgram().defineMacro("WORK_ITEMS_COUNT", scheduledWorkItems); - - final int nSeeds = seedsNeededByWorkItem * parallelSize; - final Pointer seedsBuf = allocateInts(nSeeds).order(context.getKernelsDefaultByteOrder()); - initSeeds(seedsBuf, seed); - //println(seedsBuf); - this.seeds = context.createBuffer(Usage.InputOutput, seedsBuf, true); - //this.lastOutputData = NIOUtils.directInts(parallelSize, context.getKernelsDefaultByteOrder()); - this.output = context.createBuffer(Usage.Output, Integer.class, parallelSize); - } catch (InterruptedException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to initialized parallel random", ex); - } - } - - static final int floatMask = 0x00ffffff; - static final double floatDivid = (1 << 24); - //static final int mask = (1 << 30) - 1; - //static final double divid = (1 << 30); - - public int nextInt() { - waitForData(1); - return lastData.get(consumedInts++); - } - - /** - * If true, a new batch of parallel random numbers is automatically precomputed in background as soon as one starts to consume numbers from the current batch (this gives faster random numbers, at the risk of computing more values than needed) - */ - public synchronized boolean isPreload() { - return preload; - } - /** - * If true, a new batch of parallel random numbers is automatically precomputed in background as soon as one starts to consume numbers from the current batch (this gives faster random numbers, at the risk of computing more values than needed) - */ - public synchronized void setPreload(boolean preload) throws CLBuildException { - this.preload = preload; - if (preload && preloadEvent == null) { - if (lastData == null) { - preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null); - } else if (consumedInts > 0) { - preload(); - } - } - } - private synchronized CLEvent preload() throws CLBuildException { - return preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null, preloadEvent); - } - private synchronized void waitForData(int n) { - try { - if (lastData == null) { - //lastOutputData = NIOUtils.directInts(parallelSize, context.getKernelsDefaultByteOrder()); - if (preloadEvent == null) - preloadEvent = randomProgram.gen_numbers(queue, seeds, output, globalWorkSizes, null); - - readLastOutputData(); - } - if (consumedInts > parallelSize - n) { - preload().waitFor(); - consumedInts = 0; - readLastOutputData(); - } - if (preload && preloadEvent == null) - preload(); - } catch (CLBuildException ex) { - throw new RuntimeException(ex); - } - } - private synchronized void readLastOutputData() { - if (lastData == null) - lastData = output.read(queue, preloadEvent); - else - output.read(queue, lastData, true, preloadEvent); - preloadEvent = null; - } - public long nextLong() { - return (((long)nextInt()) << 32) | nextInt(); - } - - private static final int intSignMask = 1 << 31; - public int nextInt(int n) { - if (n <= 0) - throw new IllegalArgumentException("n must be positive"); - - if ((n & -n) == n) // i.e., n is a power of 2 - return (int)((n * (long)(nextInt() & intSignMask)) >> 31); - - int bits, val; - do { - bits = nextInt() & intSignMask; - val = bits % n; - } while (bits - val + (n-1) < 0); - return val; - } - - public float nextFloat() { - return (float)((nextInt() & floatMask) / floatDivid); - } - - private static final int doubleMask = (1 << 27) - 1; - private static final double doubleDivid = 1L << 53; - - public double nextDouble() { - return (((long)(nextInt() & doubleMask) << 27) | (nextInt() & doubleMask)) / doubleDivid; - } - - public CLBuffer getSeeds() { - return seeds; - } - public CLQueue getQueue() { - return queue; - } - - /** - * Number of random numbers generated at each call of {@link ParallelRandom#next() } or {@link ParallelRandom#next(Pointer) }
      - * The numbers might not all be generated exactly in parallel, the level of parallelism is implementation-dependent. - * @return size of each buffer returned by {@link ParallelRandom#next() } - */ - public int getParallelSize() { - return parallelSize; - } - - public synchronized CLEvent doNext() { - try { - //if (mappedOutputBuffer != null) { - // //output.unmap(queue, mappedOutputBuffer); - // mappedOutputBuffer = null; - //} - return randomProgram.gen_numbers(queue, seeds, //parallelSize, - output, globalWorkSizes, null); - } catch (CLBuildException ex) { - Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to compile the random number generation routine", ex); - } - } - - /** - * Copies the next {@link ParallelRandom#getParallelSize() } random integers in the provided output buffer - * @param output - */ - public synchronized void next(Pointer output) { - CLEvent evt = doNext(); - this.output.read(queue, output, true, evt); - } - - - /** - * Returns a direct NIO buffer containing the next {@link ParallelRandom#getParallelSize() } random integers.
      - * This buffer is read only and will only be valid until any of the "next" method is called again. - * @return output buffer of capacity ; see {@link ParallelRandom#getParallelSize() } - */ - public synchronized Pointer next() { - CLEvent evt = doNext(); - //queue.finish(); evt = null; - //return outputBuffer; - //return (mappedOutputBuffer = output.map(queue, MapFlags.Read, evt)).asReadOnlyBuffer(); - return output.read(queue, evt); - } - - private void initSeeds(final Pointer seedsBuf, final long seed) throws InterruptedException { - final long nSeeds = seedsBuf.getValidElements(); - - long start = System.nanoTime(); - - // TODO benchmark threshold : - boolean parallelize = nSeeds > 10000; - //parallelize = false; - if (parallelize) { - Random random = new Random(seed); - for (long i = nSeeds; i-- != 0;) - seedsBuf.set(i, random.nextInt()); - } else { - // Parallelize seeds initialization - final int nThreads = Runtime.getRuntime().availableProcessors();// * 2; - ExecutorService service = Executors.newFixedThreadPool(nThreads); - for (int i = 0; i < nThreads; i++) { - final int iThread = i; - service.execute(new Runnable() { - - public void run() { - long n = nSeeds / nThreads; - long offset = n * iThread; - Random random = new Random(seed + iThread);// * System.currentTimeMillis()); - if (iThread == nThreads - 1) - n += nSeeds - n * nThreads; - - for (long i = n; i-- != 0;) - seedsBuf.set(offset++, random.nextInt()); - } - }); - } - service.shutdown(); - service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); - } - - long time = System.nanoTime() - start; - Logger.getLogger(ParallelRandom.class.getName()).log(Level.INFO, "Initialization of " + nSeeds + " seeds took " + (time/1000000) + " ms (" + (time / (double)nSeeds) + " ns per seed)"); - } -} diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Primitive.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Primitive.java deleted file mode 100644 index 81518f647..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Primitive.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -public enum Primitive { - Float(Float.class, 1, OpenCLType.Float), - Double(Double.class, 1, OpenCLType.Double), - Long(Long.class, 1, OpenCLType.Long), - Int(Integer.class, 1, OpenCLType.Int), - Short(Short.class, 1, OpenCLType.Short), - Byte(Byte.class, 1, OpenCLType.Byte), - - Float2(Float.class, 2, OpenCLType.Float), - Double2(Double.class, 2, OpenCLType.Double), - Long2(Long.class, 2, OpenCLType.Long), - Int2(Integer.class, 2, OpenCLType.Int), - Short2(Short.class, 2, OpenCLType.Short), - Byte2(Byte.class, 2, OpenCLType.Byte), - - Float3(Float.class, 3, OpenCLType.Float), - Double3(Double.class, 3, OpenCLType.Double), - Long3(Long.class, 3, OpenCLType.Long), - Int3(Integer.class, 3, OpenCLType.Int), - Short3(Short.class, 3, OpenCLType.Short), - Byte3(Byte.class, 3, OpenCLType.Byte), - - Float4(Float.class, 4, OpenCLType.Float), - Double4(Double.class, 4, OpenCLType.Double), - Long4(Long.class, 4, OpenCLType.Long), - Int4(Integer.class, 4, OpenCLType.Int), - Short4(Short.class, 4, OpenCLType.Short), - Byte4(Byte.class, 4, OpenCLType.Byte), - - Float8(Float.class, 8, OpenCLType.Float), - Double8(Double.class, 8, OpenCLType.Double), - Long8(Long.class, 8, OpenCLType.Long), - Int8(Integer.class, 8, OpenCLType.Int), - Short8(Short.class, 8, OpenCLType.Short), - Byte8(Byte.class, 8, OpenCLType.Byte), - - Float16(Float.class, 16, OpenCLType.Float), - Double16(Double.class, 16, OpenCLType.Double), - Long16(Long.class, 16, OpenCLType.Long), - Int16(Integer.class, 16, OpenCLType.Int), - Short16(Short.class, 16, OpenCLType.Short), - Byte16(Byte.class, 16, OpenCLType.Byte); - - Primitive(Class primitiveType, int primitiveCount, OpenCLType oclType) { - this.primitiveCount = primitiveCount; - this.primitiveType = primitiveType; - this.oclType = oclType; - } - public final OpenCLType oclType; - public final int primitiveCount; - public final Class primitiveType; - public String clTypeName() { - return name().toLowerCase(); - } - public String getRequiredPragmas() { - if (primitiveType == Double.class) - return "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"; - return ""; - } -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java deleted file mode 100644 index 2cad32740..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/ReductionUtils.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.*; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.Buffer; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.nativelibs4java.util.IOUtils; -import com.nativelibs4java.util.Pair; - -import org.bridj.Pointer; -import org.bridj.Platform; -import static org.bridj.Pointer.*; - -/** - * Parallel reduction utils (max, min, sum and product computations on OpenCL buffers of any type) - * @author Olivier - */ -public class ReductionUtils { - static final int DEFAULT_MAX_REDUCTION_SIZE = 4; - - static String source; - static final String sourcePath = ReductionUtils.class.getPackage().getName().replace('.', '/') + "/" + "Reduction.c"; - static synchronized String getSource() throws IOException { - InputStream in = Platform.getClassLoader(ReductionUtils.class).getResourceAsStream(sourcePath); - if (in == null) - throw new FileNotFoundException(sourcePath); - return source = IOUtils.readText(in); - } - - public enum Operation { - Add, - Multiply, - Min, - Max; - } - - public static Pair> getReductionCodeAndMacros(Operation op, OpenCLType valueType, int channels) throws IOException { - Map macros = new LinkedHashMap(); - String cType = valueType.toCType() + (channels == 1 ? "" : channels); - macros.put("OPERAND_TYPE", cType); - String operation, seed; - switch (op) { - case Add: - operation = "_add_"; - seed = "0"; - break; - case Multiply: - operation = "_mul_"; - seed = "1"; - break; - case Min: - operation = "_min_"; - switch (valueType) { - case Int: - seed = Integer.MAX_VALUE + ""; - break; - case Long: - seed = Long.MAX_VALUE + "LL"; - break; - case Short: - seed = Short.MAX_VALUE + ""; - break; - case Float: - seed = "MAXFLOAT"; - break; - case Double: - seed = "MAXDOUBLE"; - break; - default: - throw new IllegalArgumentException("Unhandled seed type: " + valueType); - } - - break; - case Max: - operation = "_max_"; - switch (valueType) { - case Int: - seed = Integer.MIN_VALUE + ""; - break; - case Long: - seed = Long.MIN_VALUE + "LL"; - break; - case Short: - seed = Short.MIN_VALUE + ""; - break; - case Float: - seed = "-MAXFLOAT"; - break; - case Double: - seed = "-MAXDOUBLE"; - break; - default: - throw new IllegalArgumentException("Unhandled seed type: " + valueType); - } - break; - default: - throw new IllegalArgumentException("Unhandled operation: " + op); - } - macros.put("OPERATION", operation); - macros.put("SEED", seed); - return new Pair>(getSource(), macros); - } - public interface Reductor { - /** Number of independent channels of the reductor */ - public int getChannels(); - public CLEvent reduce(CLQueue queue, CLBuffer input, long inputLength, CLBuffer output, int maxReductionSize, CLEvent... eventsToWaitFor); - public Pointer reduce(CLQueue queue, CLBuffer input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor); - public CLEvent reduce(CLQueue queue, CLBuffer input, long inputLength, Pointer output, int maxReductionSize, CLEvent... eventsToWaitFor); - /** - * Return the result of the reduction operation (with one value per channel). - */ - public Pointer reduce(CLQueue queue, CLBuffer input, CLEvent... eventsToWaitFor); - - } - /*public interface WeightedReductor { - public CLEvent reduce(CLQueue queue, CLBuffer input, CLBuffer weights, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor); - public CLEvent reduce(CLQueue queue, CLBuffer input, CLBuffer weights, long inputLength, CLBuffer output, int maxReductionSize, CLEvent... eventsToWaitFor); - }*/ - static int getNextPowerOfTwo(int i) { - int shifted = 0; - boolean lost = false; - for (;;) { - int next = i >> 1; - if (next == 0) { - if (lost) - return 1 << (shifted + 1); - else - return 1 << shifted; - } - lost = lost || (next << 1 != i); - shifted++; - i = next; - } - } - - /** - * Create a reductor for the provided operation and primitive type (on the provided number of independent channels).
      - * Channels are reduced independently, so that with 2 channels the max of elements { (1, 30), (2, 20), (3, 10) } would be (3, 30). - */ - public static Reductor createReductor(final CLContext context, Operation op, final OpenCLType valueType, final int valueChannels) throws CLBuildException { - try { - - - Pair> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels); - CLProgram program = context.createProgram(codeAndMacros.getFirst()); - program.defineMacros(codeAndMacros.getValue()); - program.build(); - CLKernel[] kernels = program.createKernels(); - if (kernels.length != 1) - throw new RuntimeException("Expected 1 kernel, found : " + kernels.length); - final CLKernel kernel = kernels[0]; - return new Reductor() { - @Override - public int getChannels() { - return valueChannels; - } - @SuppressWarnings("unchecked") - public CLEvent reduce(CLQueue queue, CLBuffer input, long inputLength, Pointer output, int maxReductionSize, CLEvent... eventsToWaitFor) { - Pair, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, maxReductionSize, eventsToWaitFor); - return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond()); - } - @Override - public Pointer reduce(CLQueue queue, CLBuffer input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) { - Pointer output = Pointer.allocateArray((Class)valueType.type, valueChannels).order(context.getByteOrder()); - CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor); - //queue.finish(); - //TODO - evt.waitFor(); - return output; - } - @Override - public Pointer reduce(CLQueue queue, CLBuffer input, CLEvent... eventsToWaitFor) { - return reduce(queue, input, input.getElementCount(), DEFAULT_MAX_REDUCTION_SIZE, eventsToWaitFor); - } - @Override - public CLEvent reduce(CLQueue queue, CLBuffer input, long inputLength, CLBuffer output, int maxReductionSize, CLEvent... eventsToWaitFor) { - Pair, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, maxReductionSize, eventsToWaitFor); - return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond()); - } - @SuppressWarnings("unchecked") - public Pair, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer input, int inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) { - if (inputLength == 1) { - return new Pair, CLEvent[]>(input, new CLEvent[0]); - } - if (inputLength == 1) { - return new Pair, CLEvent[]>(input, new CLEvent[0]); - } - CLBuffer[] tempBuffers = new CLBuffer[2]; - int depth = 0; - CLBuffer currentOutput = null; - CLEvent[] eventsArr = new CLEvent[1]; - int[] blockCountArr = new int[1]; - - int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0]; - - while (inputLength > 1) { - int blocksInCurrentDepth = inputLength / maxReductionSize; - if (inputLength > blocksInCurrentDepth * maxReductionSize) - blocksInCurrentDepth++; - - int iOutput = depth & 1; - CLBuffer currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1]; - currentOutput = (CLBuffer)tempBuffers[iOutput]; - if (currentOutput == null) - currentOutput = (CLBuffer)(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, valueType.type, blocksInCurrentDepth * valueChannels)); - - synchronized (kernel) { - kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput); - int workgroupSize = blocksInCurrentDepth; - if (workgroupSize == 1) - workgroupSize = 2; - blockCountArr[0] = workgroupSize; - eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor); - } - eventsToWaitFor = eventsArr; - inputLength = blocksInCurrentDepth; - depth++; - } - return new Pair, CLEvent[]>(currentOutput, eventsToWaitFor); - } - - }; - } catch (IOException ex) { - Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex); - throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex); - } - } -} diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java deleted file mode 100644 index c747b52f3..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/Transformer.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.CLBuffer; -import com.nativelibs4java.opencl.CLBuildException; -import com.nativelibs4java.opencl.CLContext; -import com.nativelibs4java.opencl.CLEvent; -import com.nativelibs4java.opencl.CLException; -import com.nativelibs4java.opencl.CLMem; -import com.nativelibs4java.opencl.CLQueue; -import com.nativelibs4java.util.NIOUtils; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; - -import org.bridj.*; -import static org.bridj.Pointer.*; - -/** - * Generic homogeneous transformer class - * @author ochafik - * @param primitive array class that represents the data consumed and produced by this transformer - */ -public interface Transformer { - CLContext getContext(); - A transform(CLQueue queue, A input, boolean inverse); - //B transform(CLQueue queue, B input, boolean inverse); - Pointer transform(CLQueue queue, Pointer input, boolean inverse); - CLEvent transform(CLQueue queue, CLBuffer input, CLBuffer output, boolean inverse, CLEvent... eventsToWaitFor) throws CLException; - long computeOutputSize(long inputSize); - - public abstract class AbstractTransformer implements Transformer { - protected final Class primitiveClass; - protected final CLContext context; - - public AbstractTransformer(CLContext context, Class primitiveClass) { - this.primitiveClass = primitiveClass; - this.context = context; - } - - public CLContext getContext() { return context; } - - public long computeOutputSize(long inputSize) { - return inputSize; - } - - - public A transform(CLQueue queue, A input, boolean inverse) { - return (A)transform(queue, (Pointer)pointerToArray(input), inverse).getArray(); - } - public Pointer transform(CLQueue queue, Pointer in, boolean inverse) { - long inputSize = (int)in.getValidElements(); - long length = inputSize / 2; - - CLBuffer inBuf = context.createBuffer(CLMem.Usage.Input, in, true); // true = copy - CLBuffer outBuf = context.createBuffer(CLMem.Usage.Output, primitiveClass, computeOutputSize(inputSize)); - - CLEvent dftEvt = transform(queue, inBuf, outBuf, inverse); - inBuf.release(); - - Pointer out = outBuf.read(queue, dftEvt); - outBuf.release(); - return out; - } - - } -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java deleted file mode 100644 index 5d951e3b4..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractDFT.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import java.io.IOException; -import java.nio.Buffer; - -abstract class AbstractDFT extends AbstractTransformer { - - // package-private constructor - AbstractDFT(CLContext context, Class primitiveClass) throws IOException, CLException { - super(context, primitiveClass); - } - protected abstract CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException; - - @Override - public CLEvent transform(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - int length = (int)inBuf.getElementCount() / 2; - return dft(queue, inBuf, outBuf, length, inverse ? -1 : 1, new int[]{length}, eventsToWaitFor); - } - } \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java deleted file mode 100644 index ed457af0f..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/AbstractFFTPow2.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import com.nativelibs4java.util.NIOUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bridj.*; -import static org.bridj.Pointer.*; - -// TODO implement something like http://locklessinc.com/articles/non_power_of_2_fft/ -abstract class AbstractFFTPow2 extends AbstractTransformer { - - AbstractFFTPow2(CLContext context, Class primitiveClass) { - super(context, primitiveClass); - } - - private Map> cachedOffsetsBufs = new HashMap>(); - protected synchronized CLBuffer getOffsetsBuf(int length) { - CLBuffer offsetsBuf = cachedOffsetsBufs.get(length); - if (offsetsBuf == null) { - int[] offsets = new int[length]; - fft_compute_offsetsX(offsets, length, 1, 0, 0); - - offsetsBuf = context.createBuffer(CLMem.Usage.InputOutput, pointerToInts(offsets), true); - cachedOffsetsBufs.put(length, offsetsBuf); - } - return offsetsBuf; - } - protected abstract CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException ; - protected abstract CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException; - protected abstract CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException; - - Map> cachedTwiddleFactors = new HashMap>(); - protected synchronized CLBuffer getTwiddleFactorsBuf(CLQueue queue, int N) throws CLException { - CLBuffer buf = cachedTwiddleFactors.get(N); - if (buf == null) { - int halfN = N / 2; - buf = context.createBuffer(CLMem.Usage.InputOutput, primitiveClass, N); - CLEvent.waitFor(cooleyTukeyFFTTwiddleFactors(queue, N, buf)); - cachedTwiddleFactors.put(N, buf); - } - return buf; - } - private void fft_compute_offsetsX(int[] offsetsX, int N, int s, int offsetX, int offsetY) { - if (N == 1) { - offsetsX[offsetY] = offsetX; - } else { - int halfN = N / 2; - int twiceS = s * 2; - fft_compute_offsetsX(offsetsX, halfN, twiceS, offsetX, offsetY); - fft_compute_offsetsX(offsetsX, halfN, twiceS, offsetX + s, offsetY + halfN); - } - } - - @Override - public CLEvent transform(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - int length = (int)inBuf.getElementCount() / 2; - if (Integer.bitCount(length) != 1) - throw new UnsupportedOperationException("Only supports FFTs of power-of-two-sized arrays (was given array of length " + length + ")"); - - CLBuffer offsetsBuf = getOffsetsBuf(length); - CLEvent copyEvt = cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse, eventsToWaitFor); - CLEvent dftEvt = fft(queue, inBuf, length, 1, inverse ? 1 : 0, 1, outBuf, copyEvt); - return dftEvt; - } - private CLEvent fft(CLQueue queue, CLBuffer X, int N, int s, int inverse, int blocks, CLBuffer Y, CLEvent... eventsToWaitFor) throws CLException { - if (N == 1) { - return null; - } else { - int halfN = N / 2; - int twiceS = s * 2; - - CLEvent[] evts; - if (halfN > 1) { - evts = new CLEvent[] { fft(queue, X, halfN, twiceS, inverse, blocks * 2, Y, eventsToWaitFor) }; - } else { - evts = eventsToWaitFor; - } - - return cooleyTukeyFFT(queue, Y, N, getTwiddleFactorsBuf(queue, N), inverse, new int[] { halfN, blocks }, evts); - } - } - - } - diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java deleted file mode 100644 index 1c9ddde58..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleDFT.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.nio.DoubleBuffer; - -/** - * Slow OpenCL Fourier Transform that works in all cases (double precision floating point numbers) - */ -public class DoubleDFT extends AbstractDFT { - - final DoubleDFTProgram program; - - public DoubleDFT(CLContext context) throws IOException { - super(context, Double.class); - this.program = new DoubleDFTProgram(context); - } - public DoubleDFT() throws IOException { - this(JavaCL.createBestContext(DeviceFeature.DoubleSupport)); - } - - @Override - protected CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException { - return program.dft(queue, (CLBuffer)inBuf, (CLBuffer)outBuf, length, sign, dims, null, events); - } - } diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java deleted file mode 100644 index f7c5f70e6..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/DoubleFFTPow2.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.nio.DoubleBuffer; - -/** - * OpenCL Fast Fourier Transform for array sizes that are powers of two (double precision floating point numbers) - */ -public class DoubleFFTPow2 extends AbstractFFTPow2 { - - final DoubleFFTProgram program; - - public DoubleFFTPow2(CLContext context) throws IOException, CLException { - super(context, Double.class); - this.program = new DoubleFFTProgram(context); - program.getProgram().setFastRelaxedMath(); - } - public DoubleFFTPow2() throws IOException { - this(JavaCL.createBestContext(DeviceFeature.DoubleSupport)); - } - - protected CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTTwiddleFactors(queue, N, buf, new int[] { N / 2 }, null, evts); - } - protected CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse ? 1.0 / length : 1, new int[] { length }, null, evts); - } - protected CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFT(queue, Y, N, twiddleFactors, inverse, dims, null, evts); - } - } - diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java deleted file mode 100644 index e043ffa72..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatDFT.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.util.*; -import java.io.File; -import java.io.IOException; -import java.nio.FloatBuffer; - -/** - * Slow OpenCL Fourier Transform that works in all cases (simple precision floating point numbers) - */ -public class FloatDFT extends AbstractDFT { - - final FloatDFTProgram program; - - public FloatDFT(CLContext context) throws IOException, CLException { - super(context, Float.class); - program = new FloatDFTProgram(context); - } - public FloatDFT() throws IOException { - this(JavaCL.createBestContext()); - } - - @Override - protected CLEvent dft(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, int sign, int[] dims, CLEvent... events) throws CLException { - return program.dft(queue, inBuf, outBuf, length, sign, dims, null, events); - } -} diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java deleted file mode 100644 index 4207c7098..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/FloatFFTPow2.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.nativelibs4java.opencl.util.fft; - -import com.nativelibs4java.opencl.*; -import java.io.IOException; -import java.nio.FloatBuffer; - -/** - * OpenCL Fast Fourier Transform for array sizes that are powers of two (simple precision floating point numbers) - */ -public class FloatFFTPow2 extends AbstractFFTPow2 { - - final FloatFFTProgram program; - - public FloatFFTPow2(CLContext context) throws IOException { - super(context, Float.class); - this.program = new FloatFFTProgram(context); - program.getProgram().setFastRelaxedMath(); - } - public FloatFFTPow2() throws IOException { - this(JavaCL.createBestContext()); - } - - protected CLEvent cooleyTukeyFFTTwiddleFactors(CLQueue queue, int N, CLBuffer buf, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTTwiddleFactors(queue, N, buf, new int[] { N / 2 }, null, evts); - } - protected CLEvent cooleyTukeyFFTCopy(CLQueue queue, CLBuffer inBuf, CLBuffer outBuf, int length, CLBuffer offsetsBuf, boolean inverse, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFTCopy(queue, inBuf, outBuf, length, offsetsBuf, inverse ? 1.0f / length : 1, new int[] { length }, null, evts); - } - protected CLEvent cooleyTukeyFFT(CLQueue queue, CLBuffer Y, int N, CLBuffer twiddleFactors, int inverse, int[] dims, CLEvent... evts) throws CLException { - return program.cooleyTukeyFFT(queue, Y, N, twiddleFactors, inverse, dims, null, evts); - } - } - diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java deleted file mode 100644 index 90f8f9bbf..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/fft/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * OpenCL-backed Fourier Analysis classes (DFT, power-of-two FFT and reverse DFT/FFT for complex doubles and floats inputs) - */ -package com.nativelibs4java.opencl.util.fft; diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java deleted file mode 100644 index dd0377413..000000000 --- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/util/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -/** - * Utilitary classes (parallel random, parallel reduction, parallel math, linear algebra...) - */ -package com.nativelibs4java.opencl.util; diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c deleted file mode 100644 index 347772d52..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/LinearAlgebraKernels.c +++ /dev/null @@ -1,92 +0,0 @@ -#pragma OPENCL EXTENSION cl_khr_fp64: enable - -__kernel void mulMatDouble( - __global const double* a, /*size_t aRows,*/ int aColumns, - __global const double* b, /*size_t bRows,*/ int bColumns, - __global double* c -) { - int i = get_global_id(0); - int j = get_global_id(1); - - double total = 0; - // c[i, j] = sum(a[i, k] * b[k, j]) - int iAOff = i * aColumns; - for (int k = 0; k < aColumns; k++) { - total += a[iAOff + k] * b[k * bColumns + j]; - } - c[i * bColumns + j] = total; -} - -__kernel void mulVecDouble( - __global const double* a, /*size_t aRows,*/ int aColumns, - __global const double* b, int bSize, - __global double* c -) { - size_t globalId = get_global_id(0); - size_t i = globalId; - - double total = 0; - size_t iOff = i * aColumns; - for (size_t k = 0; k < aColumns; k++) { - total += a[iOff + k] * b[k]; - } - c[i] = total; -} - -__kernel void transposeDouble( - __global const double* a, int aRows, int aColumns, - __global double* out -) { - int i = get_global_id(0); - int j = get_global_id(1); - - int outColumns = aRows; - out[i * outColumns + j] = a[j * aColumns + i]; -} - -__kernel void mulMatFloat( - __global const float* a, /*size_t aRows,*/ int aColumns, - __global const float* b, /*size_t bRows,*/ int bColumns, - __global float* c -) { - int i = get_global_id(0); - int j = get_global_id(1); - - float total = 0; - int iOff = i * aColumns; - for (int k = 0; k < aColumns; k++) { - total += a[iOff + k] * b[k * bColumns + j]; - } - c[i * bColumns + j] = total; - // c[0] = a[0];//total; - // c[1] = a[1];//total; - // c[2] = a[2];//total; - // c[3] = a[3];//total; -} - -__kernel void mulVecFloat( - __global const float* a, /*size_t aRows,*/ int aColumns, - __global const float* b, int bSize, - __global float* c -) { - int globalId = get_global_id(0); - int i = globalId; - - float total = 0; - int iOff = i * aColumns; - for (size_t k = 0; k < aColumns; k++) { - total += a[iOff + k] * b[k]; - } - c[i] = total; -} - -__kernel void transposeFloat( - __global const float* a, int aRows, int aColumns, - __global float* out -) { - int i = get_global_id(0); - int j = get_global_id(1); - - int outColumns = aRows; - out[i * outColumns + j] = a[j * aColumns + i]; -} \ No newline at end of file diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c deleted file mode 100644 index 97bd4e9c3..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/XORShiftRandom.c +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef NUMBERS_COUNT -#define NUMBERS_COUNT 0 -#endif - -#ifndef WORK_ITEMS_COUNT -#define WORK_ITEMS_COUNT get_global_size(0) -#endif - -/** - * Logic copied from http://en.wikipedia.org/wiki/Xorshift - * Requires 4 initial random seeds for each work item - */ -__kernel void gen_numbers(__global uint4* seeds, /*size_t nNumbersArg, */__global uint* output) -{ - const uint iWorkItem = get_global_id(0); -#if 1 -#define seedsOffset iWorkItem -#define nNumbers NUMBERS_COUNT -#define nWorkItems WORK_ITEMS_COUNT -#define nNumbersByWorkItem (nNumbers / nWorkItems) -#define REMAINDER (nNumbers - nNumbersByWorkItem * WORK_ITEMS_COUNT) - uint nNumbersInThisWorkItem = nNumbersByWorkItem; - if (iWorkItem == nWorkItems - 1) - nNumbersInThisWorkItem += REMAINDER; -#else - const uint seedsOffset = iWorkItem; - const uint nNumbers = nNumbersArg; - const y nWorkItems = get_global_size(0); - const uint nNumbersByWorkItem = nNumbers / nWorkItems; - uint nNumbersInThisWorkItem = nNumbersByWorkItem; - if (iWorkItem == nWorkItems - 1) - nNumbersInThisWorkItem += nNumbers - nNumbersByWorkItem * nWorkItems; -#endif - - output += iWorkItem * nNumbersByWorkItem;//outputOffset; - - //seeds += seedsOffset; - //uint4 seed = *seeds; - uint4 seed = seeds[seedsOffset]; -#if 1 - uint x = seed.x, y = seed.y, z = seed.z, w = seed.w; - for (uint i = 0; i < nNumbersInThisWorkItem; i++) { - //for (uint i = nNumbersInThisWorkItem; i--;) { - uint t = x ^ (x << 11); - x = y; y = z; z = w; - //output[outputOffset + i] = - *(output++) = - w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); - } - //*seeds = (uint4)(x, y, z, w); - seeds[seedsOffset] = (uint4)(x, y, z, w); -#else - for (uint i = 0; i < nNumbersInThisWorkItem; i++) { - uint t = seed.x ^ (seed.x << 11); - seed.xyz = seed.yzw; - *(output++) = seed.w = (seed.w ^ (seed.w >> 19)) ^ (t ^ (t >> 8)); - } - seeds[seedsOffset] = seed; -#endif -} - -#undef seedsOffset -#undef nNumbers -#undef nWorkItems -#undef nNumbersByWorkItem -#undef REMAINDER - diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl deleted file mode 100644 index 265ebc419..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleDFTProgram.cl +++ /dev/null @@ -1,44 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -__kernel void dft( - __global const double2 *in, // complex values input - __global double2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - double2 tot = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double2 value = in[k]; - - // Compute sin and cos in a single call : - double c; - double s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (double2)( - dot(value, (double2)(c, -s)), - dot(value, (double2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (double)length; - } -} diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl deleted file mode 100644 index 48a913a37..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/DoubleFFTProgram.cl +++ /dev/null @@ -1,95 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -double2 rotateValue2(double2 value, double2 sinCos) { - return (double2)( - dot(value, (double2)(sinCos.y, -sinCos.x)), - dot(value, sinCos) - ); -} - -__kernel void cooleyTukeyFFTCopy( - __global const double2* X, - __global double2* Y, - int N, - __global const int* offsetsX, - double factor) -{ - int offsetY = get_global_id(0); - if (offsetY >= N) - return; - - int offsetX = offsetsX[offsetY]; - Y[offsetY] = X[offsetX] * factor; -} - -__kernel void cooleyTukeyFFTTwiddleFactors(int N, __global double2* twiddleFactors) -{ - int k = get_global_id(0); - double param = - M_PI * 2 * k / (double)N; - double c, s = sincos(param, &c); - twiddleFactors[k] = (double2)(s, c); -} -__kernel void cooleyTukeyFFT( - __global double2* Y, - int N, - __global double2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - double2 sinCos = twiddleFactors[k]; - if (inverse) - sinCos.x = -sinCos.x; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - double2 y1 = Y[o1]; - double2 y2 = Y[o2]; - - double2 v = rotateValue2(y2, sinCos); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} -/* -__kernel void cooleyTukeyFFTTwiddleFactors4(int N, __global double2* twiddleFactors) -{ - int k = get_global_id(0); - double param2 = - M_PI * 2 * k / (double)N; - double param3 = param2 * 2; - double param4 = param2 * 3; - double c2, s2 = sincos(param2, &c2); - double c3, s3 = sincos(param3, &c3); - double c4, s4 = sincos(param4, &c4); - int offset = k * 3; - twiddleFactors[offset++] = (double2)(s2, c2); - twiddleFactors[offset++] = (double2)(s3, c3); - twiddleFactors[offset++] = (double2)(s4, c4); -} -__kernel void cooleyTukeyFFT4( - __global double2* Y, - int N, - __global double2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - double2 sinCos = twiddleFactors[k]; - if (inverse) - sinCos.x = -sinCos.x; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - double2 y1 = Y[o1]; - double2 y2 = Y[o2]; - - double2 v = rotateValue2(y2, sinCos); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} -*/ diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl deleted file mode 100644 index ec653992a..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatDFTProgram.cl +++ /dev/null @@ -1,40 +0,0 @@ -__kernel void dft( - __global const float2 *in, // complex values input - __global float2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - float2 tot = 0; - float param = (-2 * sign * i) * 3.141593f / (float)length; - - for (int k = 0; k < length; k++) { - float2 value = in[k]; - - // Compute sin and cos in a single call : - float c; - float s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (float2)( - dot(value, (float2)(c, -s)), - dot(value, (float2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (float)length; - } -} diff --git a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl b/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl deleted file mode 100644 index 68517a86a..000000000 --- a/libraries/OpenCL/JavaCL/src/main/opencl/com/nativelibs4java/opencl/util/fft/FloatFFTProgram.cl +++ /dev/null @@ -1,55 +0,0 @@ - -inline float2 rotateValue2(float2 value, float c, float s) { - return (float2)( - dot(value, (float2)(c, -s)), - dot(value, (float2)(s, c)) - ); -} - -__kernel void cooleyTukeyFFTCopy( - __global const float2* X, - __global float2* Y, - int N, - __global const int* offsetsX, - float factor) -{ - int offsetY = get_global_id(0); - if (offsetY >= N) - return; - - int offsetX = offsetsX[offsetY]; - Y[offsetY] = X[offsetX] * factor; -} - -__kernel void cooleyTukeyFFTTwiddleFactors(int N, __global float2* twiddleFactors) -{ - int k = get_global_id(0); - float param = - 3.14159265359f * 2 * k / (float)N; - float c, s = sincos(param, &c); - twiddleFactors[k] = (float2)(c, s); -} -__kernel void cooleyTukeyFFT( - __global float2* Y, - int N, - __global float2* twiddleFactors, - int inverse) -{ - int k = get_global_id(0); - int halfN = N / 2;//>> 1; - int offsetY = get_global_id(1) * N;//halfN; - - float2 tf = twiddleFactors[k]; - float c = tf.x, s = tf.y; - if (inverse) - s = -s; - - int o1 = offsetY + k; - int o2 = o1 + halfN; - float2 y1 = Y[o1]; - float2 y2 = Y[o2]; - - float2 v = rotateValue2(y2, c, s); - Y[o1] = y1 + v; - Y[o2] = y1 - v; -} - diff --git a/libraries/OpenCL/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c b/libraries/OpenCL/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c deleted file mode 100644 index 2cd1f958e..000000000 --- a/libraries/OpenCL/JavaCL/src/main/resources/com/nativelibs4java/opencl/util/Reduction.c +++ /dev/null @@ -1,41 +0,0 @@ -#define _mul_(tot, x) tot *= x; -#define _add_(tot, x) tot += x; -#define _min_(tot, x) tot = min(tot, x); -#define _max_(tot, x) tot = max(tot, x); - -#ifndef SEED -# error "No aggregation SEED defined !" -#endif - -#ifndef OPERATION -# error "No OPERATION defined !" -#endif - -#ifndef OPERAND_TYPE -#define OPERAND_TYPE int -#endif - -#ifndef OUTPUT_TYPE -#define OUTPUT_TYPE OPERAND_TYPE -#endif - -__kernel void reduce( - __global const OPERAND_TYPE* input, - long blocks, - long dataLength, - long blockLength, - __global OUTPUT_TYPE* output) -{ - long block = get_global_id(0); - if (block >= blocks) - return; - - long inputStart = block * blockLength; - long inputEnd = min(inputStart + blockLength, dataLength); - - OUTPUT_TYPE total = (OUTPUT_TYPE)SEED; - for (int inputOffset = inputStart; inputOffset < inputEnd; inputOffset++) - OPERATION(total, input[inputOffset]); - - output[block] = total; -} diff --git a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java b/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java deleted file mode 100644 index 50e8d4bcb..000000000 --- a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/DiscreteFourierTransformTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.util; -import org.apache.commons.math.complex.Complex; -import com.nativelibs4java.opencl.util.fft.*; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import java.io.IOException; -import java.util.*; -import java.nio.*; -import org.apache.commons.math.transform.FastFourierTransformer; -import org.junit.*; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class DiscreteFourierTransformTest { - - static double[] complexToInterleavedDoubles(Complex[] complexInput) { - int length = complexInput.length; - double[] output = new double[length * 2]; - for (int i = 0; i < length; i++) { - int o = i * 2; - Complex c = complexInput[i]; - output[o] = c.getReal(); - output[o + 1] = c.getImaginary(); - } - return output; - } - static Complex[] interleavedDoublesToComplex(double[] input) { - int length = input.length / 2; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - int o = i * 2; - complexOutput[i] = new Complex(input[o], input[o + 1]); - } - return complexOutput; - } - static Complex[] realDoublesToComplex(double[] input) { - int length = input.length; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - complexOutput[i] = new Complex(input[i], 0); - } - return complexOutput; - } - /* - static void assertArrayEquals(String title, Object a, Object b) { - if (a instanceof double[]) { - double[] aa = (double[])a, bb = (double[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionDouble) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } else if (a instanceof float[]) { - float[] aa = (float[])a, bb = (float[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionFloat) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } - }*/ - static final float precisionFloat = 1e-3f, precisionInverseFloat = 1e-2f; - static final double precisionDouble = 1e-10, precisionInverseDouble = 1e-5; - - static Collection createTestDoubleInputs() { - Collection ret = new ArrayList(); - for (int n : new int[] { 1, 2, 4, 8, 16, 1024 }) { - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double)(i + 1); - in[i * 2 + 1] = 0; - } - ret.add(in); - } - return ret; - } - static Collection createTestFloatInputs() { - Collection ret = new ArrayList(); - for (double[] in : createTestDoubleInputs()) - ret.add(toFloat(in)); - return ret; - } - - static float[] toFloat(double[] in) { - float[] out = new float[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = (float)in[i]; - - return out; - } - static double[] scale(double factor, double[] in) { - double[] out = new double[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = factor * in[i]; - - return out; - } - - public void testDoubleValues(String title, Transformer tr) { - FastFourierTransformer apache = new FastFourierTransformer(); - CLQueue queue = tr.getContext() == null ? null : tr.getContext().createDefaultOutOfOrderQueueIfPossible(); - for (double[] data : createTestDoubleInputs()) { - double[] expected = complexToInterleavedDoubles(apache.transform(interleavedDoublesToComplex(data))); - assertArrayEquals(title + " (n = " + (data.length / 2) + ")", expected, tr.transform(queue, data, false), precisionDouble); - } - } - public void testFloatValues(String title, Transformer tr) { - FastFourierTransformer apache = new FastFourierTransformer(); - CLQueue queue = tr.getContext() == null ? null : tr.getContext().createDefaultOutOfOrderQueueIfPossible(); - for (double[] data : createTestDoubleInputs()) { - float[] dataf = toFloat(data); - double[] expected = complexToInterleavedDoubles(apache.transform(interleavedDoublesToComplex(data))); - assertArrayEquals(title + " (n = " + (data.length / 2) + ")", toFloat(expected), tr.transform(queue, dataf, false), precisionFloat); - } - } - - @Ignore - @Test - public void testDoubleFFTValues() throws IOException { - testDoubleValues("Double FFT", new DoubleFFTPow2()); - } - @Test - public void testFloatFFTValues() throws IOException { - testFloatValues("Float FFT", new FloatFFTPow2()); - } - @Test - public void testDoubleDFTValues() throws IOException { - testDoubleValues("Double DFT", new DoubleDFT()); - } - @Test - public void testFloatDFTValues() throws IOException { - testFloatValues("Float DFT", new FloatDFT()); - } - @Test - public void testDoubleDFTInverse() throws IOException, CLException { - testDoubleTransformer("Double FFT Inverse", new DoubleDFT()); - } - @Test - public void testFloatDFTInverse() throws IOException, CLException { - testFloatTransformer("Float DFT Inverse", new FloatDFT()); - } - @Ignore - @Test - public void testDoubleFFTInverse() throws IOException, CLException { - testDoubleTransformer("Double FFT Inverse", new DoubleFFTPow2()); - } - @Test - public void testFloatFFTInverse() throws IOException, CLException { - testFloatTransformer("Float FFT Inverse", new FloatFFTPow2()); - } - void testDoubleTransformer(String title, Transformer t) throws IOException, CLException { - CLQueue queue = t.getContext().createDefaultOutOfOrderQueueIfPossible(); - //System.out.println("Context: " + t.getContext()); - for (double[] in : createTestDoubleInputs()) { - double[] out = t.transform(queue, in, false); - double[] back = t.transform(queue, out, true); - assertArrayEquals(title + " (n = " + (in.length / 2) + ")", in, back, precisionInverseDouble); - } - } - void testFloatTransformer(String title, Transformer t) throws IOException, CLException { - CLQueue queue = t.getContext().createDefaultOutOfOrderQueueIfPossible(); - //System.out.println("Context: " + t.getContext()); - for (float[] in : createTestFloatInputs()) { - float[] out = t.transform(queue, in, false); - float[] back = t.transform(queue, out, true); - assertArrayEquals(title + " (n = " + (in.length / 2) + ")", in, back, precisionInverseFloat); - } - } -} diff --git a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java b/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java deleted file mode 100644 index fd642cbb3..000000000 --- a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ParallelRandomTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.nativelibs4java.opencl.util; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import com.nativelibs4java.opencl.JavaCL; - -import org.junit.Assert; -import org.junit.Test; - -/** - * - * @author ochafik - */ -public class ParallelRandomTest { - int nPoints = 1024 * 1024; - int nLoops = 10; - long seed = 1; - - static final int mask = 0x00ffffff; - static final double divid = (1 << 24); - //static final int mask = (1 << 30) - 1; - //static final double divid = (1 << 30); - - /** - * http://fr.wikipedia.org/wiki/M%C3%A9thode_de_Monte-Carlo#Exemples - */ - @Test - public void testPICircle() { - try { - ParallelRandom random = new ParallelRandom( - JavaCL.createBestContext().createDefaultQueue(), - nPoints * 2, - seed - ); - - int nInside = 0, nTotalPoints = 0; - - for (int iLoop = 0; iLoop < nLoops; iLoop++) { - Pointer values = random.next(); - for (int iPoint = 0; iPoint < nPoints; iPoint++) { - int offset = iPoint * 2; - int ix = values.get(offset), iy = values.get(offset + 1); - float x = (float)((ix & mask) / divid); - float y = (float)((iy & mask) / divid); - - float dist = x * x + y * y; - if (dist <= 1) - nInside++; - } - nTotalPoints += nPoints; - //checkPICircleProba(nInside, nTotalPoints); - } - checkPICircleProba(nInside, nTotalPoints); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - void checkPICircleProba(int nInside, int nTotalPoints) { - double piRef = Math.PI; - double probaInside = nInside / (double)nTotalPoints; // = Pi / 4 - double piApprox = probaInside * 4; - double error = Math.abs(piApprox - piRef); - double relError = error / piRef; - System.out.println(nInside + " points inside the circle quarter over " + nTotalPoints); - System.out.println("Approximated PI = " + piApprox); - System.out.println(" Reference PI = " + piRef); - System.out.println("\tAbsolute error = " + error); - System.out.println("\tRelative error = " + (relError * 100) + " %"); - Assert.assertEquals(piRef, piApprox, 0.001); - } -} diff --git a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java b/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java deleted file mode 100644 index 6d62b14ab..000000000 --- a/libraries/OpenCL/JavaCL/src/test/java/com/nativelibs4java/opencl/util/ReductionTest.java +++ /dev/null @@ -1,134 +0,0 @@ - -package com.nativelibs4java.opencl.util; - -import com.nativelibs4java.opencl.*; -import static com.nativelibs4java.opencl.JavaCL.createBestContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import java.util.Arrays; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.nativelibs4java.opencl.util.ReductionUtils.Reductor; -import com.nativelibs4java.util.NIOUtils; - -public class ReductionTest { - - //@BeforeClass - //public static void setup() { - // com.sun.jna.Native.setProtected(true); - //} - - CLContext context; - CLQueue queue; - - @Before - public void init() { - //context = createBestContext(CLPlatform.DeviceEvaluationStrategy.BestDoubleSupportThenBiggestMaxComputeUnits);// - context = createBestContext(); - //System.out.println("Context = " + Arrays.asList(context.getDevices())); - queue = context.createDefaultQueue(); - } - - @Test - public void testMinMax() { - try { - CLBuffer input = context.createBuffer(CLMem.Usage.Input, pointerToInts( - 1110, 22, 35535, 3, 1 - ), true); - - int maxReductionSize = 2; - Pointer result = allocateInt().order(context.getByteOrder()); - - Reductor reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Min, OpenCLType.Int, 1); - reductor.reduce(queue, input, input.getElementCount(), result, maxReductionSize); - queue.finish(); - assertEquals(1, (int)result.get()); - - reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Max, OpenCLType.Int, 1); - reductor.reduce(queue, input, input.getElementCount(), result, maxReductionSize); - queue.finish(); - assertEquals(35535, (int)result.get()); - - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=26 - @Test - public void testIssue26() { - try { - float[] array = new float[4097]; - for (int i = 0; i < array.length; i++) - array[i] = 1; - - CLBuffer clBufferInput = context.createBuffer(CLMem.Usage.Input, pointerToFloats(array), true); - - ReductionUtils.Reductor reductor = ReductionUtils.createReductor( - context, - ReductionUtils.Operation.Add, - OpenCLType.Float, - 1 - ); - Pointer result = reductor.reduce(queue, clBufferInput, 4097, 64); - float sum = result.get(0); - float expected = 4097; - System.err.println("[Test of issue 26] Expected " + expected + ", got " + sum); - assertEquals(expected, sum, 0); - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } - @Test - public void testAddReduction() { - try { - int dataSize = 12345; - int channels = 1; - int maxReductionSize = 64; - - Pointer inBuf = allocateInts(channels * dataSize).order(context.getByteOrder()); - for (int i = 0; i < dataSize; i++) { - for (int c = 0; c < channels; c++) - inBuf.set(i * channels + c, i); - } - - CLBuffer in = context.createBuffer(CLMem.Usage.Input, Integer.class, channels * dataSize); - in.write(queue, inBuf, true); - - Pointer check = in.read(queue); - for (int i = 0; i < dataSize; i++) - assertEquals((int)inBuf.get(i), (int)check.get(i)); - - Pointer out = allocateInts(channels).order(context.getByteOrder()); - - Reductor reductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Add, OpenCLType.Int, channels); - - //CLEvent evt = - reductor.reduce(queue, in, dataSize, out, maxReductionSize); - //if (evt != null) - queue.finish(); - // evt.waitFor(); - //CLEvent[] evts = reductor.reduce(queue, in, 0, dataSize, out, maxReductionSize); - //queue.enqueueWaitForEvents(evts); - - int expected = dataSize * (dataSize - 1) / 2; - System.out.println("Expecting " + expected); - for (int i = 0; i < channels; i++) { - int value = out.get(i); - System.out.println("out." + i + " = " + value); - assertEquals(expected, value); - } - } catch (Exception ex) { - ex.printStackTrace(); - assertTrue(ex.toString(), false); - } - } -} diff --git a/libraries/OpenCL/LICENSE b/libraries/OpenCL/LICENSE deleted file mode 100644 index 0e05f127a..000000000 --- a/libraries/OpenCL/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2012, Olivier Chafik -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Olivier Chafik nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 THE REGENTS AND 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. diff --git a/libraries/OpenCL/LICENSE.header b/libraries/OpenCL/LICENSE.header deleted file mode 100644 index 5a3466297..000000000 --- a/libraries/OpenCL/LICENSE.header +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik (http://ochafik.free.fr/) - - This file is part of OpenCL4Java (http://code.google.com/p/nativelibs4java/wiki/OpenCL). - - OpenCL4Java is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 2.1 of the License, or - (at your option) any later version. - - OpenCL4Java is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with OpenCL4Java. If not, see . -*/ - diff --git a/libraries/OpenCL/LibCL/.gitignore b/libraries/OpenCL/LibCL/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/LibCL/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/LibCL/libcl-bridj.iml b/libraries/OpenCL/LibCL/libcl-bridj.iml deleted file mode 100644 index 2a63f7cf4..000000000 --- a/libraries/OpenCL/LibCL/libcl-bridj.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/LibCL/libcl.iml b/libraries/OpenCL/LibCL/libcl.iml deleted file mode 100644 index c51ad6a81..000000000 --- a/libraries/OpenCL/LibCL/libcl.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/LibCL/pom.xml b/libraries/OpenCL/LibCL/pom.xml deleted file mode 100644 index 52ad5064d..000000000 --- a/libraries/OpenCL/LibCL/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - 4.0.0 - com.nativelibs4java - libcl - LibCL - http://code.google.com/p/javacl/ - jar - - - Library of OpenCL functions for easy use from JavaCL - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/Bits.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/Bits.cl deleted file mode 100644 index 25bd8e195..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/Bits.cl +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _LIBCL_BITS_CL_ -#define _LIBCL_BITS_CL_ - -/** - * SWAR algorithm - * http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer - */ -int countBitsInInt(int i) -{ - i = i - ((i >> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >> 2) & 0x33333333); - return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; -} - -#define _LIBCL_BITS_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/Gaussian7x7.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/Gaussian7x7.cl deleted file mode 100644 index 9bf1121d7..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/Gaussian7x7.cl +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _LIBCL_GAUSSIAN_7x7_CL_ -#define _LIBCL_GAUSSIAN_7x7_CL_ - -// Matrix values taken from http://en.wikipedia.org/wiki/Gaussian_blur : -__constant float gaussian7x7Matrix[] = { - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00038771f, 0.01330373f, 0.11098164f, 0.22508352f, 0.11098164f, 0.01330373f, 0.00038771f, - 0.00019117f, 0.00655965f, 0.05472157f, 0.11098164f, 0.05472157f, 0.00655965f, 0.00019117f, - 0.00002292f, 0.00078633f, 0.00655965f, 0.01330373f, 0.00655965f, 0.00078633f, 0.00002292f, - 0.00000067f, 0.00002292f, 0.00019117f, 0.00038771f, 0.00019117f, 0.00002292f, 0.00000067f -}; - - -#endif // _LIBCL_GAUSSIAN_7x7_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvert.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvert.cl deleted file mode 100644 index c3ff97cce..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvert.cl +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _LIBCL_IMAGE_CONVERT_CL_ -#define _LIBCL_IMAGE_CONVERT_CL_ - -__constant float4 luminanceDot = ((float4)(1 / 3.f, 1 / 3.f, 1 / 3.f, 0)); - -void convertFloatRGBImageToGray( - read_only image2d_t inputImage, - write_only image2d_t outputImage) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - int x = get_global_id(0), y = get_global_id(1); - - int2 coords = (int2)(x, y); - float4 pixel = read_imagef(inputImage, sampler, coords); - float luminance = dot(luminanceDot, pixel); - write_imagef(outputImage, coords, (float4)(luminance, luminance, luminance, 1)); -} - -#endif // _LIBCL_IMAGE_CONVERT_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvolution.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvolution.cl deleted file mode 100644 index 5d2caeddc..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/ImageConvolution.cl +++ /dev/null @@ -1,208 +0,0 @@ -#ifndef _LIBCL_IMAGE_CONVOLUTION_CL_ -#define _LIBCL_IMAGE_CONVOLUTION_CL_ - -/** - * Compute convolution result for pixel (x, y) separately on each of the 4 pixel channels. - * @param x X coordinate of the resulting convolved pixel - * @param y Y coordinate of the resulting convolved pixel - * @param matrix Pointer to the convolution matrix - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - * @returns Convolution result - */ -float4 convolveFloatImagePixel( - read_only image2d_t inputImage, - int x, int y, - __constant float* matrix, - int matrixSize) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float4 total = (float4)0; - int matrixCenterOffset = matrixSize / 2; - - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - float factor = matrix[offset + dx]; - total += factor * pixel; - } - } - return total; -} - -/** - * Compute convolution result for pixel (x, y) with a different convolution matrix on all 4 channels. - * @param x X coordinate of the resulting convolved pixel - * @param y Y coordinate of the resulting convolved pixel - * @param matrixX Pointer to the convolution matrix for channel x - * @param matrixY Pointer to the convolution matrix for channel y - * @param matrixZ Pointer to the convolution matrix for channel z - * @param matrixW Pointer to the convolution matrix for channel w - * @param matrixSize Width and height of the convolution matrices (3 for a 3x3 matrix) - * @returns Convolution result - */ -float4 convolveFloatImagePixelChannels( - read_only image2d_t inputImage, - int x, int y, - __constant float* matrixX, - __constant float* matrixY, - __constant float* matrixZ, - __constant float* matrixW, - int matrixSize) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float4 total = (float4)0; - int matrixCenterOffset = matrixSize / 2; - - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - int pos = offset + dx; - float4 factors = (float4)(matrixX[pos], matrixY[pos], matrixZ[pos], matrixW[pos]); - total += factors * pixel; - } - } - return total; -} - -/** - * Compute convolution result for pixel (x, y), using only the x component of all input pixels. - * @param x X coordinate of the resulting convolved pixel - * @param y Y coordinate of the resulting convolved pixel - * @param matrix Pointer to the convolution matrix - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - * @returns Convolution result - */ -float convolveFloatImagePixelX( - read_only image2d_t inputImage, - int x, int y, - __constant float* matrix, - int matrixSize) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float total = 0; - int matrixCenterOffset = matrixSize / 2; - - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - float factor = matrix[offset + dx]; - total += factor * pixel.x; - } - } - return total; -} - -/** - * Compute convolution result for pixel (x, y), using the average of the x, y and z channels as input (luminance, if the pixel is RGBA). - * @param x X coordinate of the resulting convolved pixel - * @param y Y coordinate of the resulting convolved pixel - * @param matrix Pointer to the convolution matrix - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - * @returns Convolution result - */ -float convolveFloatImagePixelGray( - read_only image2d_t inputImage, - int x, int y, - __constant float* matrix, - int matrixSize) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float total = 0; - int matrixCenterOffset = matrixSize / 2; - - const float4 luminanceDot = (float4)(1/3.f, 1/3.f, 1/3.f, 0); - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - float factor = matrix[offset + dx]; - total += factor * dot(luminanceDot, pixel); - } - } - return total; -} - -/** - * Compute convolution results for pixel (x, y), using the average of the x, y and z channels as input (luminance, if the pixel is RGBA) and two different convolution matrices (interleaved in float2 cells). - * @param x X coordinate of the resulting convolved pixel - * @param y Y coordinate of the resulting convolved pixel - * @param matrix Pointer to the convolution matrices (two matrices are interleaved in this matrix's cell values components) - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - * @returns Convolution results - */ -float2 convolveFloatImagePixelGray2( - read_only image2d_t inputImage, - int x, int y, - __constant float2* matrix, - int matrixSize) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - float2 total = (float2)0; - int matrixCenterOffset = matrixSize / 2; - - const float4 luminanceDot = (float4)(1/3.f, 1/3.f, 1/3.f, 0); - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - float2 factor = matrix[offset + dx]; - total += factor * dot(luminanceDot, pixel); - } - } - return total; -} - -/** - * Compute the convolution of an image with a convolution matrix. - * The resulting image will have a constant w channel (typically, alpha) set to 1. - * @param matrix Pointer to the convolution matrix - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - */ -void convolveFloatImage( - read_only image2d_t inputImage, - __constant float* matrix, - int matrixSize, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - float4 total = convolveFloatImagePixel(inputImage, x, y, matrix, matrixSize); - - // Transparent images are not very useful ! - total.w = 1; - write_imagef(outputImage, (int2)(x, y), total); -} - -/** - * Compute the convolution of an image with a different convolution matrix on each of the 4 pixel channels. - * @param matrixX Pointer to the convolution matrix for channel x - * @param matrixY Pointer to the convolution matrix for channel y - * @param matrixZ Pointer to the convolution matrix for channel z - * @param matrixW Pointer to the convolution matrix for channel w - * @param matrixSize Width and height of the convolution matrix (3 for a 3x3 matrix) - */ -void convolveFloatImageChannels( - read_only image2d_t inputImage, - __constant float* matrixX, - __constant float* matrixY, - __constant float* matrixZ, - __constant float* matrixW, - int matrixSize, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - - float4 total = convolveFloatImagePixelChannels(inputImage, x, y, matrixX, matrixY, matrixZ, matrixW, matrixSize); - total.w = 1; - write_imagef(outputImage, (int2)(x, y), total); -} - -#endif // _LIBCL_IMAGE_CONVOLUTION_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/RichardsonLucyImageDeconvolution.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/RichardsonLucyImageDeconvolution.cl deleted file mode 100644 index 9126d5d72..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/RichardsonLucyImageDeconvolution.cl +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef _LIBCL_RICHARDSON_LUCY_IMAGE_DECONVOLUTION_CL_ -#define _LIBCL_RICHARDSON_LUCY_IMAGE_DECONVOLUTION_CL_ - -#include "LibCL/ImageConvolution.cl" -#include "LibCL/ImageConvert.cl" - -// Convert image to grayscale -void richardsonLucyDeconvolutionPre1(read_only image2d_t inputImage, write_only image2d_t outputImage) -{ - convertFloatRGBImageToGray(inputImage, outputImage); -} - -// Put I factors in w (alpha) channel -void richardsonLucyDeconvolutionPre2(read_only image2d_t inputImage, __constant float* matrix, int matrixSize, write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - float conv = convolveFloatImagePixelX(inputImage, x, y, matrix, matrixSize); - - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - int2 coords = (int2)(x, y); - float4 pixel = read_imagef(inputImage, sampler, coords); - pixel.w = conv; - write_imagef(outputImage, coords, pixel); -} - -// Put x into xyz and set w to 1 (make the image look grey again !) -void richardsonLucyDeconvolutionPost(read_only image2d_t inputImage, write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - - int2 coords = (int2)(x, y); - float4 pixel = read_imagef(inputImage, sampler, coords); - pixel.y = pixel.z = pixel.x; - pixel.w = 1; - write_imagef(outputImage, coords, pixel); -} - -void richardsonLucyDeconvolutionPass( - read_only image2d_t inputImage, - __constant float* matrix, - int matrixSize, - write_only image2d_t outputImage) -{ - int x = get_global_id(0), y = get_global_id(1); - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - const int matrixCenterOffset = matrixSize / 2; - - float total = 0; - for (int dy = 0; dy < matrixSize; dy++) { - int offset = dy * matrixSize; - for (int dx = 0; dx < matrixSize; dx++) { - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx - matrixCenterOffset, y + dy - matrixCenterOffset)); - float factor = matrix[offset + dx]; - total += factor * pixel.x / pixel.w; - } - } - - int2 coords = (int2)(x, y); - float4 pixel = read_imagef(inputImage, sampler, coords); - pixel.x *= total; - write_imagef(outputImage, coords, pixel); -} - -#define RICHARDSON_LUCY_DECONVOLUTION_PRE(matrix, matrixSize) \ - __kernel void pre1(read_only image2d_t inputImage, write_only image2d_t outputImage) { richardsonLucyDeconvolutionPre1(inputImage, outputImage); } \ - __kernel void pre2(read_only image2d_t inputImage, write_only image2d_t outputImage) { richardsonLucyDeconvolutionPre2(inputImage, matrix, matrixSize, outputImage); } - -#define RICHARDSON_LUCY_DECONVOLUTION_PASS(matrix, matrixSize, n) \ - __kernel void deconvolvePass ## n(read_only image2d_t inputImage, write_only image2d_t outputImage) { richardsonLucyDeconvolutionPass(inputImage, matrix, matrixSize, outputImage); } - -#define RICHARDSON_LUCY_DECONVOLUTION_POST() \ - __kernel void post(read_only image2d_t inputImage, write_only image2d_t outputImage) { richardsonLucyDeconvolutionPost(inputImage, outputImage); } - -#endif _LIBCL_RICHARDSON_LUCY_IMAGE_DECONVOLUTION_CL_ - diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/SobelOperator.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/SobelOperator.cl deleted file mode 100644 index ccad0de8a..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/SobelOperator.cl +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef _LIBCL_SOBEL_OPERATOR_CL_ -#define _LIBCL_SOBEL_OPERATOR_CL_ - -/** - Sobel operator - See http://en.wikipedia.org/wiki/Sobel_operator - Written by Olivier Chafik, no right reserved :-) */ - -/** - * Return (float2)(gradient, angle) of Sobel operator applied at given pixel. - */ -inline float2 sobelOperatorRGBFloat( - read_only image2d_t inputImage, - int x, - int y) -{ - const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP_TO_EDGE; - -#define PIXEL_CONTRIB(dx, dy, coefX, coefY) \ - {\ - float4 pixel = read_imagef(inputImage, sampler, (int2)(x + dx, y + dy)); \ - total += (float2)(coefX, coefY) * (float2)(((pixel.x + (int)pixel.y + (int)pixel.z) / 3.f) * pixel.w); \ - } - - float2 total = (float2)0; - -#define MX_NW 1 -#define MX_N 2 -#define MX_NE 1 -#define MX_W 0 -#define MX_C 0 -#define MX_E 0 -#define MX_SW -1 -#define MX_S -2 -#define MX_SE -1 - -#define MY_NW 1 -#define MY_N 0 -#define MY_NE -1 -#define MY_W 2 -#define MY_C 0 -#define MY_E -2 -#define MY_SW 1 -#define MY_S 0 -#define MY_SE -1 - - PIXEL_CONTRIB(-1, -1, MX_NW, MY_NW); - PIXEL_CONTRIB(0, -1, MX_N, MY_N); - PIXEL_CONTRIB(1, -1, MX_NE, MY_NE); - PIXEL_CONTRIB(-1, 0, MX_W, MY_W); - PIXEL_CONTRIB(0, 0, MX_C, MY_C); - PIXEL_CONTRIB(1, 0, MX_E, MY_E); - PIXEL_CONTRIB(-1, 1, MX_SW, MY_SW); - PIXEL_CONTRIB(0, 1, MX_S, MY_S); - PIXEL_CONTRIB(1, 1, MX_SE, MY_SE); - - float gradient = length(total); - float direction = atan2(total.y, total.x); - - return (float2)(gradient, direction); -} - -#endif // _LIBCL_SOBEL_OPERATOR_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/hsla2rgba.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/hsla2rgba.cl deleted file mode 100644 index 9eb4863c8..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/hsla2rgba.cl +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef _LIBCL_HSLA_2_RGBA_CL_ -#define _LIBCL_HSLA_2_RGBA_CL_ - -inline float hsla2rgba_sub(float x, float y, float z) { - if (z < 0) - z += 1.f; - else if (z > 1) - z -= 1.f; - - if (6 * z < 1) - return x + (y - x) * 6 * z; - if (2 * z < 1) - return y; - if (3 * z < 2) - return x + (y - x) * ((2.f / 3.f) - z) * 6; - return x; -} - -inline float4 hsla2rgba(float4 hsla) { - float - h = hsla.x, - s = hsla.y, - l = hsla.z, - a = hsla.w; - - float r, g, b; - if (s == 0) - r = g = b = l; - else { - float y; - if (l < 0.5f) - y = l * (1.0f + s); - else - y = l + s - l * s; - float x = 2.0f * l - y; - - r = hsla2rgba_sub(x, y, h + 1.f / 3.f); - g = hsla2rgba_sub(x, y, h); - b = hsla2rgba_sub(x, y, h - 1.f / 3.f); - } - return (float4)(r, g, b, a); -} - -#endif // _LIBCL_HSLA_2_RGBA_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/rgba2hsla.cl b/libraries/OpenCL/LibCL/src/main/resources/LibCL/rgba2hsla.cl deleted file mode 100644 index 8dcd76e51..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/rgba2hsla.cl +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef _LIBCL_RGBA_2_HSLA_CL_ -#define _LIBCL_RGBA_2_HSLA_CL_ - -inline float4 rgba2hsla(float4 rgba) { - float - r = rgba.x, - g = rgba.y, - b = rgba.z, - a = rgba.w; - - float mn = min(r, min(g, b)); - float mx = max(r, max(g, b)); - - float l = (mn + mx) / 2.f; - float s, h; - if (mn == mx) { - s = h = 0; - } else { - float diff = mx - mn; - float sum = mx + mn; - if (l < 0.5f) - s = diff / sum; - else - s = diff / (2.0f - sum); - if (r == mx) - h = (g - b) / diff; - else if (g == mx) - h = 2.0f + (b - r) / diff; - else //if (b == mx) - h = 4.0f + (r - g) / diff; - } - h = clamp(h / 6.0f, 0.0f, 1.0f); - return (float4)(h, s, l, a); -} - -#endif // _LIBCL_HSLA_2_RGBA_CL_ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/stdlib.h b/libraries/OpenCL/LibCL/src/main/resources/LibCL/stdlib.h deleted file mode 100644 index 1f8afb0e7..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/stdlib.h +++ /dev/null @@ -1,21 +0,0 @@ - -//#include "tcl.h" -//#ifdef NO_STDLIB_H -//# include "../compat/stdlib.h" -//#else -//# include -//#endif -//#include - -#ifndef CONST -#define CONST const -#endif - -#ifndef isspace -#define isspace(c) (c == ' ' || c == '\t' || c == '\r' || c == '\n') -#endif - -#ifndef isdigit -#define isdigit(c) (c >= '0' && c <= '9') -#endif - diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strstr.c b/libraries/OpenCL/LibCL/src/main/resources/LibCL/strstr.c deleted file mode 100644 index 147e97c47..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strstr.c +++ /dev/null @@ -1,5 +0,0 @@ - -/*__global const char * strstr ( __global const char * str1, const char * str2 ) { - -} -*/ diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtod.c b/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtod.c deleted file mode 100644 index 38565acba..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtod.c +++ /dev/null @@ -1,268 +0,0 @@ -/* - * strtod.c -- - * - * Source code for the "strtod" library procedure. - * - * Copyright (c) 1988-1993 The Regents of the University of California. - * Copyright (c) 1994 Sun Microsystems, Inc. - * - * See the file "license.terms" for information on usage and redistribution - * of this file, and for a DISCLAIMER OF ALL WARRANTIES. - * - * SCCS: @(#) strtod.c 1.9 96/12/13 15:02:46 - * - * JavaCL / LibCL (Olivier Chafik, 2011) : copied from FreeBSD - * - */ - -//#include "tcl.h" -//#ifdef NO_STDLIB_H -//# include "../compat/stdlib.h" -//#else -//# include -//#endif -//#include - -#ifndef CONST -#define CONST const -#endif - - -#ifndef TRUE -#define TRUE 1 -#define FALSE 0 -#endif -#ifndef NULL -#define NULL 0 -#endif - -const int _strtod_maxExponent_ = 511; /* Largest possible base 10 exponent. Any - * exponent larger than this will already - * produce underflow or overflow, so there's - * no need to worry about additional digits. - */ - -__constant double _strtod_powersOf10_[] = { /* Table giving binary powers of 10. Entry */ - 10., /* is 10^2^i. Used to convert decimal */ - 100., /* exponents into floating-point numbers. */ - 1.0e4, - 1.0e8, - 1.0e16, - 1.0e32, - 1.0e64, - 1.0e128, - 1.0e256 -}; - - -/* - *---------------------------------------------------------------------- - * - * strtod -- - * - * This procedure converts a floating-point number from an ASCII - * decimal representation to internal double-precision format. - * - * Results: - * The return value is the double-precision floating-point - * representation of the characters in string. If endPtr isn't - * NULL, then *endPtr is filled in with the address of the - * next character after the last one that was part of the - * floating-point number. - * - * Side effects: - * None. - * - *---------------------------------------------------------------------- - */ - -double -strtod(__global CONST char *string, /* A decimal ASCII floating-point number, - * optionally preceded by white space. - * Must have form "-I.FE-X", where I is the - * integer part of the mantissa, F is the - * fractional part of the mantissa, and X - * is the exponent. Either of the signs - * may be "+", "-", or omitted. Either I - * or F may be omitted, or both. The decimal - * point isn't necessary unless F is present. - * The "E" may actually be an "e". E and X - * may both be omitted (but not just one). - */ - __global char **endPtr /* If non-NULL, store terminating character's - * address here. */ - ) { - int sign, expSign = FALSE; - double fraction, dblExp; - __constant double *d; - __global CONST char *p; - int c; - int exp = 0; /* Exponent read from "EX" field. */ - int fracExp = 0; /* Exponent that derives from the fractional - * part. Under normal circumstatnces, it is - * the negative of the number of digits in F. - * However, if I is very long, the last digits - * of I get dropped (otherwise a long I with a - * large negative exponent could cause an - * unnecessary overflow on I alone). In this - * case, fracExp is incremented one for each - * dropped digit. */ - int mantSize; /* Number of digits in mantissa. */ - int decPt; /* Number of mantissa digits BEFORE decimal - * point. */ - __global CONST char *pExp; /* Temporarily holds location of exponent - * in string. */ - - /* - * Strip off leading blanks and check for a sign. - */ - - p = string; - while (isspace(*p)) { - p += 1; - } - if (*p == '-') { - sign = TRUE; - p += 1; - } else { - if (*p == '+') { - p += 1; - } - sign = FALSE; - } - - /* - * Count the number of digits in the mantissa (including the decimal - * point), and also locate the decimal point. - */ - - decPt = -1; - for (mantSize = 0; ; mantSize += 1) - { - c = *p; - if (!isdigit(c)) { - if ((c != '.') || (decPt >= 0)) { - break; - } - decPt = mantSize; - } - p += 1; - } - - /* - * Now suck up the digits in the mantissa. Use two integers to - * collect 9 digits each (this is faster than using floating-point). - * If the mantissa has more than 18 digits, ignore the extras, since - * they can't affect the value anyway. - */ - - pExp = p; - p -= mantSize; - if (decPt < 0) { - decPt = mantSize; - } else { - mantSize -= 1; /* One of the digits was the point. */ - } - if (mantSize > 18) { - fracExp = decPt - 18; - mantSize = 18; - } else { - fracExp = decPt - mantSize; - } - if (mantSize == 0) { - fraction = 0.0; - p = string; - goto done; - } else { - int frac1, frac2; - frac1 = 0; - for ( ; mantSize > 9; mantSize -= 1) - { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac1 = 10*frac1 + (c - '0'); - } - frac2 = 0; - for (; mantSize > 0; mantSize -= 1) - { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac2 = 10*frac2 + (c - '0'); - } - fraction = (1.0e9 * frac1) + frac2; - } - - /* - * Skim off the exponent. - */ - - p = pExp; - if ((*p == 'E') || (*p == 'e')) { - p += 1; - if (*p == '-') { - expSign = TRUE; - p += 1; - } else { - if (*p == '+') { - p += 1; - } - expSign = FALSE; - } - while (isdigit(*p)) { - exp = exp * 10 + (*p - '0'); - p += 1; - } - } - if (expSign) { - exp = fracExp - exp; - } else { - exp = fracExp + exp; - } - - /* - * Generate a floating-point number that represents the exponent. - * Do this by processing the exponent one bit at a time to combine - * many powers of 2 of 10. Then combine the exponent with the - * fraction. - */ - - if (exp < 0) { - expSign = TRUE; - exp = -exp; - } else { - expSign = FALSE; - } - if (exp > _strtod_maxExponent_) { - exp = _strtod_maxExponent_; - } - dblExp = 1.0; - - for (d = _strtod_powersOf10_; exp != 0; exp >>= 1, d += 1) { - if (exp & 01) { - dblExp *= *d; - } - } - if (expSign) { - fraction /= dblExp; - } else { - fraction *= dblExp; - } - -done: - if (endPtr != NULL) { - *endPtr = (__global char *) p; - } - - if (sign) { - return -fraction; - } - return fraction; -} diff --git a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtof.c b/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtof.c deleted file mode 100644 index 64f6e9569..000000000 --- a/libraries/OpenCL/LibCL/src/main/resources/LibCL/strtof.c +++ /dev/null @@ -1,302 +0,0 @@ -/* - * strtof.c -- - * - * Source code for the "strtof" library procedure. - * - * Copyright (c) 1988-1993 The Regents of the University of California. - * Copyright (c) 1994 Sun Microsystems, Inc. - * - * See the file "license.terms" for information on usage and redistribution - * of this file, and for a DISCLAIMER OF ALL WARRANTIES. - * - * SCCS: @(#) strtof.c 1.9 96/12/13 15:02:46 - * - * JavaCL / LibCL (Olivier Chafik, 2011) : adapted from strod.c copied from FreeBSD - * - */ - -//#include "tcl.h" -//#ifdef NO_STDLIB_H -//# include "../compat/stdlib.h" -//#else -//# include -//#endif -//#include - -#ifndef CONST -#define CONST const -#endif - - -#ifndef TRUE -#define TRUE 1 -#define FALSE 0 -#endif -#ifndef NULL -#define NULL 0 -#endif - -const float _strtof_powersOf10_[] = { // Table giving binary powers of 10. Entry - 10.0f, // is 10^2^i. Used to convert decimal - 100.0f, // exponents into floating-point numbers. - 1.0e4f, - 1.0e8f, - 1.0e16f, - 1.0e32f -}; - -/* - *---------------------------------------------------------------------- - * - * strtof -- - * - * This procedure converts a floating-point number from an ASCII - * decimal representation to internal double-precision format. - * - * Results: - * The return value is the double-precision floating-point - * representation of the characters in string. If endPtr isn't - * NULL, then *endPtr is filled in with the address of the - * next character after the last one that was part of the - * floating-point number. - * - * Side effects: - * None. - * - *---------------------------------------------------------------------- - */ - -float -strtof(__global CONST char *string, /* A decimal ASCII floating-point number, - * optionally preceded by white space. - * Must have form "-I.FE-X", where I is the - * integer part of the mantissa, F is the - * fractional part of the mantissa, and X - * is the exponent. Either of the signs - * may be "+", "-", or omitted. Either I - * or F may be omitted, or both. The decimal - * point isn't necessary unless F is present. - * The "E" may actually be an "e". E and X - * may both be omitted (but not just one). - */ - __global char **endPtr /* If non-NULL, store terminating character's - * address here. */ - ) { - int sign, expSign = FALSE; - float fraction, dblExp; - __constant float *d; - __global CONST char *p; - int c; - int exp = 0; /* Exponent read from "EX" field. */ - int fracExp = 0; /* Exponent that derives from the fractional - * part. Under normal circumstatnces, it is - * the negative of the number of digits in F. - * However, if I is very long, the last digits - * of I get dropped (otherwise a long I with a - * large negative exponent could cause an - * unnecessary overflow on I alone). In this - * case, fracExp is incremented one for each - * dropped digit. */ - int mantSize; /* Number of digits in mantissa. */ - int decPt; /* Number of mantissa digits BEFORE decimal - * point. */ - __global CONST char *pExp; /* Temporarily holds location of exponent - * in string. */ - - /* - * Strip off leading blanks and check for a sign. - */ - - p = string; - while (isspace(*p)) { - p += 1; - } - if (*p == '-') { - sign = TRUE; - p += 1; - } else { - if (*p == '+') { - p += 1; - } - sign = FALSE; - } - - /* - * Count the number of digits in the mantissa (including the decimal - * point), and also locate the decimal point. - */ - - decPt = -1; - for (mantSize = 0; ; mantSize += 1) - { - c = *p; - if (!isdigit(c)) { - if ((c != '.') || (decPt >= 0)) { - break; - } - decPt = mantSize; - } - p += 1; - } - - /* - * Now suck up the digits in the mantissa. Use two integers to - * collect 9 digits each (this is faster than using floating-point). - * If the mantissa has more than 18 digits, ignore the extras, since - * they can't affect the value anyway. - */ - - pExp = p; - p -= mantSize; - if (decPt < 0) { - decPt = mantSize; - } else { - mantSize -= 1; /* One of the digits was the point. */ - } - if (mantSize > 18) { - fracExp = decPt - 18; - mantSize = 18; - } else { - fracExp = decPt - mantSize; - } - if (mantSize == 0) { - fraction = 0.0; - p = string; - goto done; - } else { - int frac1, frac2; - frac1 = 0; - for ( ; mantSize > 9; mantSize -= 1) - { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac1 = 10*frac1 + (c - '0'); - } - frac2 = 0; - for (; mantSize > 0; mantSize -= 1) - { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac2 = 10*frac2 + (c - '0'); - } - fraction = (1.0e9f * frac1) + frac2; - } - - /* - * Skim off the exponent. - */ - - p = pExp; - if ((*p == 'E') || (*p == 'e')) { - p += 1; - if (*p == '-') { - expSign = TRUE; - p += 1; - } else { - if (*p == '+') { - p += 1; - } - expSign = FALSE; - } - while (isdigit(*p)) { - exp = exp * 10 + (*p - '0'); - p += 1; - } - } - if (expSign) { - exp = fracExp - exp; - } else { - exp = fracExp + exp; - } - - /* - * Generate a floating-point number that represents the exponent. - * Do this by processing the exponent one bit at a time to combine - * many powers of 2 of 10. Then combine the exponent with the - * fraction. - */ - - if (exp < 0) { - expSign = TRUE; - exp = -exp; - } else { - expSign = FALSE; - } - const int maxExponent = 38; /* Largest possible base 10 exponent. Any - * exponent larger than this will already - * produce underflow or overflow, so there's - * no need to worry about additional digits. - */ - - if (exp > maxExponent) { - exp = maxExponent; - } - dblExp = 1.0f; - - for (d = _strtof_powersOf10_; exp != 0; exp >>= 1, d += 1) { - if (exp & 01) { - dblExp *= *d; - } - } - /* - if (exp) { - if (exp & 01) - dblExp *= 10.0f; - exp >>= 1; - - if (exp) { - if (exp & 01) - dblExp *= 100.0f; - exp >>= 1; - - if (exp) { - if (exp & 01) - dblExp *= 1.0e4f; - exp >>= 1; - - if (exp) { - if (exp & 01) - dblExp *= 1.0e8f; - exp >>= 1; - - if (exp) { - if (exp & 01) - dblExp *= 1.0e16f; - exp >>= 1; - - if (exp) { - if (exp & 01) - dblExp *= 1.0e32f; - //exp >>= 1; - } - } - } - } - } - }*/ - - - if (expSign) { - fraction /= dblExp; - } else { - fraction *= dblExp; - } - -done: - if (endPtr != NULL) { - *endPtr = (__global char *) p; - } - - if (sign) { - return -fraction; - } - return fraction; -} diff --git a/libraries/OpenCL/MavenPlugin/.gitignore b/libraries/OpenCL/MavenPlugin/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/MavenPlugin/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/MavenPlugin/pom.xml b/libraries/OpenCL/MavenPlugin/pom.xml deleted file mode 100644 index 36c98044a..000000000 --- a/libraries/OpenCL/MavenPlugin/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - 4.0.0 - com.nativelibs4java - maven-javacl-plugin - Maven JavaCL Plugin - http://code.google.com/p/javacl/ - maven-plugin - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl-generator - - - - org.apache.maven - maven-plugin-api - 3.0.3 - - - - org.apache.maven - maven-project - 3.0-alpha-2 - - - - - - - diff --git a/libraries/OpenCL/MavenPlugin/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java b/libraries/OpenCL/MavenPlugin/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java deleted file mode 100644 index bffd14cb0..000000000 --- a/libraries/OpenCL/MavenPlugin/src/main/java/com/nativelibs4java/opencl/generator/JavaCLGeneratorMojo.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.opencl.generator; - -import com.ochafik.io.IOUtils; -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.JNAeratorConfig; -import com.ochafik.lang.jnaerator.SourceFiles; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.project.MavenProject; -import org.apache.maven.plugin.MojoExecutionException; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.*; -import java.util.ArrayList; -import org.apache.maven.model.Resource; - -/** - * Launch JNAerator to wrap native libraries in Java for use with JNA. - * @goal compile - * @phase generate-sources - * @execute phase=generate-sources - * @description Launches JNAerator with the command-line arguments contained in src/main/jnaerator/config.jnaerator. To launch from command line, use "mvn com.jnaerator:maven-jnaerator:jnaerate" - */ -public class JavaCLGeneratorMojo - extends AbstractMojo -{ - /** - * Configuration file for JNAerator. - * @parameter expression="${project.build.directory}/../src/main/jnaerator/config.jnaerator" - * @required - */ - //private File config; - - /** - * OpenCL sources tree. - * @parameter expression="${project.build.directory}/../src/main/opencl" - * @required - */ - private File sourcesDirectory; - - /** - * OpenCL test sources tree. - * @parameter expression="${project.build.directory}/../src/test/opencl" - * @required - */ - private File testSourcesDirectory; - - /** - * Output directory for JNAerated Java sources. - * @parameter expression="${project.build.directory}/generated-sources/main/java" - * @optional - */ - private File javaOutputDirectory; - - /** - * Output directory for JNAerated Java test sources. - * @parameter expression="${project.build.directory}/generated-sources/test/java" - * @optional - */ - private File testJavaOutputDirectory; - - /** - * Output directory for OpenCL sources. - * @parameter expression="${project.build.directory}/generated-resources/" - * @optional - */ - private File openCLOutputDirectory; - - /** - * Output directory for OpenCL test sources. - * @parameter expression="${project.build.directory}/generated-test-resources/" - * @optional - */ - private File testOpenCLOutputDirectory; - - /** - * @parameter expression="${project}" - * @required - * @readonly - * @since 1.0 - */ - private MavenProject project; - - - static File canonizeDir(File f) throws IOException { - if (!f.exists()) - f.mkdirs(); - return f.getCanonicalFile(); - } - - static void listOpenCLFiles(File f, Collection out) { - if (f.isHidden()) - return; - - String n = f.getName().toLowerCase(); - if (f.isDirectory()) { - if (n.equals(".svn")) - return; - - for (File ff : f.listFiles()) - listOpenCLFiles(ff, out); - } else { - if (n.endsWith(".c") || n.endsWith(".cl") || n.endsWith(".opencl")) - out.add(f); - } - } - - public void generateAll(File root, File javaOutDir, File openCLOutDir) throws IOException, MojoExecutionException { - List sources = new ArrayList(); - root = root.getCanonicalFile(); - listOpenCLFiles(root, sources); - - getLog().info("Found " + sources.size() + " files in " + root); - String rootPath = root.getCanonicalPath(); - String openCLOutPath = openCLOutDir.getCanonicalPath(); - String javaOutPath = javaOutDir.getCanonicalPath(); - for (File file : sources) { - final JNAeratorConfig config = new JNAeratorConfig(); - config.autoConf = true; - config.forceOverwrite = true; - config.outputMode = JNAeratorConfig.OutputMode.Directory; - config.outputJar = null; - if (!javaOutDir.exists()) - javaOutDir.mkdirs(); - config.outputDir = javaOutDir; - config.addSourceFile(file, null, false, true); - config.addRootDir(root); - - final String fileName = file.getName(); - String filePath = file.getCanonicalPath(); - File openCLOutFile = new File(openCLOutPath + filePath.substring(rootPath.length())); - - int i = filePath.lastIndexOf("."); - File javaOutFile = new File(javaOutPath + filePath.substring(rootPath.length(), i) + ".java"); - if (javaOutFile.exists() && javaOutFile.lastModified() > file.lastModified()) { - getLog().info("File " + fileName + " is up-to-date. Skipping generation."); - continue; - } - - File openCLOutParent = openCLOutFile.getParentFile(); - if (!openCLOutParent.exists()) - openCLOutParent.mkdirs(); - - getLog().info("Copying " + file + " to " + openCLOutFile); - FileWriter out = new FileWriter(openCLOutFile); - FileReader in = new FileReader(file); - IOUtils.readWrite(in, out); - out.close(); - in.close(); - - JavaCLGenerator generator = new JavaCLGenerator(config); - final Throwable[] ex = new Throwable[1]; - generator.jnaerate(new Feedback() { - - @Override - public void setStatus(String string) { - if (config.verbose) - getLog().info(string); - } - - @Override - public void setFinished(Throwable e) { - getLog().info("JNAeration failed !"); - e.printStackTrace(); - ex[0] = e; - } - - @Override - public void setFinished(File toOpen) { - getLog().info("JNAeration of " + fileName + " completed in " + toOpen.getAbsolutePath()); - } - - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - - } - - @Override - public void wrappersGenerated( - com.ochafik.lang.jnaerator.Result result) { - } - }); - if (ex[0] != null) - throw new MojoExecutionException( "Error JNAerating " + fileName, ex[0]); - } - } - public void execute() - throws MojoExecutionException - { - try - { - project.addCompileSourceRoot(javaOutputDirectory.getAbsolutePath()); - project.addTestCompileSourceRoot(testJavaOutputDirectory.getAbsolutePath()); - - Resource res = new Resource(); - res.setDirectory(openCLOutputDirectory.getAbsolutePath()); - project.addResource(res); - - res = new Resource(); - res.setDirectory(testOpenCLOutputDirectory.getAbsolutePath()); - project.addTestResource(res); - - generateAll(sourcesDirectory, javaOutputDirectory, openCLOutputDirectory); - generateAll(testSourcesDirectory, testJavaOutputDirectory, testOpenCLOutputDirectory); - } - catch (MojoExecutionException e ) - { - throw e; - } - catch (Exception e ) - { - throw new MojoExecutionException( "Error running JNAerator", e ); - } - } -} \ No newline at end of file diff --git a/libraries/OpenCL/NumericalBenchmark/.gitignore b/libraries/OpenCL/NumericalBenchmark/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/NumericalBenchmark/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/NumericalBenchmark/pom.xml b/libraries/OpenCL/NumericalBenchmark/pom.xml deleted file mode 100644 index 3e437eda0..000000000 --- a/libraries/OpenCL/NumericalBenchmark/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-numerical-benchmark - JavaCL Numerical Benchmark - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - com.nativelibs4java - javacl - - - org.apache.commons - commons-math - 2.2 - - - org.scala-lang - scala-library - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - org.scala-tools - maven-scala-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - org.scala-tools - maven-scala-plugin - - - - - - - - diff --git a/libraries/OpenCL/NumericalBenchmark/src/main/java/fft/FFTBench.java b/libraries/OpenCL/NumericalBenchmark/src/main/java/fft/FFTBench.java deleted file mode 100644 index dbc997a69..000000000 --- a/libraries/OpenCL/NumericalBenchmark/src/main/java/fft/FFTBench.java +++ /dev/null @@ -1,217 +0,0 @@ -package fft; - -import com.nativelibs4java.opencl.util.fft.DoubleFFTPow2; -import com.nativelibs4java.opencl.util.fft.FloatFFTPow2; -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.opencl.util.Transformer; -import com.nativelibs4java.opencl.util.Transformer.AbstractTransformer; -import com.nativelibs4java.opencl.util.fft.DoubleDFT; -import com.nativelibs4java.opencl.util.fft.FloatDFT; -import com.nativelibs4java.util.*; -import java.io.File; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.DoubleBuffer; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.commons.math.complex.Complex; -import org.apache.commons.math.transform.FastFourierTransformer; - -/** - * MVN_OPTS=" -XX:+DoEscapeAnalysis -XX:+AggressiveOpts -XX:+UseCompressedOops -XX:+UseBiasedLocking -Xmx4g " mvn compile exec:java -Dexec.mainClass=fft.FFTBench - * @author ochafik - */ -public class FFTBench { - - static double[] complexToInterleavedDoubles(Complex[] complexInput) { - int length = complexInput.length; - double[] output = new double[length * 2]; - for (int i = 0; i < length; i++) { - int o = i * 2; - Complex c = complexInput[i]; - output[o] = c.getReal(); - output[o + 1] = c.getImaginary(); - } - return output; - } - static Complex[] interleavedDoublesToComplex(double[] input) { - int length = input.length / 2; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - int o = i * 2; - complexOutput[i] = new Complex(input[o], input[o + 1]); - } - return complexOutput; - } - static Complex[] realDoublesToComplex(double[] input) { - int length = input.length; - Complex[] complexOutput = new Complex[length]; - for (int i = 0; i < length; i++) { - complexOutput[i] = new Complex(input[i], 0); - } - return complexOutput; - } - static class ApacheComplexFFT extends AbstractTransformer { - FastFourierTransformer fft = new FastFourierTransformer(); - public ApacheComplexFFT() { - super(null, Double.class, DoubleBuffer.class); - } - - @Override - public double[] transform(CLQueue queue, double[] input, boolean inverse) { - Complex[] complexInput = interleavedDoublesToComplex(input); - Complex[] output = inverse ? - fft.inversetransform(complexInput) : - fft.transform(complexInput); - return complexToInterleavedDoubles(output); - } - - @Override - public CLEvent transform(CLQueue queue, CLBuffer input, CLBuffer output, boolean inverse, CLEvent... eventsToWaitFor) throws CLException { - throw new UnsupportedOperationException("Not supported yet."); - } - - } - static void assertArrayEquals(String title, Object a, Object b) { - if (a instanceof double[]) { - double[] aa = (double[])a, bb = (double[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionDouble) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } else if (a instanceof float[]) { - float[] aa = (float[])a, bb = (float[])b; - for (int i = 0; i < aa.length; i++) { - if (Math.abs(aa[i] - bb[i]) > precisionFloat) - throw new RuntimeException("[" + title + "] Values different at index " + i + " : " + aa[i] + " vs. " + bb[i] + " !"); - } - } - } - static final float precisionFloat = 1e-3f; - static final double precisionDouble = 1e-10; - - static void gc() { - try { - System.gc(); - Thread.sleep(100); - System.gc(); - Thread.sleep(100); - } catch (InterruptedException ex) { - Logger.getLogger(FFTBench.class.getName()).log(Level.SEVERE, null, ex); - } - } - - static void test(String title, final Transformer tr, A warmupData, final A data, final CLQueue queue, boolean hasReverse, boolean firstRun) { - int warmups = 2500; - int tests = 5; - - - System.out.println("[" + title + "] Context = " + tr.getContext()); - if (firstRun) { - System.out.print("[" + title + "] Warming up..."); - for (int i = 0; i < warmups; i++) { - tr.transform(queue, warmupData, false); - if (hasReverse) - tr.transform(queue, warmupData, true); - } - System.out.println(); - } - - A trans = null; - if (hasReverse && !"1".equals(System.getenv("NO_REVERSE"))) { - System.out.print("[" + title + "] Checking consistency of inverse..."); - trans = tr.transform(queue, data, false); - A back = tr.transform(queue, trans, true); - assertArrayEquals(title, data, back); - System.out.println(); - } - gc(); - - for (int i = 0; i < tests; i++) { - time(title/* + " (transform)"*/, new Runnable() { public void run() { - tr.transform(queue, data, false); - }}); - gc(); - } - /* - if (hasReverse) - for (int i = 0; i < tests; i++) { - final A invData = trans; - time(title + " (inverse transform)", new Runnable() { public void run() { - tr.transform(queue, invData, true); - }}); - gc(); - } - */ - } - public static void main(String[] args) throws IOException, CLBuildException { - // Create a context with the best double numbers support possible : - // (try using DeviceFeature.GPU, DeviceFeature.CPU...) - - //Native.setPreserveLastError(true); - CLContext contextDoubles = JavaCL.createBestContext(DeviceFeature.DoubleSupport); - CLContext contextFloats = JavaCL.createBestContext(); - - // Create a command queue, if possible able to execute multiple jobs in parallel - // (out-of-order queues will still respect the CLEvent chaining) - CLQueue queueFloats = contextFloats.createDefaultOutOfOrderQueueIfPossible(); - CLQueue queueDoubles = contextDoubles.createDefaultOutOfOrderQueueIfPossible(); - - int nWarm = 8; - double[] warmDoubles = createTestDoubleData(nWarm); - float[] warmFloats = toFloat(warmDoubles); - boolean testDFT = false; - - boolean first = true; - for (int nTest : new int[] { 1024, 4 * 1024, 128 * 1024, 1024 * 1024, 8 * 1024 * 1024 }) { - double[] testDoubles = createTestDoubleData(nTest); - float[] testFloats = toFloat(testDoubles); - - String sizeSuffix = ", n = " + nTest; - test("JavaCL Float FFT" + sizeSuffix, new FloatFFTPow2(contextFloats), warmFloats, testFloats, queueFloats, true, first); - test("JavaCL Double FFT" + sizeSuffix, new DoubleFFTPow2(contextDoubles), warmDoubles, testDoubles, queueDoubles, true, first); - - test("Apache Complex FFT" + sizeSuffix, new ApacheComplexFFT(), warmDoubles, testDoubles, null, true, first); - //test("Apache Real FFT" + sizeSuffix, new ApacheRealFFT(), warmDoubles, testDoubles, null, false); - - if (testDFT) { - test("JavaCL Double DFT" + sizeSuffix, new DoubleDFT(contextDoubles), warmDoubles, testDoubles, queueDoubles, true, first); - test("JavaCL Float DFT" + sizeSuffix, new FloatDFT(contextFloats), warmFloats, testFloats, queueFloats, true, first); - } - if (first) - first = false; - } - } - static void time(String title, Runnable r) { - long start = System.nanoTime(); - r.run(); - long time = System.nanoTime() - start; - System.out.println("[" + title + "] = " + (time / 1000000.0) + " milliseconds"); - } - - static double[] toReal(double[] in) { - double[] inReal = new double[in.length / 2]; - for (int i = 0; i < inReal.length; i++) - inReal[i] = in[i / 2]; - - return inReal; - } - static float[] toFloat(double[] in) { - float[] out = new float[in.length]; - for (int i = 0; i < in.length; i++) - out[i] = (float)in[i]; - - return out; - } - static double[] createTestDoubleData(int n) { - //int n = 1024 * 1024; - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double) (i + 1); - in[i * 2 + 1] = 0; - } - return in; - } -} diff --git a/libraries/OpenCL/NumericalBenchmark/src/main/scala/fft/FFTScala.scala b/libraries/OpenCL/NumericalBenchmark/src/main/scala/fft/FFTScala.scala deleted file mode 100644 index f5ff3161c..000000000 --- a/libraries/OpenCL/NumericalBenchmark/src/main/scala/fft/FFTScala.scala +++ /dev/null @@ -1,292 +0,0 @@ -package fft - -import com.nativelibs4java.opencl._ - -case class Interval(offset: Int, stride: Int, length: Int) { - - def /(parts: Int): Array[Interval] = { - val newLength = length / parts - val newStride = stride * parts - (0 until parts).map(i => Interval(offset + stride * i, newStride, newLength))(collection.breakOut) - } -} -trait Op -case class Op1(i: Interval) extends Op -case class Op2(o1: Op, o2: Op) extends Op -case class Op4(o1: Op, o2: Op, o3: Op, o4: Op) extends Op - -object FFTScala { - import scala.math._ - type Cx = (Double, Double) - - - implicit def tupleOps(a: Cx) = new { - def +(b: Cx) = - (a._1 + b._1, a._2 + b._2) - def -(b: Cx) = - (a._1 - b._1, a._2 - b._2) - - def x = a._1 - def y = a._2 - def r = x - def i = y - } - def sinCos(v: Double) = (sin(v), cos(v)) - def rotateValue(a: Cx, sinCos: Cx) = { - val (s, c) = sinCos - ( - c * a.x - s * a.y, - s * a.x + c * a.y - ) - } - def dot(a: Cx, b: Cx) = - a.x * b.x + a.y * b.y - - def conjugate(a: Cx) = - (-a.y, a.x) - - - def computeOp(i: Interval): Op = { - /*if ((i.length & 3) == 0) { // i.length is a multiple of 4 - val Array(o1, o2, o3, o4) = (i / 4) map computeOp - Op4(o1, o2, o3, o4) - } else*/ if ((i.length & 1) == 0) { // i.length is odd - val Array(o1, o2) = (i / 2) map computeOp - Op2(o1, o2) - } else { - Op1(i) - } - } - - // mvn package && java -classpath target/javacl-tutorial-1.0-beta-6.jar tutorial.FFTScala - // mvn scala:run -DmainClass=tutorial.FFTScala -DaddArgs=8 - def main(args: Array[String]): Unit = { - implicit val context = JavaCL.createBestContext(CLPlatform.DeviceFeature.DoubleSupport) - implicit val queue = context.createDefaultOutOfOrderQueueIfPossible - println("Context = " + context) - - val Array(n) = args.map(_.toInt) - val in = (0 until n).flatMap(i => Seq(i.toDouble, 0/*i / 5.0*/)).toArray//Array(1, 0, 2, 0, 3, 0, 4, 0, 5.0, 0, 6, 0) - println("Data = " + in.toSeq) - - import org.apache.commons.math.complex.Complex - import org.apache.commons.math.transform.FastFourierTransformer - val apache = new FastFourierTransformer - println("Apache = " + apache.transform(in.grouped(2).map({ case Array(x, y) => new Complex(x, y)}).toArray).map(c => (c.getReal, c.getImaginary)).toSeq) - - val outDitFFT2 = ditfft2(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - println("DITFFT2 = " + outDitFFT2.toSeq) - //println("BackDITFFT2 = " + ditfft2(outDitFFT2, false).toSeq) - - val outDitFFT4 = ditfft4InPlace(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - println("DITFFT4 = " + outDitFFT4.toSeq) - //println("BackDITFFT4 = " + ditfft4InPlace(outDitFFT4, false).toSeq) - - //val outDitFFTInPlace = fft.ditfft2InPlace(in.grouped(2).map({ case Array(x, y) => (x, y) }).toArray, true) - //println("DITFFT2InPlace = " + outDitFFTInPlace.toSeq) - //println("BackDITFFT2InPlace = " + fft.ditfft2InPlace(outDitFFTInPlace, false).toSeq) - - /*val outDitFFTInPlaceCL = fft.ditfft2InPlaceCL(in, true) - println("DITFFT2InPlace = " + outDitFFTInPlaceCL.toSeq) - println("BackDITFFT2InPlaceCL = " + fft.ditfft2InPlaceCL(outDitFFTInPlaceCL, false).toSeq) - */ - - //val outFFT = fft.fft(in, true) - //println("FFT = " + outFFT.toSeq) - //println("BackFFT = " + fft.fft(outFFT, false).toSeq) - } - - // http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm - def ditfft2(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = ditfft2(X, X.length, 1, !forward) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - def ditfft2InPlace(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = new Array[(Double, Double)](X.length) - ditfft2InPlace(X, X.length, 1, !forward, 0, Y, 0) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - - private def ditfft2(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offset: Int = 0): Array[(Double, Double)] = { - assert(N >= 0) - if (N == 1) { - //println("Terminal : " + offset) - Array(X(offset)) - } - else { - val N2 = N / 2 - val s2 = s * 2 - val Y = ditfft2(X, N2, s2, inverse, offset) ++ ditfft2(X, N2, s2, inverse, offset + s) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until N / 2) { - val param: Double = - 2 * Pi * k / N.toDouble * (if (inverse) -1 else 1) - val (s, c) = sinCos(param) - - val (y1Real, y1Imag) = Y(k) - val (y2Real, y2Imag) = Y(k + N / 2) - - // (c + i * s) * (y2Real + i * y2Imag) - - val vReal = c * y2Real - s * y2Imag - val vImag = c * y2Imag + s * y2Real - Y(k) = ( - y1Real + vReal, - y1Imag + vImag - ) - Y(k + N / 2) = ( - y1Real - vReal, - y1Imag - vImag - ) - } - Y - } - } - - def ditfft4InPlace(X: Array[(Double, Double)], forward: Boolean): Array[(Double, Double)] = { - val Y = new Array[(Double, Double)](X.length) - ditfft4InPlace(X, X.length, 1, !forward, 0, Y, 0) - if (forward) - Y - else { - val l = X.length.toDouble - Y.map { case (x, y) => (x / l, y / l) } - } - } - - private def ditfft2InPlace(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offsetX: Int, Y: Array[(Double, Double)], offsetY: Int): Unit = { - //println("Inplace exec N = " + N + ", s = " + s + ", offsetX = " + offsetX + ", offsetY = " + offsetY) - assert(N >= 0) - if (N == 1) { - //println("Terminal : " + offsetX + " going to " + offsetY) - Y(offsetY) = X(offsetX) - //Array(X(offsetX)) - } - else { - val halfN = N / 2 - val twiceS = s * 2 - - ditfft2InPlace(X, halfN, twiceS, inverse, offsetX, Y, offsetY) - ditfft2InPlace(X, halfN, twiceS, inverse, offsetX + s, Y, offsetY + halfN) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until halfN) { - val param: Double = - 2 * Pi * k / N.toDouble * (if (inverse) -1 else 1) - val sc = sinCos(param) - - val p = Y(offsetY + k) - val p1 = Y(offsetY + k + N / 2) - - val t = rotateValue(p1, sc) - - Y(offsetY + k) = p + t - Y(offsetY + k + N / 2) = p - t - } - } - } - private def ditfft4InPlace(X: Array[(Double, Double)], N: Int, s: Int, inverse: Boolean, offsetX: Int, Y: Array[(Double, Double)], offsetY: Int): Unit = { - //println("Inplace exec N = " + N + ", s = " + s + ", offsetX = " + offsetX + ", offsetY = " + offsetY) - assert(N > 0) - if (N <= 1) { - //println("Terminal : " + offsetX + " going to " + offsetY) - Y(offsetY) = X(offsetX) - //Array(X(offsetX)) - } - else { - val subN = N / 4 - val subS = s * 4 - - ditfft4InPlace(X, subN, subS, inverse, offsetX, Y, offsetY) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s, Y, offsetY + subN) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s * 2, Y, offsetY + subN * 2) - ditfft4InPlace(X, subN, subS, inverse, offsetX + s * 3, Y, offsetY + subN * 3) - //println("Y(N = " + N + ") = " + Y.mkString(", ")) - for (k <- 0 until subN) { - //val fullN = subN//X.length//N - val param: Double = - 2 * Pi * k / subN.toDouble * (if (inverse) -1 else 1) - val sc1 = sinCos(param * 1) - val sc2 = sinCos(param * 2) - val sc3 = sinCos(param * 3) - - val o = offsetY + k - val o1 = o + subN - val o2 = o + subN * 2 - val o3 = o + subN * 3 - - // http://cnx.org/content/m17384/latest/ - // http://perso.telecom-paristech.fr/~danger/amen_old/fft/ - // ftp://www.ce.cmu.edu/hsuantuc/Public/toolbox/rtw/targets/tic6000/tic6000/rtlib/include/c64/dsp_fft16x16t.h - - val p = Y(o) - val p1 = Y(o1) - val p2 = Y(o2) - val p3 = Y(o3) - - def rot(a: Cx, sinCos: Cx) = { - rotateValue(a, sinCos) - /* - val (x, y) = a - val (s, c) = sinCos; - ( - c * x + s * y, - c * y - s * x - )//*/ - } -/* - val t = p + p2 - val t1 = p1 + p3 - val t2 = p - p2 - val t3 = p1 - p3 - - println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = t + t1 - Y(o1) = rot(t2 - conjugate(t3), sc1) - Y(o2) = rot(t - t1, sc2) - Y(o3) = rot(t2 + conjugate(t3), sc3) -*/ - val th = p + p2 - val tl = p - p2 - val th2 = p1 + p3 - val tl2 = p1 - p3 - - println("N = " + N + ", o = " + o + " :\n\tth = " + th + ", tl = " + tl + ", th2 = " + th2 + ", tl2 = " + tl2 + "\n\tsc1 = " + sc1 + ", sc2 = " +sc2 + ", sc3 = " + sc3) - // println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = th + th2 - Y(o1) = rot(tl - conjugate(tl2), sc1) - Y(o2) = rot(th - th2, sc2) - Y(o3) = rot(tl + conjugate(tl2), sc3) - - /* - * - // println("N = " + N + ", o = " + o + " :\n\tt = " + t + ", t1 = " + t1 + ", t2 = " + t2 + ", t3 = " + t3) - Y(o) = th + th2 - Y(o1) = rot(tl - conjugate(tl2), sc1) - Y(o2) = rot(th - th2, sc2) - Y(o3) = rot(tl + conjugate(tl2), sc3) - - */ - } - } - } -} -/* - -x x x x x x x x Interval(0, 1, 8) - -x x x x Interval(0, 2, 4) - x x x x Interval(1, 2, 4) - -x x Interval(0, 4, 2) - x x Interval(2, 4, 2) - x x Interval(1, 4, 2) - x x Interval(3, 4, 2) - -*/ \ No newline at end of file diff --git a/libraries/OpenCL/OpenCL4Java/.classpath b/libraries/OpenCL/OpenCL4Java/.classpath deleted file mode 100644 index 725911444..000000000 --- a/libraries/OpenCL/OpenCL4Java/.classpath +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/libraries/OpenCL/OpenCL4Java/.gitignore b/libraries/OpenCL/OpenCL4Java/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/OpenCL4Java/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/OpenCL4Java/.project b/libraries/OpenCL/OpenCL4Java/.project deleted file mode 100644 index acc46e366..000000000 --- a/libraries/OpenCL/OpenCL4Java/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - OpenCL4Java - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/OpenCL/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs b/libraries/OpenCL/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 377e7a5f1..000000000 --- a/libraries/OpenCL/OpenCL4Java/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:17 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/OpenCL/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs b/libraries/OpenCL/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/OpenCL/OpenCL4Java/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/OpenCL/OpenCL4Java/opencl4java-bridj.iml b/libraries/OpenCL/OpenCL4Java/opencl4java-bridj.iml deleted file mode 100644 index 72af1b343..000000000 --- a/libraries/OpenCL/OpenCL4Java/opencl4java-bridj.iml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenCL4Java/opencl4java.iml b/libraries/OpenCL/OpenCL4Java/opencl4java.iml deleted file mode 100644 index fcc43623b..000000000 --- a/libraries/OpenCL/OpenCL4Java/opencl4java.iml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenCL4Java/pom.xml b/libraries/OpenCL/OpenCL4Java/pom.xml deleted file mode 100644 index 2b9aedaca..000000000 --- a/libraries/OpenCL/OpenCL4Java/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - 4.0.0 - com.nativelibs4java - opencl4java - OpenCL4Java / BridJ - http://code.google.com/p/nativelibs4java/wiki/OpenCL - jar - - -OpenCL4Java is a thin Java wrapper around OpenCL's C API. -It uses JNA as its interop layer library, which means it works on all of the (many) JNA-supported platforms (see http://jna.dev.java.net/). -It is autogenerated by JNAerator (http://jnaerator.googlecode.com/), so updates to newer OpenCL specs are a matter of seconds. - -Note that OpenCL4Java is used by JavaCL, an Object-Oriented API that presents OpenCL in a much more practical, powerful and idiomatic way to Java. -For more info, please visit http://code.google.com/p/nativelibs4java/wiki/OpenCL. - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - bridj - - 0.6.2-SNAPSHOT - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenCL4Java/regenerate.cmd b/libraries/OpenCL/OpenCL4Java/regenerate.cmd deleted file mode 100644 index a46b7c5eb..000000000 --- a/libraries/OpenCL/OpenCL4Java/regenerate.cmd +++ /dev/null @@ -1,3 +0,0 @@ -mvn com.jnaerator:maven-jnaerator-plugin:jnaerate -del src\main\scala\*.scala -mvn install \ No newline at end of file diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl.h deleted file mode 100644 index e2889a37e..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl.h +++ /dev/null @@ -1,872 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2009 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_address_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_command_queue_properties; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_uint cl_image_info; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - - - -/******************************************************************************/ - -// Error Codes -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 - -// OpenCL Version -#define CL_VERSION_1_0 1 - -// cl_bool -#define CL_FALSE 0 -#define CL_TRUE 1 - -// cl_platform_info -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 - -// cl_device_type - bitfield -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -// cl_device_info -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 - -// cl_device_fp_config - bitfield -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) - -// cl_device_mem_cache_type -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -// cl_device_local_mem_type -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -// cl_device_exec_capabilities - bitfield -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -// cl_command_queue_properties - bitfield -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) - -// cl_context_info -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 - -// cl_context_properties -#define CL_CONTEXT_PLATFORM 0x1084 - -// cl_command_queue_info -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 - -// cl_mem_flags - bitfield -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) - -// cl_channel_order -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 - -// cl_channel_type -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE - -// cl_mem_object_type -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 - -// cl_mem_info -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 - -// cl_image_info -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 - -// cl_addressing_mode -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 - -// cl_filter_mode -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -// cl_sampler_info -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 - -// cl_map_flags - bitfield -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) - -// cl_program_info -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 - -// cl_program_build_info -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 - -// cl_build_status -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -// cl_kernel_info -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 - -// cl_kernel_work_group_info -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 - -// cl_event_info -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 - -// cl_command_type -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 - -// command execution status -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -// cl_profiling_info -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 - -/********************************************************************************************************/ - -// Platform API -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Device APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Context APIs -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (*pfn_notify)(const char *, const void *, size_t, void *) /* pfn_notify */, - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (*pfn_notify)(const char *, const void *, size_t, void *) /* pfn_notify */, - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Command Queue APIs -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetCommandQueueProperty(cl_command_queue /* command_queue */, - cl_command_queue_properties /* properties */, - cl_bool /* enable */, - cl_command_queue_properties * /* old_properties */) CL_API_SUFFIX__VERSION_1_0; - -// Memory Object APIs -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Sampler APIs -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Program Object APIs -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (*pfn_notify)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Kernel Object APIs -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Event Object APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -// Profiling APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -// Flush and Finish APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -// Enqueued Commands APIs -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* cb */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* cb */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (*user_func)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -// Extension function access -// -// Returns the extension function address for the given function name, -// or NULL if a valid function can not be found. The client must -// check to make sure the address is not NULL, before using or -// calling the returned function address. -// -extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddress(const char * /* func_name */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif // __OPENCL_CL_H - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h deleted file mode 100644 index f8ee05c40..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_gl.h +++ /dev/null @@ -1,124 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2009 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 8407 $ on $Date: 2009-06-12 10:56:38 -0700 (Fri, 12 Jun 2009) $ */ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#include -#else -#include -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// NOTE: Make sure that appropriate GL header file is included separately - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; - -// cl_gl_object_type -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 - -// cl_gl_texture_info -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 - -// CL_KHR_gl_sharing -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - GLenum /* target */, - GLint /* miplevel */, - GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - GLenum /* target */, - GLint /* miplevel */, - GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif // __OPENCL_CL_GL_H diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h deleted file mode 100644 index 95810d637..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.0/CL/cl_platform.h +++ /dev/null @@ -1,302 +0,0 @@ -/* ============================================================ - -Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved. - -Redistribution and use of this material is permitted under the following -conditions: - -Redistributions must retain the above copyright notice and all terms of this -license. - -In no event shall anyone redistributing or accessing or using this material -commence or participate in any arbitration or legal action relating to this -material against Advanced Micro Devices, Inc. or any copyright holders or -contributors. The foregoing shall survive any expiration or termination of -this license or any agreement or access or use related to this material. - -ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION -OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. - -THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT -HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY -REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO -SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERATION, OR THAT IT IS FREE -FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER -EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED -WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, -ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. -IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT -OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY -ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES, -INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS -(US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS -THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND -ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, -OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE -FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE -CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR -DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR -CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE -THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL -SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR -ACCESS OR USE RELATED TO THIS MATERIAL. - -NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS -MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO -RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER -COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH -AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS -DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. -MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, -EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, -INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS, -COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS. -MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY -LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. - -NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is -provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to -computer software and technical data, respectively. Use, duplication, -distribution or disclosure by the U.S. Government and/or DOD agencies is -subject to the full extent of restrictions in all applicable regulations, -including those found at FAR52.227 and DFARS252.227 et seq. and any successor -regulations thereof. Use of this material by the U.S. Government and/or DOD -agencies is acknowledgment of the proprietary rights of any copyright holders -and contributors, including those of Advanced Micro Devices, Inc., as well as -the provisions of FAR52.227-14 through 23 regarding privately developed and/or -commercial computer software. - -This license forms the entire agreement regarding the subject matter hereof and -supersedes all proposals and prior discussions and writings between the parties -with respect thereto. This license does not affect any ownership, rights, title, -or interest in, or relating to, this material. No terms of this license can be -modified or waived, and no breach of this license can be excused, unless done -so in a writing signed by all affected parties. Each term of this license is -separately enforceable. If any term of this license is determined to be or -becomes unenforceable or illegal, such term shall be reformed to the minimum -extent necessary in order for this license to remain in effect in accordance - -with its terms as modified by such reformation. This license shall be governed -by and construed in accordance with the laws of the State of Texas without -regard to rules on conflicts of law of any state or jurisdiction or the United -Nations Convention on the International Sale of Goods. All disputes arising out -of this license shall be subject to the jurisdiction of the federal and state -courts in Austin, Texas, and all defenses are hereby waived concerning personal -jurisdiction and venue of these courts. - -============================================================ */ - -#ifndef CL_PLATFORM_H_ -#define CL_PLATFORM_H_ - -#if !defined(_WIN32) -# include -#endif /* !_WIN32 */ -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifdef _MSC_VER -# define __CL_IMPORT __declspec(dllimport) -# define __CL_EXPORT -# define __CL_CALL __stdcall -# define __CL_SUFFIX -#else -# define __CL_IMPORT -# define __CL_EXPORT -# define __CL_CALL -# define __CL_SUFFIX -#endif - -#define CL_API_CALL __CL_CALL -#define CL_API_SUFFIX __CL_SUFFIX -#define CL_API_SUFFIX__VERSION_1_0 CL_API_SUFFIX -#define CL_EXTENSION_WEAK_LINK - -#ifdef OPENCL_EXPORTS -# define CL_API_ENTRY __CL_EXPORT -#else /* !OPENCL_EXPORTS */ -# define CL_API_ENTRY __CL_IMPORT -#endif /* !OPENCL_EXPORTS */ - -#if defined(_WIN32) -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; -typedef unsigned __int16 cl_half; -#else /* !_WIN32 */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short; -typedef uint16_t cl_ushort; -typedef int32_t cl_int; -typedef uint32_t cl_uint; -typedef int64_t cl_long; -typedef uint64_t cl_ulong; -typedef uint16_t cl_half; -#endif /* !_WIN32 */ -typedef float cl_float; -typedef double cl_double; - -typedef union cl_half2 { cl_half i16[2]; } cl_half2; -typedef union cl_half4 { cl_half i16[4]; } cl_half4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_half cl_half8 __attribute__ ((__vector_size__ (16))); -typedef cl_half cl_half16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_half8 { cl_half i16[8]; } cl_half8; -typedef union cl_half16 { cl_half i16[16]; } cl_half16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_char2 { cl_char i8[2]; } cl_char2; -typedef union cl_char4 { cl_char i8[4]; } cl_char4; -typedef union cl_char8 { cl_char i8[8]; } cl_char8; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_char cl_char16 __attribute__ ((__vector_size__ (16))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_char16 { cl_char i8[16]; } cl_char16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uchar2 { cl_uchar u8[2]; } cl_uchar2; -typedef union cl_uchar4 { cl_uchar u8[4]; } cl_uchar4; -typedef union cl_uchar8 { cl_uchar u8[8]; } cl_uchar8; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_uchar cl_uchar16 __attribute__ ((__vector_size__ (16))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uchar16 { cl_uchar u8[16]; } cl_uchar16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_short2 { cl_short i16[2]; } cl_short2; -typedef union cl_short4 { cl_short i16[4]; } cl_short4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_short cl_short8 __attribute__ ((__vector_size__ (16))); -typedef cl_short cl_short16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_short8 { cl_short i16[8]; } cl_short8; -typedef union cl_short16 { cl_short i16[16]; } cl_short16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ushort2 { cl_ushort u16[2]; } cl_ushort2; -typedef union cl_ushort4 { cl_ushort u16[4]; } cl_ushort4; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_ushort cl_ushort8 __attribute__ ((__vector_size__ (16))); -typedef cl_ushort cl_ushort16 __attribute__ ((__vector_size__ (32))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ushort8 { cl_ushort u16[8]; } cl_ushort8; -typedef union cl_ushort16 { cl_ushort u16[16]; } cl_ushort16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_int2 { cl_int i32[2]; } cl_int2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_int cl_int4 __attribute__ ((__vector_size__ (16))); -typedef cl_int cl_int8 __attribute__ ((__vector_size__ (32))); -typedef cl_int cl_int16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_int4 { cl_int i32[4]; } cl_int4; -typedef union cl_int8 { cl_int i32[8]; } cl_int8; -typedef union cl_int16 { cl_int i32[16]; } cl_int16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uint2 { cl_uint u32[2]; } cl_uint2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_uint cl_uint4 __attribute__ ((__vector_size__ (16))); -typedef cl_uint cl_uint8 __attribute__ ((__vector_size__ (32))); -typedef cl_uint cl_uint16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_uint4 { cl_uint u32[4]; } cl_uint4; -typedef union cl_uint8 { cl_uint u32[8]; } cl_uint8; -typedef union cl_uint16 { cl_uint u32[16]; } cl_uint16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_long cl_long2 __attribute__ ((__vector_size__ (16))); -typedef cl_long cl_long4 __attribute__ ((__vector_size__ (32))); -typedef cl_long cl_long8 __attribute__ ((__vector_size__ (64))); -typedef cl_long cl_long16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_long2 { cl_long i64[2]; } cl_long2; -typedef union cl_long4 { cl_long i64[4]; } cl_long4; -typedef union cl_long8 { cl_long i64[8]; } cl_long8; -typedef union cl_long16 { cl_long i64[16]; } cl_long16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_ulong cl_ulong2 __attribute__ ((__vector_size__ (16))); -typedef cl_ulong cl_ulong4 __attribute__ ((__vector_size__ (32))); -typedef cl_ulong cl_ulong8 __attribute__ ((__vector_size__ (64))); -typedef cl_ulong cl_ulong16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_ulong2 { cl_ulong u64[2]; } cl_ulong2; -typedef union cl_ulong4 { cl_ulong u64[4]; } cl_ulong4; -typedef union cl_ulong8 { cl_ulong u64[8]; } cl_ulong8; -typedef union cl_ulong16 { cl_ulong u64[16]; } cl_ulong16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_float2 { cl_float f32[2]; } cl_float2; -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_float cl_float4 __attribute__ ((__vector_size__ (16))); -typedef cl_float cl_float8 __attribute__ ((__vector_size__ (32))); -typedef cl_float cl_float16 __attribute__ ((__vector_size__ (64))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_float4 { cl_float f32[4]; } cl_float4; -typedef union cl_float8 { cl_float f32[8]; } cl_float8; -typedef union cl_float16 { cl_float f32[16]; } cl_float16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -#if defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER)) -typedef cl_double cl_double2 __attribute__ ((__vector_size__ (16))); -typedef cl_double cl_double4 __attribute__ ((__vector_size__ (32))); -typedef cl_double cl_double8 __attribute__ ((__vector_size__ (64))); -typedef cl_double cl_double16 __attribute__ ((__vector_size__ (128))); -#else /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ -typedef union cl_double2 { cl_double f64[2]; } cl_double2; -typedef union cl_double4 { cl_double f64[4]; } cl_double4; -typedef union cl_double8 { cl_double f64[8]; } cl_double8; -typedef union cl_double16 { cl_double f64[16]; } cl_double16; -#endif /*defined(__SSE__) && (defined(__GNUC__) || defined(__INTEL_COMPILER))*/ - -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX FLT_MAX -#define CL_FLT_MIN FLT_MIN -#define CL_FLT_EPSILON FLT_EPSILON - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX DBL_MAX -#define CL_DBL_MIN DBL_MIN -#define CL_DBL_EPSILON DBL_EPSILON - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* __cplusplus */ - -#endif /* CL_PLATFORM_H_ */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl.h deleted file mode 100644 index acd18cd2d..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl.h +++ /dev/null @@ -1,997 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_command_queue_properties; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_uint cl_image_info; -typedef cl_uint cl_buffer_create_type; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - - -typedef struct _cl_buffer_region { - size_t origin; - size_t size; -} cl_buffer_region; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 -#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 -#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 - -/* OpenCL Version */ -#define CL_VERSION_1_0 1 -#define CL_VERSION_1_1 1 - -/* cl_bool */ -#define CL_FALSE 0 -#define CL_TRUE 1 - -/* cl_platform_info */ -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 - -/* cl_device_type - bitfield */ -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -/* cl_device_info */ -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 -/* 0x1032 reserved for CL_DEVICE_DOUBLE_FP_CONFIG */ -/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 -#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C -#define CL_DEVICE_OPENCL_C_VERSION 0x103D - -/* cl_device_fp_config - bitfield */ -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) -#define CL_FP_SOFT_FLOAT (1 << 6) - -/* cl_device_mem_cache_type */ -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -/* cl_device_local_mem_type */ -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -/* cl_device_exec_capabilities - bitfield */ -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -/* cl_command_queue_properties - bitfield */ -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) - -/* cl_context_info */ -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 -#define CL_CONTEXT_NUM_DEVICES 0x1083 - -/* cl_context_info + cl_context_properties */ -#define CL_CONTEXT_PLATFORM 0x1084 - -/* cl_command_queue_info */ -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 - -/* cl_mem_flags - bitfield */ -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) - -/* cl_channel_order */ -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 -#define CL_Rx 0x10BA -#define CL_RGx 0x10BB -#define CL_RGBx 0x10BC - -/* cl_channel_type */ -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE - -/* cl_mem_object_type */ -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 - -/* cl_mem_info */ -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 -#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 -#define CL_MEM_OFFSET 0x1108 - -/* cl_image_info */ -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 - -/* cl_addressing_mode */ -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 -#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 - -/* cl_filter_mode */ -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -/* cl_sampler_info */ -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 - -/* cl_map_flags - bitfield */ -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) - -/* cl_program_info */ -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 - -/* cl_program_build_info */ -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 - -/* cl_build_status */ -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -/* cl_kernel_info */ -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 - -/* cl_kernel_work_group_info */ -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 -#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 -#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 - -/* cl_event_info */ -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 -#define CL_EVENT_CONTEXT 0x11D4 - -/* cl_command_type */ -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 -#define CL_COMMAND_READ_BUFFER_RECT 0x1201 -#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 -#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 -#define CL_COMMAND_USER 0x1204 - -/* command execution status */ -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -/* cl_buffer_create_type */ -#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 - -/* cl_profiling_info */ -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 - -/********************************************************************************************************/ - -/* Platform API */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Device APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Context APIs */ -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Command Queue APIs */ -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS -#warning CL_USE_DEPRECATED_OPENCL_1_0_APIS is defined. These APIs are unsupported and untested in OpenCL 1.1! -/* - * WARNING: - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. - * - * Software developers previously relying on this API are instructed to set the command queue - * properties when creating the queue, instead. - */ -extern CL_API_ENTRY cl_int CL_API_CALL -clSetCommandQueueProperty(cl_command_queue /* command_queue */, - cl_command_queue_properties /* properties */, - cl_bool /* enable */, - cl_command_queue_properties * /* old_properties */) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED; -#endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ - -/* Memory Object APIs */ -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateSubBuffer(cl_mem /* buffer */, - cl_mem_flags /* flags */, - cl_buffer_create_type /* buffer_create_type */, - const void * /* buffer_create_info */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetMemObjectDestructorCallback( cl_mem /* memobj */, - void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; - -/* Sampler APIs */ -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Program Object APIs */ -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Kernel Object APIs */ -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Event Object APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateUserEvent(cl_context /* context */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetUserEventStatus(cl_event /* event */, - cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetEventCallback( cl_event /* event */, - cl_int /* command_exec_callback_type */, - void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; - -/* Profiling APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Flush and Finish APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Enqueued Commands APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* cb */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* cb */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin */, - const size_t * /* dst_origin */, - const size_t * /* region */, - size_t /* src_row_pitch */, - size_t /* src_slice_pitch */, - size_t /* dst_row_pitch */, - size_t /* dst_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* cb */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (*user_func)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Extension function access - * - * Returns the extension function address for the given function name, - * or NULL if a valid function can not be found. The client must - * check to make sure the address is not NULL, before using or - * calling the returned function address. - */ -extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddress(const char * /* func_name */) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_H */ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h deleted file mode 100644 index f5f7371e4..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_ext.h +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11687 $ on $Date: 2010-06-11 15:17:22 -0700 (Fri, 11 Jun 2010) $ */ - -/* cl_ext.h contains OpenCL extensions which don't have external */ -/* (OpenGL, D3D) dependencies. */ - -#ifndef __CL_EXT_H -#define __CL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include - #include -#else - #include -#endif - -/* cl_khr_fp64 extension - no extension #define since it has no functions */ -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 - -/* cl_khr_fp16 extension - no extension #define since it has no functions */ -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 - -/* Memory object destruction - * - * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR - * - * Registers a user callback function that will be called when the memory object is deleted and its resources - * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback - * stack associated with memobj. The registered user callback functions are called in the reverse order in - * which they were registered. The user callback functions are called and then the memory object is deleted - * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be - * notified when the memory referenced by host_ptr, specified when the memory object is created and used as - * the storage bits for the memory object, can be reused or freed. - * - * The application may not call CL api's with the cl_mem object passed to the pfn_notify. - * - * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - */ -#define cl_APPLE_SetMemObjectDestructor 1 -cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, - void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/* Context Logging Functions - * - * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). - * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - * - * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger - */ -#define cl_APPLE_ContextLoggingFunctions 1 -extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ -extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ -extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/************************ -* cl_khr_icd extension * -************************/ -#define cl_khr_icd 1 - -/* cl_platform_info */ -#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 - -/* Additional Error Codes */ -#define CL_PLATFORM_NOT_FOUND_KHR -1001 - -extern CL_API_ENTRY cl_int CL_API_CALL -clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( - cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - - -/****************************************** -* cl_nv_device_attribute_query extension * -******************************************/ -/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ -#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 -#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 -#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 -#define CL_DEVICE_WARP_SIZE_NV 0x4003 -#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 -#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 -#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 - - -/********************************* -* cl_amd_device_attribute_query * -*********************************/ -#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 - - -#ifdef CL_VERSION_1_1 - /*********************************** - * cl_ext_device_fission extension * - ***********************************/ - #define cl_ext_device_fission 1 - - extern CL_API_ENTRY cl_int CL_API_CALL - clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int CL_API_CALL - clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef cl_ulong cl_device_partition_property_ext; - extern CL_API_ENTRY cl_int CL_API_CALL - clCreateSubDevicesEXT( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int - ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - /* cl_device_partition_property_ext */ - #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 - #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 - #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 - #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 - - /* clDeviceGetInfo selectors */ - #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 - #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 - #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 - #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 - #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 - - /* error codes */ - #define CL_DEVICE_PARTITION_FAILED_EXT -1057 - #define CL_INVALID_PARTITION_COUNT_EXT -1058 - #define CL_INVALID_PARTITION_NAME_EXT -1059 - - /* CL_AFFINITY_DOMAINs */ - #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 - #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 - #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 - #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 - #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 - #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 - - /* cl_device_partition_property_ext list terminators */ - #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) - - - -#endif /* CL_VERSION_1_1 */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __CL_EXT_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h deleted file mode 100644 index 3b4fe0690..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl.h +++ /dev/null @@ -1,155 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* - * cl_gl.h contains Khronos-approved (KHR) OpenCL extensions which have - * OpenGL dependencies. The application is responsible for #including - * OpenGL or OpenGL ES headers before #including cl_gl.h. - */ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; -typedef struct __GLsync *cl_GLsync; - -/* cl_gl_object_type */ -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 - -/* cl_gl_texture_info */ -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -/* cl_khr_gl_sharing extension */ - -#define cl_khr_gl_sharing 1 - -typedef cl_uint cl_gl_context_info; - -/* Additional Error Codes */ -#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 - -/* cl_gl_context_info */ -#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 -#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 - -/* Additional cl_context_properties */ -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLContextInfoKHR(const cl_context_properties * /* properties */, - cl_gl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( - const cl_context_properties * properties, - cl_gl_context_info param_name, - size_t param_value_size, - void * param_value, - size_t * param_value_size_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h deleted file mode 100644 index 26e47821f..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_gl_ext.h +++ /dev/null @@ -1,69 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ -/* OpenGL dependencies. */ - -#ifndef __OPENCL_CL_GL_EXT_H -#define __OPENCL_CL_GL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include -#else - #include -#endif - -/* - * For each extension, follow this template - * /* cl_VEN_extname extension */ -/* #define cl_VEN_extname 1 - * ... define new types, if any - * ... define new tokens, if any - * ... define new APIs, if any - * - * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header - * This allows us to avoid having to decide whether to include GL headers or GLES here. - */ - -/* - * cl_khr_gl_event extension - * See section 9.9 in the OpenCL 1.1 spec for more information - */ -#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromGLsyncKHR(cl_context /* context */, - cl_GLsync /* cl_GLsync */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h deleted file mode 100644 index b102ca5a2..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/cl_platform.h +++ /dev/null @@ -1,1175 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __CL_PLATFORM_H -#define __CL_PLATFORM_H - -#ifdef __APPLE__ - /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ - #include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) - #define CL_API_ENTRY - #define CL_API_CALL __stdcall - #define CL_CALLBACK __stdcall -#else - #define CL_API_ENTRY - #define CL_API_CALL - #define CL_CALLBACK -#endif - -#ifdef __APPLE__ - #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) - #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_API_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER -#else - #define CL_EXTENSION_WEAK_LINK - #define CL_API_SUFFIX__VERSION_1_0 - #define CL_EXT_SUFFIX__VERSION_1_0 - #define CL_API_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED -#endif - -#if (defined (_WIN32) && defined(_MSC_VER)) - -/* scalar types */ -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; - -typedef unsigned __int16 cl_half; -typedef float cl_float; -typedef double cl_double; - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 340282346638528859811704183484516925440.0f -#define CL_FLT_MIN 1.175494350822287507969e-38f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 -#define CL_DBL_MIN 2.225073858507201383090e-308 -#define CL_DBL_EPSILON 2.220446049250313080847e-16 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#define CL_NAN (CL_INFINITY - CL_INFINITY) -#define CL_HUGE_VALF ((cl_float) 1e50) -#define CL_HUGE_VAL ((cl_double) 1e500) -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#else - -#include - -/* scalar types */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short __attribute__((aligned(2))); -typedef uint16_t cl_ushort __attribute__((aligned(2))); -typedef int32_t cl_int __attribute__((aligned(4))); -typedef uint32_t cl_uint __attribute__((aligned(4))); -typedef int64_t cl_long __attribute__((aligned(8))); -typedef uint64_t cl_ulong __attribute__((aligned(8))); - -typedef uint16_t cl_half __attribute__((aligned(2))); -typedef float cl_float __attribute__((aligned(4))); -typedef double cl_double __attribute__((aligned(8))); - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 0x1.fffffep127f -#define CL_FLT_MIN 0x1.0p-126f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 0x1.fffffffffffffp1023 -#define CL_DBL_MIN 0x1.0p-1022 -#define CL_DBL_EPSILON 0x1.0p-52 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#if defined( __GNUC__ ) - #define CL_HUGE_VALF __builtin_huge_valf() - #define CL_HUGE_VAL __builtin_huge_val() - #define CL_NAN __builtin_nanf( "" ) -#else - #define CL_HUGE_VALF ((cl_float) 1e50) - #define CL_HUGE_VAL ((cl_double) 1e500) - float nanf( const char * ); - #define CL_NAN nanf( "" ) -#endif -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#endif - -#include - -/* Mirror types to GL types. Mirror types allow us to avoid deciding which headers to load based on whether we are using GL or GLES here. */ -typedef unsigned int cl_GLuint; -typedef int cl_GLint; -typedef unsigned int cl_GLenum; - -/* - * Vector types - * - * Note: OpenCL requires that all types be naturally aligned. - * This means that vector types must be naturally aligned. - * For example, a vector of four floats must be aligned to - * a 16 byte boundary (calculated as 4 * the natural 4-byte - * alignment of the float). The alignment qualifiers here - * will only function properly if your compiler supports them - * and if you don't actively work to defeat them. For example, - * in order for a cl_float4 to be 16 byte aligned in a struct, - * the start of the struct must itself be 16-byte aligned. - * - * Maintaining proper alignment is the user's responsibility. - */ - -/* Define basic vector types */ -#if defined( __VEC__ ) - #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ - typedef vector unsigned char __cl_uchar16; - typedef vector signed char __cl_char16; - typedef vector unsigned short __cl_ushort8; - typedef vector signed short __cl_short8; - typedef vector unsigned int __cl_uint4; - typedef vector signed int __cl_int4; - typedef vector float __cl_float4; - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_UINT4__ 1 - #define __CL_INT4__ 1 - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef float __cl_float4 __attribute__((vector_size(16))); - #else - typedef __m128 __cl_float4; - #endif - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE2__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); - typedef cl_char __cl_char16 __attribute__((vector_size(16))); - typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); - typedef cl_short __cl_short8 __attribute__((vector_size(16))); - typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); - typedef cl_int __cl_int4 __attribute__((vector_size(16))); - typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); - typedef cl_long __cl_long2 __attribute__((vector_size(16))); - typedef cl_double __cl_double2 __attribute__((vector_size(16))); - #else - typedef __m128i __cl_uchar16; - typedef __m128i __cl_char16; - typedef __m128i __cl_ushort8; - typedef __m128i __cl_short8; - typedef __m128i __cl_uint4; - typedef __m128i __cl_int4; - typedef __m128i __cl_ulong2; - typedef __m128i __cl_long2; - typedef __m128d __cl_double2; - #endif - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_INT4__ 1 - #define __CL_UINT4__ 1 - #define __CL_ULONG2__ 1 - #define __CL_LONG2__ 1 - #define __CL_DOUBLE2__ 1 -#endif - -#if defined( __MMX__ ) - #include - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); - typedef cl_char __cl_char8 __attribute__((vector_size(8))); - typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); - typedef cl_short __cl_short4 __attribute__((vector_size(8))); - typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); - typedef cl_int __cl_int2 __attribute__((vector_size(8))); - typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); - typedef cl_long __cl_long1 __attribute__((vector_size(8))); - typedef cl_float __cl_float2 __attribute__((vector_size(8))); - #else - typedef __m64 __cl_uchar8; - typedef __m64 __cl_char8; - typedef __m64 __cl_ushort4; - typedef __m64 __cl_short4; - typedef __m64 __cl_uint2; - typedef __m64 __cl_int2; - typedef __m64 __cl_ulong1; - typedef __m64 __cl_long1; - typedef __m64 __cl_float2; - #endif - #define __CL_UCHAR8__ 1 - #define __CL_CHAR8__ 1 - #define __CL_USHORT4__ 1 - #define __CL_SHORT4__ 1 - #define __CL_INT2__ 1 - #define __CL_UINT2__ 1 - #define __CL_ULONG1__ 1 - #define __CL_LONG1__ 1 - #define __CL_FLOAT2__ 1 -#endif - -#if defined( __AVX__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_float __cl_float8 __attribute__((vector_size(32))); - typedef cl_double __cl_double4 __attribute__((vector_size(32))); - #else - typedef __m256 __cl_float8; - typedef __m256d __cl_double4; - #endif - #define __CL_FLOAT8__ 1 - #define __CL_DOUBLE4__ 1 -#endif - -/* Define alignment keys */ -#if defined( __GNUC__ ) - #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) -#elif defined( _WIN32) && (_MSC_VER) - /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ - /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ - /* #include */ - /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ - #define CL_ALIGNED(_x) -#else - #warning Need to implement some method to align data here - #define CL_ALIGNED(_x) -#endif - -/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - /* .xyzw and .s0123...{f|F} are supported */ - #define CL_HAS_NAMED_VECTOR_FIELDS 1 - /* .hi and .lo are supported */ - #define CL_HAS_HI_LO_VECTOR_FIELDS 1 -#endif - -/* Define cl_vector types */ - -/* ---- cl_charn ---- */ -typedef union -{ - cl_char CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y; }; - __extension__ struct{ cl_char s0, s1; }; - __extension__ struct{ cl_char lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2; -#endif -}cl_char2; - -typedef union -{ - cl_char CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3; }; - __extension__ struct{ cl_char2 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[2]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4; -#endif -}cl_char4; - -/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ -typedef cl_char4 cl_char3; - -typedef union -{ - cl_char CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_char4 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[4]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[2]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8; -#endif -}cl_char8; - -typedef union -{ - cl_char CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_char8 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[8]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[4]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8[2]; -#endif -#if defined( __CL_CHAR16__ ) - __cl_char16 v16; -#endif -}cl_char16; - - -/* ---- cl_ucharn ---- */ -typedef union -{ - cl_uchar CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y; }; - __extension__ struct{ cl_uchar s0, s1; }; - __extension__ struct{ cl_uchar lo, hi; }; -#endif -#if defined( __cl_uchar2__) - __cl_uchar2 v2; -#endif -}cl_uchar2; - -typedef union -{ - cl_uchar CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3; }; - __extension__ struct{ cl_uchar2 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[2]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4; -#endif -}cl_uchar4; - -/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ -typedef cl_uchar4 cl_uchar3; - -typedef union -{ - cl_uchar CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uchar4 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[4]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[2]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8; -#endif -}cl_uchar8; - -typedef union -{ - cl_uchar CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uchar8 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[8]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[4]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8[2]; -#endif -#if defined( __CL_UCHAR16__ ) - __cl_uchar16 v16; -#endif -}cl_uchar16; - - -/* ---- cl_shortn ---- */ -typedef union -{ - cl_short CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y; }; - __extension__ struct{ cl_short s0, s1; }; - __extension__ struct{ cl_short lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2; -#endif -}cl_short2; - -typedef union -{ - cl_short CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3; }; - __extension__ struct{ cl_short2 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[2]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4; -#endif -}cl_short4; - -/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ -typedef cl_short4 cl_short3; - -typedef union -{ - cl_short CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_short4 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[4]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[2]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8; -#endif -}cl_short8; - -typedef union -{ - cl_short CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_short8 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[8]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[4]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8[2]; -#endif -#if defined( __CL_SHORT16__ ) - __cl_short16 v16; -#endif -}cl_short16; - - -/* ---- cl_ushortn ---- */ -typedef union -{ - cl_ushort CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y; }; - __extension__ struct{ cl_ushort s0, s1; }; - __extension__ struct{ cl_ushort lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2; -#endif -}cl_ushort2; - -typedef union -{ - cl_ushort CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3; }; - __extension__ struct{ cl_ushort2 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[2]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4; -#endif -}cl_ushort4; - -/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ -typedef cl_ushort4 cl_ushort3; - -typedef union -{ - cl_ushort CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ushort4 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[4]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[2]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8; -#endif -}cl_ushort8; - -typedef union -{ - cl_ushort CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ushort8 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[8]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[4]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8[2]; -#endif -#if defined( __CL_USHORT16__ ) - __cl_ushort16 v16; -#endif -}cl_ushort16; - -/* ---- cl_intn ---- */ -typedef union -{ - cl_int CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y; }; - __extension__ struct{ cl_int s0, s1; }; - __extension__ struct{ cl_int lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2; -#endif -}cl_int2; - -typedef union -{ - cl_int CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3; }; - __extension__ struct{ cl_int2 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[2]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4; -#endif -}cl_int4; - -/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ -typedef cl_int4 cl_int3; - -typedef union -{ - cl_int CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_int4 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[4]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[2]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8; -#endif -}cl_int8; - -typedef union -{ - cl_int CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_int8 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[8]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[4]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8[2]; -#endif -#if defined( __CL_INT16__ ) - __cl_int16 v16; -#endif -}cl_int16; - - -/* ---- cl_uintn ---- */ -typedef union -{ - cl_uint CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y; }; - __extension__ struct{ cl_uint s0, s1; }; - __extension__ struct{ cl_uint lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2; -#endif -}cl_uint2; - -typedef union -{ - cl_uint CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3; }; - __extension__ struct{ cl_uint2 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[2]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4; -#endif -}cl_uint4; - -/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ -typedef cl_uint4 cl_uint3; - -typedef union -{ - cl_uint CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uint4 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[4]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[2]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8; -#endif -}cl_uint8; - -typedef union -{ - cl_uint CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uint8 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[8]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[4]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8[2]; -#endif -#if defined( __CL_UINT16__ ) - __cl_uint16 v16; -#endif -}cl_uint16; - -/* ---- cl_longn ---- */ -typedef union -{ - cl_long CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y; }; - __extension__ struct{ cl_long s0, s1; }; - __extension__ struct{ cl_long lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2; -#endif -}cl_long2; - -typedef union -{ - cl_long CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3; }; - __extension__ struct{ cl_long2 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[2]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4; -#endif -}cl_long4; - -/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ -typedef cl_long4 cl_long3; - -typedef union -{ - cl_long CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_long4 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[4]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[2]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8; -#endif -}cl_long8; - -typedef union -{ - cl_long CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_long8 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[8]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[4]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8[2]; -#endif -#if defined( __CL_LONG16__ ) - __cl_long16 v16; -#endif -}cl_long16; - - -/* ---- cl_ulongn ---- */ -typedef union -{ - cl_ulong CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y; }; - __extension__ struct{ cl_ulong s0, s1; }; - __extension__ struct{ cl_ulong lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2; -#endif -}cl_ulong2; - -typedef union -{ - cl_ulong CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3; }; - __extension__ struct{ cl_ulong2 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[2]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4; -#endif -}cl_ulong4; - -/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ -typedef cl_ulong4 cl_ulong3; - -typedef union -{ - cl_ulong CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ulong4 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[4]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[2]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8; -#endif -}cl_ulong8; - -typedef union -{ - cl_ulong CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ulong8 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[8]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[4]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8[2]; -#endif -#if defined( __CL_ULONG16__ ) - __cl_ulong16 v16; -#endif -}cl_ulong16; - - -/* --- cl_floatn ---- */ - -typedef union -{ - cl_float CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y; }; - __extension__ struct{ cl_float s0, s1; }; - __extension__ struct{ cl_float lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2; -#endif -}cl_float2; - -typedef union -{ - cl_float CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3; }; - __extension__ struct{ cl_float2 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[2]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4; -#endif -}cl_float4; - -/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ -typedef cl_float4 cl_float3; - -typedef union -{ - cl_float CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_float4 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[4]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[2]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8; -#endif -}cl_float8; - -typedef union -{ - cl_float CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_float8 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[8]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[4]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8[2]; -#endif -#if defined( __CL_FLOAT16__ ) - __cl_float16 v16; -#endif -}cl_float16; - -/* --- cl_doublen ---- */ - -typedef union -{ - cl_double CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y; }; - __extension__ struct{ cl_double s0, s1; }; - __extension__ struct{ cl_double lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2; -#endif -}cl_double2; - -typedef union -{ - cl_double CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3; }; - __extension__ struct{ cl_double2 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[2]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4; -#endif -}cl_double4; - -/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ -typedef cl_double4 cl_double3; - -typedef union -{ - cl_double CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_double4 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[4]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[2]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8; -#endif -}cl_double8; - -typedef union -{ - cl_double CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_double8 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[8]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[4]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8[2]; -#endif -#if defined( __CL_DOUBLE16__ ) - __cl_double16 v16; -#endif -}cl_double16; - - -#ifdef __cplusplus -} -#endif - -#endif /* __CL_PLATFORM_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/opencl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/opencl.h deleted file mode 100644 index 26a638997..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.1/CL/opencl.h +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_H -#define __OPENCL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - -#include -#include -#include -#include - -#else - -#include -#include -#include -#include - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_H */ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl.h deleted file mode 100644 index c61f4ffdd..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl.h +++ /dev/null @@ -1,1239 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_command_queue_properties; -typedef intptr_t cl_device_partition_property; -typedef cl_bitfield cl_device_affinity_domain; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_bitfield cl_mem_migration_flags; -typedef cl_uint cl_image_info; -typedef cl_uint cl_buffer_create_type; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_uint cl_program_binary_type; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_arg_info; -typedef cl_uint cl_kernel_arg_address_qualifier; -typedef cl_uint cl_kernel_arg_access_qualifier; -typedef cl_bitfield cl_kernel_arg_type_qualifier; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; - - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - -typedef struct _cl_image_desc { - cl_mem_object_type image_type; - size_t image_width; - size_t image_height; - size_t image_depth; - size_t image_array_size; - size_t image_row_pitch; - size_t image_slice_pitch; - cl_uint num_mip_levels; - cl_uint num_samples; - cl_mem buffer; -} cl_image_desc; - -typedef struct _cl_buffer_region { - size_t origin; - size_t size; -} cl_buffer_region; - - -/******************************************************************************/ - -/* Error Codes */ -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 -#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 -#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 -#define CL_COMPILE_PROGRAM_FAILURE -15 -#define CL_LINKER_NOT_AVAILABLE -16 -#define CL_LINK_PROGRAM_FAILURE -17 -#define CL_DEVICE_PARTITION_FAILED -18 -#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 -#define CL_INVALID_PROPERTY -64 -#define CL_INVALID_IMAGE_DESCRIPTOR -65 -#define CL_INVALID_COMPILER_OPTIONS -66 -#define CL_INVALID_LINKER_OPTIONS -67 -#define CL_INVALID_DEVICE_PARTITION_COUNT -68 - -/* OpenCL Version */ -#define CL_VERSION_1_0 1 -#define CL_VERSION_1_1 1 -#define CL_VERSION_1_2 1 - -/* cl_bool */ -#define CL_FALSE 0 -#define CL_TRUE 1 -#define CL_BLOCKING CL_TRUE -#define CL_NON_BLOCKING CL_FALSE - -/* cl_platform_info */ -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 - -/* cl_device_type - bitfield */ -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_CUSTOM (1 << 4) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -/* cl_device_info */ -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 -/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 -#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C -#define CL_DEVICE_OPENCL_C_VERSION 0x103D -#define CL_DEVICE_LINKER_AVAILABLE 0x103E -#define CL_DEVICE_BUILT_IN_KERNELS 0x103F -#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 -#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 -#define CL_DEVICE_PARENT_DEVICE 0x1042 -#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 -#define CL_DEVICE_PARTITION_PROPERTIES 0x1044 -#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 -#define CL_DEVICE_PARTITION_TYPE 0x1046 -#define CL_DEVICE_REFERENCE_COUNT 0x1047 -#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 -#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 - -/* cl_device_fp_config - bitfield */ -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) -#define CL_FP_SOFT_FLOAT (1 << 6) -#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) - -/* cl_device_mem_cache_type */ -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -/* cl_device_local_mem_type */ -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -/* cl_device_exec_capabilities - bitfield */ -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -/* cl_command_queue_properties - bitfield */ -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) - -/* cl_context_info */ -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 -#define CL_CONTEXT_NUM_DEVICES 0x1083 - -/* cl_context_properties */ -#define CL_CONTEXT_PLATFORM 0x1084 -#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 - -/* cl_device_partition_property */ -#define CL_DEVICE_PARTITION_EQUALLY 0x1086 -#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 -#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 -#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 - -/* cl_device_affinity_domain */ -#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) -#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) -#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) -#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) -#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) -#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) - -/* cl_command_queue_info */ -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 - -/* cl_mem_flags - bitfield */ -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) -// reserved (1 << 6) -#define CL_MEM_HOST_WRITE_ONLY (1 << 7) -#define CL_MEM_HOST_READ_ONLY (1 << 8) -#define CL_MEM_HOST_NO_ACCESS (1 << 9) - -/* cl_mem_migration_flags - bitfield */ -#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) -#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) - -/* cl_channel_order */ -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 -#define CL_Rx 0x10BA -#define CL_RGx 0x10BB -#define CL_RGBx 0x10BC - -/* cl_channel_type */ -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE - -/* cl_mem_object_type */ -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 -#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 -#define CL_MEM_OBJECT_IMAGE1D 0x10F4 -#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 -#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 - -/* cl_mem_info */ -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 -#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 -#define CL_MEM_OFFSET 0x1108 - -/* cl_image_info */ -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 -#define CL_IMAGE_ARRAY_SIZE 0x1117 -#define CL_IMAGE_BUFFER 0x1118 -#define CL_IMAGE_NUM_MIP_LEVELS 0x1119 -#define CL_IMAGE_NUM_SAMPLES 0x111A - -/* cl_addressing_mode */ -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 -#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 - -/* cl_filter_mode */ -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -/* cl_sampler_info */ -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 - -/* cl_map_flags - bitfield */ -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) -#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) - -/* cl_program_info */ -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 -#define CL_PROGRAM_NUM_KERNELS 0x1167 -#define CL_PROGRAM_KERNEL_NAMES 0x1168 - -/* cl_program_build_info */ -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 -#define CL_PROGRAM_BINARY_TYPE 0x1184 - -/* cl_program_binary_type */ -#define CL_PROGRAM_BINARY_TYPE_NONE 0x0 -#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 -#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 -#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 - -/* cl_build_status */ -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -/* cl_kernel_info */ -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 -#define CL_KERNEL_ATTRIBUTES 0x1195 - -/* cl_kernel_arg_info */ -#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 -#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 -#define CL_KERNEL_ARG_TYPE_NAME 0x1198 -#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 -#define CL_KERNEL_ARG_NAME 0x119A - -/* cl_kernel_arg_address_qualifier */ -#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B -#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C -#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D -#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E - -/* cl_kernel_arg_access_qualifier */ -#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 -#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 -#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 -#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 - -/* cl_kernel_arg_type_qualifer */ -#define CL_KERNEL_ARG_TYPE_NONE 0 -#define CL_KERNEL_ARG_TYPE_CONST (1 << 0) -#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) -#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) - -/* cl_kernel_work_group_info */ -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 -#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 -#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 -#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 - -/* cl_event_info */ -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 -#define CL_EVENT_CONTEXT 0x11D4 - -/* cl_command_type */ -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 -#define CL_COMMAND_READ_BUFFER_RECT 0x1201 -#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 -#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 -#define CL_COMMAND_USER 0x1204 -#define CL_COMMAND_BARRIER 0x1205 -#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 -#define CL_COMMAND_FILL_BUFFER 0x1207 -#define CL_COMMAND_FILL_IMAGE 0x1208 - -/* command execution status */ -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -/* cl_buffer_create_type */ -#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 - -/* cl_profiling_info */ -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 - -/********************************************************************************************************/ - -/* Platform API */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Device APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateSubDevices(cl_device_id /* in_device */, - const cl_device_partition_property * /* properties */, - cl_uint /* num_devices */, - cl_device_id * /* out_devices */, - cl_uint * /* num_devices_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -/* Context APIs */ -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Command Queue APIs */ -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Memory Object APIs */ -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateSubBuffer(cl_mem /* buffer */, - cl_mem_flags /* flags */, - cl_buffer_create_type /* buffer_create_type */, - const void * /* buffer_create_info */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - const cl_image_desc * /* image_desc */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetMemObjectDestructorCallback( cl_mem /* memobj */, - void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; - -/* Sampler APIs */ -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Program Object APIs */ -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBuiltInKernels(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* kernel_names */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCompileProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_headers */, - const cl_program * /* input_headers */, - const char ** /* header_include_names */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_program CL_API_CALL -clLinkProgram(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_programs */, - const cl_program * /* input_programs */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */, - cl_int * /* errcode_ret */ ) CL_API_SUFFIX__VERSION_1_2; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadPlatformCompiler(cl_platform_id /* platform */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Kernel Object APIs */ -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelArgInfo(cl_kernel /* kernel */, - cl_uint /* arg_indx */, - cl_kernel_arg_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Event Object APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateUserEvent(cl_context /* context */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetUserEventStatus(cl_event /* event */, - cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetEventCallback( cl_event /* event */, - cl_int /* command_exec_callback_type */, - void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; - -/* Profiling APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Flush and Finish APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Enqueued Commands APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* size */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* size */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - const void * /* pattern */, - size_t /* pattern_size */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin */, - const size_t * /* dst_origin */, - const size_t * /* region */, - size_t /* src_row_pitch */, - size_t /* src_slice_pitch */, - size_t /* dst_row_pitch */, - size_t /* dst_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - const void * /* fill_color */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMigrateMemObjects(cl_command_queue /* command_queue */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_objects */, - cl_mem_migration_flags /* flags */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (CL_CALLBACK * /*user_func*/)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarkerWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrierWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetPrintfCallback(cl_context /* context */, - void (CL_CALLBACK * /* pfn_notify */)(cl_context /* program */, - cl_uint /*printf_data_len */, - char * /* printf_data_ptr */, - void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_2; - - - -/* Extension function access - * - * Returns the extension function address for the given function name, - * or NULL if a valid function can not be found. The client must - * check to make sure the address is not NULL, before using or - * calling the returned function address. - */ -extern CL_API_ENTRY void * CL_API_CALL -clGetExtensionFunctionAddressForPlatform(cl_platform_id /* platform */, - const char * /* func_name */) CL_API_SUFFIX__VERSION_1_2; - - -#ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS -#warning CL_USE_DEPRECATED_OPENCL_1_0_APIS is defined. These APIs are unsupported and untested in OpenCL 1.1! - /* - * WARNING: - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. - * - * Software developers previously relying on this API are instructed to set the command queue - * properties when creating the queue, instead. - */ - extern CL_API_ENTRY cl_int CL_API_CALL - clSetCommandQueueProperty(cl_command_queue /* command_queue */, - cl_command_queue_properties /* properties */, - cl_bool /* enable */, - cl_command_queue_properties * /* old_properties */) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED; -#endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ - - -#ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS - extern CL_API_ENTRY cl_mem CL_API_CALL - clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_mem CL_API_CALL - clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_int CL_API_CALL - clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_int CL_API_CALL - clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_int CL_API_CALL - clEnqueueBarrier(cl_command_queue /* command_queue */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_int CL_API_CALL - clUnloadCompiler(void) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY void * CL_API_CALL - clGetExtensionFunctionAddress(const char * /* func_name */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; -#endif /* CL_USE_DEPRECATED_OPENCL_1_2_APIS */ - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_H */ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_apple.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_apple.h deleted file mode 100644 index 8ba28881d..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_apple.h +++ /dev/null @@ -1,60 +0,0 @@ - -/* Context GL sharing - * - * Please check for the "cl_APPLE_gl_sharing" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using these extensions. - - * Apple extension for creating a CL context from a CGL share group - * - * This enumerated value can be specified as part of the argument passed to clCreateContext - * to allow OpenCL compliant devices in an existing CGL share group to be used as the devices in - * the newly created CL context. GL objects that were allocated in the given CGL share group can - * now be shared between CL and GL. - * - * If the and argument values to clCreateContext are 0 and NULL respectively, - * all CL compliant devices in the CGL share group will be used to create the context. - * Additional CL devices can also be specified using the and arguments. - * These, however, cannot be GPU devices. On Mac OS X, you can add the CPU to the list of CL devices - * (in addition to the CL compliant devices in the CGL share group) used to create the CL context. - * Note that if a CPU device is specified, the CGL share group must also include the GL float renderer; - * Otherwise CL_INVALID_DEVICE will be returned. - * - * NOTE: Make sure that appropriate cl_gl.h header file is included separately - */ -#define CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE 0x10000000 /* Introduced in Mac OS X 10.6 */ - -/* Apple extension for retrieving OpenGL context information for a CL context - * created via the above method. - * - * Provides a query mechanism to retrieve OpenGL context specific information - * from an OpenCL context to help identify device specific mappings and usage. - * - * For example, one possible usage would be to allow the client to map a CGL - * virtual screen index to an appropriate CL device id to insure that the - * rendering device and the compute device are the same, thus guaranteeing - * any shared OpenGL memory that is attached o a CL memory object remains - * resident on the active device. - */ -cl_int clGetGLContextInfoAPPLE ( cl_context /* context */, - void * /* platform_gl_ctx */, - cl_gl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) ; - -/* The list of supported param_name values and the information returned in param_value by - * clGetContextInfo are listed below: - - * Returns a cl_device_id for the CL device associated with the virtual screen for - * the given CGL context. Return type: cl_device_id - */ -#define CL_CGL_DEVICE_FOR_CURRENT_VIRTUAL_SCREEN_APPLE 0x10000002 /* Introduced in Mac OS X 10.6 */ - -/* Returns an array of cl_device_ids for the CL device(s) corresponding to - * the virtual screen(s) for the given CGL context. Return type: cl_device_id[] - */ -#define CL_CGL_DEVICES_FOR_SUPPORTED_VIRTUAL_SCREENS_APPLE 0x10000003 /* Introduced in Mac OS X 10.6 */ - -/* Error code returned by clGetGLContextInfoAPPLE if an invalid platform_gl_ctx is provided */ -#define CL_INVALID_GL_CONTEXT_APPLE -1000 /* Introduced in Mac OS X 10.6 */ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_ext.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_ext.h deleted file mode 100644 index 4e92c7e63..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_ext.h +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */ - -/* cl_ext.h contains OpenCL extensions which don't have external */ -/* (OpenGL, D3D) dependencies. */ - -#ifndef __CL_EXT_H -#define __CL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include - #include -#else - #include -#endif - -/* cl_khr_fp64 extension - no extension #define since it has no functions */ -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 - -/* cl_khr_fp16 extension - no extension #define since it has no functions */ -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 - -/* Memory object destruction - * - * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR - * - * Registers a user callback function that will be called when the memory object is deleted and its resources - * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback - * stack associated with memobj. The registered user callback functions are called in the reverse order in - * which they were registered. The user callback functions are called and then the memory object is deleted - * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be - * notified when the memory referenced by host_ptr, specified when the memory object is created and used as - * the storage bits for the memory object, can be reused or freed. - * - * The application may not call CL api's with the cl_mem object passed to the pfn_notify. - * - * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - */ -#define cl_APPLE_SetMemObjectDestructor 1 -cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, - void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/* Context Logging Functions - * - * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). - * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - * - * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger - */ -#define cl_APPLE_ContextLoggingFunctions 1 -extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ -extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ -extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/************************ -* cl_khr_icd extension * -************************/ -#define cl_khr_icd 1 - -/* cl_platform_info */ -#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 - -/* Additional Error Codes */ -#define CL_PLATFORM_NOT_FOUND_KHR -1001 - -extern CL_API_ENTRY cl_int CL_API_CALL -clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( - cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - - -/****************************************** -* cl_nv_device_attribute_query extension * -******************************************/ -/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ -#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 -#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 -#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 -#define CL_DEVICE_WARP_SIZE_NV 0x4003 -#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 -#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 -#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 - - -/********************************* -* cl_amd_device_attribute_query * -*********************************/ -#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 - - -#ifdef CL_VERSION_1_1 - /*********************************** - * cl_ext_device_fission extension * - ***********************************/ - #define cl_ext_device_fission 1 - - extern CL_API_ENTRY cl_int CL_API_CALL - clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int CL_API_CALL - clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef cl_ulong cl_device_partition_property_ext; - extern CL_API_ENTRY cl_int CL_API_CALL - clCreateSubDevicesEXT( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - /* cl_device_partition_property_ext */ - #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 - #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 - #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 - #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 - - /* clDeviceGetInfo selectors */ - #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 - #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 - #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 - #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 - #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 - - /* error codes */ - #define CL_DEVICE_PARTITION_FAILED_EXT -1057 - #define CL_INVALID_PARTITION_COUNT_EXT -1058 - #define CL_INVALID_PARTITION_NAME_EXT -1059 - - /* CL_AFFINITY_DOMAINs */ - #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 - #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 - #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 - #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 - #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 - #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 - - /* cl_device_partition_property_ext list terminators */ - #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) - - - -#endif /* CL_VERSION_1_1 */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __CL_EXT_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl.h deleted file mode 100644 index e8586e23c..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl.h +++ /dev/null @@ -1,163 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2011 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; -typedef struct __GLsync *cl_GLsync; - -/* cl_gl_object_type = 0x2000 - 0x200F enum values are currently taken */ -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 -#define CL_GL_OBJECT_TEXTURE2D_ARRAY 0x200E -#define CL_GL_OBJECT_TEXTURE1D 0x200F -#define CL_GL_OBJECT_TEXTURE1D_ARRAY 0x2010 -#define CL_GL_OBJECT_TEXTURE_BUFFER 0x2011 - -/* cl_gl_texture_info */ -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 - - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - - -#ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS -#warning CL_USE_DEPRECATED_OPENCL_1_1_APIS is defined. These APIs are unsupported and untested in OpenCL 1.2! - extern CL_API_ENTRY cl_mem CL_API_CALL - clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - - extern CL_API_ENTRY cl_mem CL_API_CALL - clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; -#endif /* CL_USE_DEPRECATED_OPENCL_1_2_APIS */ - -/* cl_khr_gl_sharing extension */ - -#define cl_khr_gl_sharing 1 - -typedef cl_uint cl_gl_context_info; - -/* Additional Error Codes */ -#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 - -/* cl_gl_context_info */ -#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 -#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 - -/* Additional cl_context_properties */ -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLContextInfoKHR(const cl_context_properties * /* properties */, - cl_gl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( - const cl_context_properties * properties, - cl_gl_context_info param_name, - size_t param_value_size, - void * param_value, - size_t * param_value_size_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl_ext.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl_ext.h deleted file mode 100644 index 7c9b64cfb..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_gl_ext.h +++ /dev/null @@ -1,69 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ -/* OpenGL dependencies. */ - -#ifndef __OPENCL_CL_GL_EXT_H -#define __OPENCL_CL_GL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include -#else - #include -#endif - -/* - * For each extension, follow this template - * cl_VEN_extname extension */ -/* #define cl_VEN_extname 1 - * ... define new types, if any - * ... define new tokens, if any - * ... define new APIs, if any - * - * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header - * This allows us to avoid having to decide whether to include GL headers or GLES here. - */ - -/* - * cl_khr_gl_event extension - * See section 9.9 in the OpenCL 1.1 spec for more information - */ -#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromGLsyncKHR(cl_context /* context */, - cl_GLsync /* cl_GLsync */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_platform.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_platform.h deleted file mode 100644 index c82343093..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/cl_platform.h +++ /dev/null @@ -1,1201 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11803 $ on $Date: 2010-06-25 10:02:12 -0700 (Fri, 25 Jun 2010) $ */ - -#ifndef __CL_PLATFORM_H -#define __CL_PLATFORM_H - -#ifdef __APPLE__ - /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ - #include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) - #define CL_API_ENTRY - #define CL_API_CALL __stdcall - #define CL_CALLBACK __stdcall -#else - #define CL_API_ENTRY - #define CL_API_CALL - #define CL_CALLBACK -#endif - -#ifdef __APPLE__ - #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) - #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_API_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER -#else - #define CL_EXTENSION_WEAK_LINK - #define CL_API_SUFFIX__VERSION_1_0 - #define CL_EXT_SUFFIX__VERSION_1_0 - #define CL_API_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_API_SUFFIX__VERSION_1_2 - #define CL_EXT_SUFFIX__VERSION_1_2 - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED -#endif - -#if (defined (_WIN32) && defined(_MSC_VER)) - -/* scalar types */ -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; - -typedef unsigned __int16 cl_half; -typedef float cl_float; -typedef double cl_double; - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 340282346638528859811704183484516925440.0f -#define CL_FLT_MIN 1.175494350822287507969e-38f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 -#define CL_DBL_MIN 2.225073858507201383090e-308 -#define CL_DBL_EPSILON 2.220446049250313080847e-16 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#define CL_NAN (CL_INFINITY - CL_INFINITY) -#define CL_HUGE_VALF ((cl_float) 1e50) -#define CL_HUGE_VAL ((cl_double) 1e500) -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#else - -#include - -/* scalar types */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short __attribute__((aligned(2))); -typedef uint16_t cl_ushort __attribute__((aligned(2))); -typedef int32_t cl_int __attribute__((aligned(4))); -typedef uint32_t cl_uint __attribute__((aligned(4))); -typedef int64_t cl_long __attribute__((aligned(8))); -typedef uint64_t cl_ulong __attribute__((aligned(8))); - -typedef uint16_t cl_half __attribute__((aligned(2))); -typedef float cl_float __attribute__((aligned(4))); -typedef double cl_double __attribute__((aligned(8))); - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 0x1.fffffep127f -#define CL_FLT_MIN 0x1.0p-126f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 0x1.fffffffffffffp1023 -#define CL_DBL_MIN 0x1.0p-1022 -#define CL_DBL_EPSILON 0x1.0p-52 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#if defined( __GNUC__ ) - #define CL_HUGE_VALF __builtin_huge_valf() - #define CL_HUGE_VAL __builtin_huge_val() - #define CL_NAN __builtin_nanf( "" ) -#else - #define CL_HUGE_VALF ((cl_float) 1e50) - #define CL_HUGE_VAL ((cl_double) 1e500) - float nanf( const char * ); - #define CL_NAN nanf( "" ) -#endif -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#endif - -#include - -/* Mirror types to GL types. Mirror types allow us to avoid deciding which headers to load based on whether we are using GL or GLES here. */ -typedef unsigned int cl_GLuint; -typedef int cl_GLint; -typedef unsigned int cl_GLenum; - -/* - * Vector types - * - * Note: OpenCL requires that all types be naturally aligned. - * This means that vector types must be naturally aligned. - * For example, a vector of four floats must be aligned to - * a 16 byte boundary (calculated as 4 * the natural 4-byte - * alignment of the float). The alignment qualifiers here - * will only function properly if your compiler supports them - * and if you don't actively work to defeat them. For example, - * in order for a cl_float4 to be 16 byte aligned in a struct, - * the start of the struct must itself be 16-byte aligned. - * - * Maintaining proper alignment is the user's responsibility. - */ - -/* Define basic vector types */ -#if defined( __VEC__ ) - #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ - typedef vector unsigned char __cl_uchar16; - typedef vector signed char __cl_char16; - typedef vector unsigned short __cl_ushort8; - typedef vector signed short __cl_short8; - typedef vector unsigned int __cl_uint4; - typedef vector signed int __cl_int4; - typedef vector float __cl_float4; - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_UINT4__ 1 - #define __CL_INT4__ 1 - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef float __cl_float4 __attribute__((vector_size(16))); - #else - typedef __m128 __cl_float4; - #endif - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE2__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); - typedef cl_char __cl_char16 __attribute__((vector_size(16))); - typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); - typedef cl_short __cl_short8 __attribute__((vector_size(16))); - typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); - typedef cl_int __cl_int4 __attribute__((vector_size(16))); - typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); - typedef cl_long __cl_long2 __attribute__((vector_size(16))); - typedef cl_double __cl_double2 __attribute__((vector_size(16))); - #else - typedef __m128i __cl_uchar16; - typedef __m128i __cl_char16; - typedef __m128i __cl_ushort8; - typedef __m128i __cl_short8; - typedef __m128i __cl_uint4; - typedef __m128i __cl_int4; - typedef __m128i __cl_ulong2; - typedef __m128i __cl_long2; - typedef __m128d __cl_double2; - #endif - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_INT4__ 1 - #define __CL_UINT4__ 1 - #define __CL_ULONG2__ 1 - #define __CL_LONG2__ 1 - #define __CL_DOUBLE2__ 1 -#endif - -#if defined( __MMX__ ) - #include - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); - typedef cl_char __cl_char8 __attribute__((vector_size(8))); - typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); - typedef cl_short __cl_short4 __attribute__((vector_size(8))); - typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); - typedef cl_int __cl_int2 __attribute__((vector_size(8))); - typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); - typedef cl_long __cl_long1 __attribute__((vector_size(8))); - typedef cl_float __cl_float2 __attribute__((vector_size(8))); - #else - typedef __m64 __cl_uchar8; - typedef __m64 __cl_char8; - typedef __m64 __cl_ushort4; - typedef __m64 __cl_short4; - typedef __m64 __cl_uint2; - typedef __m64 __cl_int2; - typedef __m64 __cl_ulong1; - typedef __m64 __cl_long1; - typedef __m64 __cl_float2; - #endif - #define __CL_UCHAR8__ 1 - #define __CL_CHAR8__ 1 - #define __CL_USHORT4__ 1 - #define __CL_SHORT4__ 1 - #define __CL_INT2__ 1 - #define __CL_UINT2__ 1 - #define __CL_ULONG1__ 1 - #define __CL_LONG1__ 1 - #define __CL_FLOAT2__ 1 -#endif - -#if defined( __AVX__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_float __cl_float8 __attribute__((vector_size(32))); - typedef cl_double __cl_double4 __attribute__((vector_size(32))); - #else - typedef __m256 __cl_float8; - typedef __m256d __cl_double4; - #endif - #define __CL_FLOAT8__ 1 - #define __CL_DOUBLE4__ 1 -#endif - -/* Define alignment keys */ -#if defined( __GNUC__ ) - #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) -#elif defined( _WIN32) && (_MSC_VER) - /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ - /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ - /* #include */ - /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ - #define CL_ALIGNED(_x) -#else - #warning Need to implement some method to align data here - #define CL_ALIGNED(_x) -#endif - -/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - /* .xyzw and .s0123...{f|F} are supported */ - #define CL_HAS_NAMED_VECTOR_FIELDS 1 - /* .hi and .lo are supported */ - #define CL_HAS_HI_LO_VECTOR_FIELDS 1 -#endif - -/* Define cl_vector types */ - -/* ---- cl_charn ---- */ -typedef union -{ - cl_char CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y; }; - __extension__ struct{ cl_char s0, s1; }; - __extension__ struct{ cl_char lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2; -#endif -}cl_char2; - -typedef union -{ - cl_char CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3; }; - __extension__ struct{ cl_char2 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[2]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4; -#endif -}cl_char4; - -/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ -typedef cl_char4 cl_char3; - -typedef union -{ - cl_char CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_char4 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[4]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[2]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8; -#endif -}cl_char8; - -typedef union -{ - cl_char CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_char8 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[8]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[4]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8[2]; -#endif -#if defined( __CL_CHAR16__ ) - __cl_char16 v16; -#endif -}cl_char16; - - -/* ---- cl_ucharn ---- */ -typedef union -{ - cl_uchar CL_ALIGNED(2) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y; }; - __extension__ struct{ cl_uchar s0, s1; }; - __extension__ struct{ cl_uchar lo, hi; }; -#endif -#if defined( __cl_uchar2__) - __cl_uchar2 v2; -#endif -}cl_uchar2; - -typedef union -{ - cl_uchar CL_ALIGNED(4) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3; }; - __extension__ struct{ cl_uchar2 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[2]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4; -#endif -}cl_uchar4; - -/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ -typedef cl_uchar4 cl_uchar3; - -typedef union -{ - cl_uchar CL_ALIGNED(8) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uchar4 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[4]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[2]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8; -#endif -}cl_uchar8; - -typedef union -{ - cl_uchar CL_ALIGNED(16) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uchar8 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[8]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[4]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8[2]; -#endif -#if defined( __CL_UCHAR16__ ) - __cl_uchar16 v16; -#endif -}cl_uchar16; - - -/* ---- cl_shortn ---- */ -typedef union -{ - cl_short CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y; }; - __extension__ struct{ cl_short s0, s1; }; - __extension__ struct{ cl_short lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2; -#endif -}cl_short2; - -typedef union -{ - cl_short CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3; }; - __extension__ struct{ cl_short2 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[2]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4; -#endif -}cl_short4; - -/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ -typedef cl_short4 cl_short3; - -typedef union -{ - cl_short CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_short4 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[4]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[2]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8; -#endif -}cl_short8; - -typedef union -{ - cl_short CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_short8 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[8]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[4]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8[2]; -#endif -#if defined( __CL_SHORT16__ ) - __cl_short16 v16; -#endif -}cl_short16; - - -/* ---- cl_ushortn ---- */ -typedef union -{ - cl_ushort CL_ALIGNED(4) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y; }; - __extension__ struct{ cl_ushort s0, s1; }; - __extension__ struct{ cl_ushort lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2; -#endif -}cl_ushort2; - -typedef union -{ - cl_ushort CL_ALIGNED(8) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3; }; - __extension__ struct{ cl_ushort2 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[2]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4; -#endif -}cl_ushort4; - -/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ -typedef cl_ushort4 cl_ushort3; - -typedef union -{ - cl_ushort CL_ALIGNED(16) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ushort4 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[4]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[2]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8; -#endif -}cl_ushort8; - -typedef union -{ - cl_ushort CL_ALIGNED(32) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ushort8 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[8]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[4]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8[2]; -#endif -#if defined( __CL_USHORT16__ ) - __cl_ushort16 v16; -#endif -}cl_ushort16; - -/* ---- cl_intn ---- */ -typedef union -{ - cl_int CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y; }; - __extension__ struct{ cl_int s0, s1; }; - __extension__ struct{ cl_int lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2; -#endif -}cl_int2; - -typedef union -{ - cl_int CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3; }; - __extension__ struct{ cl_int2 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[2]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4; -#endif -}cl_int4; - -/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ -typedef cl_int4 cl_int3; - -typedef union -{ - cl_int CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_int4 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[4]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[2]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8; -#endif -}cl_int8; - -typedef union -{ - cl_int CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_int8 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[8]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[4]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8[2]; -#endif -#if defined( __CL_INT16__ ) - __cl_int16 v16; -#endif -}cl_int16; - - -/* ---- cl_uintn ---- */ -typedef union -{ - cl_uint CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y; }; - __extension__ struct{ cl_uint s0, s1; }; - __extension__ struct{ cl_uint lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2; -#endif -}cl_uint2; - -typedef union -{ - cl_uint CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3; }; - __extension__ struct{ cl_uint2 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[2]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4; -#endif -}cl_uint4; - -/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ -typedef cl_uint4 cl_uint3; - -typedef union -{ - cl_uint CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_uint4 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[4]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[2]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8; -#endif -}cl_uint8; - -typedef union -{ - cl_uint CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_uint8 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[8]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[4]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8[2]; -#endif -#if defined( __CL_UINT16__ ) - __cl_uint16 v16; -#endif -}cl_uint16; - -/* ---- cl_longn ---- */ -typedef union -{ - cl_long CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y; }; - __extension__ struct{ cl_long s0, s1; }; - __extension__ struct{ cl_long lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2; -#endif -}cl_long2; - -typedef union -{ - cl_long CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3; }; - __extension__ struct{ cl_long2 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[2]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4; -#endif -}cl_long4; - -/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ -typedef cl_long4 cl_long3; - -typedef union -{ - cl_long CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_long4 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[4]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[2]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8; -#endif -}cl_long8; - -typedef union -{ - cl_long CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_long8 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[8]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[4]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8[2]; -#endif -#if defined( __CL_LONG16__ ) - __cl_long16 v16; -#endif -}cl_long16; - - -/* ---- cl_ulongn ---- */ -typedef union -{ - cl_ulong CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y; }; - __extension__ struct{ cl_ulong s0, s1; }; - __extension__ struct{ cl_ulong lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2; -#endif -}cl_ulong2; - -typedef union -{ - cl_ulong CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3; }; - __extension__ struct{ cl_ulong2 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[2]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4; -#endif -}cl_ulong4; - -/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ -typedef cl_ulong4 cl_ulong3; - -typedef union -{ - cl_ulong CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_ulong4 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[4]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[2]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8; -#endif -}cl_ulong8; - -typedef union -{ - cl_ulong CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_ulong8 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[8]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[4]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8[2]; -#endif -#if defined( __CL_ULONG16__ ) - __cl_ulong16 v16; -#endif -}cl_ulong16; - - -/* --- cl_floatn ---- */ - -typedef union -{ - cl_float CL_ALIGNED(8) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y; }; - __extension__ struct{ cl_float s0, s1; }; - __extension__ struct{ cl_float lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2; -#endif -}cl_float2; - -typedef union -{ - cl_float CL_ALIGNED(16) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3; }; - __extension__ struct{ cl_float2 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[2]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4; -#endif -}cl_float4; - -/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ -typedef cl_float4 cl_float3; - -typedef union -{ - cl_float CL_ALIGNED(32) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_float4 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[4]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[2]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8; -#endif -}cl_float8; - -typedef union -{ - cl_float CL_ALIGNED(64) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_float8 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[8]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[4]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8[2]; -#endif -#if defined( __CL_FLOAT16__ ) - __cl_float16 v16; -#endif -}cl_float16; - -/* --- cl_doublen ---- */ - -typedef union -{ - cl_double CL_ALIGNED(16) s[2]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y; }; - __extension__ struct{ cl_double s0, s1; }; - __extension__ struct{ cl_double lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2; -#endif -}cl_double2; - -typedef union -{ - cl_double CL_ALIGNED(32) s[4]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3; }; - __extension__ struct{ cl_double2 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[2]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4; -#endif -}cl_double4; - -/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ -typedef cl_double4 cl_double3; - -typedef union -{ - cl_double CL_ALIGNED(64) s[8]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; - __extension__ struct{ cl_double4 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[4]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[2]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8; -#endif -}cl_double8; - -typedef union -{ - cl_double CL_ALIGNED(128) s[16]; -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) - __extension__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __extension__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __extension__ struct{ cl_double8 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[8]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[4]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8[2]; -#endif -#if defined( __CL_DOUBLE16__ ) - __cl_double16 v16; -#endif -}cl_double16; - -/* Macro to facilitate debugging - * Usage: - * Place CL_PROGRAM_STRING_DEBUG_INFO on the line before the first line of your source. - * The first line ends with: CL_PROGRAM_STRING_BEGIN \" - * Each line thereafter of OpenCL C source must end with: \n\ - * The last line ends in "; - * - * Example: - * - * const char *my_program = CL_PROGRAM_STRING_BEGIN "\ - * kernel void foo( int a, float * b ) \n\ - * { \n\ - * // my comment \n\ - * *b[ get_global_id(0)] = a; \n\ - * } \n\ - * "; - * - * This should correctly set up the line, (column) and file information for your source - * string so you can do source level debugging. - */ -#define __CL_STRINGIFY( _x ) # _x -#define _CL_STRINGIFY( _x ) __CL_STRINGIFY( _x ) -#define CL_PROGRAM_STRING_DEBUG_INFO "#line " _CL_STRINGIFY(__LINE__) " \"" __FILE__ "\" \n\n" - -#ifdef __cplusplus -} -#endif - -#endif /* __CL_PLATFORM_H */ diff --git a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/opencl.h b/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/opencl.h deleted file mode 100644 index 685b90c03..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/headers/1.2/CL/opencl.h +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_H -#define __OPENCL_H - -#ifdef __cplusplus -extern "C" { -#endif - -//#ifdef __APPLE__ -// -//#include -//#include -//#include -//#include -// -//#else - -#include -#include -#include -#include - -//#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_H */ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java deleted file mode 100644 index 1c42fc807..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenCLLibrary.java +++ /dev/null @@ -1,963 +0,0 @@ -package com.nativelibs4java.opencl.library; -import org.bridj.BridJ; -import org.bridj.CRuntime; -import org.bridj.Callback; -import org.bridj.Pointer; -import org.bridj.SizeT; -import org.bridj.TypedPointer; -import org.bridj.ann.Library; -import org.bridj.ann.Optional; -import org.bridj.ann.Ptr; -import org.bridj.ann.Runtime; -/** - * Wrapper for library OpenCL
      - * This file was autogenerated by
      JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("OpenCL") -@Runtime(CRuntime.class) -public class OpenCLLibrary { - public static final int CL_DEVICE_TYPE_CPU = (1 << 1); - public static final int CL_SCHAR_MAX = 127; - public static final int CL_FP_INF_NAN = (1 << 1); - public static final int CL_GLX_DISPLAY_KHR = 8202; - public static final int CL_GLOBAL = 2; - public static final int CL_DEVICE_GLOBAL_MEM_SIZE = 4127; - public static final int CL_KERNEL_LOCAL_MEM_SIZE = 4530; - public static final int CL_MEM_READ_ONLY = (1 << 2); - public static final int CL_IMAGE_NUM_MIP_LEVELS = 4377; - public static final int CL_MEM_OBJECT_IMAGE1D_BUFFER = 4342; - public static final int CL_PROGRAM_REFERENCE_COUNT = 4448; - public static final int CL_GL_OBJECT_TEXTURE2D_ARRAY = 8206; - public static final double CL_M_PI_2 = 1.570796326794896557999; - public static final float CL_M_LOG2E_F = 1.44269502162933f; - public static final double CL_M_PI_4 = 0.785398163397448278999; - public static final int CL_FLT_MIN_EXP = -125; - public static final int CL_DEVICE_VENDOR_ID = 4097; - public static final int CL_FLOAT = 4318; - public static final int CL_NONE = 0; - public static final int CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT = 1; - public static final int CL_BGRA = 4278; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR = 4150; - public static final int CL_COMPILE_PROGRAM_FAILURE = -15; - public static final int CL_UNSIGNED_INT32 = 4316; - public static final int CL_DEVICE_MAX_COMPUTE_UNITS = 4098; - public static final int CL_RGBx = 4284; - public static final int CL_CHAR_MIN = (-127 - 1); - public static final int CL_DEVICE_REGISTERS_PER_BLOCK_NV = 16386; - public static final int CL_PLATFORM_EXTENSIONS = 2308; - public static final int CL_MEM_HOST_READ_ONLY = (1 << 8); - public static final int CL_DEVICE_TYPE_GPU = (1 << 2); - public static final int CL_PROGRAM_NUM_KERNELS = 4455; - public static final float CL_M_PI_F = 3.14159274101257f; - public static final int CL_LINKER_NOT_AVAILABLE = -16; - public static final int CL_READ_ONLY_CACHE = 1; - public static final int CL_IMAGE_FORMAT_MISMATCH = -9; - public static final int CL_OUT_OF_RESOURCES = -5; - public static final int CL_INVALID_IMAGE_SIZE = -40; - public static final int CL_INVALID_EVENT_WAIT_LIST = -57; - public static final int CL_DEVICE_PARTITION_FAILED = -18; - public static final int CL_IMAGE_BUFFER = 4376; - public static final int cl_APPLE_SetMemObjectDestructor = 1; - public static final int CL_UNSIGNED_INT16 = 4315; - public static final int CL_DEVICE_PRINTF_BUFFER_SIZE = 4169; - public static final int CL_COMMAND_NDRANGE_KERNEL = 4592; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT = 4106; - public static final int CL_COMMAND_FILL_IMAGE = 4616; - public static final int CL_DEVICE_MAX_CONSTANT_ARGS = 4129; - public static final int CL_PROGRAM_BINARY_TYPE_NONE = 0; - public static final int CL_CHAR_BIT = 8; - public static final int CL_DEVICE_TYPE_ALL = -1; - public static final int CL_QUEUED = 3; - public static final double CL_M_LN10 = 2.302585092994045901094; - public static final int CL_INVALID_MIP_LEVEL = -62; - public static final int CL_ADDRESS_NONE = 4400; - public static final int CL_RGBA = 4277; - public static final int CL_CONTEXT_DEVICES = 4225; - public static final int CL_DEVICE_PARTITION_MAX_SUB_DEVICES = 4163; - public static final int CL_INVALID_PARTITION_NAME_EXT = -1059; - public static final int CL_KERNEL_ARG_ACCESS_READ_ONLY = 4512; - public static final int CL_INVALID_WORK_ITEM_SIZE = -55; - public static final int CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV = 16389; - public static final int CL_INVALID_WORK_GROUP_SIZE = -54; - public static final int CL_DEVICE_ERROR_CORRECTION_SUPPORT = 4132; - public static final int CL_DBL_RADIX = 2; - public static final int CL_DEVICE_PARTITION_BY_COUNTS = 4231; - public static final int CL_NON_BLOCKING = 0; - public static final int CL_DEVICE_LOCAL_MEM_SIZE = 4131; - public static final int CL_COMMAND_RELEASE_GL_OBJECTS = 4608; - public static final int CL_ADDRESS_MIRRORED_REPEAT = 4404; - public static final int CL_INVALID_KERNEL_ARGS = -52; - public static final int CL_INVALID_GL_CONTEXT_APPLE = -1000; - public static final int CL_CONTEXT_PLATFORM = 4228; - public static final int CL_HAS_HI_LO_VECTOR_FIELDS = 1; - public static final int CL_KERNEL_ARG_TYPE_RESTRICT = (1 << 1); - public static final int CL_MEM_MAP_COUNT = 4356; - public static final int CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT = 256; - public static final int CL_PROFILING_COMMAND_SUBMIT = 4737; - public static final int CL_DBL_MIN_EXP = -1021; - public static final double CL_M_SQRT2 = 1.414213562373095145475; - public static final int CL_COMMAND_ACQUIRE_GL_OBJECTS = 4607; - public static final long CL_UINT_MAX = 4294967295L; - public static final float CL_M_SQRT1_2_F = 0.70710676908493f; - public static final double CL_M_2_SQRTPI = 1.128379167095512558561; - public static final int CL_KERNEL_ARG_INFO_NOT_AVAILABLE = -19; - public static final int CL_COMMAND_NATIVE_KERNEL = 4594; - public static final int CL_IMAGE_WIDTH = 4372; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG = 4105; - public static final int CL_INVALID_DEVICE_TYPE = -31; - public static final int CL_COMMAND_COPY_IMAGE_TO_BUFFER = 4601; - public static final int CL_GL_TEXTURE_TARGET = 8196; - public static final int CL_QUEUE_PROPERTIES = 4243; - public static final float CL_M_2_PI_F = 0.63661974668503f; - public static final int CL_COMMAND_WRITE_BUFFER_RECT = 4610; - public static final int CL_MEM_ASSOCIATED_MEMOBJECT = 4359; - public static final int CL_INVALID_ARG_VALUE = -50; - public static final int CL_CONTEXT_REFERENCE_COUNT = 4224; - public static final int CL_DEVICE_TYPE = 4096; - public static final int CL_QUEUE_CONTEXT = 4240; - public static final int CL_DEVICE_SINGLE_FP_CONFIG = 4123; - public static final int CL_SNORM_INT16 = 4305; - public static final int CL_ARGB = 4279; - public static final int CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV = 16385; - public static final int CL_KERNEL_ARG_NAME = 4506; - public static final int CL_EVENT_COMMAND_QUEUE = 4560; - public static final int CL_SUCCESS = 0; - public static final int CL_PROFILING_INFO_NOT_AVAILABLE = -7; - public static final int CL_INVALID_BUFFER_SIZE = -61; - public static final int CL_FLT_MAX_EXP = +128; - public static final int CL_INVALID_ARG_SIZE = -51; - public static final int CL_QUEUE_PROFILING_ENABLE = (1 << 1); - public static final int CL_KERNEL_REFERENCE_COUNT = 4498; - public static final int CL_KERNEL_ARG_TYPE_CONST = (1 << 0); - public static final int CL_MEM_ALLOC_HOST_PTR = (1 << 4); - public static final int CL_DEVICE_IMAGE2D_MAX_WIDTH = 4113; - public static final int CL_BUILD_PROGRAM_FAILURE = -11; - public static final int CL_COMMAND_COPY_BUFFER = 4597; - public static final int CL_KERNEL_NUM_ARGS = 4497; - public static final int CL_BUFFER_CREATE_TYPE_REGION = 4640; - public static final int CL_COMMAND_BARRIER = 4613; - public static final int CL_UNORM_SHORT_555 = 4309; - public static final int CL_INVALID_PROPERTY = -64; - public static final int CL_IMAGE_NUM_SAMPLES = 4378; - public static final int CL_PROGRAM_SOURCE = 4452; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR = 4102; - public static final int CL_PROGRAM_BINARY_TYPE = 4484; - public static final int CL_DEVICE_COMPILER_AVAILABLE = 4136; - public static final int CL_FP_ROUND_TO_INF = (1 << 4); - public static final int CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE = 4125; - public static final int CL_IMAGE_ROW_PITCH = 4370; - public static final int CL_INVALID_ARG_INDEX = -49; - public static final int CL_LINK_PROGRAM_FAILURE = -17; - public static final int CL_DEVICE_ENDIAN_LITTLE = 4134; - public static final int CL_COMMAND_READ_BUFFER = 4595; - public static final int CL_UNORM_INT_101010 = 4310; - public static final int CL_KERNEL_WORK_GROUP_SIZE = 4528; - public static final int CL_COMMAND_UNMAP_MEM_OBJECT = 4605; - public static final int CL_INVALID_PLATFORM = -32; - public static final int CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR = -1000; - public static final int CL_FLT_RADIX = 2; - public static final int CL_DEVICE_PARTITION_BY_NAMES_EXT = 16466; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT = 4104; - public static final int CL_PROGRAM_KERNEL_NAMES = 4456; - public static final int CL_SHRT_MIN = (-32767 - 1); - public static final int CL_INVALID_EVENT = -58; - public static final int CL_RG = 4274; - public static final int CL_RA = 4275; - public static final int CL_PROGRAM_BUILD_OPTIONS = 4482; - public static final int CL_INVALID_COMMAND_QUEUE = -36; - public static final int cl_khr_icd = 1; - public static final int CL_FP_ROUND_TO_NEAREST = (1 << 2); - public static final int CL_HALF_FLOAT = 4317; - public static final int CL_KERNEL_ARG_ADDRESS_LOCAL = 4508; - public static final int CL_INVALID_BINARY = -42; - public static final int CL_COMMAND_WRITE_IMAGE = 4599; - public static final int CL_INVALID_KERNEL_DEFINITION = -47; - public static final int CL_ADDRESS_CLAMP = 4402; - public static final int CL_COMMAND_USER = 4612; - public static final int CL_UNORM_SHORT_565 = 4308; - public static final int CL_UNORM_INT16 = 4307; - public static final double CL_M_2_PI = 0.636619772367581382433; - public static final int CL_ADDRESS_REPEAT = 4403; - public static final int CL_FALSE = 0; - public static final int CL_Rx = 4282; - public static final int CL_INVALID_GLOBAL_OFFSET = -56; - public static final int CL_DEVICE_PREFERRED_INTEROP_USER_SYNC = 4168; - public static final int CL_INVALID_PROGRAM = -44; - public static final int CL_INVALID_KERNEL = -48; - public static final int CL_MEM_SIZE = 4354; - public static final int CL_AFFINITY_DOMAIN_L1_CACHE_EXT = 1; - public static final int CL_PROGRAM_BINARIES = 4454; - public static final int CL_DEVICE_TYPE_DEFAULT = (1 << 0); - public static final int CL_DEVICE_IMAGE2D_MAX_HEIGHT = 4114; - public static final int CL_MEM_HOST_WRITE_ONLY = (1 << 7); - public static final int CL_INVALID_BUILD_OPTIONS = -43; - public static final int CL_DEVICE_NOT_AVAILABLE = -2; - public static final int CL_INVALID_VALUE = -30; - public static final int CL_AFFINITY_DOMAIN_L3_CACHE_EXT = 3; - public static final int CL_DEVICE_MEM_BASE_ADDR_ALIGN = 4121; - public static final int CL_DEVICE_MAX_WORK_GROUP_SIZE = 4100; - public static final int CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE = (1 << 0); - public static final int CL_SAMPLER_NORMALIZED_COORDS = 4434; - public static final int CL_EVENT_REFERENCE_COUNT = 4562; - public static final int CL_MEM_HOST_PTR = 4355; - public static final float CL_M_1_PI_F = 0.31830987334251f; - public static final int CL_INVALID_LINKER_OPTIONS = -67; - public static final int CL_MEM_OBJECT_ALLOCATION_FAILURE = -4; - public static final int CL_INVALID_MEM_OBJECT = -38; - public static final double CL_M_LN2 = 0.693147180559945286227; - public static final int CL_COMPLETE = 0; - public static final int CL_IMAGE_ARRAY_SIZE = 4375; - public static final int CL_INTENSITY = 4280; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF = 4156; - public static final int CL_INVALID_PROGRAM_EXECUTABLE = -45; - public static final int CL_KERNEL_ARG_TYPE_QUALIFIER = 4505; - public static final int CL_MEM_WRITE_ONLY = (1 << 1); - public static final int CL_GL_OBJECT_TEXTURE1D = 8207; - public static final int CL_PROGRAM_CONTEXT = 4449; - public static final int CL_PLATFORM_ICD_SUFFIX_KHR = 2336; - public static final int CL_KERNEL_ARG_TYPE_NONE = 0; - public static final int CL_KERNEL_ARG_ACCESS_WRITE_ONLY = 4513; - public static final int CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST = -14; - public static final int CL_SAMPLER_ADDRESSING_MODE = 4435; - public static final int CL_MEM_CONTEXT = 4358; - public static final int CL_DEVICE_IMAGE3D_MAX_HEIGHT = 4116; - public static final int CL_KERNEL_ARG_ADDRESS_PRIVATE = 4510; - public static final int CL_DEVICE_MAX_READ_IMAGE_ARGS = 4110; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF = 4148; - public static final int CL_DEVICE_NOT_FOUND = -1; - public static final int CL_CGL_DEVICES_FOR_SUPPORTED_VIRTUAL_SCREENS_APPLE = 268435459; - public static final int CL_RGx = 4283; - public static final int CL_DEVICE_MAX_PARAMETER_SIZE = 4119; - public static final int CL_DEVICE_IMAGE3D_MAX_DEPTH = 4117; - public static final int CL_GL_OBJECT_TEXTURE2D = 8193; - public static final int CL_MEM_HOST_NO_ACCESS = (1 << 9); - public static final int CL_INVALID_COMPILER_OPTIONS = -66; - public static final int CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT = 16467; - public static final int CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE = (1 << 5); - public static final int CL_DEVICE_TYPE_CUSTOM = (1 << 4); - public static final int CL_MEM_USE_HOST_PTR = (1 << 3); - public static final int CL_SIGNED_INT8 = 4311; - public static final int CL_DEVICE_WARP_SIZE_NV = 16387; - public static final int CL_DEVICE_OPENCL_C_VERSION = 4157; - public static final int CL_DEVICE_ADDRESS_BITS = 4109; - public static final int CL_DEVICE_PARTITION_BY_COUNTS_EXT = 16465; - public static final int CL_GL_OBJECT_BUFFER = 8192; - public static final int CL_SAMPLER_CONTEXT = 4433; - public static final int CL_GL_OBJECT_TEXTURE3D = 8194; - public static final int CL_PLATFORM_VERSION = 2305; - public static final int CL_DRIVER_VERSION = 4141; - public static final int CL_DEVICE_LOCAL_MEM_TYPE = 4130; - public static final int CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE = 4122; - public static final int CL_KERNEL_ARG_ACCESS_NONE = 4515; - public static final int CL_DEVICE_VERSION = 4143; - public static final int CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE = 268435456; - public static final int CL_PLATFORM_NOT_FOUND_KHR = -1001; - public static final float CL_M_2_SQRTPI_F = 1.12837922573090f; - public static final int CL_SIGNED_INT32 = 4313; - public static final int CL_READ_WRITE_CACHE = 2; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT = 4151; - public static final int CL_KERNEL_GLOBAL_WORK_SIZE = 4533; - public static final int CL_KERNEL_COMPILE_WORK_GROUP_SIZE = 4529; - public static final int CL_PLATFORM_PROFILE = 2304; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT = 4154; - public static final float CL_M_PI_4_F = 0.78539818525314f; - public static final int CL_DEVICE_REFERENCE_COUNT = 4167; - public static final int CL_PROFILING_COMMAND_END = 4739; - public static final int CL_DEVICE_PROFILE = 4142; - public static final int CL_INVALID_OPERATION = -59; - public static final int CL_DEVICE_REFERENCE_COUNT_EXT = 16471; - public static final int CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE = (1 << 2); - public static final int CL_MEM_TYPE = 4352; - public static final int CL_INVALID_DEVICE_PARTITION_COUNT = -68; - public static final int CL_KERNEL_CONTEXT = 4499; - public static final int CL_DEVICE_MAX_CLOCK_FREQUENCY = 4108; - public static final int CL_DEVICE_PARTITION_TYPE = 4166; - public static final int CL_BLOCKING = 1; - public static final int CL_EVENT_CONTEXT = 4564; - public static final int CL_CONTEXT_NUM_DEVICES = 4227; - public static final int CL_HAS_NAMED_VECTOR_FIELDS = 1; - public static final int CL_GL_CONTEXT_KHR = 8200; - public static final int CL_DEVICE_PROFILING_TIMER_RESOLUTION = 4133; - public static final int CL_MIGRATE_MEM_OBJECT_HOST = (1 << 0); - public static final int CL_KERNEL_ARG_ADDRESS_GLOBAL = 4507; - public static final int CL_PROGRAM_BUILD_STATUS = 4481; - public static final int CL_DEVICE_GLOBAL_MEM_CACHE_TYPE = 4124; - public static final int CL_SUBMITTED = 2; - public static final String CL_PROGRAM_STRING_DEBUG_INFO = "#line "; - public static final int CL_DEVICE_AFFINITY_DOMAIN_NUMA = (1 << 0); - public static final int CL_PLATFORM_NAME = 2306; - public static final int CL_COMMAND_COPY_BUFFER_RECT = 4611; - public static final int CL_COMPILER_NOT_AVAILABLE = -3; - public static final int CL_SNORM_INT8 = 4304; - public static final int CL_FP_FMA = (1 << 5); - public static final int CL_CONTEXT_INTEROP_USER_SYNC = 4229; - public static final int CL_PROFILING_COMMAND_START = 4738; - public static final int CL_COMMAND_COPY_IMAGE = 4600; - public static final int CL_DEVICE_MAX_WORK_ITEM_SIZES = 4101; - public static final int CL_IMAGE_ELEMENT_SIZE = 4369; - public static final int CL_DEVICE_PARENT_DEVICE = 4162; - public static final int CL_DEVICE_PARTITION_EQUALLY_EXT = 16464; - public static final int CL_INVALID_CONTEXT = -34; - public static final int CL_IMAGE_HEIGHT = 4373; - public static final int CL_DEVICE_HOST_UNIFIED_MEMORY = 4149; - public static final int CL_COMMAND_MARKER = 4606; - public static final int CL_KERNEL_ATTRIBUTES = 4501; - public static final int CL_COMMAND_MIGRATE_MEM_OBJECTS = 4614; - public static final int CL_INVALID_IMAGE_DESCRIPTOR = -65; - public static final int CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR = 8205; - public static final int CL_MAP_WRITE_INVALIDATE_REGION = (1 << 2); - public static final int CL_AFFINITY_DOMAIN_L2_CACHE_EXT = 2; - public static final int CL_EXEC_NATIVE_KERNEL = (1 << 1); - public static final int CL_USHRT_MAX = 65535; - public static final int CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR = 8198; - public static final int CL_KERNEL_PRIVATE_MEM_SIZE = 4532; - public static final int CL_KERNEL_ARG_ADDRESS_CONSTANT = 4509; - public static final int CL_DEVICE_PARTITION_BY_COUNTS_LIST_END = 0; - public static final int CL_COMMAND_MAP_IMAGE = 4604; - public static final int CL_GL_OBJECT_TEXTURE_BUFFER = 8209; - public static final int CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED = (1 << 1); - public static final int CL_EXEC_KERNEL = (1 << 0); - public static final int CL_INVALID_GL_OBJECT = -60; - public static final int CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV = 16384; - public static final int CL_COMMAND_READ_BUFFER_RECT = 4609; - public static final int CL_QUEUE_DEVICE = 4241; - public static final int CL_DEVICE_GPU_OVERLAP_NV = 16388; - public static final int CL_DEVICE_EXTENSIONS = 4144; - public static final int CL_KERNEL_ARG_TYPE_VOLATILE = (1 << 2); - public static final int CL_DBL_MAX_10_EXP = +308; - public static final int CL_FLT_MAX_10_EXP = +38; - public static final int CL_DEVICE_PARENT_DEVICE_EXT = 16468; - public static final int CL_MISALIGNED_SUB_BUFFER_OFFSET = -13; - public static final int CL_EVENT_COMMAND_EXECUTION_STATUS = 4563; - public static final int CL_DEVICE_MAX_WRITE_IMAGE_ARGS = 4111; - public static final int CL_INVALID_HOST_PTR = -37; - public static final float CL_M_SQRT2_F = 1.41421353816986f; - public static final int CL_VERSION_1_1 = 1; - public static final int CL_VERSION_1_2 = 1; - public static final int CL_VERSION_1_0 = 1; - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE = 4107; - public static final double CL_M_LOG2E = 1.442695040888963387005; - public static final int CL_SHRT_MAX = 32767; - public static final int CL_UNORM_INT8 = 4306; - public static final int CL_DEVICE_QUEUE_PROPERTIES = 4138; - public static final int CL_KERNEL_ARG_ACCESS_READ_WRITE = 4514; - public static final int CL_DEVICE_PARTITION_AFFINITY_DOMAIN = 4165; - public static final int CL_KERNEL_ARG_TYPE_NAME = 4504; - public static final int CL_BUILD_SUCCESS = 0; - public static final int CL_FP_DENORM = (1 << 0); - public static final float CL_M_LOG10E_F = 0.43429449200630f; - public static final int CL_GL_MIPMAP_LEVEL = 8197; - public static final int CL_SIGNED_INT16 = 4312; - public static final int CL_DEVICE_BUILT_IN_KERNELS = 4159; - public static final int CL_INT_MIN = (-2147483647 - 1); - public static final int CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT = 4103; - public static final int CL_DEVICE_PARTITION_STYLE_EXT = 16472; - public static final int CL_COMMAND_MAP_BUFFER = 4603; - public static final int CL_MAP_WRITE = (1 << 1); - public static final double CL_M_SQRT1_2 = 0.707106781186547572737; - public static final float CL_M_LN10_F = 2.30258512496948f; - public static final int CL_FILTER_NEAREST = 4416; - public static final int CL_CGL_DEVICE_FOR_CURRENT_VIRTUAL_SCREEN_APPLE = 268435458; - public static final int CL_KERNEL_FUNCTION_NAME = 4496; - public static final int cl_khr_gl_sharing = 1; - public static final int CL_BUILD_ERROR = -2; - public static final int CL_OUT_OF_HOST_MEMORY = -6; - public static final int CL_MEM_OBJECT_IMAGE1D_ARRAY = 4341; - public static final int CL_DEVICE_GLOBAL_MEM_CACHE_SIZE = 4126; - public static final int CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = 4099; - public static final int CL_KERNEL_ARG_ACCESS_QUALIFIER = 4503; - public static final int CL_EVENT_COMMAND_TYPE = 4561; - public static final int CL_A = 4273; - public static final int CL_DEVICES_FOR_GL_CONTEXT_KHR = 8199; - public static final int CL_MEM_OFFSET = 4360; - public static final int CL_RGB = 4276; - public static final int CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE = (1 << 1); - public static final int CL_PROGRAM_BINARY_SIZES = 4453; - public static final int CL_INVALID_DEVICE = -33; - public static final int CL_R = 4272; - public static final int CL_DEVICE_IMAGE_MAX_BUFFER_SIZE = 4160; - public static final int CL_COMMAND_WRITE_BUFFER = 4596; - public static final int CL_MEM_OBJECT_IMAGE1D = 4340; - public static final int CL_INVALID_PARTITION_COUNT_EXT = -1058; - public static final int CL_EGL_DISPLAY_KHR = 8201; - public static final int CL_TRUE = 1; - public static final int CL_BUILD_IN_PROGRESS = -3; - public static final int CL_MEM_OBJECT_BUFFER = 4336; - public static final float CL_M_PI_2_F = 1.57079637050629f; - public static final int CL_DEVICE_AFFINITY_DOMAINS_EXT = 16470; - public static final int CL_DEVICE_LINKER_AVAILABLE = 4158; - public static final int CL_CONTEXT_PROPERTIES = 4226; - public static final int CL_SCHAR_MIN = (-127 - 1); - public static final int CL_FP_SOFT_FLOAT = (1 << 6); - public static final int CL_DEVICE_VENDOR = 4140; - public static final int CL_BUILD_NONE = -1; - public static final int CL_FLT_DIG = 6; - public static final int CL_MEM_OBJECT_IMAGE2D = 4337; - public static final double CL_M_PI = 3.141592653589793115998; - public static final int CL_IMAGE_FORMAT = 4368; - public static final int CL_PLATFORM_VENDOR = 2307; - public static final int CL_DEVICE_MAX_MEM_ALLOC_SIZE = 4112; - public static final int CL_DEVICE_IMAGE_MAX_ARRAY_SIZE = 4161; - public static final int CL_PROFILING_COMMAND_QUEUED = 4736; - public static final float CL_M_LN2_F = 0.69314718246460f; - public static final int CL_DEVICE_PARTITION_TYPES_EXT = 16469; - public static final int CL_FILTER_LINEAR = 4417; - public static final int CL_COMMAND_FILL_BUFFER = 4615; - public static final int CL_DEVICE_IMAGE_SUPPORT = 4118; - public static final int CL_DEVICE_TYPE_ACCELERATOR = (1 << 3); - public static final int CL_PROGRAM_BUILD_LOG = 4483; - public static final int CL_IMAGE_DEPTH = 4374; - public static final int CL_KERNEL_PROGRAM = 4500; - public static final int CL_KERNEL_ARG_ADDRESS_QUALIFIER = 4502; - public static final int CL_MEM_OBJECT_IMAGE3D = 4338; - public static final double CL_M_1_PI = 0.318309886183790691216; - public static final float CL_M_E_F = 2.71828174591064f; - public static final int CL_FLT_MANT_DIG = 24; - public static final int CL_GL_OBJECT_TEXTURE1D_ARRAY = 8208; - public static final int CL_PROGRAM_BINARY_TYPE_EXECUTABLE = 4; - public static final int CL_LOCAL = 1; - public static final int CL_DEVICE_PROFILING_TIMER_OFFSET_AMD = 16438; - public static final int CL_QUEUE_REFERENCE_COUNT = 4242; - public static final int CL_DEVICE_PARTITION_FAILED_EXT = -1057; - public static final int CL_DEVICE_AVAILABLE = 4135; - public static final double CL_M_LOG10E = 0.434294481903251816668; - public static final int CL_IMAGE_FORMAT_NOT_SUPPORTED = -10; - public static final int CL_DBL_MAX_EXP = +1024; - public static final int CL_UCHAR_MAX = 255; - public static final int CL_DBL_MIN_10_EXP = -307; - public static final int CL_DEVICE_MAX_SAMPLERS = 4120; - public static final int CL_MEM_COPY_OVERLAP = -8; - public static final int CL_MAP_READ = (1 << 0); - public static final int CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE = (1 << 3); - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE = 4155; - public static final int CL_COMMAND_READ_IMAGE = 4598; - public static final int CL_CHAR_MAX = 127; - public static final int CL_PROGRAM_NUM_DEVICES = 4450; - public static final int CL_UNSIGNED_INT8 = 4314; - public static final int CL_DBL_DIG = 15; - public static final int cl_APPLE_ContextLoggingFunctions = 1; - public static final int CL_WGL_HDC_KHR = 8203; - public static final int CL_DBL_MANT_DIG = 53; - public static final int CL_COMMAND_COPY_BUFFER_TO_IMAGE = 4602; - public static final int CL_CGL_SHAREGROUP_KHR = 8204; - public static final int CL_PROGRAM_DEVICES = 4451; - public static final int CL_SAMPLER_REFERENCE_COUNT = 4432; - public static final int CL_MEM_READ_WRITE = (1 << 0); - public static final int CL_INVALID_KERNEL_NAME = -46; - public static final int CL_DEVICE_EXECUTION_CAPABILITIES = 4137; - public static final int CL_DEVICE_NAME = 4139; - public static final int CL_DEVICE_INTEGRATED_MEMORY_NV = 16390; - public static final int CL_MEM_REFERENCE_COUNT = 4357; - public static final int CL_INVALID_IMAGE_FORMAT_DESCRIPTOR = -39; - public static final int cl_ext_device_fission = 1; - public static final int CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE = 4128; - public static final int CL_MEM_OBJECT_IMAGE2D_ARRAY = 4339; - public static final int CL_MAP_FAILURE = -12; - public static final int CL_DEVICE_PARTITION_EQUALLY = 4230; - public static final int CL_IMAGE_SLICE_PITCH = 4371; - public static final int CL_LUMINANCE = 4281; - public static final int CL_ADDRESS_CLAMP_TO_EDGE = 4401; - public static final int CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE = (1 << 4); - public static final int CL_GL_OBJECT_RENDERBUFFER = 8195; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_INT = 4152; - public static final int CL_SAMPLER_FILTER_MODE = 4436; - public static final int CL_INVALID_QUEUE_PROPERTIES = -35; - public static final int CL_INVALID_GLOBAL_WORK_SIZE = -63; - public static final int CL_INT_MAX = 2147483647; - public static final int CL_AFFINITY_DOMAIN_NUMA_EXT = 16; - public static final int CL_FLT_MIN_10_EXP = -37; - public static final int CL_AFFINITY_DOMAIN_L4_CACHE_EXT = 4; - public static final int CL_MEM_COPY_HOST_PTR = (1 << 5); - public static final int CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN = 4232; - public static final int CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE = 4531; - public static final int CL_MEM_FLAGS = 4353; - public static final int CL_DEVICE_PARTITION_PROPERTIES = 4164; - public static final int CL_COMMAND_TASK = 4593; - public static final int CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT = (1 << 7); - public static final int CL_DEVICE_DOUBLE_FP_CONFIG = 4146; - public static final int CL_DEVICE_HALF_FP_CONFIG = 4147; - public static final int CL_FP_ROUND_TO_ZERO = (1 << 3); - public static final int CL_RUNNING = 1; - public static final int CL_DEVICE_IMAGE3D_MAX_WIDTH = 4115; - public static final int CL_DEVICE_PLATFORM = 4145; - public static final int CL_INVALID_WORK_DIMENSION = -53; - public static final int CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG = 4153; - public static final int CL_PROGRAM_BINARY_TYPE_LIBRARY = 2; - public static final double CL_M_E = 2.718281828459045090796; - public static final int CL_INVALID_SAMPLER = -41; - public static abstract class clGetGLContextInfoKHR_fn extends Callback { - public abstract int apply(Pointer > properties, int param_name, @Ptr long param_value_size, Pointer param_value, Pointer param_value_size_ret); - }; - public static abstract class clIcdGetPlatformIDsKHR_fn extends Callback { - public abstract int apply(int cl_uint1, Pointer cl_platform_idPtr1, Pointer cl_uintPtr1); - }; - public static abstract class clReleaseDeviceEXT_fn extends Callback { - public abstract int apply(OpenCLLibrary.cl_device_id cl_device_id1); - }; - public static abstract class clRetainDeviceEXT_fn extends Callback { - public abstract int apply(OpenCLLibrary.cl_device_id cl_device_id1); - }; - public static abstract class clCreateSubDevicesEXT_fn extends Callback { - public abstract int apply(OpenCLLibrary.cl_device_id cl_device_id1, Pointer cl_device_partition_property_extPtr1, int cl_uint1, Pointer cl_device_idPtr1, Pointer cl_uintPtr1); - }; - public static abstract class clCreateContext_arg1_callback extends Callback { - public abstract void apply(Pointer charPtr1, Pointer voidPtr1, @Ptr long size_t1, Pointer voidPtr2); - }; - public static abstract class clCreateContextFromType_arg1_callback extends Callback { - public abstract void apply(Pointer charPtr1, Pointer voidPtr1, @Ptr long size_t1, Pointer voidPtr2); - }; - public static abstract class clSetMemObjectDestructorCallback_arg1_callback extends Callback { - /// @param cl_mem1 user_data - public abstract void apply(OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1); - }; - public static abstract class clBuildProgram_arg1_callback extends Callback { - /// @param cl_program1 user_data - public abstract void apply(OpenCLLibrary.cl_program cl_program1, Pointer voidPtr1); - }; - public static abstract class clCompileProgram_arg1_callback extends Callback { - /// @param cl_program1 user_data - public abstract void apply(OpenCLLibrary.cl_program cl_program1, Pointer voidPtr1); - }; - public static abstract class clLinkProgram_arg1_callback extends Callback { - /// @param cl_program1 user_data - public abstract void apply(OpenCLLibrary.cl_program cl_program1, Pointer voidPtr1); - }; - public static abstract class clSetEventCallback_arg1_callback extends Callback { - public abstract void apply(@Ptr long cl_event1, int cl_int1, @Ptr long voidPtr1); - }; - public static abstract class clEnqueueNativeKernel_arg1_callback extends Callback { - public abstract void apply(Pointer voidPtr1); - }; - public static abstract class clSetPrintfCallback_arg1_callback extends Callback { - public abstract void apply(OpenCLLibrary.cl_context cl_context1, int cl_uint1, Pointer charPtr1, Pointer voidPtr1); - }; - public static abstract class clSetMemObjectDestructorAPPLE_arg1_callback extends Callback { - /// @param cl_mem1 user_data - public abstract void apply(OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1); - }; - /** - * Platform API
      - * Original signature : cl_int clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*) - */ - public native int clGetPlatformIDs(int cl_uint1, @Ptr long cl_platform_idPtr1, @Ptr long cl_uintPtr1); - /// Original signature : cl_int clGetPlatformInfo(cl_platform_id, cl_platform_info, size_t, void*, size_t*) - public native int clGetPlatformInfo(@Ptr long cl_platform_id1, int cl_platform_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Device APIs
      - * Original signature : cl_int clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*) - */ - public native int clGetDeviceIDs(@Ptr long cl_platform_id1, long cl_device_type1, int cl_uint1, @Ptr long cl_device_idPtr1, @Ptr long cl_uintPtr1); - /// Original signature : cl_int clGetDeviceInfo(cl_device_id, cl_device_info, size_t, void*, size_t*) - public native int clGetDeviceInfo(@Ptr long cl_device_id1, int cl_device_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clCreateSubDevices(cl_device_id, const cl_device_partition_property*, cl_uint, cl_device_id*, cl_uint*) - @Optional - public native int clCreateSubDevices(OpenCLLibrary.cl_device_id cl_device_id1, Pointer > cl_device_partition_propertyPtr1, int cl_uint1, Pointer cl_device_idPtr1, Pointer cl_uintPtr1); - /// Original signature : cl_int clRetainDevice(cl_device_id) - @Optional - public native int clRetainDevice(@Ptr long cl_device_id1); - /// Original signature : cl_int clReleaseDevice(cl_device_id) - @Optional - public native int clReleaseDevice(@Ptr long cl_device_id1); - /** - * Context APIs
      - * Original signature : cl_context clCreateContext(const cl_context_properties*, cl_uint, const cl_device_id*, clCreateContext_arg1_callback, void*, cl_int*) - */ - public native @Ptr long clCreateContext(@Ptr long cl_context_propertiesPtr1, int cl_uint1, @Ptr long cl_device_idPtr1, @Ptr long arg1, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_context clCreateContextFromType(const cl_context_properties*, cl_device_type, clCreateContextFromType_arg1_callback, void*, cl_int*) - public native OpenCLLibrary.cl_context clCreateContextFromType(Pointer > cl_context_propertiesPtr1, long cl_device_type1, Pointer arg1, Pointer voidPtr1, Pointer cl_intPtr1); - /// Original signature : cl_int clRetainContext(cl_context) - public native int clRetainContext(@Ptr long cl_context1); - /// Original signature : cl_int clReleaseContext(cl_context) - public native int clReleaseContext(@Ptr long cl_context1); - /// Original signature : cl_int clGetContextInfo(cl_context, cl_context_info, size_t, void*, size_t*) - public native int clGetContextInfo(@Ptr long cl_context1, int cl_context_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Command Queue APIs
      - * Original signature : cl_command_queue clCreateCommandQueue(cl_context, cl_device_id, cl_command_queue_properties, cl_int*) - */ - public native @Ptr long clCreateCommandQueue(@Ptr long cl_context1, @Ptr long cl_device_id1, long cl_command_queue_properties1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clRetainCommandQueue(cl_command_queue) - public native int clRetainCommandQueue(@Ptr long cl_command_queue1); - /// Original signature : cl_int clReleaseCommandQueue(cl_command_queue) - public native int clReleaseCommandQueue(@Ptr long cl_command_queue1); - /// Original signature : cl_int clGetCommandQueueInfo(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*) - public native int clGetCommandQueueInfo(@Ptr long cl_command_queue1, int cl_command_queue_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Memory Object APIs
      - * Original signature : cl_mem clCreateBuffer(cl_context, cl_mem_flags, size_t, void*, cl_int*) - */ - public native @Ptr long clCreateBuffer(@Ptr long cl_context1, long cl_mem_flags1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_mem clCreateSubBuffer(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*) - @Optional - public native @Ptr long clCreateSubBuffer(@Ptr long cl_mem1, long cl_mem_flags1, int cl_buffer_create_type1, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_mem clCreateImage(cl_context, cl_mem_flags, const cl_image_format*, const cl_image_desc*, void*, cl_int*) - @Optional - public native @Ptr long clCreateImage(@Ptr long cl_context1, long cl_mem_flags1, @Ptr long cl_image_formatPtr1, @Ptr long cl_image_descPtr1, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clRetainMemObject(cl_mem) - public native int clRetainMemObject(@Ptr long cl_mem1); - /// Original signature : cl_int clReleaseMemObject(cl_mem) - public native int clReleaseMemObject(@Ptr long cl_mem1); - /// Original signature : cl_int clGetSupportedImageFormats(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*) - public native int clGetSupportedImageFormats(@Ptr long cl_context1, long cl_mem_flags1, int cl_mem_object_type1, int cl_uint1, @Ptr long cl_image_formatPtr1, @Ptr long cl_uintPtr1); - /// Original signature : cl_int clGetMemObjectInfo(cl_mem, cl_mem_info, size_t, void*, size_t*) - public native int clGetMemObjectInfo(@Ptr long cl_mem1, int cl_mem_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clGetImageInfo(cl_mem, cl_image_info, size_t, void*, size_t*) - public native int clGetImageInfo(@Ptr long cl_mem1, int cl_image_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clSetMemObjectDestructorCallback(cl_mem, clSetMemObjectDestructorCallback_arg1_callback, void*) - @Optional - public native int clSetMemObjectDestructorCallback(@Ptr long cl_mem1, @Ptr long arg1, @Ptr long voidPtr1); - /** - * Sampler APIs
      - * Original signature : cl_sampler clCreateSampler(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*) - */ - public native @Ptr long clCreateSampler(@Ptr long cl_context1, int cl_bool1, int cl_addressing_mode1, int cl_filter_mode1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clRetainSampler(cl_sampler) - public native int clRetainSampler(@Ptr long cl_sampler1); - /// Original signature : cl_int clReleaseSampler(cl_sampler) - public native int clReleaseSampler(@Ptr long cl_sampler1); - /// Original signature : cl_int clGetSamplerInfo(cl_sampler, cl_sampler_info, size_t, void*, size_t*) - public native int clGetSamplerInfo(@Ptr long cl_sampler1, int cl_sampler_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Program Object APIs
      - * Original signature : cl_program clCreateProgramWithSource(cl_context, cl_uint, const char**, const size_t*, cl_int*) - */ - public native @Ptr long clCreateProgramWithSource(@Ptr long cl_context1, int cl_uint1, @Ptr long charPtrPtr1, @Ptr long size_tPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_program clCreateProgramWithBinary(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*) - public native @Ptr long clCreateProgramWithBinary(@Ptr long cl_context1, int cl_uint1, @Ptr long cl_device_idPtr1, @Ptr long size_tPtr1, @Ptr long charPtrPtr1, @Ptr long cl_intPtr1, @Ptr long cl_intPtr2); - /// Original signature : cl_program clCreateProgramWithBuiltInKernels(cl_context, cl_uint, const cl_device_id*, const char*, cl_int*) - @Optional - public native OpenCLLibrary.cl_program clCreateProgramWithBuiltInKernels(OpenCLLibrary.cl_context cl_context1, int cl_uint1, Pointer cl_device_idPtr1, Pointer charPtr1, Pointer cl_intPtr1); - /// Original signature : cl_int clRetainProgram(cl_program) - public native int clRetainProgram(@Ptr long cl_program1); - /// Original signature : cl_int clReleaseProgram(cl_program) - public native int clReleaseProgram(@Ptr long cl_program1); - /// Original signature : cl_int clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, clBuildProgram_arg1_callback, void*) - public native int clBuildProgram(@Ptr long cl_program1, int cl_uint1, @Ptr long cl_device_idPtr1, @Ptr long charPtr1, @Ptr long arg1, @Ptr long voidPtr1); - /// Original signature : cl_int clCompileProgram(cl_program, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, const char**, clCompileProgram_arg1_callback, void*) - @Optional - public native int clCompileProgram(OpenCLLibrary.cl_program cl_program1, int cl_uint1, Pointer cl_device_idPtr1, Pointer charPtr1, int cl_uint2, Pointer cl_programPtr1, Pointer > charPtrPtr1, Pointer arg1, Pointer voidPtr1); - /// Original signature : cl_program clLinkProgram(cl_context, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, clLinkProgram_arg1_callback, void*, cl_int*) - @Optional - public native OpenCLLibrary.cl_program clLinkProgram(OpenCLLibrary.cl_context cl_context1, int cl_uint1, Pointer cl_device_idPtr1, Pointer charPtr1, int cl_uint2, Pointer cl_programPtr1, Pointer arg1, Pointer voidPtr1, Pointer cl_intPtr1); - /// Original signature : cl_int clUnloadPlatformCompiler(cl_platform_id) - @Optional - public native int clUnloadPlatformCompiler(@Ptr long cl_platform_id1); - /// Original signature : cl_int clGetProgramInfo(cl_program, cl_program_info, size_t, void*, size_t*) - public native int clGetProgramInfo(@Ptr long cl_program1, int cl_program_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clGetProgramBuildInfo(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*) - public native int clGetProgramBuildInfo(@Ptr long cl_program1, @Ptr long cl_device_id1, int cl_program_build_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Kernel Object APIs
      - * Original signature : cl_kernel clCreateKernel(cl_program, const char*, cl_int*) - */ - public native @Ptr long clCreateKernel(@Ptr long cl_program1, @Ptr long charPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clCreateKernelsInProgram(cl_program, cl_uint, cl_kernel*, cl_uint*) - public native int clCreateKernelsInProgram(@Ptr long cl_program1, int cl_uint1, @Ptr long cl_kernelPtr1, @Ptr long cl_uintPtr1); - /// Original signature : cl_int clRetainKernel(cl_kernel) - public native int clRetainKernel(@Ptr long cl_kernel1); - /// Original signature : cl_int clReleaseKernel(cl_kernel) - public native int clReleaseKernel(@Ptr long cl_kernel1); - /// Original signature : cl_int clSetKernelArg(cl_kernel, cl_uint, size_t, const void*) - public native int clSetKernelArg(@Ptr long cl_kernel1, int cl_uint1, @Ptr long size_t1, @Ptr long voidPtr1); - /// Original signature : cl_int clGetKernelInfo(cl_kernel, cl_kernel_info, size_t, void*, size_t*) - public native int clGetKernelInfo(@Ptr long cl_kernel1, int cl_kernel_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clGetKernelArgInfo(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*) - @Optional - public native int clGetKernelArgInfo(@Ptr long cl_kernel1, int cl_uint1, int cl_kernel_arg_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clGetKernelWorkGroupInfo(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*) - public native int clGetKernelWorkGroupInfo(@Ptr long cl_kernel1, @Ptr long cl_device_id1, int cl_kernel_work_group_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Event Object APIs
      - * Original signature : cl_int clWaitForEvents(cl_uint, const cl_event*) - */ - public native int clWaitForEvents(int cl_uint1, @Ptr long cl_eventPtr1); - /// Original signature : cl_int clGetEventInfo(cl_event, cl_event_info, size_t, void*, size_t*) - public native int clGetEventInfo(@Ptr long cl_event1, int cl_event_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_event clCreateUserEvent(cl_context, cl_int*) - @Optional - public native @Ptr long clCreateUserEvent(@Ptr long cl_context1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clRetainEvent(cl_event) - public native int clRetainEvent(@Ptr long cl_event1); - /// Original signature : cl_int clReleaseEvent(cl_event) - public native int clReleaseEvent(@Ptr long cl_event1); - /// Original signature : cl_int clSetUserEventStatus(cl_event, cl_int) - @Optional - public native int clSetUserEventStatus(@Ptr long cl_event1, int cl_int1); - /// Original signature : cl_int clSetEventCallback(cl_event, cl_int, clSetEventCallback_arg1_callback, void*) - @Optional - public native int clSetEventCallback(@Ptr long cl_event1, int cl_int1, @Ptr long arg1, @Ptr long voidPtr1); - /** - * Profiling APIs
      - * Original signature : cl_int clGetEventProfilingInfo(cl_event, cl_profiling_info, size_t, void*, size_t*) - */ - public native int clGetEventProfilingInfo(@Ptr long cl_event1, int cl_profiling_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /** - * Flush and Finish APIs
      - * Original signature : cl_int clFlush(cl_command_queue) - */ - public native int clFlush(@Ptr long cl_command_queue1); - /// Original signature : cl_int clFinish(cl_command_queue) - public native int clFinish(@Ptr long cl_command_queue1); - /** - * Enqueued Commands APIs
      - * Original signature : cl_int clEnqueueReadBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*) - */ - public native int clEnqueueReadBuffer(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, @Ptr long size_t1, @Ptr long size_t2, @Ptr long voidPtr1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueReadBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueReadBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, Pointer size_tPtr1, Pointer size_tPtr2, Pointer size_tPtr3, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, @Ptr long size_t4, Pointer voidPtr1, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueWriteBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueWriteBuffer(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, @Ptr long size_t1, @Ptr long size_t2, @Ptr long voidPtr1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueWriteBufferRect(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueWriteBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, int cl_bool1, Pointer size_tPtr1, Pointer size_tPtr2, Pointer size_tPtr3, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, @Ptr long size_t4, Pointer voidPtr1, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueFillBuffer(cl_command_queue, cl_mem, const void*, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueFillBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueCopyBuffer(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueCopyBuffer(@Ptr long cl_command_queue1, @Ptr long cl_mem1, @Ptr long cl_mem2, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueCopyBufferRect(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueCopyBufferRect(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, Pointer size_tPtr1, Pointer size_tPtr2, Pointer size_tPtr3, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, @Ptr long size_t4, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueReadImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueReadImage(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, @Ptr long size_tPtr1, @Ptr long size_tPtr2, @Ptr long size_t1, @Ptr long size_t2, @Ptr long voidPtr1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueWriteImage(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueWriteImage(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, @Ptr long size_tPtr1, @Ptr long size_tPtr2, @Ptr long size_t1, @Ptr long size_t2, @Ptr long voidPtr1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueFillImage(cl_command_queue, cl_mem, const void*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueFillImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, Pointer voidPtr1, Pointer size_tPtr1, Pointer size_tPtr2, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueCopyImage(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueCopyImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, Pointer size_tPtr1, Pointer size_tPtr2, Pointer size_tPtr3, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueCopyImageToBuffer(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueCopyImageToBuffer(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, Pointer size_tPtr1, Pointer size_tPtr2, @Ptr long size_t1, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueCopyBufferToImage(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueCopyBufferToImage(OpenCLLibrary.cl_command_queue cl_command_queue1, OpenCLLibrary.cl_mem cl_mem1, OpenCLLibrary.cl_mem cl_mem2, @Ptr long size_t1, Pointer size_tPtr1, Pointer size_tPtr2, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : void* clEnqueueMapBuffer(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*) - public native @Ptr long clEnqueueMapBuffer(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, long cl_map_flags1, @Ptr long size_t1, @Ptr long size_t2, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2, @Ptr long cl_intPtr1); - /// Original signature : void* clEnqueueMapImage(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*) - public native @Ptr long clEnqueueMapImage(@Ptr long cl_command_queue1, @Ptr long cl_mem1, int cl_bool1, long cl_map_flags1, @Ptr long size_tPtr1, @Ptr long size_tPtr2, @Ptr long size_tPtr3, @Ptr long size_tPtr4, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2, @Ptr long cl_intPtr1); - /// Original signature : cl_int clEnqueueUnmapMemObject(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueUnmapMemObject(@Ptr long cl_command_queue1, @Ptr long cl_mem1, @Ptr long voidPtr1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueMigrateMemObjects(cl_command_queue, cl_uint, const cl_mem*, cl_mem_migration_flags, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueMigrateMemObjects(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, Pointer cl_memPtr1, long cl_mem_migration_flags1, int cl_uint2, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueNDRangeKernel(@Ptr long cl_command_queue1, @Ptr long cl_kernel1, int cl_uint1, @Ptr long size_tPtr1, @Ptr long size_tPtr2, @Ptr long size_tPtr3, int cl_uint2, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueTask(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueTask(@Ptr long cl_command_queue1, @Ptr long cl_kernel1, int cl_uint1, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueNativeKernel(cl_command_queue, clEnqueueNativeKernel_arg1_callback, void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*) - public native int clEnqueueNativeKernel(OpenCLLibrary.cl_command_queue cl_command_queue1, Pointer arg1, Pointer voidPtr1, @Ptr long size_t1, int cl_uint1, Pointer cl_memPtr1, Pointer > voidPtrPtr1, int cl_uint2, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueMarkerWithWaitList(cl_command_queue, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueMarkerWithWaitList(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clEnqueueBarrierWithWaitList(cl_command_queue, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueBarrierWithWaitList(OpenCLLibrary.cl_command_queue cl_command_queue1, int cl_uint1, Pointer cl_eventPtr1, Pointer cl_eventPtr2); - /// Original signature : cl_int clSetPrintfCallback(cl_context, clSetPrintfCallback_arg1_callback, void*) - @Optional - public native int clSetPrintfCallback(OpenCLLibrary.cl_context cl_context1, Pointer arg1, Pointer voidPtr1); - /** - * Extension function access
      - * * Returns the extension function address for the given function name,
      - * or NULL if a valid function can not be found. The client must
      - * check to make sure the address is not NULL, before using or
      - * calling the returned function address.
      - * Original signature : void* clGetExtensionFunctionAddressForPlatform(cl_platform_id, const char*) - */ - @Optional - public native Pointer clGetExtensionFunctionAddressForPlatform(OpenCLLibrary.cl_platform_id cl_platform_id1, Pointer charPtr1); - /** - * WARNING:
      - * This API introduces mutable state into the OpenCL implementation. It has been REMOVED
      - * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the
      - * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably.
      - * It is likely to be non-performant. Use of this API is not advised. Use at your own risk.
      - * * Software developers previously relying on this API are instructed to set the command queue
      - * properties when creating the queue, instead.
      - * Original signature : cl_int clSetCommandQueueProperty(cl_command_queue, cl_command_queue_properties, cl_bool, cl_command_queue_properties*) - */ - public native int clSetCommandQueueProperty(@Ptr long cl_command_queue1, long cl_command_queue_properties1, int cl_bool1, @Ptr long cl_command_queue_propertiesPtr1); - /// Original signature : cl_mem clCreateImage2D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*) - public native @Ptr long clCreateImage2D(@Ptr long cl_context1, long cl_mem_flags1, @Ptr long cl_image_formatPtr1, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_mem clCreateImage3D(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*) - public native @Ptr long clCreateImage3D(@Ptr long cl_context1, long cl_mem_flags1, @Ptr long cl_image_formatPtr1, @Ptr long size_t1, @Ptr long size_t2, @Ptr long size_t3, @Ptr long size_t4, @Ptr long size_t5, @Ptr long voidPtr1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clEnqueueMarker(cl_command_queue, cl_event*) - public native int clEnqueueMarker(@Ptr long cl_command_queue1, @Ptr long cl_eventPtr1); - /// Original signature : cl_int clEnqueueWaitForEvents(cl_command_queue, cl_uint, const cl_event*) - public native int clEnqueueWaitForEvents(@Ptr long cl_command_queue1, int cl_uint1, @Ptr long cl_eventPtr1); - /// Original signature : cl_int clEnqueueBarrier(cl_command_queue) - public native int clEnqueueBarrier(@Ptr long cl_command_queue1); - /// Original signature : cl_int clUnloadCompiler() - public native int clUnloadCompiler(); - /// Original signature : void* clGetExtensionFunctionAddress(const char*) - public native Pointer clGetExtensionFunctionAddress(Pointer charPtr1); - /// Original signature : cl_mem clCreateFromGLBuffer(cl_context, cl_mem_flags, cl_GLuint, int*) - @Optional - public native @Ptr long clCreateFromGLBuffer(@Ptr long cl_context1, long cl_mem_flags1, int cl_GLuint1, @Ptr long intPtr1); - /// Original signature : cl_mem clCreateFromGLTexture(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*) - @Optional - public native @Ptr long clCreateFromGLTexture(@Ptr long cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, @Ptr long cl_intPtr1); - /// Original signature : cl_mem clCreateFromGLRenderbuffer(cl_context, cl_mem_flags, cl_GLuint, cl_int*) - @Optional - public native @Ptr long clCreateFromGLRenderbuffer(@Ptr long cl_context1, long cl_mem_flags1, int cl_GLuint1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clGetGLObjectInfo(cl_mem, cl_gl_object_type*, cl_GLuint*) - @Optional - public native int clGetGLObjectInfo(@Ptr long cl_mem1, @Ptr long cl_gl_object_typePtr1, @Ptr long cl_GLuintPtr1); - /// Original signature : cl_int clGetGLTextureInfo(cl_mem, cl_gl_texture_info, size_t, void*, size_t*) - @Optional - public native int clGetGLTextureInfo(@Ptr long cl_mem1, int cl_gl_texture_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_int clEnqueueAcquireGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueAcquireGLObjects(@Ptr long cl_command_queue1, int cl_uint1, @Ptr long cl_memPtr1, int cl_uint2, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_int clEnqueueReleaseGLObjects(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*) - @Optional - public native int clEnqueueReleaseGLObjects(@Ptr long cl_command_queue1, int cl_uint1, @Ptr long cl_memPtr1, int cl_uint2, @Ptr long cl_eventPtr1, @Ptr long cl_eventPtr2); - /// Original signature : cl_mem clCreateFromGLTexture2D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*) - @Optional - public native @Ptr long clCreateFromGLTexture2D(@Ptr long cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, @Ptr long cl_intPtr1); - /// Original signature : cl_mem clCreateFromGLTexture3D(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*) - @Optional - public native @Ptr long clCreateFromGLTexture3D(@Ptr long cl_context1, long cl_mem_flags1, int cl_GLenum1, int cl_GLint1, int cl_GLuint1, @Ptr long cl_intPtr1); - /// Original signature : cl_int clGetGLContextInfoKHR(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*) - @Optional - public native int clGetGLContextInfoKHR(@Ptr long cl_context_propertiesPtr1, int cl_gl_context_info1, @Ptr long size_t1, @Ptr long voidPtr1, @Ptr long size_tPtr1); - /// Original signature : cl_event clCreateEventFromGLsyncKHR(cl_context, cl_GLsync, cl_int*) - @Optional - public native OpenCLLibrary.cl_event clCreateEventFromGLsyncKHR(OpenCLLibrary.cl_context cl_context1, OpenCLLibrary.cl_GLsync cl_GLsync1, Pointer cl_intPtr1); - /** - * memobj
      - * Original signature : cl_int clSetMemObjectDestructorAPPLE(cl_mem, clSetMemObjectDestructorAPPLE_arg1_callback, void*) - */ - @Optional - public native int clSetMemObjectDestructorAPPLE(OpenCLLibrary.cl_mem cl_mem1, Pointer arg1, Pointer voidPtr1); - /** - * errstr
      - * Original signature : void clLogMessagesToSystemLogAPPLE(const char*, const void*, size_t, void*) - */ - @Optional - public native void clLogMessagesToSystemLogAPPLE(Pointer charPtr1, Pointer voidPtr1, @Ptr long size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStdout sends all log messages to the file descriptor stdout
      - * errstr
      - * Original signature : void clLogMessagesToStdoutAPPLE(const char*, const void*, size_t, void*) - */ - @Optional - public native void clLogMessagesToStdoutAPPLE(Pointer charPtr1, Pointer voidPtr1, @Ptr long size_t1, Pointer voidPtr2); - /** - * clLogMessagesToStderr sends all log messages to the file descriptor stderr
      - * errstr
      - * Original signature : void clLogMessagesToStderrAPPLE(const char*, const void*, size_t, void*) - */ - @Optional - public native void clLogMessagesToStderrAPPLE(Pointer charPtr1, Pointer voidPtr1, @Ptr long size_t1, Pointer voidPtr2); - /// Original signature : cl_int clIcdGetPlatformIDsKHR(cl_uint, cl_platform_id*, cl_uint*) - @Optional - public native int clIcdGetPlatformIDsKHR(int cl_uint1, @Ptr long cl_platform_idPtr1, @Ptr long cl_uintPtr1); - /// Original signature : cl_int clReleaseDeviceEXT(cl_device_id) - @Optional - public native int clReleaseDeviceEXT(@Ptr long cl_device_id1); - /// Original signature : cl_int clRetainDeviceEXT(cl_device_id) - @Optional - public native int clRetainDeviceEXT(@Ptr long cl_device_id1); - /// Original signature : cl_int clCreateSubDevicesEXT(cl_device_id, const cl_device_partition_property_ext*, cl_uint, cl_device_id*, cl_uint*) - @Optional - public native int clCreateSubDevicesEXT(OpenCLLibrary.cl_device_id cl_device_id1, Pointer cl_device_partition_property_extPtr1, int cl_uint1, Pointer cl_device_idPtr1, Pointer cl_uintPtr1); - /** - * Apple extension for retrieving OpenGL context information for a CL context
      - * created via the above method.
      - * * Provides a query mechanism to retrieve OpenGL context specific information
      - * from an OpenCL context to help identify device specific mappings and usage.
      - *
      - * For example, one possible usage would be to allow the client to map a CGL
      - * virtual screen index to an appropriate CL device id to insure that the
      - * rendering device and the compute device are the same, thus guaranteeing
      - * any shared OpenGL memory that is attached o a CL memory object remains
      - * resident on the active device.
      - * context
      - * Original signature : cl_int clGetGLContextInfoAPPLE(cl_context, void*, cl_gl_platform_info, size_t, void*, size_t*) - */ - @Optional - public native int clGetGLContextInfoAPPLE(@Ptr long cl_context1, @Ptr long voidPtr1, int cl_gl_platform_info1, @Ptr long size_t1, @Ptr long voidPtr2, @Ptr long size_tPtr1); - public static class cl_device_id extends TypedPointer { - public cl_device_id(long address) { - super(address); - } - public cl_device_id(Pointer address) { - super(address); - } - }; - public static class cl_mem extends TypedPointer { - public cl_mem(long address) { - super(address); - } - public cl_mem(Pointer address) { - super(address); - } - }; - public static class cl_GLsync extends TypedPointer { - public cl_GLsync(long address) { - super(address); - } - public cl_GLsync(Pointer address) { - super(address); - } - }; - public static class cl_event extends TypedPointer { - public cl_event(long address) { - super(address); - } - public cl_event(Pointer address) { - super(address); - } - }; - public static class cl_platform_id extends TypedPointer { - public cl_platform_id(long address) { - super(address); - } - public cl_platform_id(Pointer address) { - super(address); - } - }; - public static class cl_command_queue extends TypedPointer { - public cl_command_queue(long address) { - super(address); - } - public cl_command_queue(Pointer address) { - super(address); - } - }; - public static class cl_context extends TypedPointer { - public cl_context(long address) { - super(address); - } - public cl_context(Pointer address) { - super(address); - } - }; - public static class cl_sampler extends TypedPointer { - public cl_sampler(long address) { - super(address); - } - public cl_sampler(Pointer address) { - super(address); - } - }; - public static class cl_program extends TypedPointer { - public cl_program(long address) { - super(address); - } - public cl_program(Pointer address) { - super(address); - } - }; - public static class cl_kernel extends TypedPointer { - public cl_kernel(long address) { - super(address); - } - public cl_kernel(Pointer address) { - super(address); - } - }; -} diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java deleted file mode 100644 index bae97a61e..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/OpenGLContextUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.nativelibs4java.opencl.library; - -import org.bridj.*; -import org.bridj.ann.*; -import static org.bridj.Pointer.*; - -/** - * JNA Wrapper for library OpenGL
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -@Library("OpenGL") -@org.bridj.ann.Runtime(CRuntime.class) -public class OpenGLContextUtils { - static { - if (Platform.isWindows()) - BridJ.addNativeLibraryAlias("OpenGL", "OpenGL32"); // even in 64 bit mode ! - else if (Platform.isUnix() && !Platform.isMacOSX()) - BridJ.addNativeLibraryAlias("OpenGL", "GL"); - - BridJ.register(); - } - /// Original signature : CGLShareGroupObj CGLGetShareGroup(CGLContextObj) - public static native Pointer CGLGetShareGroup(Pointer ctx); - /** - * * Current context functions
      - * Original signature : CGLError CGLSetCurrentContext(CGLContextObj) - */ - @Optional - public static native int CGLSetCurrentContext(Pointer ctx); - /// Original signature : CGLContextObj CGLGetCurrentContext() - @Optional - public static native Pointer CGLGetCurrentContext(); - - /** - * * Version numbers
      - * Original signature : void CGLGetVersion(GLint*, GLint*) - */ - @Optional - public static native void CGLGetVersion(Pointer majorvers, Pointer minorvers); - /** - * * Convert an error code to a string
      - * Original signature : char* CGLErrorString(CGLError)
      - * @param error @see CGLError - */ - @Optional - public static native Pointer CGLErrorString(int error); - - @Optional - public static native Pointer wglGetCurrentDC(); - @Optional - public static native Pointer wglGetCurrentContext(); - @Optional - public static native Pointer glXGetCurrentDisplay(); - @Optional - public static native Pointer glXGetCurrentContext(); -} diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java deleted file mode 100644 index 0815f8b9c..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_buffer_region.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.nativelibs4java.opencl.library; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; -/** - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("OpenCL") -public class cl_buffer_region extends StructObject { - public cl_buffer_region() { - super(); - } - @Ptr - @Field(0) - public long origin() { - return this.io.getSizeTField(this, 0); - } - @Ptr - @Field(0) - public cl_buffer_region origin(long origin) { - this.io.setSizeTField(this, 0, origin); - return this; - } - @Ptr - @Field(1) - public long size() { - return this.io.getSizeTField(this, 1); - } - @Ptr - @Field(1) - public cl_buffer_region size(long size) { - this.io.setSizeTField(this, 1, size); - return this; - } - public cl_buffer_region(Pointer pointer) { - super(pointer); - } -} diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_desc.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_desc.java deleted file mode 100644 index 1b455480c..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_desc.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.nativelibs4java.opencl.library; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -import org.bridj.ann.Ptr; -/** - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("OpenCL") -public class cl_image_desc extends StructObject { - public cl_image_desc() { - super(); - } - /// C type : cl_mem_object_type - @Field(0) - public int image_type() { - return this.io.getIntField(this, 0); - } - /// C type : cl_mem_object_type - @Field(0) - public cl_image_desc image_type(int image_type) { - this.io.setIntField(this, 0, image_type); - return this; - } - @Ptr - @Field(1) - public long image_width() { - return this.io.getSizeTField(this, 1); - } - @Ptr - @Field(1) - public cl_image_desc image_width(long image_width) { - this.io.setSizeTField(this, 1, image_width); - return this; - } - @Ptr - @Field(2) - public long image_height() { - return this.io.getSizeTField(this, 2); - } - @Ptr - @Field(2) - public cl_image_desc image_height(long image_height) { - this.io.setSizeTField(this, 2, image_height); - return this; - } - @Ptr - @Field(3) - public long image_depth() { - return this.io.getSizeTField(this, 3); - } - @Ptr - @Field(3) - public cl_image_desc image_depth(long image_depth) { - this.io.setSizeTField(this, 3, image_depth); - return this; - } - @Ptr - @Field(4) - public long image_array_size() { - return this.io.getSizeTField(this, 4); - } - @Ptr - @Field(4) - public cl_image_desc image_array_size(long image_array_size) { - this.io.setSizeTField(this, 4, image_array_size); - return this; - } - @Ptr - @Field(5) - public long image_row_pitch() { - return this.io.getSizeTField(this, 5); - } - @Ptr - @Field(5) - public cl_image_desc image_row_pitch(long image_row_pitch) { - this.io.setSizeTField(this, 5, image_row_pitch); - return this; - } - @Ptr - @Field(6) - public long image_slice_pitch() { - return this.io.getSizeTField(this, 6); - } - @Ptr - @Field(6) - public cl_image_desc image_slice_pitch(long image_slice_pitch) { - this.io.setSizeTField(this, 6, image_slice_pitch); - return this; - } - /// C type : cl_uint - @Field(7) - public int num_mip_levels() { - return this.io.getIntField(this, 7); - } - /// C type : cl_uint - @Field(7) - public cl_image_desc num_mip_levels(int num_mip_levels) { - this.io.setIntField(this, 7, num_mip_levels); - return this; - } - /// C type : cl_uint - @Field(8) - public int num_samples() { - return this.io.getIntField(this, 8); - } - /// C type : cl_uint - @Field(8) - public cl_image_desc num_samples(int num_samples) { - this.io.setIntField(this, 8, num_samples); - return this; - } - public cl_image_desc(Pointer pointer) { - super(pointer); - } -} diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java deleted file mode 100644 index 33037edc9..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/cl_image_format.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nativelibs4java.opencl.library; -import org.bridj.Pointer; -import org.bridj.StructObject; -import org.bridj.ann.Field; -import org.bridj.ann.Library; -/** - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java or BridJ . - */ -@Library("OpenCL") -public class cl_image_format extends StructObject { - public cl_image_format() { - super(); - } - /// C type : cl_channel_order - @Field(0) - public int image_channel_order() { - return this.io.getIntField(this, 0); - } - /// C type : cl_channel_order - @Field(0) - public cl_image_format image_channel_order(int image_channel_order) { - this.io.setIntField(this, 0, image_channel_order); - return this; - } - /// C type : cl_channel_type - @Field(1) - public int image_channel_data_type() { - return this.io.getIntField(this, 1); - } - /// C type : cl_channel_type - @Field(1) - public cl_image_format image_channel_data_type(int image_channel_data_type) { - this.io.setIntField(this, 1, image_channel_data_type); - return this; - } - public cl_image_format(Pointer pointer) { - super(pointer); - } -} diff --git a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java b/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java deleted file mode 100644 index 746ee8c0d..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/java/com/nativelibs4java/opencl/library/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Raw OpenCL API bindings. - */ -package com.nativelibs4java.opencl.library; diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator deleted file mode 100644 index 2add7884a..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.MacOSX.jnaerator +++ /dev/null @@ -1,11 +0,0 @@ -"$(DIR)/OpenCL.base.jnaerator" - --DAVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER= --D__APPLE__= - -//-framework OpenCL - -//-framework OpenGL -//-package com.nativelibs4java.opengl.library -framework OpenGL - --v diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.OtherPlatforms.jnaerator +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator deleted file mode 100644 index 3f21a9046..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.Win32ATIStream.jnaerator +++ /dev/null @@ -1,11 +0,0 @@ -"$(DIR)/OpenCL.base.jnaerator" - -"-Dcl_bitfield=unsigned long" --library OpenCL - "-D_MSC_VER=1" -// "-D__CL_IMPORT=__declspec(dllimport)" - "C:\Program Files\ATI Stream\include\CL\cl_platform.h" - "-IC:\Program Files\ATI Stream\include" - "C:\Program Files\ATI Stream\include\CL\cl.h" - "C:\Program Files\ATI Stream\include\CL\cl_gl.h" - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator deleted file mode 100644 index 8b1378917..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/OpenCL.base.jnaerator +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.1.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.1.jnaerator deleted file mode 100644 index efcc27c44..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.1.jnaerator +++ /dev/null @@ -1,36 +0,0 @@ --nocpp --noMangling --noJar -noComp --runtime BridJ - --gccLong --limitComments - -"-Dextern=" -"-D__stdcall=" -"-D__declspec(x)=x" -"-D__extension__=" - --U_MSC_VER -//-U__APPLE__ -//-U__cplusplus -//-U_WIN32 --DCL_USE_DEPRECATED_OPENCL_1_0_APIS=1 - -//-o "$(DIR)/../../../target/generated-sources/java" - -//-choicesOut "$(DIR)/OpenCL.choices" --v - --package com.nativelibs4java.opencl.library --libraryNamingPrefixes cl --library OpenCL - "-I$(DIR)/../headers/1.1" - "$(DIR)/../headers/1.1/CL/cl_platform.h" - "$(DIR)/../headers/1.1/CL/opencl.h" - "$(DIR)/../headers/1.1/CL/cl.h" - "$(DIR)/../headers/1.1/CL/cl_ext.h" - "$(DIR)/../headers/1.1/CL/cl_gl.h" - "$(DIR)/../headers/1.1/CL/cl_gl_ext.h" - --onlineDoc "Khronos Documentation for {0}" "http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/{0}.html" diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.2.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.2.jnaerator deleted file mode 100644 index 4d42ef2c5..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config-1.2.jnaerator +++ /dev/null @@ -1,42 +0,0 @@ --dontCastConstants - --nocpp --noMangling -//-noJar -noComp --runtime BridJ - --gccLong --genRawBindings --limitComments - -"-Dextern=" -"-D__stdcall=" -"-D__declspec(x)=x" -"-D__extension__=" - --U_MSC_VER -//-U__APPLE__ -//-U__cplusplus -//-U_WIN32 --DCL_USE_DEPRECATED_OPENCL_1_0_APIS=1 --DCL_USE_DEPRECATED_OPENCL_1_1_APIS=1 --DCL_USE_DEPRECATED_OPENCL_1_2_APIS=1 - --v - --package com.nativelibs4java.opencl.library --libraryNamingPrefixes cl --library OpenCL - "-I$(DIR)/../headers/1.2" - //"$(DIR)/../headers/1.2/CL/cl_platform.h" - "$(DIR)/../headers/1.2/CL/opencl.h" - "$(DIR)/../headers/1.2/CL/cl_apple.h" - - //"$(DIR)/../headers/1.2/CL/cl.h" - //"$(DIR)/../headers/1.2/CL/cl_ext.h" - //"$(DIR)/../headers/1.2/CL/cl_gl.h" - //"$(DIR)/../headers/1.2/CL/cl_gl_ext.h" - //"$(DIR)/../headers/1.2/CL/t.h" - - --onlineDoc "Khronos Documentation for {0}" "http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/{0}.html" diff --git a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config.jnaerator b/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config.jnaerator deleted file mode 100644 index f73609d84..000000000 --- a/libraries/OpenCL/OpenCL4Java/src/main/jnaerator/config.jnaerator +++ /dev/null @@ -1 +0,0 @@ -"$(DIR)/config-1.2.jnaerator" diff --git a/libraries/OpenCL/OpenGLDemos/.gitignore b/libraries/OpenCL/OpenGLDemos/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/OpenGLDemos/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos-bridj.iml b/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos-bridj.iml deleted file mode 100644 index 93ec40b5e..000000000 --- a/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos-bridj.iml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos.iml b/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos.iml deleted file mode 100644 index 94d2a9abe..000000000 --- a/libraries/OpenCL/OpenGLDemos/javacl-opengl-demos.iml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenGLDemos/pom.xml b/libraries/OpenCL/OpenGLDemos/pom.xml deleted file mode 100644 index 4f9e4633b..000000000 --- a/libraries/OpenCL/OpenGLDemos/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-opengl-demos - JavaCL OpenGL Demos / BridJ - http://code.google.com/p/javacl/ - jar - - - true - com.nativelibs4java.opencl.demos.particles.ParticlesDemo - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - - - com.nativelibs4java - javacl-demos - - - - org.swinglabs - swing-layout - 1.0.3 - - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form b/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form deleted file mode 100644 index cce20a24c..000000000 --- a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.form +++ /dev/null @@ -1,196 +0,0 @@ - - -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java b/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java deleted file mode 100644 index 0e93d0c43..000000000 --- a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/JavaCLSettingsPanel.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * JavaCL - Java API and utilities for OpenCL - * http://javacl.googlecode.com/ - * - * Copyright (c) 2009-2011, Olivier Chafik (http://ochafik.com/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.opencl.demos; - -import com.nativelibs4java.opencl.CLDevice; -import com.nativelibs4java.opencl.CLPlatform; -import com.nativelibs4java.opencl.JavaCL; -import com.nativelibs4java.opencl.demos.hardware.HardwareReport; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLProfile; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -/** - * - * @author ochafik - */ -public class JavaCLSettingsPanel extends javax.swing.JPanel { - - /** - * - */ - private static final long serialVersionUID = -3840797355369910724L; - - public void removeOpenGLComponents() { - configFromGLCheck.getParent().remove(configFromGLCheck); - awtRenderingCheck.getParent().remove(awtRenderingCheck); - invalidate(); - } - - /** Creates new form JavaCLSettingsPanel */ - public JavaCLSettingsPanel() { - initComponents(); - - Border border = UIManager.getBorder( "TitledBorder.aquaVariant" ); - if (border == null) - border = new EtchedBorder(); - settingsPanel.setBorder(new TitledBorder(border, "OpenCL & OpenGL Settings")); - platformCombo.setModel(new DefaultComboBoxModel(getPlatforms().toArray())); - platformChanged(null); - normalButtActionPerformed(null); - } - - public boolean isDirectGLRendering() { - return awtRenderingCheck.isSelected(); - } - public void setDirectGLRendering(boolean b) { - awtRenderingCheck.setSelected(b); - } - - public CLDevice getDevice() { - return (CLDevice)deviceCombo.getSelectedItem(); - } - - public List getPlatforms() { - CLPlatform[] platforms = JavaCL.listPlatforms(); - boolean hasSharing = false; - plat: for (CLPlatform platform : platforms) - if (platform.isGLSharingSupported()) - for (CLDevice device : platform.listAllDevices(false)) - if (device.isGLSharingSupported()) { - hasSharing = true; - break plat; - } - - configFromGLCheck.setEnabled(hasSharing); - if (!hasSharing) { - configFromGLCheck.setText(configFromGLCheck.getText() + " (unavailable option)"); - configFromGLCheck.setToolTipText("Did not find any OpenCL platform with OpenGL sharing support."); - } - - return Arrays.asList(platforms); - } - - public List getGLProfiles() { - List list = new ArrayList(); - list.add(GLProfile.GL2); - return list; - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - @SuppressWarnings("unchecked") - // //GEN-BEGIN:initComponents - private void initComponents() { - - settingsPanel = new javax.swing.JPanel(); - fastestButt = new javax.swing.JButton(); - safestButt = new javax.swing.JButton(); - normalButt = new javax.swing.JButton(); - detailsButt = new javax.swing.JButton(); - awtRenderingCheck = new javax.swing.JCheckBox(); - configFromGLCheck = new javax.swing.JCheckBox(); - platformLab = new javax.swing.JLabel(); - platformCombo = new javax.swing.JComboBox(); - deviceLab = new javax.swing.JLabel(); - deviceCombo = new javax.swing.JComboBox(); - - fastestButt.setText("Fastest (unstable)"); - fastestButt.setToolTipText("Best performance, typically unstable."); - fastestButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - fastestButtActionPerformed(evt); - } - }); - - safestButt.setText("Safest (slow)"); - safestButt.setToolTipText("Choose this if you've experienced crashes or black screens with the other modes"); - safestButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - safestButtActionPerformed(evt); - } - }); - - normalButt.setFont(normalButt.getFont().deriveFont(normalButt.getFont().getStyle() | java.awt.Font.BOLD)); - normalButt.setText("Normal (advised)"); - normalButt.setToolTipText("Usually the best compromise."); - normalButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - normalButtActionPerformed(evt); - } - }); - - detailsButt.setText("Details"); - detailsButt.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - detailsButtActionPerformed(evt); - } - }); - - awtRenderingCheck.setSelected(true); - awtRenderingCheck.setText("Direct OpenGL AWT Rendering (faster)"); - awtRenderingCheck.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - awtRenderingCheckActionPerformed(evt); - } - }); - - configFromGLCheck.setText("Configure from OpenGL context"); - configFromGLCheck.setToolTipText("Attempt to share data between OpenCL and OpenGL. \nThis is not well supported by existing graphic card drivers might crash the program."); - configFromGLCheck.addChangeListener(new javax.swing.event.ChangeListener() { - public void stateChanged(javax.swing.event.ChangeEvent evt) { - configFromGLChanged(evt); - } - }); - configFromGLCheck.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - configFromGLCheckActionPerformed(evt); - } - }); - - platformLab.setText("Platform"); - - platformCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - platformCombo.setMinimumSize(new java.awt.Dimension(16, 27)); - platformCombo.addItemListener(new java.awt.event.ItemListener() { - public void itemStateChanged(java.awt.event.ItemEvent evt) { - platformChanged(evt); - } - }); - platformCombo.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - platformComboActionPerformed(evt); - } - }); - - deviceLab.setText("Device"); - - deviceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); - deviceCombo.setMinimumSize(new java.awt.Dimension(16, 27)); - - org.jdesktop.layout.GroupLayout settingsPanelLayout = new org.jdesktop.layout.GroupLayout(settingsPanel); - settingsPanel.setLayout(settingsPanelLayout); - settingsPanelLayout.setHorizontalGroup( - settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanelLayout.createSequentialGroup() - .addContainerGap() - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) - .add(platformLab) - .add(deviceLab)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanelLayout.createSequentialGroup() - .add(fastestButt) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(normalButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(safestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .add(configFromGLCheck) - .add(awtRenderingCheck) - .add(org.jdesktop.layout.GroupLayout.TRAILING, settingsPanelLayout.createSequentialGroup() - .add(platformCombo, 0, 354, Short.MAX_VALUE) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(detailsButt)) - .add(org.jdesktop.layout.GroupLayout.TRAILING, deviceCombo, 0, 448, Short.MAX_VALUE)) - .addContainerGap()) - ); - settingsPanelLayout.setVerticalGroup( - settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(org.jdesktop.layout.GroupLayout.TRAILING, settingsPanelLayout.createSequentialGroup() - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(safestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .add(fastestButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .add(normalButt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) - .add(configFromGLCheck) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(platformCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .add(platformLab) - .add(detailsButt)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(settingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) - .add(deviceCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .add(deviceLab)) - .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(awtRenderingCheck)) - ); - - org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); - this.setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - ); - layout.setVerticalGroup( - layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(settingsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - ); - }// //GEN-END:initComponents - - private void configFromGLCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configFromGLCheckActionPerformed - - }//GEN-LAST:event_configFromGLCheckActionPerformed - - private void awtRenderingCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_awtRenderingCheckActionPerformed - // TODO add your handling code here: - }//GEN-LAST:event_awtRenderingCheckActionPerformed - - private void platformComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_platformComboActionPerformed - // TODO add your handling code here: - }//GEN-LAST:event_platformComboActionPerformed - - private void platformChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_platformChanged - CLPlatform platform = (CLPlatform)platformCombo.getSelectedItem(); - if (platform != null) { - CLDevice[] devices = platform.listAllDevices(true); - deviceCombo.setModel(new DefaultComboBoxModel(devices)); - setDevice(platform.getBestDevice()); - } else { - deviceCombo.setModel(new DefaultComboBoxModel(new Object[0])); - } - }//GEN-LAST:event_platformChanged - - - private void fastestButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fastestButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(true); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(true); - }//GEN-LAST:event_fastestButtActionPerformed - - private void normalButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_normalButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(true); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(false); - }//GEN-LAST:event_normalButtActionPerformed - - private void safestButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_safestButtActionPerformed - selectBestDevice(); - if (awtRenderingCheck.isEnabled()) - awtRenderingCheck.setSelected(false); - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(false); - }//GEN-LAST:event_safestButtActionPerformed - - private void configFromGLChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_configFromGLChanged - platformCombo.setEnabled(!configFromGLCheck.isSelected()); - deviceCombo.setEnabled(!configFromGLCheck.isSelected()); - platformLab.setEnabled(!configFromGLCheck.isSelected()); - deviceLab.setEnabled(!configFromGLCheck.isSelected()); - }//GEN-LAST:event_configFromGLChanged - - private void detailsButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_detailsButtActionPerformed - CLPlatform platform = (CLPlatform)platformCombo.getSelectedItem(); - if (platform != null) { - JComponent c = HardwareReport.getHardwareReportComponent(platform); - c.setMaximumSize(new Dimension(600, 600)); - c.setPreferredSize(new Dimension(600, 600)); - JOptionPane.showMessageDialog(this, c, "HardwareReport for platform '" + platform.getName() + "'", JOptionPane.INFORMATION_MESSAGE); - } - }//GEN-LAST:event_detailsButtActionPerformed - - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JCheckBox awtRenderingCheck; - private javax.swing.JCheckBox configFromGLCheck; - private javax.swing.JButton detailsButt; - private javax.swing.JComboBox deviceCombo; - private javax.swing.JLabel deviceLab; - private javax.swing.JButton fastestButt; - private javax.swing.JButton normalButt; - private javax.swing.JComboBox platformCombo; - private javax.swing.JLabel platformLab; - private javax.swing.JButton safestButt; - private javax.swing.JPanel settingsPanel; - // End of variables declaration//GEN-END:variables - - private void setDevice(CLDevice device) { - if (device == null) { - deviceCombo.setSelectedIndex(-1); - return; - } - - CLPlatform platform = device.getPlatform(); - if (!platform.equals(platformCombo.getSelectedItem())) - platformCombo.setSelectedItem(platform); - - for (int i = 0, len = deviceCombo.getModel().getSize(); i < len; i++) { - CLDevice d = (CLDevice)deviceCombo.getModel().getElementAt(i); - if (device.equals(d)) { - deviceCombo.setSelectedItem(d); - break; - } - } - } - - private void selectBestDevice() { - setDevice(JavaCL.getBestDevice()); - } - - public boolean isGLSharingEnabled() { - return configFromGLCheck.isEnabled() && configFromGLCheck.isSelected(); - } - - public void setGLSharingEnabled(boolean b) { - if (configFromGLCheck.isEnabled()) - configFromGLCheck.setSelected(b); - } - -} diff --git a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java b/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java deleted file mode 100644 index 532f9039a..000000000 --- a/libraries/OpenCL/OpenGLDemos/src/main/java/com/nativelibs4java/opencl/demos/particles/ParticlesDemo.java +++ /dev/null @@ -1,648 +0,0 @@ -/*********************************************************************** - - Copyright (c) 2008, 2009, Memo Akten, www.memo.tv - *** The Mega Super Awesome Visuals Company *** - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of MSA Visuals nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. - * - * ***********************************************************************/ - -package com.nativelibs4java.opencl.demos.particles; - - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.demos.JavaCLSettingsPanel; -import com.nativelibs4java.opencl.demos.SetupUtils; -import com.nativelibs4java.util.*; -import java.util.logging.*; - -import javax.swing.*; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; - -import javax.media.opengl.*; -import static javax.media.opengl.GL.*; -import javax.media.opengl.awt.*; - -import com.jogamp.opengl.util.*; -import com.jogamp.common.nio.*; - -import java.awt.*; -import java.awt.event.*; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileReader; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.nio.ByteBuffer; -import java.util.Map; -import java.util.Random; -import javax.imageio.ImageIO; -import static javax.media.opengl.GL.*; -import javax.media.opengl.glu.GLU; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.basic.BasicMenuUI.ChangeHandler; - -/** - * - * @author Olivier (ported to JavaCL/OpenCL4Java) - */ -public class ParticlesDemo implements GLEventListener { - - public static Component createGLCanvas(int width, int height, boolean useSwing) { - GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - Component canvas = useSwing ? new GLJPanel(caps) : new GLCanvas(caps); - canvas.setSize(width, height); - canvas.setIgnoreRepaint(true); - canvas.setPreferredSize(new Dimension(width, height)); - canvas.setSize(new Dimension(width, height)); - - return canvas; - } - - static File lastFile; - volatile boolean paused; - final static float DEFAULT_MOUSE_WEIGHT = 0.7f; - volatile float mouseWeight = DEFAULT_MOUSE_WEIGHT; - - static class ParticlesCountItem { - public int count; - public String string; - public ParticlesCountItem(int count, String string) { - this.count = count; - this.string = string; - } - @Override - public String toString() { - return string; - } - - } - - public static void main(String[] args) { - try { - System.setProperty("sun.java2d.noddraw","true"); - - try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {} - SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); - - - JFrame f = new JFrame("JavaCL Particles Demo"); - Box tb = Box.createHorizontalBox(); - final JButton openImage = new JButton("Import"), saveImage = new JButton("Export"), changeBlend = new JButton("Change Blend"); - tb.add(openImage); - //tb.add(saveImage); - tb.add(changeBlend); - //final JCheckBox limi - final AssertionError[] err = new AssertionError[1]; - - - final ParticlesDemo demo = new ParticlesDemo(); - final int nSpeeds = 21; - - final JSlider speedSlider = new JSlider(0, nSpeeds - 1); - speedSlider.setValue(nSpeeds / 2); - //f.getContentPane().add("West", slider); - - tb.add(speedSlider); - //slider.setOrientation(JSlider.VERTICAL); - speedSlider.addChangeListener(new ChangeListener() { - - @Override - public void stateChanged(ChangeEvent e) { - int d = speedSlider.getValue() - nSpeeds / 2; - demo.speedFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * DEFAULT_SPEED_FACTOR; - } - - }); - - changeBlend.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent ae) { - demo.iBlend = (demo.iBlend + 1) % demo.blends.length; - } - - }); - - final Component canvas = createGLCanvas(1000, 800, demo.settings.isDirectGLRendering()); - f.setLayout(new BorderLayout()); - f.add("Center", canvas); - - saveImage.addActionListener(new ActionListener() { - - @SuppressWarnings("deprecation") - @Override - public void actionPerformed(ActionEvent ae) { - boolean paused = demo.paused; - demo.paused = true; - - BufferedImage im = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics g = im.createGraphics(); - canvas.paint(g); - g.dispose(); - - FileDialog fc = new FileDialog((Frame)null); - fc.setMode(FileDialog.SAVE); - fc.show(); - if (fc.getFile() != null) { - try { - ImageIO.write(im, "jpeg", lastFile = new File(new File(fc.getDirectory()), fc.getFile())); - } catch (Exception ex) { - ParticlesDemo.exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - demo.paused = paused; - } - - }); - - openImage.addActionListener(new ActionListener() { - - @SuppressWarnings("deprecation") - @Override - public void actionPerformed(ActionEvent ae) { - boolean paused = demo.paused; - demo.paused = true; - - FileDialog fc = new FileDialog((Frame)null); - fc.setMode(FileDialog.LOAD); - fc.show(); - if (fc.getFile() != null) { - try { - BufferedImage im = ImageIO.read(lastFile = new File(new File(fc.getDirectory()), fc.getFile())); - demo.setImage(im); - } catch (Exception ex) { - ParticlesDemo.exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - demo.paused = paused; - } - - }); - - canvas.addMouseWheelListener(new MouseWheelListener() { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - if (e.getUnitsToScroll() > 0) - for (int i = e.getUnitsToScroll(); i-- != 0;) - demo.mouseWeight *= 1.1f; - else - for (int i = -e.getUnitsToScroll(); i-- != 0;) - demo.mouseWeight /= 1.1f; - } - }); - canvas.addKeyListener(new KeyAdapter() { - - @Override - public void keyPressed(KeyEvent ke) { - switch (ke.getKeyCode()) { - case KeyEvent.VK_SPACE: - demo.paused = !demo.paused; - break; - case KeyEvent.VK_DELETE: - case KeyEvent.VK_BACK_SPACE: - demo.mouseWeight = 1; - break; - } - } - - - - }); - final JSlider sliderMass = new JSlider(0, nSpeeds - 1); - sliderMass.setValue(nSpeeds / 2); - //f.getContentPane().add("East", sliderMass); - //sliderMass.setOrientation(JSlider.VERTICAL); - sliderMass.addChangeListener(new ChangeListener() { - - @Override - public void stateChanged(ChangeEvent e) { - int d = sliderMass.getValue() - nSpeeds / 2; - demo.massFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * DEFAULT_MASS_FACTOR; - } - - }); - tb.add(sliderMass); - - f.add("North", tb); - - canvas.addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent me) { - if (me.getButton() != MouseEvent.BUTTON1 || me.isMetaDown() || me.isControlDown()) - demo.mouseWeight = 1; - else - demo.paused = !demo.paused; - } - - @Override - public void mouseExited(MouseEvent e) { - demo.hasMouse = false; - } - - @Override - public void mouseEntered(MouseEvent e) { - demo.hasMouse = true; - } - - - - - }); - canvas.addMouseMotionListener(new MouseMotionAdapter() { - - @Override - public void mouseMoved(MouseEvent e) { - demo.mouseX = e.getX(); - demo.mouseY = e.getY(); - demo.lastMouseMove = System.currentTimeMillis(); - } - - }); - - //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.addWindowListener(new WindowAdapter() { - - @Override - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - f.pack(); - - f.setVisible(true); - - FPSAnimator animator; - if (canvas instanceof GLCanvas) { - ((GLCanvas)canvas).addGLEventListener(demo); - animator = new FPSAnimator(((GLCanvas)canvas), 30); - } else { - ((GLJPanel)canvas).addGLEventListener(demo); - animator = new FPSAnimator(((GLJPanel)canvas), 30); - } - - //animator.setRunAsFastAsPossible(true); - animator.start(); - } catch (Exception ex) { - exception(ex); - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public void setImage(BufferedImage image) { - mouseWeight = DEFAULT_MOUSE_WEIGHT; - - int iWidth = image.getWidth(), iHeight = image.getHeight(); - int[] pixels = image.getRGB(0, 0, iWidth, iHeight, null, 0, iWidth); - int nPixels = iWidth * iHeight; - float[] nonEmptyPixelsX = new float[nPixels], nonEmptyPixelsY = new float[nPixels]; - int[] nonEmptyPixels = new int[nPixels]; - - int nNonEmptyPixels = 0; - int hw = iWidth / 2, hh = iHeight / 2; - for (int iPixel = 0; iPixel < nPixels; iPixel++) { - int pixel = pixels[iPixel]; - if ((pixel & 0xff000000) != 0) - { - int y = iPixel / iWidth, x = iPixel - y * iWidth; - nonEmptyPixels[nNonEmptyPixels] = pixel; - nonEmptyPixelsX[nNonEmptyPixels] = x - hw; - nonEmptyPixelsY[nNonEmptyPixels] = hh - y; - nNonEmptyPixels++; - } - } - - queue.finish(); - - Pointer positionsView = interleavedColorAndPositionsTemp.as(Float.class); - Pointer colorView = interleavedColorAndPositionsTemp.as(Integer.class); - for (int iPoint = 0; iPoint < particlesCount; iPoint++) { - int iPixel = (int)(random.nextFloat() * (nNonEmptyPixels - 1)); - - velocities.set(iPixel, 0f); - velocities.set(iPixel + 1, 0f); - - int colorOffset = iPoint * (elementSize / 4); - int posOffset = iPoint * (elementSize / 4) + 1; - - colorView.set(colorOffset, nonEmptyPixels[iPixel]); - positionsView.set(posOffset, nonEmptyPixelsX[iPixel]); - positionsView.set(posOffset + 1, nonEmptyPixelsY[iPixel]); - } - velocitiesMem.write(queue, velocities, false); - - if (useOpenGLContext) - interleavedColorAndPositionsMem.acquireGLObject(queue); - interleavedColorAndPositionsMem.write(queue, interleavedColorAndPositionsTemp, false); - if (useOpenGLContext) - interleavedColorAndPositionsMem.releaseGLObject(queue); - - queue.finish(); - } - - CLContext context; - CLQueue queue; - - boolean useOpenGLContext = false; - int particlesCount; - int[] vbo = new int[1]; - - static final float DEFAULT_SLOWDOWN_FACTOR = 0.7f; - static final float DEFAULT_SPEED_FACTOR = 2f, DEFAULT_MASS_FACTOR = 2; - float mouseX, mouseY, width, height, massFactor = DEFAULT_MASS_FACTOR, speedFactor = DEFAULT_SPEED_FACTOR, slowDownFactor = DEFAULT_SLOWDOWN_FACTOR; - boolean hasMouse = false; - boolean limitToScreen = false; - - long lastMouseMove; - Pointer velocities; - //CLKernel updateParticleKernel; - ParticlesDemoProgram particlesProgram; - CLBuffer massesMem, velocitiesMem; - CLBuffer interleavedColorAndPositionsMem; - Pointer interleavedColorAndPositionsTemp; - - int elementSize = 4 * 4;//4 + 2 * 4 + 4; // 4 color bytes and 2 position floats, 1 dummy alignment float - - CLBuffer colorsMem; - - Random random = new Random(System.nanoTime()); - JavaCLSettingsPanel settings = new JavaCLSettingsPanel(); - - public ParticlesDemo() { - - ParticlesCountItem[] items = new ParticlesCountItem[] { - new ParticlesCountItem(1024, "1K"), - new ParticlesCountItem(1024 * 10,"10K"), - new ParticlesCountItem(1024 * 100,"100K"), - new ParticlesCountItem(1024 * 1000,"1M"), - new ParticlesCountItem(1024 * 10000,"10M") - }; - JComboBox cb = new JComboBox(items); - cb.setSelectedIndex(2); - JLabel lb = new JLabel("Number of particles"); - Box countPanel = Box.createHorizontalBox(); - SetupUtils.setEtchedTitledBorder(countPanel, "Particles Demo Settings"); - countPanel.add(lb); - countPanel.add(Box.createHorizontalStrut(5)); - countPanel.add(cb); - cb.setMinimumSize(new Dimension(100, 10)); - cb.setMaximumSize(new Dimension(200, Integer.MAX_VALUE)); - countPanel.add(Box.createHorizontalGlue()); - - - //sett.removeOpenGLComponents(); - - final JPanel opts = new JPanel(new BorderLayout()); - JLabel detailsLab = new JLabel("Advanced OpenCL settings...", JLabel.RIGHT); - detailsLab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - opts.add("Center", detailsLab); - detailsLab.addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent e) { - opts.removeAll(); - opts.add("Center", settings); - opts.invalidate(); - Component c = opts.getParent(); - while (c != null) { - if (c instanceof Frame) { - ((Frame)c).pack(); - break; - } - if (c instanceof JDialog) { - ((JDialog)c).pack(); - break; - } - c = c.getParent(); - } - } - - }); - - int opt = JOptionPane.showConfirmDialog(null, new Object[] { countPanel, opts }, "JavaCL Particles Demo", JOptionPane.OK_CANCEL_OPTION); - if (opt != JOptionPane.OK_OPTION) - System.exit(0); - - useOpenGLContext = settings.isGLSharingEnabled(); - particlesCount = ((ParticlesCountItem)cb.getSelectedItem()).count; - } - - int[] blends = new int[] { - GL_ONE_MINUS_SRC_ALPHA, - GL_ONE, - GL_ONE_MINUS_DST_ALPHA, - GL_ONE_MINUS_DST_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_SRC_ALPHA, - GL_DST_ALPHA, - GL_SRC_COLOR, - GL_DST_COLOR, - }; - volatile int iBlend = 0; - - public static void exception(Throwable ex) { - StringWriter sout = new StringWriter(); - ex.printStackTrace(new PrintWriter(sout)); - JOptionPane.showMessageDialog(null, sout.toString(), "[Error] " + ParticlesDemo.class.getSimpleName() + " JavaCL Demo", JOptionPane.ERROR_MESSAGE); - } - @Override - public void init(GLAutoDrawable glad) { - try { - GL2 gl = (GL2)glad.getGL(); - gl.glClearColor(0, 0, 0, 1); - gl.glClear(GL_COLOR_BUFFER_BIT); - //gl.glViewport(0, 0, (int)width, (int)height); - gl.glEnable(GL_BLEND); - gl.glEnable(GL2.GL_POINT_SMOOTH); - - try { - if (useOpenGLContext) { - context = JavaCL.createContextFromCurrentGL(); - } - } catch (Exception ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, "Sharing of context between OpenCL and OpenGL failed.\n" + - "The demo will run fine without anyway.", "JavaCL Demo", JOptionPane.OK_OPTION); - } - if (context == null) { - useOpenGLContext = false; - CLDevice device = settings.getDevice(); - if (device == null) - device = JavaCL.getBestDevice(); - context = JavaCL.createContext(null, device); - } - queue = context.createDefaultQueue(); - - Pointer masses = allocateFloats(particlesCount).order(context.getByteOrder()); - velocities = allocateFloats(2 * particlesCount).order(context.getByteOrder()); - interleavedColorAndPositionsTemp = allocateBytes(elementSize * particlesCount).order(context.getByteOrder()); - - Pointer positionsView = interleavedColorAndPositionsTemp.as(Float.class); - for (int i = 0; i < particlesCount; i++) { - masses.set(i, 0.5f + 0.5f * random.nextFloat()); - - velocities.set(i * 2, (random.nextFloat() - 0.5f) * 0.2f); - velocities.set(i * 2 + 1, (random.nextFloat() - 0.5f) * 0.2f); - - int colorOffset = i * elementSize; - int posOffset = i * (elementSize / 4) + 1; - - byte r = (byte)128, g = r, b = r, a = r; - interleavedColorAndPositionsTemp.set(colorOffset++, r); - interleavedColorAndPositionsTemp.set(colorOffset++, g); - interleavedColorAndPositionsTemp.set(colorOffset++, b); - interleavedColorAndPositionsTemp.set(colorOffset, a); - - float x = (random.nextFloat() - 0.5f) * 200, - y = (random.nextFloat() - 0.5f) * 200; - - positionsView.set(posOffset, (float)x); - positionsView.set(posOffset + 1, y); - - } - velocitiesMem = context.createBuffer(Usage.InputOutput, velocities, false); - massesMem = context.createBuffer(Usage.Input, masses, true); - - gl.glGenBuffers(1, vbo, 0); - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - gl.glBufferData(GL_ARRAY_BUFFER, (int) interleavedColorAndPositionsTemp.getValidBytes(), interleavedColorAndPositionsTemp.getByteBuffer(), GL2.GL_DYNAMIC_COPY); - gl.glBindBuffer(GL_ARRAY_BUFFER, 0); - - if (useOpenGLContext) { - interleavedColorAndPositionsMem = context.createBufferFromGLBuffer(Usage.InputOutput, vbo[0]); - } else - interleavedColorAndPositionsMem = context.createBuffer(Usage.InputOutput, interleavedColorAndPositionsTemp, false); - - String hsv2rgbSrc = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("HSVtoRGB.c")); - //String src = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("ParticlesDemo.c")); - CLProgram program = context.createProgram(hsv2rgbSrc); - particlesProgram = new ParticlesDemoProgram(program); - //updateParticleKernel = program.build().createKernel("updateParticle"); - - updateKernelArgs(); - - gl.glPointSize(2f); - - } catch (Exception ex) { - Logger.getLogger(ParticlesDemo.class.getName()).log(Level.SEVERE, null, ex); - ex.printStackTrace(); - exception(ex); - System.exit(1); - } - } - - @Override - public void dispose(GLAutoDrawable glad) { - - } - - @Override - public void display(GLAutoDrawable glad) { - - GL2 gl = (GL2)glad.getGL(); - - gl.glBlendFunc(GL_SRC_ALPHA, blends[iBlend]); - - gl.glMatrixMode(GL2.GL_PROJECTION); - gl.glLoadIdentity(); - new GLU().gluOrtho2D(-width / 2 - 1, width / 2 + 1, -height/2 - 1, height/2 + 1); - gl.glMatrixMode(GL2.GL_MODELVIEW); - - gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); - - if (useOpenGLContext) { - queue.finish(); - } else { - //interleavedColorAndPositionsMem.map(queue, CLMem.MapFlags.Read); - interleavedColorAndPositionsMem.read(queue, interleavedColorAndPositionsTemp, true); - gl.glBufferSubData(GL_ARRAY_BUFFER, 0, (int)interleavedColorAndPositionsTemp.getValidBytes(), interleavedColorAndPositionsTemp.getByteBuffer()); - //interleavedColorAndPositionsMem.unmap(queue, interleavedColorAndPositionsTemp); - } - - gl.glClear(GL_COLOR_BUFFER_BIT); - - gl.glColor3f(1.0f, 1.0f, 1.0f); - //gl.glEnableClientState(GL_VERTEX_ARRAY); - //gl.glEnableClientState(GL_COLOR_ARRAY); - - //gl.glColorPointer(4, GL_UNSIGNED_BYTE, elementSize, - gl.glInterleavedArrays(GL2.GL_C4UB_V2F, elementSize, 0); - - gl.glDrawArrays(GL_POINTS, 0, particlesCount); - gl.glBindBuffer(GL_ARRAY_BUFFER, 0); - - if (!paused) - updateKernelArgs(); - } - - @Override - public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) { - this.width = width; - this.height = height; - - } - - private synchronized void updateKernelArgs() { - if (useOpenGLContext) - interleavedColorAndPositionsMem.acquireGLObject(queue); - - try { - CLEvent evt = particlesProgram.updateParticle( - queue, - massesMem, - velocitiesMem, - interleavedColorAndPositionsMem.as(Float.class), - new float[] {mouseX - width / 2f, height / 2f - mouseY}, - new float[] {width, height}, - massFactor, - speedFactor, - slowDownFactor, - hasMouse ? mouseWeight : 0, - (byte)(limitToScreen ? 1 : 0), - new int[] { particlesCount }, null - ); - evt.release(); // the gc might be to slow to reclaim the event, so do manual memory management here - - } catch (Throwable ex) { - exception(ex); - System.exit(1); - } - - if (useOpenGLContext) - interleavedColorAndPositionsMem.releaseGLObject(queue); - } -} diff --git a/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c b/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c deleted file mode 100644 index 3e2384d3f..000000000 --- a/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/HSVtoRGB.c +++ /dev/null @@ -1,55 +0,0 @@ - -// Copied from http://www.cs.rit.edu/~ncs/color/t_convert.html - -uchar4 HSVAtoRGBA(float4 hsva) -{ - float h = hsva.x, s = hsva.y, v = hsva.z, a = hsva.w; - float r, g, b; - - int i; - float f, p, q, t; - if (s == 0) { - // achromatic (grey) - r = g = b = v; - return (uchar4)(r * 255, g * 255, b * 255, a * 255); - } - h /= 60; // sector 0 to 5 - i = floor( h ); - f = h - i; // factorial part of h - p = v * ( 1 - s ); - q = v * ( 1 - s * f ); - t = v * ( 1 - s * ( 1 - f ) ); - switch( i ) { - case 0: - r = v; - g = t; - b = p; - break; - case 1: - r = q; - g = v; - b = p; - break; - case 2: - r = p; - g = v; - b = t; - break; - case 3: - r = p; - g = q; - b = v; - break; - case 4: - r = t; - g = p; - b = v; - break; - default: // case 5: - r = v; - g = p; - b = q; - break; - } - return (uchar4)(r * 255, g * 255, b * 255, a * 255); -} \ No newline at end of file diff --git a/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c b/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c deleted file mode 100644 index 3fc83c8cb..000000000 --- a/libraries/OpenCL/OpenGLDemos/src/main/opencl/com/nativelibs4java/opencl/demos/particles/ParticlesDemoProgram.c +++ /dev/null @@ -1,105 +0,0 @@ -/*********************************************************************** - - Copyright (c) 2008, 2009, Memo Akten, www.memo.tv - *** The Mega Super Awesome Visuals Company *** - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of MSA Visuals nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. - * - * ***********************************************************************/ - -// Ported to JavaCL/OpenCL4Java (+ added colors) by Olivier Chafik - -#define REPULSION_FORCE 4.0f -#define CENTER_FORCE2 0.0005f - -#define PI 3.141f - -//#pragma OpenCL cl_khr_byte_addressable_store : enable - -__kernel void updateParticle( - __global float* masses, - __global float2* velocities, - //__global Particle* particles, - __global float4* particles, - //__global char* pParticles, - const float2 mousePos, - const float2 dimensions, - float massFactor, - float speedFactor, - float slowDownFactor, - float mouseWeight, - char limitToScreen -) { - int id = get_global_id(0); - - float4 particle = particles[id]; - - uchar4 color = as_uchar4(particle.x); - - float2 position = particle.yz; - float2 diff = mousePos - position; - - float invDistSQ = 1.0f / dot(diff, diff); - diff *= 200.0f * invDistSQ; - - float mass = massFactor * masses[id]; - float2 velocity = velocities[id]; - velocity -= mass * position * CENTER_FORCE2 - diff * mass * mouseWeight; - position += speedFactor * velocities[id]; - - if (limitToScreen) { - float2 halfDims = dimensions / 2.0f; - position = clamp(position, -halfDims, halfDims); - } - - float dirDot = cross((float4)(diff, (float2)0), (float4)(velocity, (float2)0)).z; - float speed = length(velocity); - - float f = speed / 4 / mass; - float hue = (dirDot < 0 ? f : f + 1) / 2; - hue = clamp(hue, 0.0f, 1.0f) * 360; - - float opacity = clamp(0.1f + f, 0.0f, 1.0f); - float saturation = mass / 2; - float brightness = 0.6f + opacity * 0.3f; - - uchar4 targetColor = HSVAtoRGBA((float4)(hue, saturation, brightness, opacity)); - - float colorSpeedFactor = min(0.01f * speedFactor, 1.0f), otherColorSpeedFactor = 1 - colorSpeedFactor; - color = (uchar4)( - (uchar)(targetColor.x * colorSpeedFactor + color.x * otherColorSpeedFactor), - (uchar)(targetColor.y * colorSpeedFactor + color.y * otherColorSpeedFactor), - (uchar)(targetColor.z * colorSpeedFactor + color.z * otherColorSpeedFactor), - (uchar)(targetColor.w * colorSpeedFactor + color.w * otherColorSpeedFactor) - ); - - particle.x = as_float(color); - particle.yz = position; - - particles[id] = particle; - - velocity *= slowDownFactor; - velocities[id] = velocity; -} diff --git a/libraries/OpenCL/README.md b/libraries/OpenCL/README.md new file mode 100644 index 000000000..7d09d0aeb --- /dev/null +++ b/libraries/OpenCL/README.md @@ -0,0 +1,3 @@ +[JavaCL](http://javacl.googlecode.com) has migrated to its own repository: [ochafik/JavaCL](http://github.com/ochafik/JavaCL). + +Please [file issues there](http://github.com/ochafik/JavaCL/issues). diff --git a/libraries/OpenCL/ScalaCL.svg b/libraries/OpenCL/ScalaCL.svg deleted file mode 100644 index 5da756bf3..000000000 --- a/libraries/OpenCL/ScalaCL.svg +++ /dev/null @@ -1,235 +0,0 @@ - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - OpenCL - - - CPU - - - - GPU - - OpenCL4Java - JNA - - Java - - Scala - ScalaCL - - diff --git a/libraries/OpenCL/Tutorials/.gitignore b/libraries/OpenCL/Tutorials/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Tutorials/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Tutorials/DFT/.gitignore b/libraries/OpenCL/Tutorials/DFT/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Tutorials/DFT/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Tutorials/DFT/javacl-dft-tutorial.iml b/libraries/OpenCL/Tutorials/DFT/javacl-dft-tutorial.iml deleted file mode 100644 index 3fbd5899a..000000000 --- a/libraries/OpenCL/Tutorials/DFT/javacl-dft-tutorial.iml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Tutorials/DFT/pom.xml b/libraries/OpenCL/Tutorials/DFT/pom.xml deleted file mode 100644 index 2a5d03526..000000000 --- a/libraries/OpenCL/Tutorials/DFT/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-dft-tutorial - JavaCL Tutorial - http://code.google.com/p/javacl/ - jar - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - ../.. - - - - - com.nativelibs4java - javacl - - - org.apache.commons - commons-math - 2.2 - - - org.scala-lang - scala-library - - - - - - - com.nativelibs4java - maven-javacl-plugin - - - org.scala-tools - maven-scala-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - org.scala-tools - maven-scala-plugin - - - - - - - - diff --git a/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT.java b/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT.java deleted file mode 100644 index cddafe1e4..000000000 --- a/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT.java +++ /dev/null @@ -1,101 +0,0 @@ -package tutorial; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLPlatform.DeviceFeature; -import com.nativelibs4java.util.*; -import java.io.IOException; -import java.nio.DoubleBuffer; -import org.bridj.Pointer; - -public class DFT { - - final CLQueue queue; - final CLContext context; - final CLProgram program; - final CLKernel kernel; - - public DFT(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - this.context = queue.getContext(); - - String source = IOUtils.readText(DFT.class.getResource("DiscreteFourierTransformProgram.cl")); - program = context.createProgram(source); - kernel = program.createKernel("dft"); - } - - /** - * Method that takes complex values in input (sequence of pairs of real and imaginary values) and - * returns the Discrete Fourier Transform of these values if forward == true or the inverse - * transform if forward == false. - */ - public synchronized Pointer dft(Pointer in, boolean forward) { - assert in.getValidElements() % 2 == 0; - int length = (int)in.getValidElements() / 2; - - // Create an input CLBuffer that will be a copy of the NIO buffer : - CLBuffer inBuf = context.createDoubleBuffer(CLMem.Usage.Input, in, true); // true = copy - - // Create an output CLBuffer : - CLBuffer outBuf = context.createDoubleBuffer(CLMem.Usage.Output, length * 2); - - // Set the args of the kernel : - kernel.setArgs(inBuf, outBuf, length, forward ? 1 : -1); - - // Ask for `length` parallel executions of the kernel in 1 dimension : - CLEvent dftEvt = kernel.enqueueNDRange(queue, new int[]{ length }); - - // Return an NIO buffer read from the output CLBuffer : - return outBuf.read(queue, dftEvt); - } - - /// Wrapper method that takes and returns double arrays - public double[] dft(double[] complexValues, boolean forward) { - Pointer outBuffer = dft(Pointer.pointerToDoubles(complexValues), forward); - return outBuffer.getDoubles(); - } - - public static void main(String[] args) throws IOException, CLBuildException { - // Create a context with the best double numbers support possible : - // (try using DeviceFeature.GPU, DeviceFeature.CPU...) - CLContext context = JavaCL.createBestContext(DeviceFeature.DoubleSupport); - - // Create a command queue, if possible able to execute multiple jobs in parallel - // (out-of-order queues will still respect the CLEvent chaining) - CLQueue queue = context.createDefaultOutOfOrderQueueIfPossible(); - - DFT dft = new DFT(queue); - //DFT2 dft = new DFT2(queue); - - // Create some fake test data : - double[] in = createTestDoubleData(); - - // Transform the data (spatial -> frequency transform) : - double[] transformed = dft.dft(in, true); - - for (int i = 0; i < transformed.length / 2; i++) { - // Print the transformed complex values (real + i * imaginary) - System.out.println(transformed[i * 2] + "\t + \ti * " + transformed[i * 2 + 1]); - } - - // Reverse-transform the transformed data (frequency -> spatial transform) : - double[] backTransformed = dft.dft(transformed, false); - - // Check the transform + inverse transform give the original data back : - double precision = 1e-5; - for (int i = 0; i < in.length; i++) { - if (Math.abs(in[i] - backTransformed[i]) > precision) - throw new RuntimeException("Different values in back-transformed array than in original array !"); - } - } - - static double[] createTestDoubleData() { - int n = 32; - double[] in = new double[2 * n]; - - for (int i = 0; i < n; i++) { - in[i * 2] = 1 / (double) (i + 1); - in[i * 2 + 1] = 0; - } - return in; - } -} diff --git a/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT2.java b/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT2.java deleted file mode 100644 index 5b617d659..000000000 --- a/libraries/OpenCL/Tutorials/DFT/src/main/java/tutorial/DFT2.java +++ /dev/null @@ -1,37 +0,0 @@ -package tutorial; - -import com.nativelibs4java.opencl.*; -import java.io.IOException; -import java.nio.DoubleBuffer; -import org.bridj.Pointer; - -public class DFT2 { - - final CLQueue queue; - final CLContext context; - final DiscreteFourierTransformProgram program; - - public DFT2(CLQueue queue) throws IOException, CLBuildException { - this.queue = queue; - this.context = queue.getContext(); - this.program = new DiscreteFourierTransformProgram(context); - } - - public synchronized Pointer dft(Pointer in, boolean forward) throws CLBuildException { - assert in.getValidElements() % 2 == 0; - int length = (int)in.getValidElements() / 2; - - CLBuffer inBuf = context.createDoubleBuffer(CLMem.Usage.Input, in, true); // true = copy - CLBuffer outBuf = context.createDoubleBuffer(CLMem.Usage.Output, length * 2); - - // The following call is type-safe, thanks to the JavaCL Maven generator : - // (if the OpenCL function signature changes, the generated Java definition will be updated and compilation will fail) - CLEvent dftEvt = program.dft(queue, inBuf, outBuf, length, forward ? 1 : -1, new int[]{length}, null); - return outBuf.read(queue, dftEvt); - } - - public double[] dft(double[] complexValues, boolean forward) throws CLBuildException { - Pointer outBuffer = dft(Pointer.pointerToDoubles(complexValues), forward); - return outBuffer.getDoubles(); - } - } diff --git a/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c b/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c deleted file mode 100644 index 3b6a472df..000000000 --- a/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.c +++ /dev/null @@ -1,33 +0,0 @@ -void dft( - const double *in, // complex values input (packed real and imaginary) - double *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - for (int i = 0; i < length; i++) - { - // Initialize sum and inner arguments - double totReal = 0, totImag = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double valueReal = in[k * 2], valueImag = in[k * 2 + 1]; - double arg = k * param; - double c = cos(arg), sin(arg); - - totReal += valueReal * c - valueImag * s; - totImag += valueReal * s + valueImag * c; - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i * 2] = totReal; - out[i * 2 + 1] = totImag; - } else { - // backward transform (frequential -> space) - out[i * 2] = totReal / (double)length; - out[i * 2 + 1] = totImag / (double)length; - } - } -} diff --git a/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl b/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl deleted file mode 100644 index 265ebc419..000000000 --- a/libraries/OpenCL/Tutorials/DFT/src/main/opencl/tutorial/DiscreteFourierTransformProgram.cl +++ /dev/null @@ -1,44 +0,0 @@ -// Enable double-precision floating point numbers support. -// Not all platforms / devices support this, so you may have to switch to floats. -#pragma OPENCL EXTENSION cl_khr_fp64 : enable - -__kernel void dft( - __global const double2 *in, // complex values input - __global double2 *out, // complex values output - int length, // number of input and output values - int sign) // sign modifier in the exponential : - // 1 for forward transform, -1 for backward. -{ - // Get the varying parameter of the parallel execution : - int i = get_global_id(0); - - // In case we're executed "too much", check bounds : - if (i >= length) - return; - - // Initialize sum and inner arguments - double2 tot = 0; - double param = (-2 * sign * i) * M_PI / (double)length; - - for (int k = 0; k < length; k++) { - double2 value = in[k]; - - // Compute sin and cos in a single call : - double c; - double s = sincos(k * param, &c); - - // This adds (value.x * c - value.y * s, value.x * s + value.y * c) to the sum : - tot += (double2)( - dot(value, (double2)(c, -s)), - dot(value, (double2)(s, c)) - ); - } - - if (sign == 1) { - // forward transform (space -> frequential) - out[i] = tot; - } else { - // backward transform (frequential -> space) - out[i] = tot / (double)length; - } -} diff --git a/libraries/OpenCL/Tutorials/Simple/.gitignore b/libraries/OpenCL/Tutorials/Simple/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Tutorials/Simple/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Tutorials/Simple/javacl-simple-tutorial.iml b/libraries/OpenCL/Tutorials/Simple/javacl-simple-tutorial.iml deleted file mode 100644 index c51ad6a81..000000000 --- a/libraries/OpenCL/Tutorials/Simple/javacl-simple-tutorial.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Tutorials/Simple/pom.xml b/libraries/OpenCL/Tutorials/Simple/pom.xml deleted file mode 100644 index ccbacbce0..000000000 --- a/libraries/OpenCL/Tutorials/Simple/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - 4.0.0 - com.nativelibs4java - javacl-simple-tutorial - jar - JavaCL Simple Tutorial Archetype - - - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - ../.. - - - diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/META-INF/maven/archetype-metadata.xml b/libraries/OpenCL/Tutorials/Simple/src/main/resources/META-INF/maven/archetype-metadata.xml deleted file mode 100644 index 17ff875b1..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/META-INF/maven/archetype-metadata.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - JavaCLTutorial - - - - com.mycompany - - - - com.mycompany - - - - - - - - src/main/java - - **/*.java - - - - - src/main/opencl - - **/*.cl - - - - - diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/.gitignore b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/pom.xml b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/pom.xml deleted file mode 100644 index ca7ddbd9a..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - JavaCL Tutorial - ${groupId} - ${artifactId} - ${version} - jar - - - - sonatype - Sonatype OSS Snapshots Repository - http://oss.sonatype.org/content/groups/public - - - - - - sonatype - Sonatype OSS Snapshots Repository - http://oss.sonatype.org/content/groups/public - - - - - - com.nativelibs4java - javacl - 1.0-SNAPSHOT - - - - - - - - com.nativelibs4java - maven-javacl-plugin - 1.0-SNAPSHOT - - - - compile - - - - - - - diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial1.java b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial1.java deleted file mode 100644 index ae5887695..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial1.java +++ /dev/null @@ -1,54 +0,0 @@ -package ${package}; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.util.*; -import com.nativelibs4java.util.*; -import org.bridj.Pointer; -import java.nio.ByteOrder; -import static org.bridj.Pointer.*; -import static java.lang.Math.*; -import java.io.IOException; - -public class JavaCLTutorial1 { - public static void main(String[] args) throws IOException { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - ByteOrder byteOrder = context.getByteOrder(); - - int n = 1024; - Pointer - aPtr = allocateFloats(n).order(byteOrder), - bPtr = allocateFloats(n).order(byteOrder); - - for (int i = 0; i < n; i++) { - aPtr.set(i, (float)cos(i)); - bPtr.set(i, (float)sin(i)); - } - - // Create OpenCL input buffers (using the native memory pointers aPtr and bPtr) : - CLBuffer - a = context.createFloatBuffer(Usage.Input, aPtr), - b = context.createFloatBuffer(Usage.Input, bPtr); - - // Create an OpenCL output buffer : - CLBuffer out = context.createFloatBuffer(Usage.Output, n); - - // Read the program sources and compile them : - String src = IOUtils.readText(JavaCLTutorial1.class.getResource("TutorialKernels.cl")); - CLProgram program = context.createProgram(src); - - // Get and call the kernel : - CLKernel addFloatsKernel = program.createKernel("add_floats"); - addFloatsKernel.setArgs(a, b, out, n); - int[] globalSizes = new int[] { n }; - CLEvent addEvt = addFloatsKernel.enqueueNDRange(queue, globalSizes); - - Pointer outPtr = out.read(queue, addEvt); // blocks until add_floats finished - - // Print the first 10 output values : - for (int i = 0; i < 10 && i < n; i++) - System.out.println("out[" + i + "] = " + outPtr.get(i)); - - } -} \ No newline at end of file diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial2.java b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial2.java deleted file mode 100644 index 18467f2a3..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial2.java +++ /dev/null @@ -1,48 +0,0 @@ -package ${package}; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.util.*; -import com.nativelibs4java.util.*; -import org.bridj.Pointer; -import java.nio.ByteOrder; -import static org.bridj.Pointer.*; -import static java.lang.Math.*; -import java.io.IOException; - -public class JavaCLTutorial2 { - public static void main(String[] args) throws IOException { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - ByteOrder byteOrder = context.getByteOrder(); - - int n = 1024; - Pointer - aPtr = allocateFloats(n).order(byteOrder), - bPtr = allocateFloats(n).order(byteOrder); - - for (int i = 0; i < n; i++) { - aPtr.set(i, (float)cos(i)); - bPtr.set(i, (float)sin(i)); - } - - // Create OpenCL input buffers (using the native memory pointers aPtr and bPtr) : - CLBuffer - a = context.createFloatBuffer(Usage.Input, aPtr), - b = context.createFloatBuffer(Usage.Input, bPtr); - - // Create an OpenCL output buffer : - CLBuffer out = context.createFloatBuffer(Usage.Output, n); - - TutorialKernels kernels = new TutorialKernels(context); - int[] globalSizes = new int[] { n }; - CLEvent addEvt = kernels.add_floats(queue, a, b, out, n, globalSizes, null); - - Pointer outPtr = out.read(queue, addEvt); // blocks until add_floats finished - - // Print the first 10 output values : - for (int i = 0; i < 10 && i < n; i++) - System.out.println("out[" + i + "] = " + outPtr.get(i)); - - } -} diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial3.java b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial3.java deleted file mode 100644 index c5d277767..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/java/JavaCLTutorial3.java +++ /dev/null @@ -1,37 +0,0 @@ -package ${package}; - -import com.nativelibs4java.opencl.*; -import com.nativelibs4java.opencl.CLMem.Usage; -import com.nativelibs4java.opencl.util.*; -import com.nativelibs4java.util.*; -import org.bridj.Pointer; -import static org.bridj.Pointer.*; -import static java.lang.Math.*; -import java.io.IOException; - -public class JavaCLTutorial3 { - public static void main(String[] args) throws IOException { - CLContext context = JavaCL.createBestContext(); - CLQueue queue = context.createDefaultQueue(); - - int n = 1024; - - // Create OpenCL input and output buffers - CLBuffer - a = context.createFloatBuffer(Usage.InputOutput, n), // a and b and read AND written to - b = context.createFloatBuffer(Usage.InputOutput, n), - out = context.createFloatBuffer(Usage.Output, n); - - TutorialKernels kernels = new TutorialKernels(context); - int[] globalSizes = new int[] { n }; - CLEvent fillEvt = kernels.fill_in_values(queue, a, b, n, globalSizes, null); - CLEvent addEvt = kernels.add_floats(queue, a, b, out, n, globalSizes, null, fillEvt); - - Pointer outPtr = out.read(queue, addEvt); // blocks until add_floats finished - - // Print the first 10 output values : - for (int i = 0; i < 10 && i < n; i++) - System.out.println("out[" + i + "] = " + outPtr.get(i)); - - } -} diff --git a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/opencl/TutorialKernels.cl b/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/opencl/TutorialKernels.cl deleted file mode 100644 index d3ac14a1a..000000000 --- a/libraries/OpenCL/Tutorials/Simple/src/main/resources/archetype-resources/src/main/opencl/TutorialKernels.cl +++ /dev/null @@ -1,18 +0,0 @@ -__kernel void add_floats(__global const float* a, __global const float* b, __global float* out, int n) -{ - int i = get_global_id(0); - if (i >= n) - return; - - out[i] = a[i] + b[i]; -} - -__kernel void fill_in_values(__global float* a, __global float* b, int n) -{ - int i = get_global_id(0); - if (i >= n) - return; - - a[i] = cos((float)i); - b[i] = sin((float)i); -} \ No newline at end of file diff --git a/libraries/OpenCL/Tutorials/javacl-tutorials-root.iml b/libraries/OpenCL/Tutorials/javacl-tutorials-root.iml deleted file mode 100644 index d4bc3aaf0..000000000 --- a/libraries/OpenCL/Tutorials/javacl-tutorials-root.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/Tutorials/pom.xml b/libraries/OpenCL/Tutorials/pom.xml deleted file mode 100644 index 26693e897..000000000 --- a/libraries/OpenCL/Tutorials/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-tutorials-root - pom - JavaCL Tutorials Root / BridJ - - - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - .. - - - - DFT - Simple - - diff --git a/libraries/OpenCL/getJOGL b/libraries/OpenCL/getJOGL deleted file mode 100644 index 013c92d8a..000000000 --- a/libraries/OpenCL/getJOGL +++ /dev/null @@ -1,37 +0,0 @@ - -BASE_URL="http://jogamp.org/deployment/webstart" -OS_NAMES="macosx-universal linux-i586 linux-amd64 windows-i586 windows-amd64" - -mkdir jogl -cd jogl - -for OS_NAME in $OS_NAMES ; do - mkdir $OS_NAME - cd $OS_NAME - - for N in gluegen-rt jogl.all nativewindow.all ; do - wget $BASE_URL/$N.jar.gz - gzip -d $N.jar.gz ; - done - - for N in gluegen-rt jogl nativewindow ; do - wget $BASE_URL/$N-natives-$OS_NAME.jar - unzip $N-natives-$OS_NAME.jar - rm $N-natives-$OS_NAME.jar - rm -fR META-INF ; - done - - zip ../jogl-$OS_NAME.zip * - - cd .. - rm -fR $OS_NAME - - cp jogl-$OS_NAME.zip jogl-$OS_NAME-`date '+%Y%m%d'`.zip - mv jogl-$OS_NAME.zip jogl-$OS_NAME-latest.zip ; -done - -for OS_NAME in $OS_NAMES ; do - echo "Platform $OS_NAME :" - unzip -l jogl-$OS_NAME-latest.zip - echo "" ; -done diff --git a/libraries/OpenCL/opencl4java-root-bridj.iml b/libraries/OpenCL/opencl4java-root-bridj.iml deleted file mode 100644 index 467882a00..000000000 --- a/libraries/OpenCL/opencl4java-root-bridj.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/opencl4java-root.iml b/libraries/OpenCL/opencl4java-root.iml deleted file mode 100644 index d4bc3aaf0..000000000 --- a/libraries/OpenCL/opencl4java-root.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/libraries/OpenCL/pom.xml b/libraries/OpenCL/pom.xml deleted file mode 100644 index cad329938..000000000 --- a/libraries/OpenCL/pom.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - javacl-parent - 1.0-SNAPSHOT - pom - JavaCL Parent Project - 2009 - http://code.google.com/p/nativelibs4java/wiki/OpenCL - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - LibCL - InteractiveImageDemo - Generator - MavenPlugin - OpenCL4Java - Demos - JavaCL - JavaCL-Shaded - JavaCL-OSGi - Core - Blas - OpenGLDemos - Tutorials - - - - - - com.nativelibs4java - opencl4java - ${project.version} - - - com.nativelibs4java - javacl-blas - ${project.version} - - - com.nativelibs4java - javacl-core - ${project.version} - - - com.nativelibs4java - javacl-demos - ${project.version} - - - com.nativelibs4java - javacl-numerical-benchmark - ${project.version} - - - com.nativelibs4java - javacl-generator - ${project.version} - - - com.nativelibs4java - javacl-opengl-demos - ${project.version} - - - com.nativelibs4java - javacl - ${project.version} - - - com.nativelibs4java - javacl-tutorials-root - ${project.version} - - - com.nativelibs4java - javacl-dft-tutorial - ${project.version} - - - com.nativelibs4java - javacl-simple-tutorial - ${project.version} - - - com.nativelibs4java - maven-javacl-plugin - ${project.version} - - - com.nativelibs4java - libcl - ${project.version} - - - - com.nativelibs4java - jnaerator - ${jnaerator.version} - - - - - - - - - com.nativelibs4java - maven-javacl-plugin - ${project.version} - - - - compile - - - - - - - - - - diff --git a/libraries/OpenCL/runComp b/libraries/OpenCL/runComp deleted file mode 100644 index 4c0c47482..000000000 --- a/libraries/OpenCL/runComp +++ /dev/null @@ -1,2 +0,0 @@ -cd target/classes -scala -classpath ~/.m2/repository/com/jnaerator/jnaerator-runtime/0.9.2-SNAPSHOT/jnaerator-runtime-0.9.2-SNAPSHOT.jar:. scalacl.ScalaCLTestRun diff --git a/libraries/OpenCL/runComp.cmd b/libraries/OpenCL/runComp.cmd deleted file mode 100644 index f1022354d..000000000 --- a/libraries/OpenCL/runComp.cmd +++ /dev/null @@ -1,9 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -set M2REPO=\Users\Olivier\.m2\repository -pushd . -cd target\classes -scala -classpath %M2REPO%\com\jnaerator\jnaerator-runtime\0.9.3-SNAPSHOT\jnaerator-runtime-0.9.3-SNAPSHOT.jar;. scalacl.ScalaCLTestRun - -popd diff --git a/libraries/PThread/pom.xml b/libraries/PThread/pom.xml index f2faa501b..4707e745b 100644 --- a/libraries/PThread/pom.xml +++ b/libraries/PThread/pom.xml @@ -7,15 +7,15 @@ PThread4Java Java bindings for the Unix pthread library http://code.google.com/p/nativelibs4java/wiki - 0.2-SNAPSHOT + 0.2 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT - .. + 1.9 + ../.. @@ -28,20 +28,23 @@ - - - - - com.nativelibs4java - maven-jnaerator-plugin - ${jnaerator.version} - - src/main/java - - - - - + + + regenerate + + + + com.nativelibs4java + maven-jnaerator-plugin + ${jnaerator.version} + + src/main/java + + + + + + diff --git a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/PthreadLibrary.java b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/PthreadLibrary.java index e42ebec67..b17fdfb67 100644 --- a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/PthreadLibrary.java +++ b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/PthreadLibrary.java @@ -6,6 +6,7 @@ import org.bridj.SizeT; import org.bridj.TypedPointer; import org.bridj.ann.Library; +import org.bridj.ann.Name; import org.bridj.ann.Ptr; import org.bridj.ann.Runtime; import org.bridj.util.DefaultParameterizedType; @@ -21,28 +22,28 @@ public class PthreadLibrary { static { BridJ.register(); } - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_PROCESS_SHARED = (int)1; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_4_0 = (int)40000; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_MUTEX_RECURSIVE = (int)2; - /// native declaration : /usr/include/_types.h - public static final int __DARWIN_WCHAR_MAX = (int)2147483647; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/_types.h */ + public static final int __DARWIN_WCHAR_MAX = (int)0x7fffffff; + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_4_3 = (int)40300; - /// native declaration : /usr/include/pthread_impl.h + /** native declaration : /usr/include/pthread_impl.h */ public static final int SCHED_RR = (int)2; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_4_1 = (int)40100; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_4_2 = (int)40200; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_SCOPE_SYSTEM = (int)1; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_MUTEX_ERRORCHECK = (int)1; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_ONCE_SIG_init = (int)816954554; + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_ONCE_SIG_init = (int)0x30B1BCBA; /** * define
      * Conversion Error : { 0x30B1BCBA, { 0 } }
      @@ -50,43 +51,45 @@ public class PthreadLibrary { * native declaration : /usr/include/pthread.h:0
      * { 0x30B1BCBA, { 0 } } */ - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_NA = (int)9999; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_PRIO_INHERIT = (int)1; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_PROCESS_PRIVATE = (int)2; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_FIRSTFIT_MUTEX_SIG_init = (int)850045859; - /// native declaration : /usr/include/pthread_impl.h + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_FIRSTFIT_MUTEX_SIG_init = (int)0x32AAABA3; + /** native declaration : /usr/include/pthread_impl.h */ public static final int __SCHED_PARAM_SIZE__ = (int)4; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_3 = (int)1030; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_RECURSIVE_MUTEX_SIG_init = (int)850045858; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_RECURSIVE_MUTEX_SIG_init = (int)0x32AAABA2; + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_2 = (int)1020; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_1 = (int)1010; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_0 = (int)1000; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_7 = (int)1070; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_INHERIT_SCHED = (int)1; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_6 = (int)1060; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_5 = (int)1050; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __MAC_10_4 = (int)1040; - /// native declaration : /usr/include/_types.h + /** native declaration : /usr/include/_types.h */ public static final int _FORTIFY_SOURCE = (int)2; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/Availability.h */ + public static final int __MAC_10_8 = (int)1080; + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_MUTEX_NORMAL = (int)0; - /// native declaration : /usr/include/time.h + /** native declaration : /usr/include/time.h */ public static final int CLOCKS_PER_SEC = (int)1000000; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final Pointer PTHREAD_CANCELED = (Pointer)(Pointer.pointerToAddress(1)); /** * define
      @@ -95,44 +98,48 @@ public class PthreadLibrary { * native declaration : /usr/include/pthread.h:0
      * { 0x3CB0B1BB, { 0 } } */ - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_MUTEX_DEFAULT = (int)0; - /// native declaration : /usr/include/pthread.h - public static final int PTHREAD_CANCEL_DISABLE = (int)0; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ + public static final int PTHREAD_CANCEL_DISABLE = (int)0x00; + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_PRIO_PROTECT = (int)2; - /// native declaration : /usr/include/pthread.h - public static final int PTHREAD_CANCEL_ENABLE = (int)1; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/pthread.h */ + public static final int PTHREAD_CANCEL_ENABLE = (int)0x01; + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_NA = (int)99999; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_EXPLICIT_SCHED = (int)2; - /// native declaration : /usr/include/pthread.h - public static final int PTHREAD_CANCEL_ASYNCHRONOUS = (int)0; - /// native declaration : /usr/include/time.h + /** native declaration : /usr/include/pthread.h */ + public static final int PTHREAD_CANCEL_ASYNCHRONOUS = (int)0x00; + /** native declaration : /usr/include/time.h */ public static final int NULL = (int)0; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_SCOPE_PROCESS = (int)2; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_CREATE_JOINABLE = (int)1; - /// native declaration : /usr/include/_types.h - public static final int __DARWIN_WCHAR_MIN = (int)(-2147483647 - 1); - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/_types.h */ + public static final int __DARWIN_WCHAR_MIN = (int)(0x7fffffff - 1); + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_2_0 = (int)20000; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_2_1 = (int)20100; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_2_2 = (int)20200; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_COND_SIG_init = (int)1018212795; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_COND_SIG_init = (int)0x3CB0B1BB; + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_PRIO_NONE = (int)0; - /// native declaration : /usr/include/pthread.h + /** native declaration : /usr/include/pthread.h */ public static final int PTHREAD_CREATE_DETACHED = (int)2; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_RWLOCK_SIG_init = (int)766030772; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_ERRORCHECK_MUTEX_SIG_init = (int)850045857; + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_RWLOCK_SIG_init = (int)0x2DA8B3B4; + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_ERRORCHECK_MUTEX_SIG_init = (int)0x32AAABA1; + /** native declaration : /usr/include/Availability.h */ + public static final int __IPHONE_5_1 = (int)50100; + /** native declaration : /usr/include/Availability.h */ + public static final int __IPHONE_5_0 = (int)50000; /** * define
      * Conversion Error : { 0x2DA8B3B4, { 0 } }
      @@ -140,8 +147,8 @@ public class PthreadLibrary { * native declaration : /usr/include/pthread.h:0
      * { 0x2DA8B3B4, { 0 } } */ - /// native declaration : /usr/include/pthread.h - public static final int PTHREAD_CANCEL_DEFERRED = (int)2; + /** native declaration : /usr/include/pthread.h */ + public static final int PTHREAD_CANCEL_DEFERRED = (int)0x02; /** * define
      * Conversion Error : { 0x32AAABA7, { 0 } }
      @@ -149,11 +156,11 @@ public class PthreadLibrary { * native declaration : /usr/include/pthread.h:0
      * { 0x32AAABA7, { 0 } } */ - /// native declaration : /usr/include/pthread_impl.h + /** native declaration : /usr/include/pthread_impl.h */ public static final int SCHED_OTHER = (int)1; - /// native declaration : /usr/include/pthread_impl.h - public static final int _PTHREAD_MUTEX_SIG_init = (int)850045863; - /// native declaration : /usr/include/pthread_impl.h + /** native declaration : /usr/include/pthread_impl.h */ + public static final int _PTHREAD_MUTEX_SIG_init = (int)0x32AAABA7; + /** native declaration : /usr/include/pthread_impl.h */ public static final int SCHED_FIFO = (int)4; /** * define
      @@ -169,46 +176,50 @@ public class PthreadLibrary { * native declaration : /usr/include/pthread.h:0
      * { 0x32AAABA1, { 0 } } */ - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_3_2 = (int)30200; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_3_1 = (int)30100; - /// native declaration : /usr/include/Availability.h + /** native declaration : /usr/include/Availability.h */ public static final int __IPHONE_3_0 = (int)30000; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_atfork_arg1_callback extends Callback { public abstract void apply(); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_atfork_arg2_callback extends Callback { public abstract void apply(); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_atfork_arg3_callback extends Callback { public abstract void apply(); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_create_arg1_callback extends Callback { - public abstract Pointer apply(Pointer voidPtr1); + public final Pointer apply(Pointer voidPtr1) { + return Pointer.pointerToAddress(apply(Pointer.getPeer(voidPtr1))); + } + @Ptr + public abstract long apply(@Ptr long voidPtr1); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_key_create_arg1_callback extends Callback { - public abstract void apply(Pointer voidPtr1); + public final void apply(Pointer voidPtr1) { + apply(Pointer.getPeer(voidPtr1)); + } + public abstract void apply(@Ptr long voidPtr1); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_once_arg1_callback extends Callback { public abstract void apply(); }; - /// native declaration : /usr/include/pthread.h:0 - /// native declaration : /usr/include/pthread.h:0 + /** native declaration : /usr/include/pthread.h:0 */ public static abstract class pthread_create_suspended_np_arg1_callback extends Callback { - public abstract Pointer apply(Pointer voidPtr1); + public final Pointer apply(Pointer voidPtr1) { + return Pointer.pointerToAddress(apply(Pointer.getPeer(voidPtr1))); + } + @Ptr + public abstract long apply(@Ptr long voidPtr1); }; /** * Original signature : int sched_yield()
      @@ -229,7 +240,11 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : char* asctime(tm*)
      * native declaration : /usr/include/time.h:121 */ - public static native Pointer asctime(Pointer tmPtr1); + public static Pointer asctime(Pointer tmPtr1) { + return Pointer.pointerToAddress(asctime(Pointer.getPeer(tmPtr1)), Byte.class); + } + @Ptr + protected native static long asctime(@Ptr long tmPtr1); /** * Original signature : clock_t clock()
      * native declaration : /usr/include/time.h:122 @@ -240,7 +255,11 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : char* ctime(const time_t*)
      * native declaration : /usr/include/time.h:123 */ - public static native Pointer ctime(Pointer time_tPtr1); + public static Pointer ctime(Pointer time_tPtr1) { + return Pointer.pointerToAddress(ctime(Pointer.getPeer(time_tPtr1)), Byte.class); + } + @Ptr + protected native static long ctime(@Ptr long time_tPtr1); /** * Original signature : double difftime(time_t, time_t)
      * native declaration : /usr/include/time.h:124 @@ -250,40 +269,68 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : tm* getdate(const char*)
      * native declaration : /usr/include/time.h:125 */ - public static native Pointer getdate(Pointer charPtr1); + public static Pointer getdate(Pointer charPtr1) { + return Pointer.pointerToAddress(getdate(Pointer.getPeer(charPtr1)), tm.class); + } + @Ptr + protected native static long getdate(@Ptr long charPtr1); /** * Original signature : tm* gmtime(const time_t*)
      * native declaration : /usr/include/time.h:126 */ - public static native Pointer gmtime(Pointer time_tPtr1); + public static Pointer gmtime(Pointer time_tPtr1) { + return Pointer.pointerToAddress(gmtime(Pointer.getPeer(time_tPtr1)), tm.class); + } + @Ptr + protected native static long gmtime(@Ptr long time_tPtr1); /** * Original signature : tm* localtime(const time_t*)
      * native declaration : /usr/include/time.h:127 */ - public static native Pointer localtime(Pointer time_tPtr1); + public static Pointer localtime(Pointer time_tPtr1) { + return Pointer.pointerToAddress(localtime(Pointer.getPeer(time_tPtr1)), tm.class); + } + @Ptr + protected native static long localtime(@Ptr long time_tPtr1); /** * Original signature : time_t mktime(tm*)
      * native declaration : /usr/include/time.h:128 */ @Ptr - public static native long mktime(Pointer tmPtr1); + public static long mktime(Pointer tmPtr1) { + return mktime(Pointer.getPeer(tmPtr1)); + } + @Ptr + protected native static long mktime(@Ptr long tmPtr1); /** * Original signature : size_t strftime(char*, size_t, const char*, tm*)
      * native declaration : /usr/include/time.h:129 */ @Ptr - public static native long strftime(Pointer charPtr1, @Ptr long size_t1, Pointer charPtr2, Pointer tmPtr1); + public static long strftime(Pointer charPtr1, @Ptr long size_t1, Pointer charPtr2, Pointer tmPtr1) { + return strftime(Pointer.getPeer(charPtr1), size_t1, Pointer.getPeer(charPtr2), Pointer.getPeer(tmPtr1)); + } + @Ptr + protected native static long strftime(@Ptr long charPtr1, @Ptr long size_t1, @Ptr long charPtr2, @Ptr long tmPtr1); /** * Original signature : char* strptime(const char*, const char*, tm*)
      * native declaration : /usr/include/time.h:130 */ - public static native Pointer strptime(Pointer charPtr1, Pointer charPtr2, Pointer tmPtr1); + public static Pointer strptime(Pointer charPtr1, Pointer charPtr2, Pointer tmPtr1) { + return Pointer.pointerToAddress(strptime(Pointer.getPeer(charPtr1), Pointer.getPeer(charPtr2), Pointer.getPeer(tmPtr1)), Byte.class); + } + @Ptr + protected native static long strptime(@Ptr long charPtr1, @Ptr long charPtr2, @Ptr long tmPtr1); /** * Original signature : time_t time(time_t*)
      * native declaration : /usr/include/time.h:131 */ @Ptr - public static native long time(Pointer time_tPtr1); + public static long time(Pointer time_tPtr1) { + return time(Pointer.getPeer(time_tPtr1)); + } + @Ptr + protected native static long time(@Ptr long time_tPtr1); /** * Original signature : void tzset()
      * native declaration : /usr/include/time.h:134 @@ -294,22 +341,38 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : char* asctime_r(tm*, char*)
      * native declaration : /usr/include/time.h:138 */ - public static native Pointer asctime_r(Pointer tmPtr1, Pointer charPtr1); + public static Pointer asctime_r(Pointer tmPtr1, Pointer charPtr1) { + return Pointer.pointerToAddress(asctime_r(Pointer.getPeer(tmPtr1), Pointer.getPeer(charPtr1)), Byte.class); + } + @Ptr + protected native static long asctime_r(@Ptr long tmPtr1, @Ptr long charPtr1); /** * Original signature : char* ctime_r(const time_t*, char*)
      * native declaration : /usr/include/time.h:139 */ - public static native Pointer ctime_r(Pointer time_tPtr1, Pointer charPtr1); + public static Pointer ctime_r(Pointer time_tPtr1, Pointer charPtr1) { + return Pointer.pointerToAddress(ctime_r(Pointer.getPeer(time_tPtr1), Pointer.getPeer(charPtr1)), Byte.class); + } + @Ptr + protected native static long ctime_r(@Ptr long time_tPtr1, @Ptr long charPtr1); /** * Original signature : tm* gmtime_r(const time_t*, tm*)
      * native declaration : /usr/include/time.h:140 */ - public static native Pointer gmtime_r(Pointer time_tPtr1, Pointer tmPtr1); + public static Pointer gmtime_r(Pointer time_tPtr1, Pointer tmPtr1) { + return Pointer.pointerToAddress(gmtime_r(Pointer.getPeer(time_tPtr1), Pointer.getPeer(tmPtr1)), tm.class); + } + @Ptr + protected native static long gmtime_r(@Ptr long time_tPtr1, @Ptr long tmPtr1); /** * Original signature : tm* localtime_r(const time_t*, tm*)
      * native declaration : /usr/include/time.h:141 */ - public static native Pointer localtime_r(Pointer time_tPtr1, Pointer tmPtr1); + public static Pointer localtime_r(Pointer time_tPtr1, Pointer tmPtr1) { + return Pointer.pointerToAddress(localtime_r(Pointer.getPeer(time_tPtr1), Pointer.getPeer(tmPtr1)), tm.class); + } + @Ptr + protected native static long localtime_r(@Ptr long time_tPtr1, @Ptr long tmPtr1); /** * Original signature : time_t posix2time(time_t)
      * native declaration : /usr/include/time.h:144 @@ -332,199 +395,318 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * native declaration : /usr/include/time.h:150 */ @Ptr - public static native long timelocal(Pointer tmPtr1); + public static long timelocal(Pointer tmPtr1) { + return timelocal(Pointer.getPeer(tmPtr1)); + } + @Ptr + protected native static long timelocal(@Ptr long tmPtr1); /** * Original signature : time_t timegm(const tm*)
      * native declaration : /usr/include/time.h:151 */ @Ptr - public static native long timegm(Pointer tmPtr1); + public static long timegm(Pointer tmPtr1) { + return timegm(Pointer.getPeer(tmPtr1)); + } + @Ptr + protected native static long timegm(@Ptr long tmPtr1); /** * Original signature : int nanosleep(timespec*, timespec*)
      * native declaration : /usr/include/time.h:155 */ - public static native int nanosleep(Pointer timespecPtr1, Pointer timespecPtr2); + public static int nanosleep(Pointer timespecPtr1, Pointer timespecPtr2) { + return nanosleep(Pointer.getPeer(timespecPtr1), Pointer.getPeer(timespecPtr2)); + } + protected native static int nanosleep(@Ptr long timespecPtr1, @Ptr long timespecPtr2); /** * Prototypes for all PTHREAD interfaces
      - * Original signature : int pthread_atfork(pthread_atfork_arg1_callback, pthread_atfork_arg2_callback, pthread_atfork_arg3_callback)
      + * Original signature : int pthread_atfork(pthread_atfork_arg1_callback*, pthread_atfork_arg2_callback*, pthread_atfork_arg3_callback*)
      * native declaration : /usr/include/pthread.h:211 */ - public static native int pthread_atfork(Pointer arg1, Pointer arg2, Pointer arg3); + public static int pthread_atfork(Pointer arg1, Pointer arg2, Pointer arg3) { + return pthread_atfork(Pointer.getPeer(arg1), Pointer.getPeer(arg2), Pointer.getPeer(arg3)); + } + protected native static int pthread_atfork(@Ptr long arg1, @Ptr long arg2, @Ptr long arg3); /** * Original signature : int pthread_attr_destroy(pthread_attr_t*)
      * native declaration : /usr/include/pthread.h:213 */ - public static native int pthread_attr_destroy(Pointer pthread_attr_tPtr1); + public static int pthread_attr_destroy(Pointer pthread_attr_tPtr1) { + return pthread_attr_destroy(Pointer.getPeer(pthread_attr_tPtr1)); + } + protected native static int pthread_attr_destroy(@Ptr long pthread_attr_tPtr1); /** * Original signature : int pthread_attr_getdetachstate(const pthread_attr_t*, int*)
      * native declaration : /usr/include/pthread.h:214 */ - public static native int pthread_attr_getdetachstate(Pointer pthread_attr_tPtr1, Pointer intPtr1); + public static int pthread_attr_getdetachstate(Pointer pthread_attr_tPtr1, Pointer intPtr1) { + return pthread_attr_getdetachstate(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_attr_getdetachstate(@Ptr long pthread_attr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_attr_getguardsize(const pthread_attr_t*, size_t*)
      * native declaration : /usr/include/pthread.h:216 */ - public static native int pthread_attr_getguardsize(Pointer pthread_attr_tPtr1, Pointer size_tPtr1); + public static int pthread_attr_getguardsize(Pointer pthread_attr_tPtr1, Pointer size_tPtr1) { + return pthread_attr_getguardsize(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(size_tPtr1)); + } + protected native static int pthread_attr_getguardsize(@Ptr long pthread_attr_tPtr1, @Ptr long size_tPtr1); /** * Original signature : int pthread_attr_getinheritsched(const pthread_attr_t*, int*)
      * native declaration : /usr/include/pthread.h:218 */ - public static native int pthread_attr_getinheritsched(Pointer pthread_attr_tPtr1, Pointer intPtr1); + public static int pthread_attr_getinheritsched(Pointer pthread_attr_tPtr1, Pointer intPtr1) { + return pthread_attr_getinheritsched(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_attr_getinheritsched(@Ptr long pthread_attr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_attr_getschedparam(const pthread_attr_t*, sched_param*)
      * native declaration : /usr/include/pthread.h:220 */ - public static native int pthread_attr_getschedparam(Pointer pthread_attr_tPtr1, Pointer sched_paramPtr1); + public static int pthread_attr_getschedparam(Pointer pthread_attr_tPtr1, Pointer sched_paramPtr1) { + return pthread_attr_getschedparam(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(sched_paramPtr1)); + } + protected native static int pthread_attr_getschedparam(@Ptr long pthread_attr_tPtr1, @Ptr long sched_paramPtr1); /** * Original signature : int pthread_attr_getschedpolicy(const pthread_attr_t*, int*)
      * native declaration : /usr/include/pthread.h:222 */ - public static native int pthread_attr_getschedpolicy(Pointer pthread_attr_tPtr1, Pointer intPtr1); + public static int pthread_attr_getschedpolicy(Pointer pthread_attr_tPtr1, Pointer intPtr1) { + return pthread_attr_getschedpolicy(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_attr_getschedpolicy(@Ptr long pthread_attr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_attr_getscope(const pthread_attr_t*, int*)
      * native declaration : /usr/include/pthread.h:224 */ - public static native int pthread_attr_getscope(Pointer pthread_attr_tPtr1, Pointer intPtr1); + public static int pthread_attr_getscope(Pointer pthread_attr_tPtr1, Pointer intPtr1) { + return pthread_attr_getscope(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_attr_getscope(@Ptr long pthread_attr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_attr_getstack(const pthread_attr_t*, void**, size_t*)
      * native declaration : /usr/include/pthread.h:225 */ - public static native int pthread_attr_getstack(Pointer pthread_attr_tPtr1, Pointer > voidPtrPtr1, Pointer size_tPtr1); + public static int pthread_attr_getstack(Pointer pthread_attr_tPtr1, Pointer > voidPtrPtr1, Pointer size_tPtr1) { + return pthread_attr_getstack(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(voidPtrPtr1), Pointer.getPeer(size_tPtr1)); + } + protected native static int pthread_attr_getstack(@Ptr long pthread_attr_tPtr1, @Ptr long voidPtrPtr1, @Ptr long size_tPtr1); /** * Original signature : int pthread_attr_getstackaddr(const pthread_attr_t*, void**)
      * native declaration : /usr/include/pthread.h:227 */ - public static native int pthread_attr_getstackaddr(Pointer pthread_attr_tPtr1, Pointer > voidPtrPtr1); + public static int pthread_attr_getstackaddr(Pointer pthread_attr_tPtr1, Pointer > voidPtrPtr1) { + return pthread_attr_getstackaddr(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(voidPtrPtr1)); + } + protected native static int pthread_attr_getstackaddr(@Ptr long pthread_attr_tPtr1, @Ptr long voidPtrPtr1); /** * Original signature : int pthread_attr_getstacksize(const pthread_attr_t*, size_t*)
      * native declaration : /usr/include/pthread.h:229 */ - public static native int pthread_attr_getstacksize(Pointer pthread_attr_tPtr1, Pointer size_tPtr1); + public static int pthread_attr_getstacksize(Pointer pthread_attr_tPtr1, Pointer size_tPtr1) { + return pthread_attr_getstacksize(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(size_tPtr1)); + } + protected native static int pthread_attr_getstacksize(@Ptr long pthread_attr_tPtr1, @Ptr long size_tPtr1); /** * Original signature : int pthread_attr_init(pthread_attr_t*)
      * native declaration : /usr/include/pthread.h:231 */ - public static native int pthread_attr_init(Pointer pthread_attr_tPtr1); + public static int pthread_attr_init(Pointer pthread_attr_tPtr1) { + return pthread_attr_init(Pointer.getPeer(pthread_attr_tPtr1)); + } + protected native static int pthread_attr_init(@Ptr long pthread_attr_tPtr1); /** * Original signature : int pthread_attr_setdetachstate(pthread_attr_t*, int)
      * native declaration : /usr/include/pthread.h:232 */ - public static native int pthread_attr_setdetachstate(Pointer pthread_attr_tPtr1, int int1); + public static int pthread_attr_setdetachstate(Pointer pthread_attr_tPtr1, int int1) { + return pthread_attr_setdetachstate(Pointer.getPeer(pthread_attr_tPtr1), int1); + } + protected native static int pthread_attr_setdetachstate(@Ptr long pthread_attr_tPtr1, int int1); /** * Original signature : int pthread_attr_setguardsize(pthread_attr_t*, size_t)
      * native declaration : /usr/include/pthread.h:234 */ - public static native int pthread_attr_setguardsize(Pointer pthread_attr_tPtr1, @Ptr long size_t1); + public static int pthread_attr_setguardsize(Pointer pthread_attr_tPtr1, @Ptr long size_t1) { + return pthread_attr_setguardsize(Pointer.getPeer(pthread_attr_tPtr1), size_t1); + } + protected native static int pthread_attr_setguardsize(@Ptr long pthread_attr_tPtr1, @Ptr long size_t1); /** * Original signature : int pthread_attr_setinheritsched(pthread_attr_t*, int)
      * native declaration : /usr/include/pthread.h:235 */ - public static native int pthread_attr_setinheritsched(Pointer pthread_attr_tPtr1, int int1); + public static int pthread_attr_setinheritsched(Pointer pthread_attr_tPtr1, int int1) { + return pthread_attr_setinheritsched(Pointer.getPeer(pthread_attr_tPtr1), int1); + } + protected native static int pthread_attr_setinheritsched(@Ptr long pthread_attr_tPtr1, int int1); /** * Original signature : int pthread_attr_setschedparam(pthread_attr_t*, sched_param*)
      * native declaration : /usr/include/pthread.h:237 */ - public static native int pthread_attr_setschedparam(Pointer pthread_attr_tPtr1, Pointer sched_paramPtr1); + public static int pthread_attr_setschedparam(Pointer pthread_attr_tPtr1, Pointer sched_paramPtr1) { + return pthread_attr_setschedparam(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(sched_paramPtr1)); + } + protected native static int pthread_attr_setschedparam(@Ptr long pthread_attr_tPtr1, @Ptr long sched_paramPtr1); /** * Original signature : int pthread_attr_setschedpolicy(pthread_attr_t*, int)
      * native declaration : /usr/include/pthread.h:239 */ - public static native int pthread_attr_setschedpolicy(Pointer pthread_attr_tPtr1, int int1); + public static int pthread_attr_setschedpolicy(Pointer pthread_attr_tPtr1, int int1) { + return pthread_attr_setschedpolicy(Pointer.getPeer(pthread_attr_tPtr1), int1); + } + protected native static int pthread_attr_setschedpolicy(@Ptr long pthread_attr_tPtr1, int int1); /** * Original signature : int pthread_attr_setscope(pthread_attr_t*, int)
      * native declaration : /usr/include/pthread.h:241 */ - public static native int pthread_attr_setscope(Pointer pthread_attr_tPtr1, int int1); + public static int pthread_attr_setscope(Pointer pthread_attr_tPtr1, int int1) { + return pthread_attr_setscope(Pointer.getPeer(pthread_attr_tPtr1), int1); + } + protected native static int pthread_attr_setscope(@Ptr long pthread_attr_tPtr1, int int1); /** * Original signature : int pthread_attr_setstack(pthread_attr_t*, void*, size_t)
      * native declaration : /usr/include/pthread.h:242 */ - public static native int pthread_attr_setstack(Pointer pthread_attr_tPtr1, Pointer voidPtr1, @Ptr long size_t1); + public static int pthread_attr_setstack(Pointer pthread_attr_tPtr1, Pointer voidPtr1, @Ptr long size_t1) { + return pthread_attr_setstack(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(voidPtr1), size_t1); + } + protected native static int pthread_attr_setstack(@Ptr long pthread_attr_tPtr1, @Ptr long voidPtr1, @Ptr long size_t1); /** * Original signature : int pthread_attr_setstackaddr(pthread_attr_t*, void*)
      * native declaration : /usr/include/pthread.h:244 */ - public static native int pthread_attr_setstackaddr(Pointer pthread_attr_tPtr1, Pointer voidPtr1); + public static int pthread_attr_setstackaddr(Pointer pthread_attr_tPtr1, Pointer voidPtr1) { + return pthread_attr_setstackaddr(Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(voidPtr1)); + } + protected native static int pthread_attr_setstackaddr(@Ptr long pthread_attr_tPtr1, @Ptr long voidPtr1); /** * Original signature : int pthread_attr_setstacksize(pthread_attr_t*, size_t)
      * native declaration : /usr/include/pthread.h:246 */ - public static native int pthread_attr_setstacksize(Pointer pthread_attr_tPtr1, @Ptr long size_t1); + public static int pthread_attr_setstacksize(Pointer pthread_attr_tPtr1, @Ptr long size_t1) { + return pthread_attr_setstacksize(Pointer.getPeer(pthread_attr_tPtr1), size_t1); + } + protected native static int pthread_attr_setstacksize(@Ptr long pthread_attr_tPtr1, @Ptr long size_t1); /** * Original signature : int pthread_cancel(pthread_t)
      * native declaration : /usr/include/pthread.h:247 */ - public static native int pthread_cancel(PthreadLibrary.pthread_t pthread_t1); + public static int pthread_cancel(PthreadLibrary.pthread_t pthread_t1) { + return pthread_cancel(Pointer.getPeer(pthread_t1)); + } + protected native static int pthread_cancel(@Ptr long pthread_t1); /** * Original signature : int pthread_cond_broadcast(pthread_cond_t*)
      * native declaration : /usr/include/pthread.h:249 */ - public static native int pthread_cond_broadcast(Pointer pthread_cond_tPtr1); + public static int pthread_cond_broadcast(Pointer pthread_cond_tPtr1) { + return pthread_cond_broadcast(Pointer.getPeer(pthread_cond_tPtr1)); + } + protected native static int pthread_cond_broadcast(@Ptr long pthread_cond_tPtr1); /** * Original signature : int pthread_cond_destroy(pthread_cond_t*)
      * native declaration : /usr/include/pthread.h:250 */ - public static native int pthread_cond_destroy(Pointer pthread_cond_tPtr1); + public static int pthread_cond_destroy(Pointer pthread_cond_tPtr1) { + return pthread_cond_destroy(Pointer.getPeer(pthread_cond_tPtr1)); + } + protected native static int pthread_cond_destroy(@Ptr long pthread_cond_tPtr1); /** * Original signature : int pthread_cond_init(pthread_cond_t*, const pthread_condattr_t*)
      * native declaration : /usr/include/pthread.h:251 */ - public static native int pthread_cond_init(Pointer pthread_cond_tPtr1, Pointer pthread_condattr_tPtr1); + public static int pthread_cond_init(Pointer pthread_cond_tPtr1, Pointer pthread_condattr_tPtr1) { + return pthread_cond_init(Pointer.getPeer(pthread_cond_tPtr1), Pointer.getPeer(pthread_condattr_tPtr1)); + } + protected native static int pthread_cond_init(@Ptr long pthread_cond_tPtr1, @Ptr long pthread_condattr_tPtr1); /** * Original signature : int pthread_cond_signal(pthread_cond_t*)
      * native declaration : /usr/include/pthread.h:253 */ - public static native int pthread_cond_signal(Pointer pthread_cond_tPtr1); + public static int pthread_cond_signal(Pointer pthread_cond_tPtr1) { + return pthread_cond_signal(Pointer.getPeer(pthread_cond_tPtr1)); + } + protected native static int pthread_cond_signal(@Ptr long pthread_cond_tPtr1); /** * Original signature : int pthread_cond_timedwait(pthread_cond_t*, pthread_mutex_t*, timespec*)
      * native declaration : /usr/include/pthread.h:254 */ - public static native int pthread_cond_timedwait(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1, Pointer timespecPtr1); + public static int pthread_cond_timedwait(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1, Pointer timespecPtr1) { + return pthread_cond_timedwait(Pointer.getPeer(pthread_cond_tPtr1), Pointer.getPeer(pthread_mutex_tPtr1), Pointer.getPeer(timespecPtr1)); + } + protected native static int pthread_cond_timedwait(@Ptr long pthread_cond_tPtr1, @Ptr long pthread_mutex_tPtr1, @Ptr long timespecPtr1); /** * Original signature : int pthread_cond_wait(pthread_cond_t*, pthread_mutex_t*)
      * native declaration : /usr/include/pthread.h:257 */ - public static native int pthread_cond_wait(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1); + public static int pthread_cond_wait(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1) { + return pthread_cond_wait(Pointer.getPeer(pthread_cond_tPtr1), Pointer.getPeer(pthread_mutex_tPtr1)); + } + protected native static int pthread_cond_wait(@Ptr long pthread_cond_tPtr1, @Ptr long pthread_mutex_tPtr1); /** * Original signature : int pthread_condattr_destroy(pthread_condattr_t*)
      * native declaration : /usr/include/pthread.h:259 */ - public static native int pthread_condattr_destroy(Pointer pthread_condattr_tPtr1); + public static int pthread_condattr_destroy(Pointer pthread_condattr_tPtr1) { + return pthread_condattr_destroy(Pointer.getPeer(pthread_condattr_tPtr1)); + } + protected native static int pthread_condattr_destroy(@Ptr long pthread_condattr_tPtr1); /** * Original signature : int pthread_condattr_init(pthread_condattr_t*)
      * native declaration : /usr/include/pthread.h:260 */ - public static native int pthread_condattr_init(Pointer pthread_condattr_tPtr1); + public static int pthread_condattr_init(Pointer pthread_condattr_tPtr1) { + return pthread_condattr_init(Pointer.getPeer(pthread_condattr_tPtr1)); + } + protected native static int pthread_condattr_init(@Ptr long pthread_condattr_tPtr1); /** * Original signature : int pthread_condattr_getpshared(const pthread_condattr_t*, int*)
      * native declaration : /usr/include/pthread.h:261 */ - public static native int pthread_condattr_getpshared(Pointer pthread_condattr_tPtr1, Pointer intPtr1); + public static int pthread_condattr_getpshared(Pointer pthread_condattr_tPtr1, Pointer intPtr1) { + return pthread_condattr_getpshared(Pointer.getPeer(pthread_condattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_condattr_getpshared(@Ptr long pthread_condattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_condattr_setpshared(pthread_condattr_t*, int)
      * native declaration : /usr/include/pthread.h:263 */ - public static native int pthread_condattr_setpshared(Pointer pthread_condattr_tPtr1, int int1); + public static int pthread_condattr_setpshared(Pointer pthread_condattr_tPtr1, int int1) { + return pthread_condattr_setpshared(Pointer.getPeer(pthread_condattr_tPtr1), int1); + } + protected native static int pthread_condattr_setpshared(@Ptr long pthread_condattr_tPtr1, int int1); /** - * Original signature : int pthread_create(pthread_t*, const pthread_attr_t*, pthread_create_arg1_callback, void*)
      + * Original signature : int pthread_create(pthread_t*, const pthread_attr_t*, pthread_create_arg1_callback*, void*)
      * native declaration : /usr/include/pthread.h:265 */ - public static native int pthread_create(Pointer pthread_tPtr1, Pointer pthread_attr_tPtr1, Pointer arg1, Pointer voidPtr1); + public static int pthread_create(Pointer pthread_tPtr1, Pointer pthread_attr_tPtr1, Pointer arg1, Pointer voidPtr1) { + return pthread_create(Pointer.getPeer(pthread_tPtr1), Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(arg1), Pointer.getPeer(voidPtr1)); + } + protected native static int pthread_create(@Ptr long pthread_tPtr1, @Ptr long pthread_attr_tPtr1, @Ptr long arg1, @Ptr long voidPtr1); /** * Original signature : int pthread_detach(pthread_t)
      * native declaration : /usr/include/pthread.h:269 */ - public static native int pthread_detach(PthreadLibrary.pthread_t pthread_t1); + public static int pthread_detach(PthreadLibrary.pthread_t pthread_t1) { + return pthread_detach(Pointer.getPeer(pthread_t1)); + } + protected native static int pthread_detach(@Ptr long pthread_t1); /** * Original signature : int pthread_equal(pthread_t, pthread_t)
      * native declaration : /usr/include/pthread.h:270 */ - public static native int pthread_equal(PthreadLibrary.pthread_t pthread_t1, PthreadLibrary.pthread_t pthread_t2); + public static int pthread_equal(PthreadLibrary.pthread_t pthread_t1, PthreadLibrary.pthread_t pthread_t2) { + return pthread_equal(Pointer.getPeer(pthread_t1), Pointer.getPeer(pthread_t2)); + } + protected native static int pthread_equal(@Ptr long pthread_t1, @Ptr long pthread_t2); /** * Original signature : void pthread_exit(void*)
      * native declaration : /usr/include/pthread.h:272 */ - public static native void pthread_exit(Pointer voidPtr1); + public static void pthread_exit(Pointer voidPtr1) { + pthread_exit(Pointer.getPeer(voidPtr1)); + } + protected native static void pthread_exit(@Ptr long voidPtr1); /** * Original signature : int pthread_getconcurrency()
      * native declaration : /usr/include/pthread.h:273 @@ -534,22 +716,36 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : int pthread_getschedparam(pthread_t, int*, sched_param*)
      * native declaration : /usr/include/pthread.h:274 */ - public static native int pthread_getschedparam(PthreadLibrary.pthread_t pthread_t1, Pointer intPtr1, Pointer sched_paramPtr1); + public static int pthread_getschedparam(PthreadLibrary.pthread_t pthread_t1, Pointer intPtr1, Pointer sched_paramPtr1) { + return pthread_getschedparam(Pointer.getPeer(pthread_t1), Pointer.getPeer(intPtr1), Pointer.getPeer(sched_paramPtr1)); + } + protected native static int pthread_getschedparam(@Ptr long pthread_t1, @Ptr long intPtr1, @Ptr long sched_paramPtr1); /** * Original signature : void* pthread_getspecific(pthread_key_t)
      * native declaration : /usr/include/pthread.h:275 */ - public static native Pointer pthread_getspecific(@Ptr long pthread_key_t1); + public static Pointer pthread_getspecific(@Ptr long pthread_key_t1) { + return Pointer.pointerToAddress(pthread_getspecific$2(pthread_key_t1)); + } + @Ptr + @Name("pthread_getspecific") + protected native static long pthread_getspecific$2(@Ptr long pthread_key_t1); /** * Original signature : int pthread_join(pthread_t, void**)
      * native declaration : /usr/include/pthread.h:276 */ - public static native int pthread_join(PthreadLibrary.pthread_t pthread_t1, Pointer > voidPtrPtr1); + public static int pthread_join(PthreadLibrary.pthread_t pthread_t1, Pointer > voidPtrPtr1) { + return pthread_join(Pointer.getPeer(pthread_t1), Pointer.getPeer(voidPtrPtr1)); + } + protected native static int pthread_join(@Ptr long pthread_t1, @Ptr long voidPtrPtr1); /** - * Original signature : int pthread_key_create(pthread_key_t*, pthread_key_create_arg1_callback)
      + * Original signature : int pthread_key_create(pthread_key_t*, pthread_key_create_arg1_callback*)
      * native declaration : /usr/include/pthread.h:277 */ - public static native int pthread_key_create(Pointer pthread_key_tPtr1, Pointer arg1); + public static int pthread_key_create(Pointer pthread_key_tPtr1, Pointer arg1) { + return pthread_key_create(Pointer.getPeer(pthread_key_tPtr1), Pointer.getPeer(arg1)); + } + protected native static int pthread_key_create(@Ptr long pthread_key_tPtr1, @Ptr long arg1); /** * Original signature : int pthread_key_delete(pthread_key_t)
      * native declaration : /usr/include/pthread.h:278 @@ -559,162 +755,260 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : int pthread_mutex_destroy(pthread_mutex_t*)
      * native declaration : /usr/include/pthread.h:279 */ - public static native int pthread_mutex_destroy(Pointer pthread_mutex_tPtr1); + public static int pthread_mutex_destroy(Pointer pthread_mutex_tPtr1) { + return pthread_mutex_destroy(Pointer.getPeer(pthread_mutex_tPtr1)); + } + protected native static int pthread_mutex_destroy(@Ptr long pthread_mutex_tPtr1); /** * Original signature : int pthread_mutex_getprioceiling(const pthread_mutex_t*, int*)
      * native declaration : /usr/include/pthread.h:280 */ - public static native int pthread_mutex_getprioceiling(Pointer pthread_mutex_tPtr1, Pointer intPtr1); + public static int pthread_mutex_getprioceiling(Pointer pthread_mutex_tPtr1, Pointer intPtr1) { + return pthread_mutex_getprioceiling(Pointer.getPeer(pthread_mutex_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutex_getprioceiling(@Ptr long pthread_mutex_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_mutex_init(pthread_mutex_t*, const pthread_mutexattr_t*)
      * native declaration : /usr/include/pthread.h:281 */ - public static native int pthread_mutex_init(Pointer pthread_mutex_tPtr1, Pointer pthread_mutexattr_tPtr1); + public static int pthread_mutex_init(Pointer pthread_mutex_tPtr1, Pointer pthread_mutexattr_tPtr1) { + return pthread_mutex_init(Pointer.getPeer(pthread_mutex_tPtr1), Pointer.getPeer(pthread_mutexattr_tPtr1)); + } + protected native static int pthread_mutex_init(@Ptr long pthread_mutex_tPtr1, @Ptr long pthread_mutexattr_tPtr1); /** * Original signature : int pthread_mutex_lock(pthread_mutex_t*)
      * native declaration : /usr/include/pthread.h:282 */ - public static native int pthread_mutex_lock(Pointer pthread_mutex_tPtr1); + public static int pthread_mutex_lock(Pointer pthread_mutex_tPtr1) { + return pthread_mutex_lock(Pointer.getPeer(pthread_mutex_tPtr1)); + } + protected native static int pthread_mutex_lock(@Ptr long pthread_mutex_tPtr1); /** * Original signature : int pthread_mutex_setprioceiling(pthread_mutex_t*, int, int*)
      * native declaration : /usr/include/pthread.h:283 */ - public static native int pthread_mutex_setprioceiling(Pointer pthread_mutex_tPtr1, int int1, Pointer intPtr1); + public static int pthread_mutex_setprioceiling(Pointer pthread_mutex_tPtr1, int int1, Pointer intPtr1) { + return pthread_mutex_setprioceiling(Pointer.getPeer(pthread_mutex_tPtr1), int1, Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutex_setprioceiling(@Ptr long pthread_mutex_tPtr1, int int1, @Ptr long intPtr1); /** * Original signature : int pthread_mutex_trylock(pthread_mutex_t*)
      * native declaration : /usr/include/pthread.h:284 */ - public static native int pthread_mutex_trylock(Pointer pthread_mutex_tPtr1); + public static int pthread_mutex_trylock(Pointer pthread_mutex_tPtr1) { + return pthread_mutex_trylock(Pointer.getPeer(pthread_mutex_tPtr1)); + } + protected native static int pthread_mutex_trylock(@Ptr long pthread_mutex_tPtr1); /** * Original signature : int pthread_mutex_unlock(pthread_mutex_t*)
      * native declaration : /usr/include/pthread.h:285 */ - public static native int pthread_mutex_unlock(Pointer pthread_mutex_tPtr1); + public static int pthread_mutex_unlock(Pointer pthread_mutex_tPtr1) { + return pthread_mutex_unlock(Pointer.getPeer(pthread_mutex_tPtr1)); + } + protected native static int pthread_mutex_unlock(@Ptr long pthread_mutex_tPtr1); /** * Original signature : int pthread_mutexattr_destroy(pthread_mutexattr_t*)
      * native declaration : /usr/include/pthread.h:286 */ - public static native int pthread_mutexattr_destroy(Pointer pthread_mutexattr_tPtr1); + public static int pthread_mutexattr_destroy(Pointer pthread_mutexattr_tPtr1) { + return pthread_mutexattr_destroy(Pointer.getPeer(pthread_mutexattr_tPtr1)); + } + protected native static int pthread_mutexattr_destroy(@Ptr long pthread_mutexattr_tPtr1); /** * Original signature : int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t*, int*)
      * native declaration : /usr/include/pthread.h:287 */ - public static native int pthread_mutexattr_getprioceiling(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1); + public static int pthread_mutexattr_getprioceiling(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1) { + return pthread_mutexattr_getprioceiling(Pointer.getPeer(pthread_mutexattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutexattr_getprioceiling(@Ptr long pthread_mutexattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_mutexattr_getprotocol(const pthread_mutexattr_t*, int*)
      * native declaration : /usr/include/pthread.h:288 */ - public static native int pthread_mutexattr_getprotocol(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1); + public static int pthread_mutexattr_getprotocol(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1) { + return pthread_mutexattr_getprotocol(Pointer.getPeer(pthread_mutexattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutexattr_getprotocol(@Ptr long pthread_mutexattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_mutexattr_getpshared(const pthread_mutexattr_t*, int*)
      * native declaration : /usr/include/pthread.h:289 */ - public static native int pthread_mutexattr_getpshared(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1); + public static int pthread_mutexattr_getpshared(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1) { + return pthread_mutexattr_getpshared(Pointer.getPeer(pthread_mutexattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutexattr_getpshared(@Ptr long pthread_mutexattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_mutexattr_gettype(const pthread_mutexattr_t*, int*)
      * native declaration : /usr/include/pthread.h:290 */ - public static native int pthread_mutexattr_gettype(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1); + public static int pthread_mutexattr_gettype(Pointer pthread_mutexattr_tPtr1, Pointer intPtr1) { + return pthread_mutexattr_gettype(Pointer.getPeer(pthread_mutexattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_mutexattr_gettype(@Ptr long pthread_mutexattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_mutexattr_init(pthread_mutexattr_t*)
      * native declaration : /usr/include/pthread.h:291 */ - public static native int pthread_mutexattr_init(Pointer pthread_mutexattr_tPtr1); + public static int pthread_mutexattr_init(Pointer pthread_mutexattr_tPtr1) { + return pthread_mutexattr_init(Pointer.getPeer(pthread_mutexattr_tPtr1)); + } + protected native static int pthread_mutexattr_init(@Ptr long pthread_mutexattr_tPtr1); /** * Original signature : int pthread_mutexattr_setprioceiling(pthread_mutexattr_t*, int)
      * native declaration : /usr/include/pthread.h:292 */ - public static native int pthread_mutexattr_setprioceiling(Pointer pthread_mutexattr_tPtr1, int int1); + public static int pthread_mutexattr_setprioceiling(Pointer pthread_mutexattr_tPtr1, int int1) { + return pthread_mutexattr_setprioceiling(Pointer.getPeer(pthread_mutexattr_tPtr1), int1); + } + protected native static int pthread_mutexattr_setprioceiling(@Ptr long pthread_mutexattr_tPtr1, int int1); /** * Original signature : int pthread_mutexattr_setprotocol(pthread_mutexattr_t*, int)
      * native declaration : /usr/include/pthread.h:293 */ - public static native int pthread_mutexattr_setprotocol(Pointer pthread_mutexattr_tPtr1, int int1); + public static int pthread_mutexattr_setprotocol(Pointer pthread_mutexattr_tPtr1, int int1) { + return pthread_mutexattr_setprotocol(Pointer.getPeer(pthread_mutexattr_tPtr1), int1); + } + protected native static int pthread_mutexattr_setprotocol(@Ptr long pthread_mutexattr_tPtr1, int int1); /** * Original signature : int pthread_mutexattr_setpshared(pthread_mutexattr_t*, int)
      * native declaration : /usr/include/pthread.h:294 */ - public static native int pthread_mutexattr_setpshared(Pointer pthread_mutexattr_tPtr1, int int1); + public static int pthread_mutexattr_setpshared(Pointer pthread_mutexattr_tPtr1, int int1) { + return pthread_mutexattr_setpshared(Pointer.getPeer(pthread_mutexattr_tPtr1), int1); + } + protected native static int pthread_mutexattr_setpshared(@Ptr long pthread_mutexattr_tPtr1, int int1); /** * Original signature : int pthread_mutexattr_settype(pthread_mutexattr_t*, int)
      * native declaration : /usr/include/pthread.h:295 */ - public static native int pthread_mutexattr_settype(Pointer pthread_mutexattr_tPtr1, int int1); + public static int pthread_mutexattr_settype(Pointer pthread_mutexattr_tPtr1, int int1) { + return pthread_mutexattr_settype(Pointer.getPeer(pthread_mutexattr_tPtr1), int1); + } + protected native static int pthread_mutexattr_settype(@Ptr long pthread_mutexattr_tPtr1, int int1); /** - * Original signature : int pthread_once(pthread_once_t*, pthread_once_arg1_callback)
      + * Original signature : int pthread_once(pthread_once_t*, pthread_once_arg1_callback*)
      * native declaration : /usr/include/pthread.h:296 */ - public static native int pthread_once(Pointer pthread_once_tPtr1, Pointer arg1); + public static int pthread_once(Pointer pthread_once_tPtr1, Pointer arg1) { + return pthread_once(Pointer.getPeer(pthread_once_tPtr1), Pointer.getPeer(arg1)); + } + protected native static int pthread_once(@Ptr long pthread_once_tPtr1, @Ptr long arg1); /** * Original signature : int pthread_rwlock_destroy(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:297 */ - public static native int pthread_rwlock_destroy(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_destroy(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_destroy(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_destroy(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_init(pthread_rwlock_t*, const pthread_rwlockattr_t*)
      * native declaration : /usr/include/pthread.h:298 */ - public static native int pthread_rwlock_init(Pointer pthread_rwlock_tPtr1, Pointer pthread_rwlockattr_tPtr1); + public static int pthread_rwlock_init(Pointer pthread_rwlock_tPtr1, Pointer pthread_rwlockattr_tPtr1) { + return pthread_rwlock_init(Pointer.getPeer(pthread_rwlock_tPtr1), Pointer.getPeer(pthread_rwlockattr_tPtr1)); + } + protected native static int pthread_rwlock_init(@Ptr long pthread_rwlock_tPtr1, @Ptr long pthread_rwlockattr_tPtr1); /** * Original signature : int pthread_rwlock_rdlock(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:299 */ - public static native int pthread_rwlock_rdlock(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_rdlock(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_rdlock(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_rdlock(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_tryrdlock(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:300 */ - public static native int pthread_rwlock_tryrdlock(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_tryrdlock(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_tryrdlock(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_tryrdlock(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_trywrlock(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:301 */ - public static native int pthread_rwlock_trywrlock(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_trywrlock(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_trywrlock(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_trywrlock(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_wrlock(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:302 */ - public static native int pthread_rwlock_wrlock(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_wrlock(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_wrlock(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_wrlock(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_unlock(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:303 */ - public static native int pthread_rwlock_unlock(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_unlock(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_unlock(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_unlock(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlockattr_destroy(pthread_rwlockattr_t*)
      * native declaration : /usr/include/pthread.h:304 */ - public static native int pthread_rwlockattr_destroy(Pointer pthread_rwlockattr_tPtr1); + public static int pthread_rwlockattr_destroy(Pointer pthread_rwlockattr_tPtr1) { + return pthread_rwlockattr_destroy(Pointer.getPeer(pthread_rwlockattr_tPtr1)); + } + protected native static int pthread_rwlockattr_destroy(@Ptr long pthread_rwlockattr_tPtr1); /** * Original signature : int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t*, int*)
      * native declaration : /usr/include/pthread.h:305 */ - public static native int pthread_rwlockattr_getpshared(Pointer pthread_rwlockattr_tPtr1, Pointer intPtr1); + public static int pthread_rwlockattr_getpshared(Pointer pthread_rwlockattr_tPtr1, Pointer intPtr1) { + return pthread_rwlockattr_getpshared(Pointer.getPeer(pthread_rwlockattr_tPtr1), Pointer.getPeer(intPtr1)); + } + protected native static int pthread_rwlockattr_getpshared(@Ptr long pthread_rwlockattr_tPtr1, @Ptr long intPtr1); /** * Original signature : int pthread_rwlockattr_init(pthread_rwlockattr_t*)
      * native declaration : /usr/include/pthread.h:307 */ - public static native int pthread_rwlockattr_init(Pointer pthread_rwlockattr_tPtr1); + public static int pthread_rwlockattr_init(Pointer pthread_rwlockattr_tPtr1) { + return pthread_rwlockattr_init(Pointer.getPeer(pthread_rwlockattr_tPtr1)); + } + protected native static int pthread_rwlockattr_init(@Ptr long pthread_rwlockattr_tPtr1); /** * Original signature : int pthread_rwlockattr_setpshared(pthread_rwlockattr_t*, int)
      * native declaration : /usr/include/pthread.h:308 */ - public static native int pthread_rwlockattr_setpshared(Pointer pthread_rwlockattr_tPtr1, int int1); + public static int pthread_rwlockattr_setpshared(Pointer pthread_rwlockattr_tPtr1, int int1) { + return pthread_rwlockattr_setpshared(Pointer.getPeer(pthread_rwlockattr_tPtr1), int1); + } + protected native static int pthread_rwlockattr_setpshared(@Ptr long pthread_rwlockattr_tPtr1, int int1); /** * Original signature : pthread_t pthread_self()
      * native declaration : /usr/include/pthread.h:310 */ - public static native PthreadLibrary.pthread_t pthread_self(); + public static PthreadLibrary.pthread_t pthread_self() { + return new PthreadLibrary.pthread_t(pthread_self$2()); + } + @Ptr + @Name("pthread_self") + protected native static long pthread_self$2(); /** * Original signature : int pthread_setcancelstate(int, int*)
      * native declaration : /usr/include/pthread.h:312 */ - public static native int pthread_setcancelstate(int int1, Pointer intPtr1); + public static int pthread_setcancelstate(int int1, Pointer intPtr1) { + return pthread_setcancelstate(int1, Pointer.getPeer(intPtr1)); + } + protected native static int pthread_setcancelstate(int int1, @Ptr long intPtr1); /** * Original signature : int pthread_setcanceltype(int, int*)
      * native declaration : /usr/include/pthread.h:313 */ - public static native int pthread_setcanceltype(int int1, Pointer intPtr1); + public static int pthread_setcanceltype(int int1, Pointer intPtr1) { + return pthread_setcanceltype(int1, Pointer.getPeer(intPtr1)); + } + protected native static int pthread_setcanceltype(int int1, @Ptr long intPtr1); /** * Original signature : int pthread_setconcurrency(int)
      * native declaration : /usr/include/pthread.h:314 @@ -724,12 +1018,18 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : int pthread_setschedparam(pthread_t, int, sched_param*)
      * native declaration : /usr/include/pthread.h:315 */ - public static native int pthread_setschedparam(PthreadLibrary.pthread_t pthread_t1, int int1, Pointer sched_paramPtr1); + public static int pthread_setschedparam(PthreadLibrary.pthread_t pthread_t1, int int1, Pointer sched_paramPtr1) { + return pthread_setschedparam(Pointer.getPeer(pthread_t1), int1, Pointer.getPeer(sched_paramPtr1)); + } + protected native static int pthread_setschedparam(@Ptr long pthread_t1, int int1, @Ptr long sched_paramPtr1); /** * Original signature : int pthread_setspecific(pthread_key_t, const void*)
      * native declaration : /usr/include/pthread.h:318 */ - public static native int pthread_setspecific(@Ptr long pthread_key_t1, Pointer voidPtr1); + public static int pthread_setspecific(@Ptr long pthread_key_t1, Pointer voidPtr1) { + return pthread_setspecific(pthread_key_t1, Pointer.getPeer(voidPtr1)); + } + protected native static int pthread_setspecific(@Ptr long pthread_key_t1, @Ptr long voidPtr1); /** * Original signature : void pthread_testcancel()
      * native declaration : /usr/include/pthread.h:320 @@ -745,58 +1045,91 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : int pthread_threadid_np(pthread_t, __uint64_t*)
      * native declaration : /usr/include/pthread.h:326 */ - public static native int pthread_threadid_np(PthreadLibrary.pthread_t pthread_t1, Pointer __uint64_tPtr1); + public static int pthread_threadid_np(PthreadLibrary.pthread_t pthread_t1, Pointer __uint64_tPtr1) { + return pthread_threadid_np(Pointer.getPeer(pthread_t1), Pointer.getPeer(__uint64_tPtr1)); + } + protected native static int pthread_threadid_np(@Ptr long pthread_t1, @Ptr long __uint64_tPtr1); /** * Original signature : int pthread_rwlock_longrdlock_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:328 */ - public static native int pthread_rwlock_longrdlock_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_longrdlock_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_longrdlock_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_longrdlock_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_yieldwrlock_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:329 */ - public static native int pthread_rwlock_yieldwrlock_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_yieldwrlock_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_yieldwrlock_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_yieldwrlock_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_downgrade_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:330 */ - public static native int pthread_rwlock_downgrade_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_downgrade_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_downgrade_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_downgrade_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_upgrade_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:331 */ - public static native int pthread_rwlock_upgrade_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_upgrade_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_upgrade_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_upgrade_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_tryupgrade_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:332 */ - public static native int pthread_rwlock_tryupgrade_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_tryupgrade_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_tryupgrade_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_tryupgrade_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_held_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:333 */ - public static native int pthread_rwlock_held_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_held_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_held_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_held_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_rdheld_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:334 */ - public static native int pthread_rwlock_rdheld_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_rdheld_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_rdheld_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_rdheld_np(@Ptr long pthread_rwlock_tPtr1); /** * Original signature : int pthread_rwlock_wrheld_np(pthread_rwlock_t*)
      * native declaration : /usr/include/pthread.h:335 */ - public static native int pthread_rwlock_wrheld_np(Pointer pthread_rwlock_tPtr1); + public static int pthread_rwlock_wrheld_np(Pointer pthread_rwlock_tPtr1) { + return pthread_rwlock_wrheld_np(Pointer.getPeer(pthread_rwlock_tPtr1)); + } + protected native static int pthread_rwlock_wrheld_np(@Ptr long pthread_rwlock_tPtr1); /** * SPI to set and get pthread name
      * Original signature : int pthread_getname_np(pthread_t, char*, size_t)
      * native declaration : /usr/include/pthread.h:338 */ - public static native int pthread_getname_np(PthreadLibrary.pthread_t pthread_t1, Pointer charPtr1, @Ptr long size_t1); + public static int pthread_getname_np(PthreadLibrary.pthread_t pthread_t1, Pointer charPtr1, @Ptr long size_t1) { + return pthread_getname_np(Pointer.getPeer(pthread_t1), Pointer.getPeer(charPtr1), size_t1); + } + protected native static int pthread_getname_np(@Ptr long pthread_t1, @Ptr long charPtr1, @Ptr long size_t1); /** * Original signature : int pthread_setname_np(const char*)
      * native declaration : /usr/include/pthread.h:339 */ - public static native int pthread_setname_np(Pointer charPtr1); + public static int pthread_setname_np(Pointer charPtr1) { + return pthread_setname_np(Pointer.getPeer(charPtr1)); + } + protected native static int pthread_setname_np(@Ptr long charPtr1); /** * returns non-zero if the current thread is the main thread
      * Original signature : int pthread_main_np()
      @@ -808,57 +1141,88 @@ public static abstract class pthread_create_suspended_np_arg1_callback extends C * Original signature : mach_port_t pthread_mach_thread_np(pthread_t)
      * native declaration : /usr/include/pthread.h:344 */ - public static native int pthread_mach_thread_np(PthreadLibrary.pthread_t pthread_t1); + public static int pthread_mach_thread_np(PthreadLibrary.pthread_t pthread_t1) { + return pthread_mach_thread_np(Pointer.getPeer(pthread_t1)); + } + protected native static int pthread_mach_thread_np(@Ptr long pthread_t1); /** * Original signature : size_t pthread_get_stacksize_np(pthread_t)
      * native declaration : /usr/include/pthread.h:345 */ @Ptr - public static native long pthread_get_stacksize_np(PthreadLibrary.pthread_t pthread_t1); + public static long pthread_get_stacksize_np(PthreadLibrary.pthread_t pthread_t1) { + return pthread_get_stacksize_np(Pointer.getPeer(pthread_t1)); + } + @Ptr + protected native static long pthread_get_stacksize_np(@Ptr long pthread_t1); /** * Original signature : void* pthread_get_stackaddr_np(pthread_t)
      * native declaration : /usr/include/pthread.h:346 */ - public static native Pointer pthread_get_stackaddr_np(PthreadLibrary.pthread_t pthread_t1); + public static Pointer pthread_get_stackaddr_np(PthreadLibrary.pthread_t pthread_t1) { + return Pointer.pointerToAddress(pthread_get_stackaddr_np(Pointer.getPeer(pthread_t1))); + } + @Ptr + protected native static long pthread_get_stackaddr_np(@Ptr long pthread_t1); /** * Like pthread_cond_signal(), but only wake up the specified pthread
      * Original signature : int pthread_cond_signal_thread_np(pthread_cond_t*, pthread_t)
      * native declaration : /usr/include/pthread.h:349 */ - public static native int pthread_cond_signal_thread_np(Pointer pthread_cond_tPtr1, PthreadLibrary.pthread_t pthread_t1); + public static int pthread_cond_signal_thread_np(Pointer pthread_cond_tPtr1, PthreadLibrary.pthread_t pthread_t1) { + return pthread_cond_signal_thread_np(Pointer.getPeer(pthread_cond_tPtr1), Pointer.getPeer(pthread_t1)); + } + protected native static int pthread_cond_signal_thread_np(@Ptr long pthread_cond_tPtr1, @Ptr long pthread_t1); /** * Like pthread_cond_timedwait, but use a relative timeout
      * Original signature : int pthread_cond_timedwait_relative_np(pthread_cond_t*, pthread_mutex_t*, timespec*)
      * native declaration : /usr/include/pthread.h:352 */ - public static native int pthread_cond_timedwait_relative_np(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1, Pointer timespecPtr1); + public static int pthread_cond_timedwait_relative_np(Pointer pthread_cond_tPtr1, Pointer pthread_mutex_tPtr1, Pointer timespecPtr1) { + return pthread_cond_timedwait_relative_np(Pointer.getPeer(pthread_cond_tPtr1), Pointer.getPeer(pthread_mutex_tPtr1), Pointer.getPeer(timespecPtr1)); + } + protected native static int pthread_cond_timedwait_relative_np(@Ptr long pthread_cond_tPtr1, @Ptr long pthread_mutex_tPtr1, @Ptr long timespecPtr1); /** * Like pthread_create(), but leaves the thread suspended
      - * Original signature : int pthread_create_suspended_np(pthread_t*, const pthread_attr_t*, pthread_create_suspended_np_arg1_callback, void*)
      + * Original signature : int pthread_create_suspended_np(pthread_t*, const pthread_attr_t*, pthread_create_suspended_np_arg1_callback*, void*)
      * native declaration : /usr/include/pthread.h:357 */ - public static native int pthread_create_suspended_np(Pointer pthread_tPtr1, Pointer pthread_attr_tPtr1, Pointer arg1, Pointer voidPtr1); + public static int pthread_create_suspended_np(Pointer pthread_tPtr1, Pointer pthread_attr_tPtr1, Pointer arg1, Pointer voidPtr1) { + return pthread_create_suspended_np(Pointer.getPeer(pthread_tPtr1), Pointer.getPeer(pthread_attr_tPtr1), Pointer.getPeer(arg1), Pointer.getPeer(voidPtr1)); + } + protected native static int pthread_create_suspended_np(@Ptr long pthread_tPtr1, @Ptr long pthread_attr_tPtr1, @Ptr long arg1, @Ptr long voidPtr1); /** * Original signature : int pthread_kill(pthread_t, int)
      * native declaration : /usr/include/pthread.h:361 */ - public static native int pthread_kill(PthreadLibrary.pthread_t pthread_t1, int int1); + public static int pthread_kill(PthreadLibrary.pthread_t pthread_t1, int int1) { + return pthread_kill(Pointer.getPeer(pthread_t1), int1); + } + protected native static int pthread_kill(@Ptr long pthread_t1, int int1); /** * Original signature : pthread_t pthread_from_mach_thread_np(mach_port_t)
      * native declaration : /usr/include/pthread.h:363 */ - public static native PthreadLibrary.pthread_t pthread_from_mach_thread_np(int mach_port_t1); + public static PthreadLibrary.pthread_t pthread_from_mach_thread_np(int mach_port_t1) { + return new PthreadLibrary.pthread_t(pthread_from_mach_thread_np$2(mach_port_t1)); + } + @Ptr + @Name("pthread_from_mach_thread_np") + protected native static long pthread_from_mach_thread_np$2(int mach_port_t1); /** * Original signature : int pthread_sigmask(int, const sigset_t*, sigset_t*)
      * native declaration : /usr/include/pthread.h:365 */ - public static native int pthread_sigmask(int int1, Pointer sigset_tPtr1, Pointer sigset_tPtr2); + public static int pthread_sigmask(int int1, Pointer sigset_tPtr1, Pointer sigset_tPtr2) { + return pthread_sigmask(int1, Pointer.getPeer(sigset_tPtr1), Pointer.getPeer(sigset_tPtr2)); + } + protected native static int pthread_sigmask(int int1, @Ptr long sigset_tPtr1, @Ptr long sigset_tPtr2); /** * Original signature : void pthread_yield_np()
      * native declaration : /usr/include/pthread.h:366 */ public static native void pthread_yield_np(); - /// C type : extern char*[] + /** C type : extern char*[] */ public Pointer > tzname() { try { return (Pointer >)BridJ.getNativeLibrary("pthread").getSymbolPointer("tzname").as(DefaultParameterizedType.paramType(Pointer.class, DefaultParameterizedType.paramType(Pointer.class, Byte.class))).get(); @@ -866,7 +1230,7 @@ public Pointer > tzname() { throw new RuntimeException($ex$); } } - /// C type : extern char*[] + /** C type : extern char*[] */ public PthreadLibrary tzname(Pointer > tzname) { try { { @@ -911,54 +1275,6 @@ public PthreadLibrary daylight(int daylight) { throw new RuntimeException($ex$); } } - public static class pthread_rwlock_t extends TypedPointer { - public pthread_rwlock_t(long address) { - super(address); - } - public pthread_rwlock_t(Pointer address) { - super(address); - } - }; - public static class pthread_mutex_t extends TypedPointer { - public pthread_mutex_t(long address) { - super(address); - } - public pthread_mutex_t(Pointer address) { - super(address); - } - }; - public static class pthread_condattr_t extends TypedPointer { - public pthread_condattr_t(long address) { - super(address); - } - public pthread_condattr_t(Pointer address) { - super(address); - } - }; - public static class pthread_mutexattr_t extends TypedPointer { - public pthread_mutexattr_t(long address) { - super(address); - } - public pthread_mutexattr_t(Pointer address) { - super(address); - } - }; - public static class pthread_attr_t extends TypedPointer { - public pthread_attr_t(long address) { - super(address); - } - public pthread_attr_t(Pointer address) { - super(address); - } - }; - public static class pthread_rwlockattr_t extends TypedPointer { - public pthread_rwlockattr_t(long address) { - super(address); - } - public pthread_rwlockattr_t(Pointer address) { - super(address); - } - }; public static class pthread_t extends TypedPointer { public pthread_t(long address) { super(address); @@ -967,25 +1283,4 @@ public pthread_t(Pointer address) { super(address); } }; - public static class pthread_once_t extends TypedPointer { - public pthread_once_t(long address) { - super(address); - } - public pthread_once_t(Pointer address) { - super(address); - } - }; - public static class pthread_cond_t extends TypedPointer { - public pthread_cond_t(long address) { - super(address); - } - public pthread_cond_t(Pointer address) { - super(address); - } - }; - /// Undefined type - /// Undefined type - public static interface timespec { - - }; } diff --git a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/sched_param.java b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/sched_param.java index 2c6bb765a..da48727d3 100644 --- a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/sched_param.java +++ b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/sched_param.java @@ -1,4 +1,5 @@ package com.nativelibs4java.pthread; +import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Array; @@ -12,8 +13,8 @@ */ @Library("pthread") public class sched_param extends StructObject { - public sched_param() { - super(); + static { + BridJ.register(); } @Field(0) public int sched_priority() { @@ -24,12 +25,15 @@ public sched_param sched_priority(int sched_priority) { this.io.setIntField(this, 0, sched_priority); return this; } - /// C type : char[4] + /** C type : char[4] */ @Array({4}) @Field(1) public Pointer __opaque() { return this.io.getPointerField(this, 1); } + public sched_param() { + super(); + } public sched_param(Pointer pointer) { super(pointer); } diff --git a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/tm.java b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/tm.java index a89bf1efa..fc1dcee79 100644 --- a/libraries/PThread/src/main/java/com/nativelibs4java/pthread/tm.java +++ b/libraries/PThread/src/main/java/com/nativelibs4java/pthread/tm.java @@ -1,4 +1,5 @@ package com.nativelibs4java.pthread; +import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Field; @@ -12,115 +13,115 @@ */ @Library("pthread") public class tm extends StructObject { - public tm() { - super(); + static { + BridJ.register(); } - /// seconds after the minute [0-60] + /** seconds after the minute [0-60] */ @Field(0) public int tm_sec() { return this.io.getIntField(this, 0); } - /// seconds after the minute [0-60] + /** seconds after the minute [0-60] */ @Field(0) public tm tm_sec(int tm_sec) { this.io.setIntField(this, 0, tm_sec); return this; } - /// minutes after the hour [0-59] + /** minutes after the hour [0-59] */ @Field(1) public int tm_min() { return this.io.getIntField(this, 1); } - /// minutes after the hour [0-59] + /** minutes after the hour [0-59] */ @Field(1) public tm tm_min(int tm_min) { this.io.setIntField(this, 1, tm_min); return this; } - /// hours since midnight [0-23] + /** hours since midnight [0-23] */ @Field(2) public int tm_hour() { return this.io.getIntField(this, 2); } - /// hours since midnight [0-23] + /** hours since midnight [0-23] */ @Field(2) public tm tm_hour(int tm_hour) { this.io.setIntField(this, 2, tm_hour); return this; } - /// day of the month [1-31] + /** day of the month [1-31] */ @Field(3) public int tm_mday() { return this.io.getIntField(this, 3); } - /// day of the month [1-31] + /** day of the month [1-31] */ @Field(3) public tm tm_mday(int tm_mday) { this.io.setIntField(this, 3, tm_mday); return this; } - /// months since January [0-11] + /** months since January [0-11] */ @Field(4) public int tm_mon() { return this.io.getIntField(this, 4); } - /// months since January [0-11] + /** months since January [0-11] */ @Field(4) public tm tm_mon(int tm_mon) { this.io.setIntField(this, 4, tm_mon); return this; } - /// years since 1900 + /** years since 1900 */ @Field(5) public int tm_year() { return this.io.getIntField(this, 5); } - /// years since 1900 + /** years since 1900 */ @Field(5) public tm tm_year(int tm_year) { this.io.setIntField(this, 5, tm_year); return this; } - /// days since Sunday [0-6] + /** days since Sunday [0-6] */ @Field(6) public int tm_wday() { return this.io.getIntField(this, 6); } - /// days since Sunday [0-6] + /** days since Sunday [0-6] */ @Field(6) public tm tm_wday(int tm_wday) { this.io.setIntField(this, 6, tm_wday); return this; } - /// days since January 1 [0-365] + /** days since January 1 [0-365] */ @Field(7) public int tm_yday() { return this.io.getIntField(this, 7); } - /// days since January 1 [0-365] + /** days since January 1 [0-365] */ @Field(7) public tm tm_yday(int tm_yday) { this.io.setIntField(this, 7, tm_yday); return this; } - /// Daylight Savings Time flag + /** Daylight Savings Time flag */ @Field(8) public int tm_isdst() { return this.io.getIntField(this, 8); } - /// Daylight Savings Time flag + /** Daylight Savings Time flag */ @Field(8) public tm tm_isdst(int tm_isdst) { this.io.setIntField(this, 8, tm_isdst); return this; } - /// offset from CUT in seconds + /** offset from CUT in seconds */ @Ptr @Field(9) public long tm_gmtoff() { return this.io.getSizeTField(this, 9); } - /// offset from CUT in seconds + /** offset from CUT in seconds */ @Ptr @Field(9) public tm tm_gmtoff(long tm_gmtoff) { @@ -144,6 +145,9 @@ public tm tm_zone(Pointer tm_zone) { this.io.setPointerField(this, 10, tm_zone); return this; } + public tm() { + super(); + } public tm(Pointer pointer) { super(pointer); } diff --git a/libraries/RELEASE.txt b/libraries/RELEASE.txt new file mode 100644 index 000000000..79c964a4e --- /dev/null +++ b/libraries/RELEASE.txt @@ -0,0 +1,46 @@ +- Update CHANGELOG files in jnaerator, BridJ, OpenCL +- Move Velocity, Utils, BridJ, JNAerator, JavaCL, Parent to release versions +- Remove ~/.m2/repository/com/nativelibs4java and make sure the following command succeeds (runs the tests): + mvn clean install -o +- Deploy to staged repo, create release tags and upload artifacts to Google Code + scripts/tagAndUpload_BridJ_JNAerator_JavaCL +- Prepare release notes: + - Run this + scripts/prepareReleaseNotes + - Paste first section of CHANGELOG.html files into a new post at http://ochafik.com/wp-admin +- Close staged repo on http://oss.sonatype.org +- Test staged repo with a dummy sbt project +- Release stage repo +- Upload release Javadocs to sourceforge FTP + cd BridJ + uploadJavadoc $BRIDJ_VERSION bridj/api + cd OpenCL + uploadJavadoc $JAVACL_VERSION javacl/api + ... +- Move back to snapshot versions +- Upload new snapshot javadocs to sourceforge FTP + cd BridJ + uploadJavadoc development bridj/api + cd OpenCL + uploadJavadoc development javacl/api +- Log onto sourceforge and point javacl/current to $JAVACL_VERSION and bridj/current to $BRIDJ_VERSION +- Deploy snapshots + mvn clean javadoc:jar deploy -DskipTests -Pgpg,coordinated-release +- Edit JNLP files for all demos to point to new snapshot +- Build WebStart artifacts: + cd jnaerator/jnaerator + for F in $PWD/jnaerator/jnaerator $PWD/OpenCL/InteractiveImageDemo $PWD/OpenCL/Demos; do + cd $F + mvn -Pwebstart -Dstorepass=$KEYSTORE_PASS -DskipTests clean install + done +- Upload JNLP and JAR files to Sourceforge FTPs +- Update wikis + - BridJ (front page, download, faq?) + - JNAerator (front page, ...?) + - JavaCL (front page, download) + - ScalaCL / Scalaxy (...) +- Send emails to: + - jna-users (JNAerator + BridJ) + - nativelibs4java (BridJ, JNAerator, JavaCL, ScalaCL, Scalaxy) +- Post blog links on Twitter, G+ +- Send blog links to DZone diff --git a/libraries/Runtime/JNI/pom.xml b/libraries/Runtime/JNI/pom.xml index ae07105e2..dd3bdf39c 100644 --- a/libraries/Runtime/JNI/pom.xml +++ b/libraries/Runtime/JNI/pom.xml @@ -6,7 +6,7 @@ jni JNI BridJ Bindings http://code.google.com/p/bridj - 0.7-SNAPSHOT + 0.7 jar - org.scala-tools - maven-scala-plugin + net.alchim31.maven + scala-maven-plugin @@ -102,9 +102,8 @@ - org.scala-tools - maven-scala-plugin - ${scala.version} + net.alchim31.maven + scala-maven-plugin org.codehaus.mojo diff --git a/libraries/ScalaCL/.gitignore b/libraries/ScalaCL/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/ScalaCL/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/ScalaCL/Collections/ABOUT b/libraries/ScalaCL/Collections/ABOUT deleted file mode 100644 index f0cec53c1..000000000 --- a/libraries/ScalaCL/Collections/ABOUT +++ /dev/null @@ -1,28 +0,0 @@ - - ScalaCL makes Scala faster and GPGPU trivial. - It features : - - a compiler plugin that optimizes regular Scala code without adding any dependency - - a library of OpenCL-backed collections that execute Scala code (map, filter...) on GPUs transparently, thanks to the compiler plugin - -Website: - http://scalacl.googlecode.com/ - -Author: - Olivier Chafik - http://ochafik.free.fr/blog/ - http://twitter.com/ochafik - -Current features : -- CLArray[T], CLRange (create with CLArray(1, 2, 3...), new CLArray[Int](n), Seq.cl or Seq.toCLArray) with accelerated .map, .filter, .zip and .zipWithIndex operations (when the inline closures are convertible by the compiler plugin) - -> For more details, see http://code.google.com/p/scalacl/wiki/CLConvertibleLanguageSubset -- Transformation of regular Scala operations on Array[T] and inline ranges : .map, .foreach, .reduce/fold/scan|Left/Right, .sum... - -> For more details, see http://code.google.com/p/scalacl/wiki/ScalaCLPlugin - -Planned features : -- better translation of Scala functions to OpenCL kernels to support more Scala constructs -- rewrite of operation streams into loops when functions are side-effect-free (a.map(f1).map(f2).filter(f3).takeWhile(f4)...) -- auto-vectorization of OpenCL code - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list diff --git a/libraries/ScalaCL/Collections/build.sbt b/libraries/ScalaCL/Collections/build.sbt deleted file mode 100644 index 547501f66..000000000 --- a/libraries/ScalaCL/Collections/build.sbt +++ /dev/null @@ -1,17 +0,0 @@ -name := "scalacl" - -version := "0.3-SNAPSHOT" - -organization := "com.nativelibs4java" - -//scalaHome := Some(file("/Users/ochafik/bin/scala-2.10.0.r25286-b20110715023800")) - -scalaVersion := "2.9.1" - -resolvers += "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - -libraryDependencies ++= Seq( - "com.nativelibs4java" % "javacl" % "1.0-SNAPSHOT", - "com.novocode" % "junit-interface" % "0.5" % "test->default" -) - diff --git a/libraries/ScalaCL/Collections/copyToScala b/libraries/ScalaCL/Collections/copyToScala deleted file mode 100644 index 2279a8bb2..000000000 --- a/libraries/ScalaCL/Collections/copyToScala +++ /dev/null @@ -1,19 +0,0 @@ -VERSION="`cat pom.xml | grep '\(.*\)<\/version>.*/\1/g'`" -#VERSION="0.2.Beta1" - -LIB_JAR_OUT="$SCALA_HOME/lib" -PLUGIN_JAR_OUT="$SCALA_HOME/misc/scala-devel/plugins" - -LIB_JAR_IN="target" -PLUGIN_JAR_IN="../ScalaCLPlugin/target" - -LIB_JAR="scalacl-$VERSION-shaded.jar" -PLUGIN_JAR="scalacl-compiler-plugin-$VERSION.jar" - -rm $LIB_JAR_OUT/scalacl*.jar -rm $PLUGIN_JAR_OUT/scalacl*.jar - -if [[ "$NO_COPY" != "1" ]] ; then - cp $LIB_JAR_IN/$LIB_JAR $LIB_JAR_OUT - cp $PLUGIN_JAR_IN/$PLUGIN_JAR $PLUGIN_JAR_OUT ; -fi diff --git a/libraries/ScalaCL/Collections/nbactions.xml b/libraries/ScalaCL/Collections/nbactions.xml deleted file mode 100644 index bca0516b7..000000000 --- a/libraries/ScalaCL/Collections/nbactions.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - run - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - runtime - -classpath %classpath scalacl.Test - java - - - - debug - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - runtime - -Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath scalacl.Test - true - java - - - - profile - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - ${profiler.args} -classpath %classpath scalacl.Test - profile - ${profiler.java} - - - diff --git a/libraries/ScalaCL/Collections/pom.xml b/libraries/ScalaCL/Collections/pom.xml deleted file mode 100644 index de668a3ab..000000000 --- a/libraries/ScalaCL/Collections/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - scalacl - ScalaCL Collections - http://code.google.com/p/scalacl/ - jar - - -ScalaCL Collections are GPGPU-stored collections which execute some of their operations (filter, map...) straight on the GPU. - - - - com.nativelibs4java - scalacl-parent - 0.3-SNAPSHOT - .. - - - - - com.nativelibs4java - javacl - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - - - - - diff --git a/libraries/ScalaCL/Collections/project-old/build.properties b/libraries/ScalaCL/Collections/project-old/build.properties deleted file mode 100644 index a443cb099..000000000 --- a/libraries/ScalaCL/Collections/project-old/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -#Project properties -#Wed Sep 15 03:28:59 CEST 2010 -project.organization=com.nativelibs4java -project.name=scalacl2 -sbt.version=0.7.5.RC0 -project.version=0.1-SNAPSHOT -build.scala.versions=2.9.0.1 -project.initialize=false diff --git a/libraries/ScalaCL/Collections/project-old/build/ScalaCL2Project.scala b/libraries/ScalaCL/Collections/project-old/build/ScalaCL2Project.scala deleted file mode 100644 index 6e1ccde57..000000000 --- a/libraries/ScalaCL/Collections/project-old/build/ScalaCL2Project.scala +++ /dev/null @@ -1,8 +0,0 @@ -import sbt._ - -class ScalaCL2Project(info: ProjectInfo) extends DefaultProject(info) -{ - val nativelibs4javaRepo = "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - val JavaCLBridJ = "com.nativelibs4java" % "javacl-bridj" % "1.0-SNAPSHOT" - val junitInterface = "com.novocode" % "junit-interface" % "0.5" % "test->default" -} diff --git a/libraries/ScalaCL/Collections/project/boot/other/net.java.dev.jna/jna/3.2.3/jna-3.2.3.jar b/libraries/ScalaCL/Collections/project/boot/other/net.java.dev.jna/jna/3.2.3/jna-3.2.3.jar deleted file mode 100644 index be4031408..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/other/net.java.dev.jna/jna/3.2.3/jna-3.2.3.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/sbt.boot.lock b/libraries/ScalaCL/Collections/project/boot/sbt.boot.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/jline.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/jline.jar deleted file mode 100644 index 889a19892..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/jline.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-compiler.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-compiler.jar deleted file mode 100644 index 551596023..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-compiler.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-library.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-library.jar deleted file mode 100644 index 250a5dd64..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/lib/scala-library.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/actions_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/actions_2.8.1-0.10.1.jar deleted file mode 100644 index b7a43adb9..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/actions_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/api_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/api_2.8.1-0.10.1.jar deleted file mode 100644 index 9fbcb01e7..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/api_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/cache_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/cache_2.8.1-0.10.1.jar deleted file mode 100644 index 5a42d8ed2..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/cache_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classfile_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classfile_2.8.1-0.10.1.jar deleted file mode 100644 index dcf935dd2..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classfile_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classpath_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classpath_2.8.1-0.10.1.jar deleted file mode 100644 index e8d475fe6..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/classpath_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/collections_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/collections_2.8.1-0.10.1.jar deleted file mode 100644 index f0f0ef252..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/collections_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-codec-1.2.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-codec-1.2.jar deleted file mode 100644 index 67cb720f5..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-codec-1.2.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-httpclient-3.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-httpclient-3.1.jar deleted file mode 100644 index 7c59774ae..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-httpclient-3.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-logging-1.0.4.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-logging-1.0.4.jar deleted file mode 100644 index b73a80fab..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/commons-logging-1.0.4.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compile_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compile_2.8.1-0.10.1.jar deleted file mode 100644 index 02c141d2d..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compile_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.8.1.final/compiler-interface-bin-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.8.1.final/compiler-interface-bin-0.10.1.jar deleted file mode 100644 index e1d42f935..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.8.1.final/compiler-interface-bin-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.0.1/compiler-interface-bin-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.0.1/compiler-interface-bin-0.10.1.jar deleted file mode 100644 index 47582fbed..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.0.1/compiler-interface-bin-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.1.final__50.0/compiler-interface-bin_2.9.1.final__50.0-0.10.1_20110714T111957.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.1.final__50.0/compiler-interface-bin_2.9.1.final__50.0-0.10.1_20110714T111957.jar deleted file mode 100644 index 898000c83..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-bin_2.9.1.final__50.0/compiler-interface-bin_2.9.1.final__50.0-0.10.1_20110714T111957.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-src/compiler-interface-src-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-src/compiler-interface-src-0.10.1.jar deleted file mode 100644 index 38ecb4f45..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/compiler-interface-src/compiler-interface-src-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/completion_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/completion_2.8.1-0.10.1.jar deleted file mode 100644 index ea20a69c5..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/completion_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/control_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/control_2.8.1-0.10.1.jar deleted file mode 100644 index 14b7da9d7..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/control_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/discovery_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/discovery_2.8.1-0.10.1.jar deleted file mode 100644 index 72817ce95..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/discovery_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/incremental-compiler_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/incremental-compiler_2.8.1-0.10.1.jar deleted file mode 100644 index d11d6730c..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/incremental-compiler_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/io_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/io_2.8.1-0.10.1.jar deleted file mode 100644 index 59dc4aa6a..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/io_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy-2.2.0.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy-2.2.0.jar deleted file mode 100644 index 7e73dab66..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy-2.2.0.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy_2.8.1-0.10.1.jar deleted file mode 100644 index 7647e3db7..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/ivy_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jline-0.9.94.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jline-0.9.94.jar deleted file mode 100644 index dede3721d..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jline-0.9.94.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jsch-0.1.31.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jsch-0.1.31.jar deleted file mode 100644 index 9ab8b2702..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/jsch-0.1.31.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/launcher-interface_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/launcher-interface_2.8.1-0.10.1.jar deleted file mode 100644 index b2a847686..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/launcher-interface_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/logging_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/logging_2.8.1-0.10.1.jar deleted file mode 100644 index 760cd7906..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/logging_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/main_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/main_2.8.1-0.10.1.jar deleted file mode 100644 index ba8cecf41..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/main_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/persist_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/persist_2.8.1-0.10.1.jar deleted file mode 100644 index 0d72bb3cf..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/persist_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/process_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/process_2.8.1-0.10.1.jar deleted file mode 100644 index 4facac1af..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/process_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/run_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/run_2.8.1-0.10.1.jar deleted file mode 100644 index 633f4cf1b..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/run_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbinary_2.8.1-0.4.0.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbinary_2.8.1-0.4.0.jar deleted file mode 100644 index 88caf402d..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbinary_2.8.1-0.4.0.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbt.components.lock b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbt.components.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbt_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbt_2.8.1-0.10.1.jar deleted file mode 100644 index 41adcd9f5..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/sbt_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/task-system_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/task-system_2.8.1-0.10.1.jar deleted file mode 100644 index 97ef36257..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/task-system_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tasks_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tasks_2.8.1-0.10.1.jar deleted file mode 100644 index 3b99809c6..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tasks_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/test-interface-0.5.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/test-interface-0.5.jar deleted file mode 100644 index d63c555a3..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/test-interface-0.5.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/testing_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/testing_2.8.1-0.10.1.jar deleted file mode 100644 index 6d9a3c4ac..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/testing_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tracking_2.8.1-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tracking_2.8.1-0.10.1.jar deleted file mode 100644 index 9305f7cba..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/tracking_2.8.1-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/xsbti/interface-0.10.1.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/xsbti/interface-0.10.1.jar deleted file mode 100644 index 6f0209ccc..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.1/xsbti/interface-0.10.1.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jansi.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jansi.jar deleted file mode 100644 index 75ae09ab4..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jansi.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jline.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jline.jar deleted file mode 100644 index 0a018cc90..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/jline.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-compiler.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-compiler.jar deleted file mode 100644 index 5e5ef82ae..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-compiler.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-library.jar b/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-library.jar deleted file mode 100644 index d38bb5afd..000000000 Binary files a/libraries/ScalaCL/Collections/project/boot/scala-2.9.1/lib/scala-library.jar and /dev/null differ diff --git a/libraries/ScalaCL/Collections/project/boot/update.log b/libraries/ScalaCL/Collections/project/boot/update.log deleted file mode 100644 index 63f0711ec..000000000 --- a/libraries/ScalaCL/Collections/project/boot/update.log +++ /dev/null @@ -1,217 +0,0 @@ -setting 'ivy.default.settings.dir' to 'jar:file:/Users/ochafik/bin/sbt-launch-0.10.1.jar!/org/apache/ivy/core/settings' -setting 'ivy.basedir' to '/Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/.' -setting 'ivy.default.conf.dir' to 'jar:file:/Users/ochafik/bin/sbt-launch-0.10.1.jar!/org/apache/ivy/core/settings' -impossible to define new type: class not found: org.apache.ivy.plugins.version.PatternVersionMatcher in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.trigger.LogTrigger in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.DualResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.VsftpResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.conflict.RegexpConflictManager in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.SshResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.VfsResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.signer.bouncycastle.OpenPGPSignatureGenerator in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.SFTPResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.packager.PackagerResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.ant.AntCallTrigger in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.plugins.resolver.IvyRepResolver in [] nor Ivy classloader -impossible to define new type: class not found: org.apache.ivy.ant.AntBuildTrigger in [] nor Ivy classloader -impossible to define glob matcher: org.apache.ivy.plugins.matcher.GlobPatternMatcher was not found. -setting 'java.runtime.name' to 'Java(TM) SE Runtime Environment' -setting 'sun.boot.library.path' to '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries' -setting 'java.vm.version' to '20.1-b02-383' -setting 'awt.nativeDoubleBuffering' to 'true' -setting 'gopherProxySet' to 'false' -setting 'mrj.build' to '11A511' -setting 'java.vm.vendor' to 'Apple Inc.' -setting 'java.vendor.url' to 'http://www.apple.com/' -setting 'path.separator' to ':' -setting 'java.vm.name' to 'Java HotSpot(TM) 64-Bit Server VM' -setting 'file.encoding.pkg' to 'sun.io' -setting 'sun.java.launcher' to 'SUN_STANDARD' -setting 'user.country' to 'FR' -setting 'sun.os.patch.level' to 'unknown' -setting 'java.vm.specification.name' to 'Java Virtual Machine Specification' -setting 'user.dir' to '/Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL' -setting 'java.runtime.version' to '1.6.0_26-b03-383-11A511' -setting 'java.awt.graphicsenv' to 'apple.awt.CGraphicsEnvironment' -setting 'java.endorsed.dirs' to '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/endorsed' -setting 'os.arch' to 'x86_64' -setting 'java.io.tmpdir' to '/var/folders/2w/_9jzy4jd1fs2px9l2yjkmwfc0000gp/T/' -setting 'line.separator' to ' -' -setting 'java.vm.specification.vendor' to 'Sun Microsystems Inc.' -setting 'os.name' to 'Mac OS X' -setting 'sun.jnu.encoding' to 'MacRoman' -setting 'java.library.path' to '.:/Users/ochafik/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java' -setting 'java.specification.name' to 'Java Platform API Specification' -setting 'java.class.version' to '50.0' -setting 'sun.management.compiler' to 'HotSpot 64-Bit Tiered Compilers' -setting 'os.version' to '10.7.1' -setting 'http.nonProxyHosts' to 'local|*.local|169.254/16|*.169.254/16' -setting 'user.home' to '/Users/ochafik' -setting 'user.timezone' to 'Europe/London' -setting 'java.awt.printerjob' to 'apple.awt.CPrinterJob' -setting 'file.encoding' to 'MacRoman' -setting 'java.specification.version' to '1.6' -setting 'java.class.path' to '/Users/ochafik/bin/sbt-launch-0.10.1.jar' -setting 'user.name' to 'ochafik' -setting 'java.vm.specification.version' to '1.0' -setting 'sun.java.command' to '/Users/ochafik/bin/sbt-launch-0.10.1.jar' -setting 'java.home' to '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home' -setting 'sun.arch.data.model' to '64' -setting 'user.language' to 'fr' -setting 'java.specification.vendor' to 'Sun Microsystems Inc.' -setting 'awt.toolkit' to 'apple.awt.CToolkit' -setting 'java.vm.info' to 'mixed mode' -setting 'java.version' to '1.6.0_26' -setting 'java.ext.dirs' to '/Users/ochafik/Library/Java/Extensions:/Library/Java/Extensions:/System/Library/Java/Extensions:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/ext' -setting 'sun.boot.class.path' to '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar:/System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/ui.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsse.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jce.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/charsets.jar' -setting 'java.vendor' to 'Apple Inc.' -setting 'file.separator' to '/' -setting 'java.vendor.url.bug' to 'http://bugreport.apple.com/' -setting 'sun.io.unicode.encoding' to 'UnicodeLittle' -setting 'sun.cpu.endian' to 'little' -setting 'mrj.version' to '1070.1.6.0_26-383' -setting 'socksNonProxyHosts' to 'local|*.local|169.254/16|*.169.254/16' -setting 'ftp.nonProxyHosts' to 'local|*.local|169.254/16|*.169.254/16' -setting 'sun.cpu.isalist' to '' -setting 'ivy.default.ivy.user.dir' to '/Users/ochafik/.ivy2' -setting 'ivy.home' to '/Users/ochafik/.ivy2' -setting 'ivy.cache.dir' to '/Users/ochafik/.ivy2/cache' -no default cache defined: set to /Users/ochafik/.ivy2/cache -setting 'ivy.checksums' to 'sha1,md5' -setting 'ivy.basedir' to '/Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot' -setting 'basedir' to '/Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot' -setting 'scala' to '2.9.1' -:: resolving dependencies :: org.scala-tools.sbt#boot-scala;1.0 - confs: [default] - validate = true - refresh = false -resolving dependencies for configuration 'default' -== resolving dependencies for org.scala-tools.sbt#boot-scala;1.0 [default] -loadData of org.scala-tools.sbt#boot-scala;1.0 of rootConf=default -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-compiler;2.9.1 [default->default] -loadData of org.scala-lang#scala-compiler;2.9.1 of rootConf=default - using redefined-public to resolve org.scala-lang#scala-compiler;2.9.1 -redefined-public: Checking cache for: dependency: org.scala-lang#scala-compiler;2.9.1 {default=[default, optional(default)]} -redefined-public: no namespace defined: using system -No entry is found in the ModuleDescriptorCache : /Users/ochafik/.ivy2/cache/org.scala-lang/scala-compiler/ivy-2.9.1.xml -post 1.3 ivy file: using exact as default matcher - found ivy file in cache for org.scala-lang#scala-compiler;2.9.1 (resolved by Scala-Tools Maven2 Repository): /Users/ochafik/.ivy2/cache/org.scala-lang/scala-compiler/ivy-2.9.1.xml -redefined-public: module revision found in cache: org.scala-lang#scala-compiler;2.9.1 -redefined-public: no latest strategy defined: using default - found org.scala-lang#scala-compiler;2.9.1 in Scala-Tools Maven2 Repository -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-compiler;2.9.1 [default->runtime] -loadData of org.scala-lang#scala-compiler;2.9.1 of rootConf=default -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-compiler;2.9.1 [default->compile] -loadData of org.scala-lang#scala-compiler;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->master(*)] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default - using redefined-public to resolve org.scala-lang#scala-library;2.9.1 -redefined-public: Checking cache for: dependency: org.scala-lang#scala-library;2.9.1 {compile=[compile(*), master(*)], runtime=[runtime(*)]} -No entry is found in the ModuleDescriptorCache : /Users/ochafik/.ivy2/cache/org.scala-lang/scala-library/ivy-2.9.1.xml -post 1.3 ivy file: using exact as default matcher - found ivy file in cache for org.scala-lang#scala-library;2.9.1 (resolved by Scala-Tools Maven2 Repository): /Users/ochafik/.ivy2/cache/org.scala-lang/scala-library/ivy-2.9.1.xml -redefined-public: module revision found in cache: org.scala-lang#scala-library;2.9.1 - found org.scala-lang#scala-library;2.9.1 in Scala-Tools Maven2 Repository -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->compile(*)] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->default] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->runtime] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->compile] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [compile->master] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [runtime->runtime(*)] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#scala-library;2.9.1 [runtime->compile] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -default is loaded and no conf to load. Skip loading -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-compiler;2.9.1 [default->master] -loadData of org.scala-lang#scala-compiler;2.9.1 of rootConf=default -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-compiler;2.9.1 [default->optional(default)] -loadData of org.scala-lang#scala-compiler;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#jline;2.9.1 [optional->master(*)] -loadData of org.scala-lang#jline;2.9.1 of rootConf=default - using redefined-public to resolve org.scala-lang#jline;2.9.1 -redefined-public: Checking cache for: dependency: org.scala-lang#jline;2.9.1 {optional=[compile(*), master(*)]} -No entry is found in the ModuleDescriptorCache : /Users/ochafik/.ivy2/cache/org.scala-lang/jline/ivy-2.9.1.xml -post 1.3 ivy file: using exact as default matcher - found ivy file in cache for org.scala-lang#jline;2.9.1 (resolved by Scala-Tools Maven2 Repository): /Users/ochafik/.ivy2/cache/org.scala-lang/jline/ivy-2.9.1.xml -redefined-public: module revision found in cache: org.scala-lang#jline;2.9.1 - found org.scala-lang#jline;2.9.1 in Scala-Tools Maven2 Repository -== resolving dependencies org.scala-lang#scala-compiler;2.9.1->org.scala-lang#jline;2.9.1 [optional->compile(*)] -loadData of org.scala-lang#jline;2.9.1 of rootConf=default -== resolving dependencies org.scala-lang#jline;2.9.1->org.fusesource.jansi#jansi;1.4 [compile->master(*)] -loadData of org.fusesource.jansi#jansi;1.4 of rootConf=default - using redefined-public to resolve org.fusesource.jansi#jansi;1.4 -redefined-public: Checking cache for: dependency: org.fusesource.jansi#jansi;1.4 {compile=[compile(*), master(*)], runtime=[runtime(*)]} -No entry is found in the ModuleDescriptorCache : /Users/ochafik/.ivy2/cache/org.fusesource.jansi/jansi/ivy-1.4.xml -post 1.3 ivy file: using exact as default matcher - found ivy file in cache for org.fusesource.jansi#jansi;1.4 (resolved by redefined-public): /Users/ochafik/.ivy2/cache/org.fusesource.jansi/jansi/ivy-1.4.xml -redefined-public: module revision found in cache: org.fusesource.jansi#jansi;1.4 - found org.fusesource.jansi#jansi;1.4 in redefined-public -== resolving dependencies org.scala-lang#jline;2.9.1->org.fusesource.jansi#jansi;1.4 [compile->compile(*)] -loadData of org.fusesource.jansi#jansi;1.4 of rootConf=default -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-library;2.9.1 [default->default] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -default is loaded and no conf to load. Skip loading -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-library;2.9.1 [default->runtime] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -default is loaded and no conf to load. Skip loading -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-library;2.9.1 [default->compile] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -default is loaded and no conf to load. Skip loading -== resolving dependencies org.scala-tools.sbt#boot-scala;1.0->org.scala-lang#scala-library;2.9.1 [default->master] -loadData of org.scala-lang#scala-library;2.9.1 of rootConf=default -default is loaded and no conf to load. Skip loading -Nbr of module to sort : 4 -Sort dependencies of : org.scala-lang#scala-compiler;2.9.1 / Number of dependencies = 2 -Sort dependencies of : org.scala-lang#scala-library;2.9.1 / Number of dependencies = 0 -Sort done for : org.scala-lang#scala-library;2.9.1 -Sort dependencies of : org.scala-lang#jline;2.9.1 / Number of dependencies = 1 -Sort dependencies of : org.fusesource.jansi#jansi;1.4 / Number of dependencies = 1 -Sort done for : org.fusesource.jansi#jansi;1.4 -Sort done for : org.scala-lang#jline;2.9.1 -Sort done for : org.scala-lang#scala-compiler;2.9.1 -Module descriptor is processed : org.scala-lang#scala-library;2.9.1 -Module descriptor is processed : org.scala-lang#jline;2.9.1 -Module descriptor is processed : org.fusesource.jansi#jansi;1.4 - resolved ivy file produced in /Users/ochafik/.ivy2/cache/resolved-org.scala-tools.sbt-boot-scala-1.0.xml -:: downloading artifacts :: - [NOT REQUIRED] org.scala-lang#scala-compiler;2.9.1!scala-compiler.jar - [NOT REQUIRED] org.scala-lang#scala-library;2.9.1!scala-library.jar - [NOT REQUIRED] org.scala-lang#jline;2.9.1!jline.jar - [NOT REQUIRED] org.fusesource.jansi#jansi;1.4!jansi.jar -:: resolution report :: resolve 155ms :: artifacts dl 3ms -Nbr of module to sort : 4 -Sort dependencies of : org.scala-lang#scala-compiler;2.9.1 / Number of dependencies = 2 -Sort dependencies of : org.scala-lang#scala-library;2.9.1 / Number of dependencies = 0 -Sort done for : org.scala-lang#scala-library;2.9.1 -Sort dependencies of : org.scala-lang#jline;2.9.1 / Number of dependencies = 1 -Sort dependencies of : org.fusesource.jansi#jansi;1.4 / Number of dependencies = 1 -Sort done for : org.fusesource.jansi#jansi;1.4 -Sort done for : org.scala-lang#jline;2.9.1 -Sort done for : org.scala-lang#scala-compiler;2.9.1 -Module descriptor is processed : org.scala-lang#scala-library;2.9.1 -Module descriptor is processed : org.scala-lang#jline;2.9.1 -Module descriptor is processed : org.fusesource.jansi#jansi;1.4 - report for org.scala-tools.sbt#boot-scala;1.0 default produced in /Users/ochafik/.ivy2/cache/org.scala-tools.sbt-boot-scala-default.xml - resolve done (155ms resolve - 3ms download) -:: retrieving :: org.scala-tools.sbt#boot-scala - checkUpToDate=true -no explicit confs given for retrieve, using ivy file: /Users/ochafik/.ivy2/cache/resolved-org.scala-tools.sbt-boot-scala-1.0.xml -using ivy parser to parse /Users/ochafik/.ivy2/cache/resolved-org.scala-tools.sbt-boot-scala-1.0.xml -post 1.3 ivy file: using exact as default matcher - confs: [default] - retrieving /Users/ochafik/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.9.1.jar - to /Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot/scala-2.9.1/lib/scala-library.jar - retrieving /Users/ochafik/.ivy2/cache/org.scala-lang/scala-compiler/jars/scala-compiler-2.9.1.jar - to /Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot/scala-2.9.1/lib/scala-compiler.jar - retrieving /Users/ochafik/.ivy2/cache/org.scala-lang/jline/jars/jline-2.9.1.jar - to /Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot/scala-2.9.1/lib/jline.jar - retrieving /Users/ochafik/.ivy2/cache/org.fusesource.jansi/jansi/jars/jansi-1.4.jar - to /Users/ochafik/github/nativelibs4java/libraries/OpenCL/ScalaCL/project/boot/scala-2.9.1/lib/jansi.jar - 4 artifacts copied, 0 already retrieved (19939kB/53ms) - retrieve done (53ms) diff --git a/libraries/ScalaCL/Collections/project/build.properties b/libraries/ScalaCL/Collections/project/build.properties deleted file mode 100644 index f2ccdfa37..000000000 --- a/libraries/ScalaCL/Collections/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.11.0 diff --git a/libraries/ScalaCL/Collections/sbazPackage b/libraries/ScalaCL/Collections/sbazPackage deleted file mode 100755 index 7f4f2f603..000000000 --- a/libraries/ScalaCL/Collections/sbazPackage +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -MVN_VERSION="`cat pom.xml | grep '\(.*\)<\/version>.*/\1/g'`" -SBAZ_VERSION_AUTO="`echo $MVN_VERSION | sed -e "s/-SNAPSHOT/-SNAPSHOT-\`date '+%Y%m%d'\`/g"`" -SBAZ_VERSION=${SBAZ_VERSION:-$SBAZ_VERSION_AUTO} -LINK_BASE="http://nativelibs4java.sourceforge.net/sbaz/scalacl/" -#LINK_BASE="http://ochafik.com/sbaz/scalacl/" - -SCALACL_HOME="`pwd`" - -echo "###################################################" -echo "# ScalaCL : " -echo "# Maven version = $MVN_VERSION" -echo "# sbaz version = $SBAZ_VERSION" -echo "###################################################" - -echo "# Building ScalaCL Collections" -mvn -Djarsigner.skip=false -Dstorepass=$KEYSTORE_PASS package -DskipTests - -cd ../Plugin -echo "# Building ScalaCL Compiler Plugin" -mvn -Djarsigner.skip=false -Dstorepass=$KEYSTORE_PASS package -DskipTests -cd $SCALACL_HOME - - -TEMP_OUT=target/sbaz_out -LIB_JAR_OUT=$TEMP_OUT/lib -PLUGIN_JAR_OUT=$TEMP_OUT/misc/scala-devel/plugins - -rm -fR $TEMP_OUT - -mkdir -p $LIB_JAR_OUT -mkdir -p $PLUGIN_JAR_OUT - -echo "# Copying libraries" -if [[ "$DONT_USE_SHADED" == "1" ]] ; then - export SBAZ_VERSION="$SBAZ_VERSION-devel" - NL4J_BASE="/Users/ochafik/.m2/repository/com/nativelibs4java" - cp target/scalacl-$MVN_VERSION.jar $LIB_JAR_OUT - cp $NL4J_BASE/bridj/0.5/bridj-5.jar $LIB_JAR_OUT - cp $NL4J_BASE/opencl4java-bridj/1.0.0-RC1/opencl4java-bridj-1.0.0-RC1.jar $LIB_JAR_OUT - cp $NL4J_BASE/javacl-core-bridj/1.0.0-RC1/javacl-core-bridj-1.0.0-RC1.jar $LIB_JAR_OUT - cp $NL4J_BASE/javacl-bridj/1.0.0-RC1/javacl-bridj-1.0.0-RC1.jar $LIB_JAR_OUT - cp $NL4J_BASE/libcl-bridj/1.0.0-RC1/libcl-bridj-1.0.0-RC1.jar $LIB_JAR_OUT ; -else - cp target/scalacl-$MVN_VERSION-shaded.jar $LIB_JAR_OUT ; -fi - -echo "# Copied the following libraries :" -ls -l $LIB_JAR_OUT - -echo "# Copying compiler plugin libraries" -cp ../Plugin/target/scalacl-compiler-plugin-$MVN_VERSION.jar $PLUGIN_JAR_OUT - -echo "# Packing for sbaz" -sbaz pack scalacl $TEMP_OUT \ - --linkbase $LINK_BASE \ - --version $SBAZ_VERSION \ - --outdir src/main/sbaz \ - --descfile ABOUT || ( echo "sbaz pack failed" && exit 1 ) - -mkdir -p src/main/sbaz - -sbaz remove scalacl -sbaz compact -#sbaz retract scalacl/$SBAZ_VERSION -if [[ "$DONT_SHARE" == "1" ]] ; then - echo "Not sharing the package (use SHARE=1 to share)" - echo src/main/sbaz/scalacl-$SBAZ_VERSION.sbp ; -else - sbaz share *.advert ; -fi -mv *.advert src/main/sbaz -open src/main/sbaz - -echo "Now please copy 'src/main/sbaz/scalacl-$SBAZ_VERSION.sbp' to '$LINK_BASE'" diff --git a/libraries/ScalaCL/Collections/scalacl.iml b/libraries/ScalaCL/Collections/scalacl.iml deleted file mode 100644 index 6fb8a6d1a..000000000 --- a/libraries/ScalaCL/Collections/scalacl.iml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Collections/scalacl.ipr b/libraries/ScalaCL/Collections/scalacl.ipr deleted file mode 100644 index 53b637d25..000000000 --- a/libraries/ScalaCL/Collections/scalacl.ipr +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Collections/scalacl.iws b/libraries/ScalaCL/Collections/scalacl.iws deleted file mode 100644 index cc658fdbc..000000000 --- a/libraries/ScalaCL/Collections/scalacl.iws +++ /dev/null @@ -1,1050 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Plugin DevKit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - - - - - - - 1294611912726 - 1294611912726 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Collections/scalacl2-bridj.iml b/libraries/ScalaCL/Collections/scalacl2-bridj.iml deleted file mode 100644 index ed1ca6525..000000000 --- a/libraries/ScalaCL/Collections/scalacl2-bridj.iml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Collections/src/main/resources/scalacl/impl/scan_kernel.cl b/libraries/ScalaCL/Collections/src/main/resources/scalacl/impl/scan_kernel.cl deleted file mode 100644 index fbb61b8c2..000000000 --- a/libraries/ScalaCL/Collections/src/main/resources/scalacl/impl/scan_kernel.cl +++ /dev/null @@ -1,422 +0,0 @@ -// -// File: scan_kernel.cl -// -// Abstract: This example shows how to perform an efficient parallel prefix sum (aka Scan) -// using OpenCL. Scan is a common data parallel primitive which can be used for -// variety of different operations -- this example uses local memory for storing -// partial sums and avoids memory bank conflicts on architectures which serialize -// memory operations that are serviced on the same memory bank by offsetting the -// loads and stores based on the size of the local group and the number of -// memory banks (see appropriate macro definition). As a result, this example -// requires that the local group size > 1. -// -// Version: <1.0> -// -// Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") -// in consideration of your agreement to the following terms, and your use, -// installation, modification or redistribution of this Apple software -// constitutes acceptance of these terms. If you do not agree with these -// terms, please do not use, install, modify or redistribute this Apple -// software. -// -// In consideration of your agreement to abide by the following terms, and -// subject to these terms, Apple grants you a personal, non - exclusive -// license, under Apple's copyrights in this original Apple software ( the -// "Apple Software" ), to use, reproduce, modify and redistribute the Apple -// Software, with or without modifications, in source and / or binary forms; -// provided that if you redistribute the Apple Software in its entirety and -// without modifications, you must retain this notice and the following text -// and disclaimers in all such redistributions of the Apple Software. Neither -// the name, trademarks, service marks or logos of Apple Inc. may be used to -// endorse or promote products derived from the Apple Software without specific -// prior written permission from Apple. Except as expressly stated in this -// notice, no other rights or licenses, express or implied, are granted by -// Apple herein, including but not limited to any patent rights that may be -// infringed by your derivative works or by other works in which the Apple -// Software may be incorporated. -// -// The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -// WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -// WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION -// ALONE OR IN COMBINATION WITH YOUR PRODUCTS. -// -// IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -// CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION -// AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER -// UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR -// OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Copyright ( C ) 2008 Apple Inc. All Rights Reserved. -// -//////////////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef DATA_TYPE -#define DATA_TYPE float -#endif - -#define MEMORY_BANK_COUNT (16) // Adjust to your architecture -#define LOG2_MEMORY_BANK_COUNT (4) // Set to log2(MEMORY_BANK_COUNT) -#define ELIMINATE_CONFLICTS (0) // Enable for slow address calculation, but zero bank conflicts - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -#if (ELIMINATE_CONFLICTS) -#define MEMORY_BANK_OFFSET(index) ((index) >> LOG2_MEMORY_BANK_COUNT + (index) >> (2*LOG2_MEMORY_BANK_COUNT)) -#else -#define MEMORY_BANK_OFFSET(index) ((index) >> LOG2_MEMORY_BANK_COUNT) -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -uint4 -GetAddressMapping(int index) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - uint2 global_index; - global_index.x = index + local_id; - global_index.y = global_index.x + group_size; - - uint2 local_index; - local_index.x = local_id; - local_index.y = local_id + group_size; - - return (uint4)(global_index.x, global_index.y, local_index.x, local_index.y); -} - -void -LoadLocalFromGlobal( - __local DATA_TYPE *shared_data, - __global const DATA_TYPE *input_data, - const uint4 address_pair, - const uint n) -{ - const uint global_index_a = address_pair.x; - const uint global_index_b = address_pair.y; - - const uint local_index_a = address_pair.z; - const uint local_index_b = address_pair.w; - - const uint bank_offset_a = MEMORY_BANK_OFFSET(local_index_a); - const uint bank_offset_b = MEMORY_BANK_OFFSET(local_index_b); - - shared_data[local_index_a + bank_offset_a] = input_data[global_index_a]; - shared_data[local_index_b + bank_offset_b] = input_data[global_index_b]; -} - -void -LoadLocalFromGlobalNonPowerOfTwo( - __local DATA_TYPE *shared_data, - __global const DATA_TYPE *input_data, - const uint4 address_pair, - const uint n) -{ - const uint global_index_a = address_pair.x; - const uint global_index_b = address_pair.y; - - const uint local_index_a = address_pair.z; - const uint local_index_b = address_pair.w; - - const uint bank_offset_a = MEMORY_BANK_OFFSET(local_index_a); - const uint bank_offset_b = MEMORY_BANK_OFFSET(local_index_b); - - shared_data[local_index_a + bank_offset_a] = input_data[global_index_a]; - shared_data[local_index_b + bank_offset_b] = (local_index_b < n) ? input_data[global_index_b] : 0; - - barrier(CLK_LOCAL_MEM_FENCE); -} - -void -StoreLocalToGlobal( - __global DATA_TYPE* output_data, - __local const DATA_TYPE* shared_data, - const uint4 address_pair, - const uint n) -{ - barrier(CLK_LOCAL_MEM_FENCE); - - const uint global_index_a = address_pair.x; - const uint global_index_b = address_pair.y; - - const uint local_index_a = address_pair.z; - const uint local_index_b = address_pair.w; - - const uint bank_offset_a = MEMORY_BANK_OFFSET(local_index_a); - const uint bank_offset_b = MEMORY_BANK_OFFSET(local_index_b); - - output_data[global_index_a] = shared_data[local_index_a + bank_offset_a]; - output_data[global_index_b] = shared_data[local_index_b + bank_offset_b]; -} - -void -StoreLocalToGlobalNonPowerOfTwo( - __global DATA_TYPE* output_data, - __local const DATA_TYPE* shared_data, - const uint4 address_pair, - const uint n) -{ - barrier(CLK_LOCAL_MEM_FENCE); - - const uint global_index_a = address_pair.x; - const uint global_index_b = address_pair.y; - - const uint local_index_a = address_pair.z; - const uint local_index_b = address_pair.w; - - const uint bank_offset_a = MEMORY_BANK_OFFSET(local_index_a); - const uint bank_offset_b = MEMORY_BANK_OFFSET(local_index_b); - - output_data[global_index_a] = shared_data[local_index_a + bank_offset_a]; - if(local_index_b < n) - output_data[global_index_b] = shared_data[local_index_b + bank_offset_b]; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -void -ClearLastElement( - __local DATA_TYPE* shared_data, - int group_index) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - if (local_id == 0) - { - int index = (group_size << 1) - 1; - index += MEMORY_BANK_OFFSET(index); - shared_data[index] = 0; - } -} - -void -ClearLastElementStoreSum( - __local DATA_TYPE* shared_data, - __global DATA_TYPE *partial_sums, - int group_index) -{ - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - const uint local_id = get_local_id(0); - - if (local_id == 0) - { - int index = (group_size << 1) - 1; - index += MEMORY_BANK_OFFSET(index); - partial_sums[group_index] = shared_data[index]; - shared_data[index] = 0; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -uint -BuildPartialSum( - __local DATA_TYPE *shared_data) -{ - const uint local_id = get_local_id(0); - const uint group_size = get_local_size(0); - const uint two = 2; - uint stride = 1; - - for (uint j = group_size; j > 0; j >>= 1) - { - barrier(CLK_LOCAL_MEM_FENCE); - - if (local_id < j) - { - int i = mul24(mul24(two, stride), local_id); - - uint local_index_a = i + stride - 1; - uint local_index_b = local_index_a + stride; - - local_index_a += MEMORY_BANK_OFFSET(local_index_a); - local_index_b += MEMORY_BANK_OFFSET(local_index_b); - - shared_data[local_index_b] += shared_data[local_index_a]; - } - - stride *= two; - } - - return stride; -} - -void -ScanRootToLeaves( - __local DATA_TYPE *shared_data, - uint stride) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - const uint two = 2; - - for (uint j = 1; j <= group_size; j *= two) - { - stride >>= 1; - - barrier(CLK_LOCAL_MEM_FENCE); - - if (local_id < j) - { - int i = mul24(mul24(two, stride), local_id); - - uint local_index_a = i + stride - 1; - uint local_index_b = local_index_a + stride; - - local_index_a += MEMORY_BANK_OFFSET(local_index_a); - local_index_b += MEMORY_BANK_OFFSET(local_index_b); - - DATA_TYPE t = shared_data[local_index_a]; - shared_data[local_index_a] = shared_data[local_index_b]; - shared_data[local_index_b] += t; - } - } -} - -void -PreScanGroup( - __local DATA_TYPE *shared_data, - int group_index) -{ - const uint group_id = get_global_id(0) / get_local_size(0); - - int stride = BuildPartialSum(shared_data); - ClearLastElement(shared_data, (group_index == 0) ? group_id : group_index); - ScanRootToLeaves(shared_data, stride); -} - -void -PreScanGroupStoreSum( - __global DATA_TYPE *partial_sums, - __local DATA_TYPE *shared_data, - int group_index) -{ - const uint group_id = get_global_id(0) / get_local_size(0); - - int stride = BuildPartialSum(shared_data); - ClearLastElementStoreSum(shared_data, partial_sums, (group_index == 0) ? group_id : group_index); - ScanRootToLeaves(shared_data, stride); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -__kernel void -PreScanKernel( - __global DATA_TYPE *output_data, - __global const DATA_TYPE *input_data, - __local DATA_TYPE* shared_data, - const uint group_index, - const uint base_index, - const uint n) -{ - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - uint local_index = (base_index == 0) ? mul24(group_id, (group_size << 1)) : base_index; - uint4 address_pair = GetAddressMapping(local_index); - - LoadLocalFromGlobal(shared_data, input_data, address_pair, n); - PreScanGroup(shared_data, group_index); - StoreLocalToGlobal(output_data, shared_data, address_pair, n); -} - -__kernel void -PreScanStoreSumKernel( - __global DATA_TYPE *output_data, - __global const DATA_TYPE *input_data, - __global DATA_TYPE *partial_sums, - __local DATA_TYPE* shared_data, - const uint group_index, - const uint base_index, - const uint n) -{ - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - uint local_index = (base_index == 0) ? mul24(group_id, (group_size << 1)) : base_index; - uint4 address_pair = GetAddressMapping(local_index); - - LoadLocalFromGlobal(shared_data, input_data, address_pair, n); - PreScanGroupStoreSum(partial_sums, shared_data, group_index); - StoreLocalToGlobal(output_data, shared_data, address_pair, n); -} - -__kernel void -PreScanStoreSumNonPowerOfTwoKernel( - __global DATA_TYPE *output_data, - __global const DATA_TYPE *input_data, - __global DATA_TYPE *partial_sums, - __local DATA_TYPE* shared_data, - const uint group_index, - const uint base_index, - const uint n) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - uint local_index = (base_index == 0) ? mul24(group_id, (group_size << 1)) : base_index; - uint4 address_pair = GetAddressMapping(local_index); - - LoadLocalFromGlobalNonPowerOfTwo(shared_data, input_data, address_pair, n); - PreScanGroupStoreSum(partial_sums, shared_data, group_index); - StoreLocalToGlobalNonPowerOfTwo(output_data, shared_data, address_pair, n); -} - -__kernel void -PreScanNonPowerOfTwoKernel( - __global DATA_TYPE *output_data, - __global const DATA_TYPE *input_data, - __local DATA_TYPE* shared_data, - const uint group_index, - const uint base_index, - const uint n) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - uint local_index = (base_index == 0) ? mul24(group_id, (group_size << 1)) : base_index; - uint4 address_pair = GetAddressMapping(local_index); - - LoadLocalFromGlobalNonPowerOfTwo(shared_data, input_data, address_pair, n); - PreScanGroup(shared_data, group_index); - StoreLocalToGlobalNonPowerOfTwo(output_data, shared_data, address_pair, n); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -__kernel void UniformAddKernel( - __global DATA_TYPE *output_data, - __global DATA_TYPE *input_data, - __local DATA_TYPE *shared_data, - const uint group_offset, - const uint base_index, - const uint n) -{ - const uint local_id = get_local_id(0); - const uint group_id = get_global_id(0) / get_local_size(0); - const uint group_size = get_local_size(0); - - if (local_id == 0) - shared_data[0] = input_data[group_id + group_offset]; - - barrier(CLK_LOCAL_MEM_FENCE); - - uint address = mul24(group_id, (group_size << 1)) + base_index + local_id; - - output_data[address] += shared_data[0]; - if( (local_id + group_size) < n) - output_data[address + group_size] += shared_data[0]; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - diff --git a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.advert b/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.advert deleted file mode 100644 index 3264f1a50..000000000 --- a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.advert +++ /dev/null @@ -1,32 +0,0 @@ - - scalacl0.3-SNAPSHOT-20120110 - ScalaCL makes Scala faster and GPGPU trivial. - It features : - - a compiler plugin that optimizes regular Scala code without adding any dependency - - a library of OpenCL-backed collections that execute Scala code (map, filter...) on GPUs transparently, thanks to the compiler plugin - -Website: - http://scalacl.googlecode.com/ - -Author: - Olivier Chafik <olivier.chafik@gmail.com> - http://ochafik.free.fr/blog/ - http://twitter.com/ochafik - -Current features : -- CLArray[T], CLRange (create with CLArray(1, 2, 3...), new CLArray[Int](n), Seq.cl or Seq.toCLArray) with accelerated .map, .filter, .zip and .zipWithIndex operations (when the inline closures are convertible by the compiler plugin) - -> For more details, see http://code.google.com/p/scalacl/wiki/CLConvertibleLanguageSubset -- Transformation of regular Scala operations on Array[T] and inline ranges : .map, .foreach, .reduce/fold/scan|Left/Right, .sum... - -> For more details, see http://code.google.com/p/scalacl/wiki/ScalaCLPlugin - -Planned features : -- better translation of Scala functions to OpenCL kernels to support more Scala constructs -- rewrite of operation streams into loops when functions are side-effect-free (a.map(f1).map(f2).filter(f3).takeWhile(f4)...) -- auto-vectorization of OpenCL code - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-0.3-SNAPSHOT-20120110.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.sbp b/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.sbp deleted file mode 100644 index 008d8d025..000000000 Binary files a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120110.sbp and /dev/null differ diff --git a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.advert b/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.advert deleted file mode 100644 index 946fa3011..000000000 --- a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.advert +++ /dev/null @@ -1,32 +0,0 @@ - - scalacl0.3-SNAPSHOT-20120114 - ScalaCL makes Scala faster and GPGPU trivial. - It features : - - a compiler plugin that optimizes regular Scala code without adding any dependency - - a library of OpenCL-backed collections that execute Scala code (map, filter...) on GPUs transparently, thanks to the compiler plugin - -Website: - http://scalacl.googlecode.com/ - -Author: - Olivier Chafik <olivier.chafik@gmail.com> - http://ochafik.free.fr/blog/ - http://twitter.com/ochafik - -Current features : -- CLArray[T], CLRange (create with CLArray(1, 2, 3...), new CLArray[Int](n), Seq.cl or Seq.toCLArray) with accelerated .map, .filter, .zip and .zipWithIndex operations (when the inline closures are convertible by the compiler plugin) - -> For more details, see http://code.google.com/p/scalacl/wiki/CLConvertibleLanguageSubset -- Transformation of regular Scala operations on Array[T] and inline ranges : .map, .foreach, .reduce/fold/scan|Left/Right, .sum... - -> For more details, see http://code.google.com/p/scalacl/wiki/ScalaCLPlugin - -Planned features : -- better translation of Scala functions to OpenCL kernels to support more Scala constructs -- rewrite of operation streams into loops when functions are side-effect-free (a.map(f1).map(f2).filter(f3).takeWhile(f4)...) -- auto-vectorization of OpenCL code - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-0.3-SNAPSHOT-20120114.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.sbp b/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.sbp deleted file mode 100644 index 2bf748815..000000000 Binary files a/libraries/ScalaCL/Collections/src/main/sbaz/scalacl-0.3-SNAPSHOT-20120114.sbp and /dev/null differ diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLArray.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLArray.scala deleted file mode 100644 index 0d06c2792..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLArray.scala +++ /dev/null @@ -1,337 +0,0 @@ -package scalacl - -import impl._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ -import com.nativelibs4java.opencl.util._ -import scala.collection.IndexedSeqLike -import scala.collection.mutable.{ArrayBuffer, IndexedSeqOptimized, Builder} -import scala.collection.generic._ -import scala.annotation.unchecked.uncheckedVariance - -object CLArray { - val MaxReductionSize = Option(System.getenv("SCALACL_MAX_REDUCTION_SIZE")).getOrElse("32").toInt - - lazy val indexCode = new CLSimpleCode(""" - __kernel void indexCode(int size, __global int* out) { - int i = get_global_id(0); - if (i >= size) - return; - - out[i] = i; - } - """) - - def apply[A](values: A*)(implicit context: Context, dataIO: CLDataIO[A]) = - fromSeq(values) - - def fromSeq[A](values: Seq[A])(implicit context: Context, dataIO: CLDataIO[A]) = { - implicit val t = dataIO.t - val valuesArray = values.toArray - val length = valuesArray.length - if (t.erasure.isPrimitive) { - new CLArray[A](length, if (length == 0) null else Array(new CLGuardedBuffer[A](length).update(valuesArray).asInstanceOf[CLGuardedBuffer[Any]])) - } else { - val a = new CLArray[A](length) - // TODO find a faster way to handle initial copy of complex types !!! - for (i <- 0 until length) - dataIO.store(values(i), a.buffers, 0) - - a - } - } - - def newBuilder[A](implicit context: Context, dataIO: CLDataIO[A]): Builder[A, CLArray[A]] = - new ArrayBuffer[A].mapResult(b => fromSeq(b)) -} -import CLFilteredArray.{PresenceType, toBool, toPresence} - -trait CLWithForeach[A, +Repr <: CLCollectionLike[A, Repr] with CLCollection[A]] { - //self => - this: Repr => - - override def foreach[U](f: A => U): Unit = { - f match { - case clf: CLRunnable if !clf.isOnlyInScalaSpace && !useScalaFunctions => - clf.run( - args = Array(this), - reads = Array(this), // TODO handle captured arrays - writes = Array() // TODO handle captured arrays - )( - dims = Array(length) - )(context) - case _ => - foreachFallback(f) - } - } - protected def foreachFallback[U](f: A => U): Unit = { - executingScalaFallbackOperation("foreachFallback") - for (i <- 0 until length) - f(this(i)) - } -} -trait MappableToCLArray[A, +Repr <: CLCollectionLike[A, Repr] with CLCollection[A]] -extends CLWithForeach[A, Repr] -{ - //self => - this: Repr => - //this: CLIndexedSeq[A] with CLIndexedSeqLike[A, Repr] => //with WithContext with CLEventBoundContainer => // CLIndexedSeqLike[A, Repr] => - - def length: Int - protected def mapFallback[B](f: A => B, out: CLArray[B]): Unit - override def map[B, That](f: A => B, out: That)(implicit bf: CanBuildFrom[Repr, B, That]): That = { - if (!bf.isInstanceOf[CLCanBuildFrom[Repr, B, That]]) - return toSeq.map(f)(bf.asInstanceOf[CanBuildFrom[Seq[A], B, That]]) - - val result = reuse(out, new CLArray[B](length)(context, bf.dataIO)) - - f match { - case clf: CLRunnable if !clf.isOnlyInScalaSpace && !useScalaFunctions => - clf.run( - args = Array(this, result), - reads = Array(this), - writes = Array(result) - )( - dims = Array(length) - )(context) - case _ => - mapFallback(f, result) - } - result.asInstanceOf[That] - } -} - -/** - * Array-like collection stored in OpenCL buffers, which uses CLFunction in map, filter operations.
      - * CLArray is a mutable yet asynchronous structure : - * $ - `a.map(f).map(g)` returns an unfinished CLArray - * $ - New reads wait for past writes to finish - * $ - New writes wait for past reads and writes to finish - */ -class CLArray[A]( - val length: Int, - protected[scalacl] val buffers: Array[CLGuardedBuffer[Any]] -)( - implicit val context: Context, - val dataIO: CLDataIO[A] -) - extends IndexedSeqOptimized[A, CLIndexedSeq[A]] - with CopiableToCLArray[A] - with CLIndexedSeq[A]//IndexedSeq[A] - with GenericTraversableTemplate[A, CLArray] - with CLIndexedSeqLike[A, CLIndexedSeq[A]] - with MappableToCLArray[A, CLIndexedSeq[A]] -{ - def this(length: Int)(implicit context: Context, dataIO: CLDataIO[A]) = - this(length, if (length > 0) dataIO.createBuffers(length) else null) - - override def companion: GenericCompanion[CLArray] = new SeqFactory[CLArray] { - def newBuilder[AA]: Builder[AA, CLArray[AA]] = - CLArray.newBuilder[AA](context, dataIO.asInstanceOf[CLDataIO[AA]]) - } - - override def release = if (length > 0) buffers.foreach(_.release) - - override def eventBoundComponents = if (length > 0) buffers else Seq() - - type Repr = CLIndexedSeq[A] - - assert(length == 0 || buffers.forall(_.buffer.getElementCount == length)) - - import CLArray._ - import dataIO.t - - override def newBuilder: Builder[A, CLArray[A]] = CLArray.newBuilder[A] - - override def toArray = if (length > 0) dataIO.toArray(buffers) else Array[A]() - override def copyToArray[B >: A](out: Array[B], start: Int, len: Int): Unit = if (length > 0) { - dataIO.copyToArray(buffers, out, start, len) - } - - override def toCLArray = this - - override def apply(index: Int): A = - if (length > 0) - dataIO.extract(buffers, index).get - else - throw new ArrayIndexOutOfBoundsException("Empty CLArray !") - - /** - * Mutate a specific element of the array - */ - def update(index: Int, value: A): Unit = - if (length > 0) - dataIO.store(value, buffers, index) - else - throw new ArrayIndexOutOfBoundsException("Empty CLArray !") - - /** - * Mutate all items of this array with a CLFunction - */ - def update(f: A => A): CLArray[A] = - map(f, this)(new CLCanBuildFrom[Repr, A, CLArray[A]] { - override def dataIO = CLArray.this.dataIO - override def apply() = newBuilder.asInstanceOf[Builder[A, CLArray[A]]] - override def apply(from: Repr) = newBuilder.asInstanceOf[Builder[A, CLArray[A]]] - }) - - override def zip$into[A1 >: A, B, That](that: Iterable[B], out: That)(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = { - if (!that.isInstanceOf[CLCollection[_]]) - super.zip(that) - else { - val thatArray = that.asInstanceOf[CLCollection[B]].toCLArray - - val result = reuse(out, new CLArray[(A1, B)](length)(context, bf.dataIO)) - (buffers ++ thatArray.buffers).zip(result.buffers).map(p => p._1.copyTo(p._2)) - result.asInstanceOf[That] - } - } - - def zip$ShareBuffers[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = - zip$into[A1, B, That](that, new CLArray[(A1, B)](length, buffers ++ that.asInstanceOf[CLArray[B]].buffers)(context, bf.dataIO).asInstanceOf[That]) - - override def zipWithIndex$into[A1 >: A, That](out: That)(implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = { - val result = reuse(out, new CLArray[(A1, Int)](length)(context, bf.dataIO)) - val indexBuffer = result.buffers.last.asInstanceOf[CLGuardedBuffer[Int]] - buffers.zip(result.buffers.take(buffers.size)).map(p => p._1.copyTo(p._2)) - - val kernel = indexCode.getKernel(context) - kernel.synchronized { - kernel.setArgs(length.asInstanceOf[Object], indexBuffer.buffer) - CLEventBound.syncBlock(Array(), Array(indexBuffer), evts => { - kernel.enqueueNDRange(context.queue, Array(length), evts:_*) - }) - } - result.asInstanceOf[That] - } - - def zipWithIndex$ShareBuffers[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = - zipWithIndex$into[A1, That](new CLArray[(A1, Int)](length, buffers ++ Array(new CLGuardedBuffer[Int](length).asInstanceOf[CLGuardedBuffer[Any]]))(context, bf.dataIO).asInstanceOf[That]) - - - protected def reduce[B >: A](op: ReductionUtils.Operation): B = { - assert(buffers.length == 1) - val buffer = buffers.head.asInstanceOf[CLGuardedBuffer[A]] - val (reductionType, channels) = dataIO.reductionType - val reductor = ReductionUtils.createReductor(context, op, reductionType, channels).asInstanceOf[ReductionUtils.Reductor[A]] - - val reduction = org.bridj.Pointer.allocate(dataIO.pointerIO) - CLEventBound.syncBlock(Array(buffer), Array(), evts => { - reductor.reduce(context.queue, buffer.buffer, length: Long, reduction, MaxReductionSize, evts: _*).waitFor - null - }) - reduction.get - } - - protected def isDefaultOrdering(cmp: Ordering[_]) = - cmp == Boolean || - cmp == Byte || - cmp == Char || - cmp == Double || - cmp == Float || - cmp == Int || - cmp == Long || - cmp == Short - - protected def isDefaultNumeric(num: Numeric[_]) = { - import Numeric._ - - num == ByteIsIntegral || - num == CharIsIntegral || - num == DoubleIsFractional || - num == FloatIsFractional || - num == IntIsIntegral || - num == LongIsIntegral || - num == ShortIsIntegral - } - - /** - * Perform parallel sum of this array's values, if the implicit numeric is the default one (otherwise, perform slow sum that reads data back from OpenCL to Scala memory) - */ - override def sum[B >: A](implicit num: Numeric[B]): B = - if (isDefaultNumeric(num)) - reduce[B](ReductionUtils.Operation.Add) - else - super.sum[B] - - /** - * Perform parallel product of this array's values, if the implicit numeric is the default one (otherwise, perform slow product that reads data back from OpenCL to Scala memory) - */ - override def product[B >: A](implicit num: Numeric[B]): B = - if (isDefaultNumeric(num)) - reduce[B](ReductionUtils.Operation.Multiply) - else - super.product[B] - - /** - * Perform parallel min of this array's values, if the implicit ordering is the default one (otherwise, perform slow min that reads data back from OpenCL to Scala memory) - */ - override def min[B >: A](implicit cmp: Ordering[B]): A = - if (isDefaultOrdering(cmp)) - reduce[A](ReductionUtils.Operation.Min) - else - super.min[B] - - /** - * Perform parallel max of this array's values, if the implicit ordering is the default one (otherwise, perform slow max that reads data back from OpenCL to Scala memory) - */ - override def max[B >: A](implicit cmp: Ordering[B]): A = - if (isDefaultOrdering(cmp)) - reduce[A](ReductionUtils.Operation.Max) - else - super.max[B] - - /** - * Clone this CLArray
      - * TODO copy-on-write cloning - */ - override def clone: CLArray[A] = - new CLArray[A](length, if (length > 0) buffers.map(_.clone) else null) // TODO map in parallel - - override def size = length - - protected override def mapFallback[B](f: A => B, result: CLArray[B]) = { - executingScalaFallbackOperation("mapFallback") - for (i <- 0 until length) - result(i) = f(this(i)) - } - - //override def foreach[U](f: A => U): Unit = - // toArray(dataIO.t) foreach f - - override def filter(p: A => Boolean) = - filter(p, new CLFilteredArray[A](length))//.toCLArray - - override def filterFallback[That <: CLCollection[A]](p: A => Boolean, out: That)(implicit ff: CLCanFilterFrom[Repr, A, That]) = { - import scala.concurrent.ops._ - executingScalaFallbackOperation("filterFallback") - - out match { - case filteredOut: CLFilteredArray[A] => - val copy = if (filteredOut.array == this) null else future { - copyTo(filteredOut.array) - } - - val presenceArr = new Array[PresenceType](length) - for (i <- 0 until length) { - val value = this(i) - presenceArr(i) = toPresence(p(value)) - } - filteredOut.presence.update(presenceArr) - Option(copy).foreach(_()) - } - } - - def copyTo(other: CLArray[A]) = { - import scala.concurrent.ops._ - - assert(length == other.length) - if (length > 0) { - assert(buffers.length == other.buffers.length) - for ((from, to) <- buffers.zip(other.buffers)) - from.copyTo(to) - } - } -} - diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLCollection.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLCollection.scala deleted file mode 100644 index 591a58cb4..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLCollection.scala +++ /dev/null @@ -1,139 +0,0 @@ -package scalacl - -import impl._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ -import scala.collection._ -import scala.collection.mutable.Builder -import scala.collection.generic._ - -trait WithContext { - def context: Context - -} - -object CLCollection extends SeqFactory[CLCollection] { - implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, CLCollection[A]] = new GenericCanBuildFrom[A] - def newBuilder[A]: Builder[A, CLCollection[A]] = error("Not implemented") // TODO -} - -trait CLCollection[A] -extends Seq[A] - with GenericTraversableTemplate[A, CLCollection] - with CLCollectionLike[A, CLCollection[A]] -{ - override def companion: GenericCompanion[CLCollection] = CLCollection -} - -trait CLCollectionLike[A, +Repr] - extends WithContext - with CLEventBoundContainer - //with Traversable[A] - with IterableLike[A, Repr] -{ - //this: Repr => - self => - - def release: Unit - - def toArray: Array[A] = toCLArray.toArray - override def toSeq = toArray.toSeq - override def toSet[B >: A] = toArray.toSet[B] - override def toIndexedSeq[B >: A] = toArray.toIndexedSeq[B] - - override def copyToArray[B >: A](a: Array[B], start: Int, len: Int): Unit = toCLArray.copyToArray(a, start, len) - override def toArray[B >: A](implicit b: ClassManifest[B]) = { - val out = new Array[B](size) - copyToArray(out, 0, size) - out - } - - def toCLArray: CLArray[A] - - override def toString = getClass.getSimpleName + "(" + toArray.mkString(", ") + ")" - - def zip$into[A1 >: A, B, That](that: Iterable[B], out: That)(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = - toCLArray.zip$into[A1, B, That](that, out)(bf.asInstanceOf[CanBuildFrom[CLIndexedSeq[A],(A1, B),That]]) - - def zipWithIndex$into[A1 >: A, That](out: That)(implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = - toCLArray.zipWithIndex$into[A1, That](out)(bf.asInstanceOf[CanBuildFrom[CLIndexedSeq[A],(A1, Int),That]]) - - override def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = - zip$into[A1, B, That](that, null.asInstanceOf[That])(bf) - - override def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = - zipWithIndex$into[A1, That](null.asInstanceOf[That])(bf) - - def zip$shareBuffers[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = - toCLArray.zip$shareBuffers[A1, B, That](that)(bf.asInstanceOf[CanBuildFrom[CLIndexedSeq[A],(A1, B),That]]) - - def zipWithIndex$shareBuffers[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = - toCLArray.zipWithIndex$shareBuffers[A1, That](bf.asInstanceOf[CanBuildFrom[CLIndexedSeq[A],(A1, Int),That]]) - - def map[B, That](f: A => B, out: That)(implicit bf: CanBuildFrom[Repr, B, That]): That - - override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = - map(f, null.asInstanceOf[That]) - - protected def filterFallback[That <: CLCollection[A]](p: A => Boolean, out: That)(implicit ff: CLCanFilterFrom[Repr, A, That]): Unit - - //def filter[That](p: A => Boolean, out: That)(implicit ff: CLCanFilterFrom[Repr, A, That]): That = { - def filter[That <: CLCollection[A]](p: A => Boolean, out: That)(implicit ff: CLCanFilterFrom[Repr, A, That]): That = { - val result = reuse(out, ff.newFilterResult(this.asInstanceOf[Repr]))//new CLFilteredArray[A](length)) - - p match { - case clf: CLRunnable if !clf.isOnlyInScalaSpace && !useScalaFunctions => - val filteredOut = result.asInstanceOf[CLFilteredArray[A]] - val valuesOut = filteredOut.array - val presenceOut = filteredOut.presence - val valuesIn = (this: Any) match { - case r: CLRange => - r.asInstanceOf[CopiableToCLArray[A]] - case a: CLArray[A] => - a - case fa: CLFilteredArray[A] => - fa.array - } - valuesIn.copyTo(valuesOut) - clf.run( - args = Array(this, presenceOut), - reads = Array(this), - writes = Array(result, presenceOut) - )( - dims = Array(ff.rawLength(this.asInstanceOf[Repr])) - )(ff.context) - case _ => - filterFallback(p, result) - } - result - } -} - -object CLIndexedSeq extends SeqFactory[CLIndexedSeq] { - implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, CLIndexedSeq[A]] = new GenericCanBuildFrom[A] - def newBuilder[A]: Builder[A, CLIndexedSeq[A]] = error("Not implemented") // TODO -} - - -trait CLIndexedSeq[A] -extends CLCollection[A] - with IndexedSeq[A] - with GenericTraversableTemplate[A, CLIndexedSeq] - with CLIndexedSeqLike[A, CLIndexedSeq[A]] -{ - //protected override def newBuilder: Builder[A, CLIndexedSeq[A]] - override def companion: GenericCompanion[CLIndexedSeq] = CLIndexedSeq -} - -trait CLIndexedSeqLike[A, +Repr] -extends CLCollectionLike[A, Repr] - with IndexedSeqLike[A, Repr] -{ self => - //self => - //this: Repr => - //this: Repr with CLIndexedSeq[A] =>//Repr => - - //def apply(index: Int): A - //def update(index: Int, value: A): Unit -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLFilteredArray.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLFilteredArray.scala deleted file mode 100644 index 949e95a67..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLFilteredArray.scala +++ /dev/null @@ -1,199 +0,0 @@ -package scalacl - -import impl._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ -import scala.collection.IndexedSeqLike -import scala.collection.mutable.Builder -import scala.collection.generic._ - -import com.nativelibs4java.opencl._ -import org.bridj.Pointer -import org.bridj.Pointer._ -import scala.collection.JavaConversions._ - -object CLFilteredArray { - def newBuilder[A](implicit context: Context, dataIO: CLDataIO[A]): Builder[A, CLFilteredArray[A]] = - error("Not implemented") // TODO - - /* - type PresenceType = Boolean - val presenceCLType = "char" - @inline def toBool(p: PresenceType) = p - @inline def toPresence(b: Boolean) = b - //*/ - //* - type PresenceType = Int - val presenceCLType = "int" - @inline def toBool(p: PresenceType) = p != 0 - @inline def toPresence(b: Boolean) = if (b) 1 else 0 - //*/ -} -import CLFilteredArray.{PresenceType, toBool, toPresence} - -class CLFilteredArray[A]( - protected[scalacl] val array: CLArray[A], - protected[scalacl] val presence: CLGuardedBuffer[PresenceType] -)( - implicit val context: Context, - val dataIO: CLDataIO[A] -) -extends IndexedSeq[A] - with GenericTraversableTemplate[A, CLFilteredArray] - with CLIndexedSeq[A] - //with IndexedSeqLike[A, CLFilteredArray[A]] - with CLIndexedSeqLike[A, CLFilteredArray[A]] - with CLWithForeach[A, CLFilteredArray[A]] -{ - def this(array: CLArray[A])(implicit context: Context, dataIO: CLDataIO[A]) = - this(array, if (array.length > 0) new CLGuardedBuffer[PresenceType](array.length + 1) else null) - - def this(length: Int)(implicit context: Context, dataIO: CLDataIO[A]) = - this(new CLArray[A](length)) - - def this(length: Int, presence: CLGuardedBuffer[PresenceType])(implicit context: Context, dataIO: CLDataIO[A]) = - this(new CLArray[A](length), presence) - - assert(presence.size == array.length + 1) - - override def companion: GenericCompanion[CLFilteredArray] = new SeqFactory[CLFilteredArray] { - def newBuilder[AA]: Builder[AA, CLFilteredArray[AA]] = - CLFilteredArray.newBuilder[AA](context, dataIO.asInstanceOf[CLDataIO[AA]]) // TODO fix this hack ! - } - override def eventBoundComponents = array.eventBoundComponents ++ (if (presence == null) Seq() else Seq(presence)) - - import array._ - - override def release = { - array.release - if (presence != null) - presence.release - } - - override def length = sizeFuture.get - protected def sizeFuture = { - if (presence == null) - new CLInstantFuture(0) - else { - val ps = updatedPresencePrefixSum - ps(array.length) // presence prefix sum buffer is of length array.length + 1 - } - } - -// assert(buffers.forall(_.buffer.getElementCount == length)) - assert(array != null) - assert(array.length == 0 || presence != null) - - override def newBuilder = CLFilteredArray.newBuilder[A] - - //lazy val buffersList = buffers.toList - lazy val presencePrefixSum = if (presence == null) null else new CLGuardedBuffer[Int](array.length + 1) - - override def clone = - new CLFilteredArray[A](array.clone, if (presence == null) null else presence.clone) - - def apply(index: Int) = { - // TODO: find some faster way to run this in non-OpenCL mode : - toCLArray.apply(index) - } - def update(index: Int, value: A) = { - // TODO: make this faster - toCLArray.update(index, value) - } - - def toCLArray: CLArray[A] = { - val prefixSum = updatedPresencePrefixSum - val size = this.size - //println("SIZE = " + size) - //println("presence = " + presence.toArray.toSeq) - //println("updatedPresencePrefixSum = " + updatedPresencePrefixSum.toArray.toSeq) - new CLArray[A](size, if (size == 0) null else buffers.map(b => { - val out = new CLGuardedBuffer[Any](size)(context, b.dataIO) - PrefixSum.copyPrefixed(size, prefixSum, b, out)(b.t, context) - out - })) - } - - var prefixSumUpToDate = false - def updatedPresencePrefixSum = this.synchronized { - if (!prefixSumUpToDate) { - if (presence != null) - //PrefixSum.prefixSumByte(presence, presencePrefixSum) - PrefixSum.prefixSumInt(presence, presencePrefixSum) - prefixSumUpToDate = true - } - presencePrefixSum - } - - override def sum[B >: A](implicit num: Numeric[B]): B = - toCLArray.sum[B] // TODO ! - - def map[B, That](f: A => B, out: That)(implicit bf: CanBuildFrom[CLFilteredArray[A], B, That]): That = { - if (!bf.isInstanceOf[CLCanBuildFrom[Repr, B, That]]) - return toSeq.map(f)(bf.asInstanceOf[CanBuildFrom[Seq[A], B, That]]) - - implicit val dataIO = bf.dataIO - val result = reuse(out, new CLFilteredArray[B](array.length, if (presence == null) null else presence.clone)) - - if (presence != null) - f match { - case clf: CLRunnable if !clf.isOnlyInScalaSpace && !useScalaFunctions => - clf.run( - args = Array(this, result), - reads = Array(this), - writes = Array(result) - )( - dims = Array(array.length) - ) - case _ => - mapFallback(f, result) - } - result.asInstanceOf[That] - } - - protected def mapFallback[B](f: A => B, result: CLFilteredArray[B]): Unit = { - import scala.concurrent.ops._ - executingScalaFallbackOperation("mapFallback") - - val copyPres = if (result == this) null else future { - presence.copyTo(result.presence) - } - val presenceArr = presence.toArray - for (i <- 0 until length) { - if (toBool(presenceArr(i))) - result.array(i) = f(array(i)) - } - Option(copyPres).foreach(_()) - } - override def filterFallback[That <: CLCollection[A]](p: A => Boolean, out: That)(implicit ff: CLCanFilterFrom[CLFilteredArray[A], A, That]) = { - import scala.concurrent.ops._ - executingScalaFallbackOperation("mapFallback") - if (presence != null) - out match { - case filteredOut: CLFilteredArray[A] => - val copy = if (filteredOut == this) null else future { - array.copyTo(filteredOut.array) - } - val presenceArr = presence.toArray - for (i <- 0 until length) { - if (toBool(presenceArr(i))) { - val value = array(i) - if (!p(value)) - presenceArr(i) = toPresence(false) - } - } - filteredOut.presence.update(presenceArr) - Option(copy).foreach(_()) - } - } - - protected override def foreachFallback[U](f: A => U): Unit = if (presence != null) { - executingScalaFallbackOperation("foreachFallback") - val presenceArr = presence.toArray - for (i <- 0 until length) { - if (toBool(presenceArr(i))) - f(array(i)) - } - } -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLRange.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLRange.scala deleted file mode 100644 index 2db090410..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/CLRange.scala +++ /dev/null @@ -1,144 +0,0 @@ -package scalacl - -import impl._ -import scala.collection.IndexedSeqLike -import scala.collection.generic.CanBuildFrom - - -object CLRange { - def convertToRange(buf: CLGuardedBuffer[Int]): Range = { - val Array(from, to, by, inclusive) = buf.toArray - if (inclusive == 0) - from until to by by - else - from to to by by - } - lazy val toCLArrayCode = new CLSimpleCode(""" - __kernel void toCLArray(int size, __global const int* range, __global int* out) { - int i = get_global_id(0); - if (i >= size) - return; - - // from, to, by, inclusive - int from = range[0], by = range[2]; - out[i] = from + by * i; - } - """) - def copyToCLArray(range: CLGuardedBuffer[Int], output: CLGuardedBuffer[Int])(implicit context: Context) = { - val size = output.buffer.getElementCount.toInt - val kernel = toCLArrayCode.getKernel(context) - val globalSizes = Array(size) - kernel.synchronized { - kernel.setArgs(size.asInstanceOf[Object], range.buffer, output.buffer) - CLEventBound.syncBlock(Array(range), Array(output), evts => { - kernel.enqueueNDRange(context.queue, globalSizes, evts:_*) - }) - } - } - - - implicit def canFilterFrom(implicit ctx: Context, io: CLDataIO[Int]): CLCanFilterFrom[CLRange, Int, CLFilteredArray[Int]] = - new CLCanFilterFrom[CLRange, Int, CLFilteredArray[Int]] { - override def dataIO = io - override def context = ctx - def rawLength(from: CLRange): Int = from.size - def newFilterResult(from: CLRange) = new CLFilteredArray[Int](from.size)(context, io) - } - -} - -import CLFilteredArray.{PresenceType, toBool, toPresence} - -class CLRange( - protected[scalacl] val buffer: CLGuardedBuffer[Int] -)( - implicit val context: Context -) - extends IndexedSeq[Int] - with CopiableToCLArray[Int] - with CLIndexedSeq[Int] - with CLIndexedSeqLike[Int, CLIndexedSeq[Int]] - with MappableToCLArray[Int, CLIndexedSeq[Int]] -{ - def this(range: Range)(implicit context: Context) = - this(new CLGuardedBuffer[Int](Array(range.start, range.end, range.step, if (range.isInclusive) 1 else 0))) - - override def eventBoundComponents = Seq(buffer) - override def release = buffer.release - - import CLRange._ - - override def toArray: Array[Int] = toRange.toArray - - override def newBuilder = error("Not implemented") - override def toCLArray = { - val size = length - val outBuffer = new CLGuardedBuffer[Int](size) - val out = new CLArray[Int](size, Array(outBuffer.asInstanceOf[CLGuardedBuffer[Any]])) - copyToCLArray(buffer, outBuffer) - out - } - - def copyTo(a: CLArray[Int]) = { - assert(a.length == length) - val Array(outBuffer) = a.buffers - copyToCLArray(buffer, outBuffer.asInstanceOf[CLGuardedBuffer[Int]]) - } - - protected override def mapFallback[B](f: Int => B, result: CLArray[B]) = { - executingScalaFallbackOperation("mapFallback") - var offset = 0 - for (i <- toRange) { - result(offset) = f(i) - offset += 1 - } - } - - protected override def foreachFallback[U](f: Int => U) = { - executingScalaFallbackOperation("foreachFallback") - for (i <- toRange) { - f(i) - } - } - - override def filter(p: Int => Boolean): CLFilteredArray[Int] = // TODO ? toCLArray.filter(p) - filter(p, new CLFilteredArray[Int](length))//.toCLArray - - override def filterFallback[That <: CLCollection[Int]](p: Int => Boolean, out: That)(implicit ff: CLCanFilterFrom[CLIndexedSeq[Int], Int, That]) = { - import scala.concurrent.ops._ - executingScalaFallbackOperation("filterFallback") - out match { - case filteredOut: CLFilteredArray[Int] => - val copy = future { - copyToCLArray(buffer, filteredOut.array.buffers.head.asInstanceOf[CLGuardedBuffer[Int]]) - } - val range = toRange - val presenceArr = new Array[PresenceType](range.size) - var offset = 0 - for (i <- range) { - if (p(i)) - presenceArr(offset) = toPresence(true) - offset += 1 - } - filteredOut.presence.update(presenceArr) - copy() - } - } - - override def apply(index: Int): Int = - toRange.apply(index) - - override def length = toRange.length - override def size = length - - def toRange = convertToRange(buffer) - - override def foreach[U](f: Int => U): Unit = - toRange foreach f - - //TODO Changed in Scala 2.9.0 : Range.slice no longer returns a Range ! - //override def slice(from: Int, to: Int) = new CLRange(toRange.slice(from, to)) - - //override def sizeFuture: CLFuture[Int] = new CLInstantFuture[Int](toRange.size) -} - diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/ScalaCL.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/ScalaCL.scala deleted file mode 100644 index 9270beb17..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/ScalaCL.scala +++ /dev/null @@ -1,389 +0,0 @@ -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ -import scala.collection.JavaConversions._ -import scalacl.impl._ - -package scalacl { - trait AbstractProduct extends Product { - def productValues: Array[Any] - override def productArity = productValues.length - override def productElement(n: Int) = productValues(n) - override def productIterator = productValues.toIterator - override def canEqual(that: Any) = getClass.isInstance(that.asInstanceOf[AnyRef]) - } - class Context(val context: CLContext, val queue: CLQueue) extends AbstractProduct { - def this(context: CLContext) = this(context, context.createDefaultQueue())//createDefaultOutOfOrderQueueIfPossible()) - def this() = this(JavaCL.createBestContext(CLPlatform.DeviceFeature.OutOfOrderQueueSupport, CLPlatform.DeviceFeature.MaxComputeUnits)) - - def release = { - queue.release - context.release - } - override def toString = "Context(platform = " + context.getPlatform.getName + ", devices = " + context.getDevices.mkString(", ") + ")" - - override def productValues = Array(context, queue) - //println("Is out of order queue : " + queue.getProperties.contains(CLDevice.QueueProperties.OutOfOrderExecModeEnable)) - } - object Context { - def best = new Context() - def best(preferredFeatures: CLPlatform.DeviceFeature*) = { - new Context(JavaCL.createBestContext(preferredFeatures:_*)) - } - - def apply = best - def apply(devices: CLDevice*) = new Context(JavaCL.createContext(null, devices:_*)) - - def platforms = JavaCL.listPlatforms.map(Platform) - } - case class Platform(platform: CLPlatform) { - def name = platform.getName - def vendor = platform.getVendor - def devices = platform.listAllDevices(true) - def bestDevice = platform.getBestDevice - def bestDevice(preferredFeatures: CLPlatform.DeviceFeature*) = - CLPlatform.getBestDevice( - java.util.Arrays.asList(preferredFeatures:_*), - java.util.Arrays.asList(devices:_*) - ) - } -} -package object scalacl { - - var verbose = - "1" == System.getenv("SCALACL_VERBOSE") - - var useFastRelaxedMath = - "0" != System.getenv("SCALACL_STRICT_MATH") - - var useScalaFunctions = - "1" == System.getenv("SCALACL_USE_SCALA_FUNCTIONS") - - var enforceUsingOpenCL = - "1" == System.getenv("SCALACL_ENFORCE_OPENCL") - - type Device = CLDevice - - // backward compatibility - @deprecated - type ScalaCLContext = Context - - - val GPU = CLPlatform.DeviceFeature.GPU - val CPU = CLPlatform.DeviceFeature.CPU - val DoubleSupport = CLPlatform.DeviceFeature.DoubleSupport - val MaxComputeUnits = CLPlatform.DeviceFeature.MaxComputeUnits - val NativeEndianness = CLPlatform.DeviceFeature.NativeEndianness - val ImageSupport = CLPlatform.DeviceFeature.ImageSupport - val OutOfOrderQueueSupport = CLPlatform.DeviceFeature.OutOfOrderQueueSupport - val MostImageFormats = CLPlatform.DeviceFeature.MostImageFormats - - def customCode( - source: String, - compilerArguments: Array[String] = Array(), - macros: Map[String, String] = Map() - ): CLCode = { - new CLSimpleCode( - Array(source), - compilerArguments, - macros - ) - } - - private[scalacl] def executingScalaFallbackOperation(opName: => String) = { - if (enforceUsingOpenCL) - throw new RuntimeException("Not using OpenCL !") - if (verbose) - println("Running " + opName + " instead of OpenCL version") - } - - private[scalacl] def reuse[T](value: Any, create: => T): T = - if (value != null && value.isInstanceOf[T]) - value.asInstanceOf[T] - else - create - - implicit def Context2Context(sc: Context) = sc.context - - /*implicit def canBuildArrayFromIndexedSeq[A](implicit context: Context, io: CLDataIO[A]) = - new CLCanBuildFrom[CLIndexedSeq[_], A, CLArray[A]] { - override def dataIO = io - override def apply(from: CLIndexedSeq[_]) = CLArray.newBuilder[A](context, dataIO) - override def apply() = CLArray.newBuilder[A](context, dataIO) - } - */ - implicit def canBuildIndexedSeqFromIndexedSeq[A](implicit context: Context, io: CLDataIO[A]) = - new CLCanBuildFrom[CLIndexedSeq[_], A, CLIndexedSeq[A]] { - override def dataIO = io - override def apply(from: CLIndexedSeq[_]) = CLFilteredArray.newBuilder[A]//(context, dataIO) - override def apply() = CLFilteredArray.newBuilder[A]//(context, dataIO) - } - implicit def canBuildArrayFromArray[A](implicit context: Context, io: CLDataIO[A]) = - new CLCanBuildFrom[CLArray[_], A, CLArray[A]] { - override def dataIO = io - override def apply(from: CLArray[_]) = CLArray.newBuilder[A](context, dataIO) - override def apply() = CLArray.newBuilder[A](context, dataIO) - } -/* - implicit def canBuildFromFilteredArray[A](implicit context: Context, io: CLDataIO[A]) = - new CLCanBuildFrom[CLFilteredArray[_], A, CLFilteredArray[A]] { - override def dataIO = io - override def apply(from: CLFilteredArray[_]) = CLFilteredArray.newBuilder[A](context, dataIO) - override def apply() = CLFilteredArray.newBuilder[A](context, dataIO) - } - */ - - implicit def canFilterFromIndexedSeq[A](implicit ctx: Context, io: CLDataIO[A]) = - new CLCanFilterFrom[CLIndexedSeq[A], A, CLFilteredArray[A]] { - override def dataIO = io - override def context = ctx - def rawLength(from: CLIndexedSeq[A]): Int = from match { - case r: CLRange => - r.length - case a: CLArray[A] => - a.length - case fa: CLFilteredArray[A] => - fa.array.length - } - def newFilterResult(from: CLIndexedSeq[A]) = new CLFilteredArray[A](rawLength(from)) - } - - implicit def CastCanBuildFrom2CL[Repr, B, That](bf: CanBuildFrom[Repr, B, That]): CLCanBuildFrom[Repr, B, That] = bf match { - case cbf: CLCanBuildFrom[Repr, B, That] => - cbf - case _ => - error("Not a " + classOf[CLCanBuildFrom[Repr, B, That]].getName + ": " + bf) - } - //implicit def CanBuildFrom2CLDataIO[Repr, B, That](bf: CanBuildFrom[Repr, B, That]): CLDataIO[B] = - // bf.dataIO - - implicit def Tuple2ToCLDataIO[T1, T2]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2]) = - new CLTupleDataIO[(T1, T2)]( - Array(io1, io2).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2] - ) - ) - - - implicit def Tuple3ToCLDataIO[T1, T2, T3]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3]) = - new CLTupleDataIO[(T1, T2, T3)]( - Array(io1, io2, io3).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3] - ) - ) - - implicit def Tuple4ToCLDataIO[T1, T2, T3, T4]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3], - io4: CLDataIO[T4]) = - new CLTupleDataIO[(T1, T2, T3, T4)]( - Array(io1, io2, io3, io4).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3, t._4), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3], - a(3).asInstanceOf[T4] - ) - ) - - implicit def Tuple5ToCLDataIO[T1, T2, T3, T4, T5]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3], - io4: CLDataIO[T4], - io5: CLDataIO[T5]) = - new CLTupleDataIO[(T1, T2, T3, T4, T5)]( - Array(io1, io2, io3, io4, io5).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3, t._4, t._5), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3], - a(3).asInstanceOf[T4], - a(4).asInstanceOf[T5] - ) - ) - - implicit def Tuple6ToCLDataIO[T1, T2, T3, T4, T5, T6]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3], - io4: CLDataIO[T4], - io5: CLDataIO[T5], - io6: CLDataIO[T6]) = - new CLTupleDataIO[(T1, T2, T3, T4, T5, T6)]( - Array(io1, io2, io3, io4, io5, io6).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3, t._4, t._5, t._6), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3], - a(3).asInstanceOf[T4], - a(4).asInstanceOf[T5], - a(5).asInstanceOf[T6] - ) - ) - - implicit def Tuple7ToCLDataIO[T1, T2, T3, T4, T5, T6, T7]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3], - io4: CLDataIO[T4], - io5: CLDataIO[T5], - io6: CLDataIO[T6], - io7: CLDataIO[T7]) = - new CLTupleDataIO[(T1, T2, T3, T4, T5, T6, T7)]( - Array(io1, io2, io3, io4, io5, io6, io7).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3, t._4, t._5, t._6, t._7), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3], - a(3).asInstanceOf[T4], - a(4).asInstanceOf[T5], - a(5).asInstanceOf[T6], - a(6).asInstanceOf[T7] - ) - ) - - implicit def Tuple8ToCLDataIO[T1, T2, T3, T4, T5, T6, T7, T8]( - implicit - io1: CLDataIO[T1], - io2: CLDataIO[T2], - io3: CLDataIO[T3], - io4: CLDataIO[T4], - io5: CLDataIO[T5], - io6: CLDataIO[T6], - io7: CLDataIO[T7], - io8: CLDataIO[T8]) = - new CLTupleDataIO[(T1, T2, T3, T4, T5, T6, T7, T8)]( - Array(io1, io2, io3, io4, io5, io6, io7, io8).map(_.asInstanceOf[CLDataIO[Any]]), - t => Array(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8), - a => ( - a(0).asInstanceOf[T1], - a(1).asInstanceOf[T2], - a(2).asInstanceOf[T3], - a(3).asInstanceOf[T4], - a(4).asInstanceOf[T5], - a(5).asInstanceOf[T6], - a(6).asInstanceOf[T7], - a(7).asInstanceOf[T8] - ) - ) - - implicit val IntCLDataIO = CLIntDataIO - implicit val ShortCLDataIO = CLShortDataIO - implicit val ByteCLDataIO = CLByteDataIO - implicit val CharCLDataIO = CLCharDataIO - implicit val LongCLDataIO = CLLongDataIO - implicit val BooleanCLDataIO = CLBooleanDataIO - implicit val FloatCLDataIO = CLFloatDataIO - implicit val DoubleCLDataIO = CLDoubleDataIO - //implicit def AnyValCLDataIO[T <: AnyVal](implicit t: ClassManifest[T]) = new CLValDataIO[T] - - implicit def Expression2CLFunction[K, V](fx: (K => V, Array[String]))(implicit kIO: CLDataIO[K], vIO: CLDataIO[V]): CLFunction[K, V] = { - val (function, expressions) = fx - new CLFunction[K, V](function, Array(), Array(), expressions, Array()) - } - implicit def ExpressionWithCaptures2CLFunction[K, V](fx: (K => V, Array[String], impl.CapturedIOs))(implicit kIO: CLDataIO[K], vIO: CLDataIO[V]): CLFunction[K, V] = { - val (function, expressions, captures) = fx - new CLFunction[K, V](function, Array(), Array(), expressions, Array(), captures) - } - - /** - * This MUST be transformed by the ScalaCL compiler plugin to be usable in an OpenCL context (otherwise operations will happen in Scala land - */ - implicit def Function2CLFunction[K, V](f: K => V)(implicit kIO: CLDataIO[K], vIO: CLDataIO[V]): CLFunction[K, V] = { - new CLFunction[K, V](f, Array(), Array(), Array(), Array()) - } - - private val functionsCache = scala.collection.mutable.HashMap[Long, CLFunction[_, _]]() - - def getCachedFunction[K, V]( - uid: Long, - function: K => V, - outerDeclarations: => Array[String], - declarations: => Array[String], - expressions: => Array[String], - extraInputBufferArgsIOs: => Array[CLDataIO[Any]], - extraOutputBufferArgsIOs: => Array[CLDataIO[Any]], - extraScalarArgsIOs: => Array[CLDataIO[Any]] - )(implicit kIO: CLDataIO[K], vIO: CLDataIO[V]): CLFunction[K, V] = { - functionsCache synchronized { - functionsCache.getOrElseUpdate( - uid, - new CLFunction[K, V]( - function, - outerDeclarations, - declarations, - expressions, - Array(), - CapturedIOs( - extraInputBufferArgsIOs, - extraOutputBufferArgsIOs, - extraScalarArgsIOs - ) - ).asInstanceOf[CLFunction[_, _]] - ).asInstanceOf[CLFunction[K, V]] - } - } - - class CLTransformableRange(r: Range)(implicit context: Context) { - def toCLRange = new CLRange(r) - def toCLArray = toCLRange.toCLArray - def toCL = toCLRange - def cl = toCLRange - } - implicit def Range2CLRangeMethods(r: Range)(implicit context: Context) = - new CLTransformableRange(r) - - /*implicit def RichIndexedSeqCL[T](c: IndexedSeq[T])(implicit context: Context, dataIO: CLDataIO[T]) = new { - def toCLArray = CLArray.fromSeq(c) - def toCL = toCLArray - def cl = toCLArray - }*/ - class CLTransformableSeq[T](seq: Seq[T])(implicit context: Context, io: CLDataIO[T]) { - def toCLArray = CLArray.fromSeq(seq) - def toCL = toCLArray - def cl = toCLArray - } - - implicit def Seq2CLTransformableSeq[T](seq: Seq[T])(implicit context: Context, io: CLDataIO[T]) = - new CLTransformableSeq(seq) - - implicit def Array2CLTransformableSeq[T](arr: Array[T])(implicit context: Context, io: CLDataIO[T]) = - new CLTransformableSeq(arr) - - - - class RichCLKernel(k: CLKernel) { - def setArgs(args: Any*) = k.setArgs(args.map(_.asInstanceOf[Object]):_*) - - def enqueueNDRange(global: Array[Int], local: Array[Int] = null)(args: Any*)(implicit context: Context) = k synchronized { - setArgs(args: _*) - k.enqueueNDRange(context.queue, global, local) - } - } - implicit def CLKernel2RichCLKernel(k: CLKernel) = new RichCLKernel(k) - -} - diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/ApplePrefixSum.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/ApplePrefixSum.scala deleted file mode 100644 index 00c6f158a..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/ApplePrefixSum.scala +++ /dev/null @@ -1,507 +0,0 @@ -package scalacl -package impl - -// Ported from http://developer.apple.com/library/mac/#samplecode/OpenCL_Parallel_Prefix_Sum_Example/ -// -// File: scan.c -// -// Abstract: This example shows how to perform an efficient parallel prefix sum (aka Scan) -// using OpenCL. Scan is a common data parallel primitive which can be used for -// variety of different operations -- this example uses local memory for storing -// partial sums and avoids memory bank conflicts on architectures which serialize -// memory operations that are serviced on the same memory bank by offsetting the -// loads and stores based on the size of the local group and the number of -// memory banks (see appropriate macro definition). As a result, this example -// requires that the local group size > 1. -// -// Version: <1.0> -// -// Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") -// in consideration of your agreement to the following terms, and your use, -// installation, modification or redistribution of this Apple software -// constitutes acceptance of these terms. If you do not agree with these -// terms, please do not use, install, modify or redistribute this Apple -// software. -// -// In consideration of your agreement to abide by the following terms, and -// subject to these terms, Apple grants you a personal, non - exclusive -// license, under Apple's copyrights in this original Apple software ( the -// "Apple Software" ), to use, reproduce, modify and redistribute the Apple -// Software, with or without modifications, in source and / or binary forms; -// provided that if you redistribute the Apple Software in its entirety and -// without modifications, you must retain this notice and the following text -// and disclaimers in all such redistributions of the Apple Software. Neither -// the name, trademarks, service marks or logos of Apple Inc. may be used to -// endorse or promote products derived from the Apple Software without specific -// prior written permission from Apple. Except as expressly stated in this -// notice, no other rights or licenses, express or implied, are granted by -// Apple herein, including but not limited to any patent rights that may be -// infringed by your derivative works or by other works in which the Apple -// Software may be incorporated. -// -// The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -// WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -// WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION -// ALONE OR IN COMBINATION WITH YOUR PRODUCTS. -// -// IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -// CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION -// AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER -// UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR -// OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Copyright ( C ) 2008 Apple Inc. All Rights Reserved. -// -//////////////////////////////////////////////////////////////////////////////////////////////////// -import com.nativelibs4java.opencl._ -import scala.math._ -import org.bridj._ -import org.bridj.Pointer._ - -object ApplePrefixSum { - - def printf(fmt: String, args: Any*) = System.out.printf(fmt, args.map(_.asInstanceOf[Object]): _*) - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - val dataSize = 4 - - val DEBUG_INFO = (0) - var GROUP_SIZE = 256 - val NUM_BANKS = (16) - val MAX_ERROR = (1e-7) - val SEPARATOR = ("----------------------------------------------------------------------\n") - - val iterations = 1000 - val count = 1024 * 1024 - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - var ComputeDeviceId: CLDevice = _ - var ComputeCommands: CLQueue = _ - var ComputeContext: CLContext = _ - var ComputeProgram: CLProgram = _ - var ComputeKernels: Array[CLKernel] = _ - var ScanPartialSums: Array[CLBuffer[java.lang.Float]] = _ - var ElementsAllocated = 0 - var LevelsAllocated = 0 - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - object KernelMethods { - val PRESCAN = 0 - val PRESCAN_STORE_SUM = 1 - val PRESCAN_STORE_SUM_NON_POWER_OF_TWO = 2 - val PRESCAN_NON_POWER_OF_TWO = 3 - val UNIFORM_ADD = 4 - } - - import KernelMethods._ - - val KernelNames = Array( - "PreScanKernel", - "PreScanStoreSumKernel", - "PreScanStoreSumNonPowerOfTwoKernel", - "PreScanNonPowerOfTwoKernel", - "UniformAddKernel" - ) - - val KernelCount = KernelNames.size - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - def IsPowerOfTwo(n: Int) = - ((n & (n - 1)) == 0) - - def floorPow2(n: Int) = { - var v = n - var ret = 0 - while (v != 0) { - v = v >> 1 - ret += 1 - } - ret - } - - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - def - CreatePartialSumBuffers(count: Int) { - ElementsAllocated = count - - var group_size = GROUP_SIZE - var element_count = count - - var level = 0 - - do { - val group_count = max(1, ceil(element_count.toFloat / (2.0f * group_size)).toInt) - if (group_count > 1) { - level += 1 - } - element_count = group_count - - } while (element_count > 1) - - ScanPartialSums = new Array[CLBuffer[java.lang.Float]](level) - LevelsAllocated = level - - element_count = count - level = 0 - - do { - var group_count = max(1, ceil(element_count / (2.0f * group_size)).toInt) - if (group_count > 1) { - ScanPartialSums(level) = ComputeContext.createBuffer(CLMem.Usage.InputOutput, classOf[java.lang.Float], group_count) - level += 1 - } - - element_count = group_count - - } while (element_count > 1) - } - - def - ReleasePartialSums { - ScanPartialSums.map(_.release) - ScanPartialSums = null - ElementsAllocated = 0 - LevelsAllocated = 0 - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - def - PreScan( - global: Array[Int], - local: Array[Int], - shared: Long, - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - n: Int, - group_index: Int, - base_index: Int) { - /* - printf("PreScan: Global[%4d] Local[%4d] Shared[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n", - global(0).toInt, local(0).toInt, shared.toInt, group_index, base_index, n) - */ - var k = ComputeKernels(PRESCAN) - - k.setArgs(output_data, input_data, new LocalSize(shared), group_index, base_index, n) - k.enqueueNDRange(ComputeCommands, global, local) - } - - def - PreScanStoreSum( - global: Array[Int], - local: Array[Int], - shared: Long, - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - partial_sums: CLBuffer[java.lang.Float], - n: Int, - group_index: Int, - base_index: Int) { - /* - printf("PreScan: Global[%4d] Local[%4d] Shared[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n", - global(0).toInt, local(0).toInt, shared.toInt, group_index, base_index, n) - */ - var k = ComputeKernels(PRESCAN_STORE_SUM) - - k.setArgs(output_data, input_data, partial_sums, new LocalSize(shared), group_index, base_index, n) - k.enqueueNDRange(ComputeCommands, global, local) - } - - def - PreScanStoreSumNonPowerOfTwo( - global: Array[Int], - local: Array[Int], - shared: Long, - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - partial_sums: CLBuffer[java.lang.Float], - n: Int, - group_index: Int, - base_index: Int) { - /* - printf("PreScanStoreSumNonPowerOfTwo: Global[%4d] Local[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n", - global(0).toInt, local(0).toInt, shared.toInt, group_index, base_index, n) - */ - var k = ComputeKernels(PRESCAN_STORE_SUM_NON_POWER_OF_TWO) - k.setArgs(output_data, input_data, partial_sums, new LocalSize(shared), group_index, base_index, n) - k.enqueueNDRange(ComputeCommands, global, local) - } - - def - PreScanNonPowerOfTwo( - global: Array[Int], - local: Array[Int], - shared: Long, - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - n: Int, - group_index: Int, - base_index: Int) { - /* - printf("PreScanNonPowerOfTwo: Global[%4d] Local[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n", - global(0).toInt, local(0).toInt, shared.toInt, group_index, base_index, n) - */ - var k = ComputeKernels(PRESCAN_NON_POWER_OF_TWO) - k.setArgs(output_data, input_data, new LocalSize(shared), group_index, base_index, n) - k.enqueueNDRange(ComputeCommands, global, local) - } - - def - UniformAdd( - global: Array[Int], - local: Array[Int], - output_data: CLBuffer[java.lang.Float], - partial_sums: CLBuffer[java.lang.Float], - n: Int, - group_offset: Int, - base_index: Int) { - /* - printf("UniformAdd: Global[%4d] Local[%4d] BlockOffset[%4d] BaseIndex[%4d] Entries[%d]\n", - global(0).toInt, local(0).toInt, group_offset, base_index, n) - */ - var k = ComputeKernels(UNIFORM_ADD) - - k.setArgs(output_data, partial_sums, new LocalSize(dataSize), group_offset, base_index, n) - k.enqueueNDRange(ComputeCommands, global, local) - } - - - def - PreScanBufferRecursive( - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - max_group_size: Int, - max_work_item_count: Int, - element_count: Int, - level: Int) { - var group_size = max_group_size - var group_count = max(1, ceil(element_count / (2.0f * group_size)).toInt) - var work_item_count = 0 - - if (group_count > 1) - work_item_count = group_size - else if (IsPowerOfTwo(element_count)) - work_item_count = element_count / 2 - else - work_item_count = floorPow2(element_count) - - work_item_count = if (work_item_count > max_work_item_count) max_work_item_count else work_item_count - - var element_count_per_group = work_item_count * 2 - var last_group_element_count = element_count - (group_count - 1) * element_count_per_group - var remaining_work_item_count = max(1, last_group_element_count / 2) - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - var remainder = 0 - var last_shared = 0L - - - if (last_group_element_count != element_count_per_group) { - remainder = 1 - - if (!IsPowerOfTwo(last_group_element_count)) - remaining_work_item_count = floorPow2(last_group_element_count) - - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - var padding = (2 * remaining_work_item_count) / NUM_BANKS - last_shared = 4 /*sizeof(float)*/ * (2 * remaining_work_item_count + padding) - } - - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - val global = Array(max(1, group_count - remainder) * work_item_count, 1) - val local = Array(work_item_count, 1) - - var padding = element_count_per_group / NUM_BANKS - var shared = 4L /*sizeof(float)*/ * (element_count_per_group + padding) - - var partial_sums = if (level >= LevelsAllocated) null else ScanPartialSums(level) - - if (group_count > 1) { - PreScanStoreSum(global, local, shared, output_data, input_data, partial_sums, work_item_count * 2, 0, 0) - - if (remainder != 0) { - var last_global = Array(1 * remaining_work_item_count, 1) - var last_local = Array(remaining_work_item_count, 1) - - PreScanStoreSumNonPowerOfTwo( - last_global, last_local, last_shared, - output_data, input_data, partial_sums, - last_group_element_count, - group_count - 1, - element_count - last_group_element_count) - } - - PreScanBufferRecursive(partial_sums, partial_sums, max_group_size, max_work_item_count, group_count, level + 1) - UniformAdd(global, local, output_data, partial_sums, element_count - last_group_element_count, 0, 0) - - if (remainder != 0) { - var last_global = Array(1 * remaining_work_item_count, 1) - var last_local = Array(remaining_work_item_count, 1) - - UniformAdd( - last_global, last_local, - output_data, partial_sums, - last_group_element_count, - group_count - 1, - element_count - last_group_element_count) - } - } - else if (IsPowerOfTwo(element_count)) { - PreScan(global, local, shared, output_data, input_data, work_item_count * 2, 0, 0) - } - else { - PreScanNonPowerOfTwo(global, local, shared, output_data, input_data, element_count, 0, 0) - } - } - - def - PreScanBuffer( - output_data: CLBuffer[java.lang.Float], - input_data: CLBuffer[java.lang.Float], - max_group_size: Int, - max_work_item_count: Int, - element_count: Int) { - PreScanBufferRecursive(output_data, input_data, max_group_size, max_work_item_count, element_count, 0) - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - def ScanReference(reference: Pointer[java.lang.Float], input: Pointer[java.lang.Float], count: Int) { - reference(0) = 0 - var total_sum = 0.0 - - for (i <- 1 until count) { - total_sum += input(i - 1).floatValue - reference(i) = input(i - 1).floatValue + reference(i - 1).floatValue - } - if (total_sum != reference(count - 1)) - printf("Warning: Exceeding single-precision accuracy. Scan will be inaccurate.\n") - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - - def main2(args: Array[String]): Unit = { - var t0 = 0L - var t1 = 0L - var t2 = 0L - var output_buffer: CLBuffer[java.lang.Float] = null - var input_buffer: CLBuffer[java.lang.Float] = null - - // Create some random input data on the host - // - val rand = new java.util.Random(System.nanoTime) - var float_data = allocateFloats(count) - for (i <- 0 until count) { - float_data(i) = (10 * rand.nextFloat).toInt - } - - // Connect to a GPU compute device - // - - val source: String = com.nativelibs4java.util.IOUtils.readText(Platform.getClassLoader(classOf[GroupedPrefixSum[_]]).getResourceAsStream("scalacl/impl/scan_kernel.cl")) - - // Create a compute ComputeContext - // - ComputeContext = JavaCL.createBestContext(CLPlatform.DeviceFeature.GPU) - ComputeDeviceId = ComputeContext.getDevices()(0) - var max_workgroup_size = ComputeDeviceId.getMaxWorkGroupSize - - GROUP_SIZE = min(GROUP_SIZE, max_workgroup_size.toInt) - - ComputeCommands = ComputeContext.createDefaultQueue() - - // Create the compute program from the source buffer - // - ComputeProgram = ComputeContext.createProgram(source).build - - ComputeKernels = KernelNames.map(n => ComputeProgram.createKernel(n)) - var wgSize = ComputeKernels.map(_.getWorkGroupSize.get(ComputeDeviceId).longValue.toInt).min - GROUP_SIZE = min(GROUP_SIZE, wgSize.toInt) - - // Create the input buffer on the device - // - //val buffer_size = sizeof(float) * count - input_buffer = ComputeContext.createBuffer(CLMem.Usage.InputOutput, classOf[java.lang.Float], count) - - // Fill the input buffer with the host allocated random data - // - input_buffer.write(ComputeCommands, float_data, true) - - // Create the output buffer on the device - // - output_buffer = ComputeContext.createBuffer(CLMem.Usage.InputOutput, classOf[java.lang.Float], count) - - val result = allocateFloats(count) - output_buffer.write(ComputeCommands, result, true) - - CreatePartialSumBuffers(count) - PreScanBuffer(output_buffer, input_buffer, GROUP_SIZE, GROUP_SIZE, count) - - printf("Starting timing run of '%d' iterations...\n", iterations) - - t1 = System.nanoTime - t0 = t1 - for (i <- 0 until iterations) { - PreScanBuffer(output_buffer, input_buffer, GROUP_SIZE, GROUP_SIZE, count) - } - ComputeCommands.finish - t2 = System.nanoTime - - - // Calculate the statistics for execution time and throughput - // - val t = (t2 - t1) / 1000000000.0 - printf("Exec Time: %.2f ms\n", 1000.0 * t / iterations) - printf("Throughput: %.2f GB/sec\n", 1e-9 * (count * dataSize) * iterations / t) - printf(SEPARATOR) - - // Read back the results that were computed on the device - // - output_buffer.read(ComputeCommands, result, true) - - // Verify the results are correct - // - var reference = allocateFloats(count) - ScanReference(reference, float_data, count) - - var errorValue = 0.0f - var diff = 0.0f - for (i <- 0 until count) { - diff = abs(reference(i).floatValue - result(i).floatValue) - errorValue = if (diff > errorValue) diff else errorValue - } - - if (errorValue > MAX_ERROR) { - error("Error: Incorrect results obtained! Max error = " + errorValue) - } - else { - printf("Results Validated!\n") - printf(SEPARATOR) - } - - // Shutdown and cleanup - // - ReleasePartialSums - ComputeKernels.map(_.release) - ComputeProgram.release - input_buffer.release - output_buffer.release - ComputeCommands.release - ComputeContext.release - - ComputeKernels = null - float_data.release - reference.release - result.release - } - - -} \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCanBuildFrom.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCanBuildFrom.scala deleted file mode 100644 index e231e28b4..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCanBuildFrom.scala +++ /dev/null @@ -1,29 +0,0 @@ -package scalacl - -package impl - -import scalacl._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ - -import org.bridj.Pointer -import org.bridj.PointerIO -import scala.math._ -import scala.collection.mutable.Builder - -trait CLCanBuildFrom[-From, Elem, +To] extends CanBuildFrom[From, Elem, To] { - def dataIO: CLDataIO[Elem] -} - -trait CLCanFilterFrom[-From, Elem, +To] { - def context: Context - def dataIO: CLDataIO[Elem] - - def rawLength(from: From): Int - def newFilterResult(from: From): To - //def apply(from: From): Builder[Elem, To] - //def apply(): Builder[Elem, To] -} - - diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCode.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCode.scala deleted file mode 100644 index 9df290fbf..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLCode.scala +++ /dev/null @@ -1,119 +0,0 @@ -package scalacl - -package impl - -import _root_.scala.collection._ - -import com.nativelibs4java.opencl._ - -trait CLCode { - protected val sources: Array[String] - protected val macros: Map[String, String] - protected val compilerArguments: Array[String] - - private val flatten: ((String, String)) => String = { case ((a: String, b: String)) => a + b } - private lazy val strs = sources ++ macros.map(flatten)// ++ compilerArguments ++ templateParameters.toSeq.map(flatten) - private lazy val hc = strs.map(_.hashCode).reduceLeft(_ ^ _) - - private val map = new mutable.HashMap[CLContext, (CLProgram, Map[String, CLKernel])] - - def compile(context: Context): Unit = getProgramAndKernels(context) - - private[impl] def getProgramAndKernels(context: Context): (CLProgram, Map[String, CLKernel]) = map.synchronized { - map.getOrElseUpdate( - context.context, - { - val srcs = - if (context.context.isByteAddressableStoreSupported) - sources.map("#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable\n" + _) - else - sources - - val program = context.context.createProgram(srcs:_*) - if (useFastRelaxedMath) - program.setFastRelaxedMath - for ((key, value) <- macros) - program.defineMacro(key, value) - - /* - import java.io._ - val out = new PrintStream(new FileOutputStream("out.cl")) - out.println("// " + compilerArguments.mkString(" ")) - out.println(srcs.mkString("\n")) - out.close - */ - - compilerArguments.foreach(program.addBuildOption(_)) - (program, program.createKernels.map(k => (k.getFunctionName, k)).toMap) - } - ) - } - - def release(context: Context): Unit = map.synchronized { - for ((program, kernels) <- map.get(context.context)) { - kernels.values.foreach(_.release) - program.release - map.remove(context.context) - } - } - def getKernel(context: Context, name: String = null) = { - val kernels = getProgramAndKernels(context)._2 - if (name == null) - kernels.values.head - else - kernels(name) - } - - override def hashCode = hc - override def equals(o: Any) = o.isInstanceOf[CLCode] && strs.equals(o.asInstanceOf[CLCode].strs) - - /** - * Execute the code using the provided arguments (may be CLArray instances, CLGuardedBuffer instances, CLBuffer instances or primitive values), using the provided global sizes (and optional local group sizes) and respecting the execution order of arguments declared as "read from" and "written to".
      - * Example : - * - import scalacl._ - implicit val context = Context.best(CPU) - val n = 100 - val f = 0.5f - val sinCosOutputs: CLArray[Float] = new CLArray[Float](2 * n) - val sinCosCode = customCode(""" - __kernel void sinCos(__global float2* outputs, float f) { - int i = get_global_id(0); - float c, s = sincos(i * f, &c); - outputs[i] = (float2)(s, c); - } - """) - sinCosCode.execute( - args = Array(sinCosOutputs, f), - writes = Array(sinCosOutputs), - globalSizes = Array(n) - ) - val resCL = sinCosOutputs.toArray - * - */ - def execute( - args: Array[Any], - globalSizes: Array[Int], - localSizes: Array[Int] = null, - reads: Array[CLEventBoundContainer] = Array(), - writes: Array[CLEventBoundContainer] = Array(), - kernelName: String = null - )(implicit context: Context): Unit = { - val flatArgs: Array[Object] = args.flatMap(_ match { - case b: CLArray[_] => - b.buffers.map(_.buffer.asInstanceOf[Object]) - case b: CLGuardedBuffer[_] => - Array[Object](b.buffer) - case a => - Array[Object](a.asInstanceOf[Object]) - }) - val kernel = getKernel(context, kernelName) - kernel.synchronized { - //println("flatArgs = " + flatArgs.map(a => a + ": " + a.getClass.getSimpleName).mkString(", ")) - kernel.setArgs(flatArgs:_*) - CLEventBound.syncBlock(CLEventBound.flatten(reads), CLEventBound.flatten(writes), evts => { - kernel.enqueueNDRange(context.queue, globalSizes, localSizes, evts:_*) - }) - } - } -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLDataIO.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLDataIO.scala deleted file mode 100644 index 6f2dbae82..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLDataIO.scala +++ /dev/null @@ -1,525 +0,0 @@ -package scalacl - -package impl - -import scalacl._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ -import com.nativelibs4java.opencl.util._ - -import org.bridj.Pointer -import org.bridj.PointerIO -import scala.math._ - -object CLDataIO { - abstract sealed class ArgType - object Value extends ArgType - object InputPointer extends ArgType - object OutputPointer extends ArgType -} - -trait CLDataIO[T] { - implicit val t: ClassManifest[T] - val elementCount: Int - val pointerIO: PointerIO[T] - def elementSize: Int - def elements: Seq[CLDataIO[Any]] - def clType: String - - lazy val clearSource = new CLSimpleCode(""" - __kernel void clearKernel(int size, __global """ + clType + """* buffer) { - int i = get_global_id(0); - if (i >= size) - return; - - buffer[i] = (""" + clType + """)0; - } - """) - def clear(buffer: CLBuffer[T], evts: CLEvent*)(implicit context: Context): CLEvent = { - val kernel = clearSource.getKernel(context) - kernel.synchronized { - val size = buffer.getElementCount.toInt - kernel.setArgs(size, buffer) - kernel.enqueueNDRange(context.queue, Array(size), evts:_*) - } - } - def reductionType: (OpenCLType, Int) = error("Not a reductible type : " + this) - - def createBuffers(length: Int)(implicit context: Context): Array[CLGuardedBuffer[Any]] - - def openCLKernelArgDeclarations(nameBasis: String, argType: CLDataIO.ArgType, offset: Int): Seq[String] - def openCLKernelNthItemExprs(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, n: String): Seq[(String, List[Int])] - def openCLIntermediateKernelTupleElementsExprs(expr: String): Seq[(String, List[Int])] - - def openCLIthTupleElementNthItemExpr(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, indexes: List[Int], n: String): String - - def extract(arrays: Array[Array[Any]], index: Int): T = { - assert(elementCount == arrays.length) - extract(arrays, 0, index) - } - def extract(arrays: Array[CLGuardedBuffer[Any]], index: Int): CLFuture[T] = { - assert(elementCount == arrays.length) - extract(arrays, 0, index) - //CLInstantFuture(extract(arrays.map(_.toArray.asInstanceOf[Array[Any]]), index)) - } - def store(v: T, arrays: Array[CLGuardedBuffer[Any]], index: Int): Unit = { - assert(elementCount == arrays.length) - store(v, arrays, 0, index) - } - def extract(pointers: Array[Pointer[Any]], index: Int): T = { - //extract(pointers.map(_.toArray.asInstanceOf[Array[Any]]), index) - assert(elementCount == pointers.length) - extract(pointers, 0, index) - } - def store(v: T, pointers: Array[Pointer[Any]], index: Int): Unit = { - assert(elementCount == pointers.length) - store(v, pointers, 0, index) - } - - def extract(arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): CLFuture[T] - - def store(v: T, arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): Unit - - def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): T - def extract(arrays: Array[Array[Any]], offset: Int, index: Int): T - - def store(v: T, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit - - def exprs(arrayExpr: String): Seq[String] - - def toArray(arrays: Array[CLGuardedBuffer[Any]]): Array[T] = { - val size = arrays.head.buffer.getElementCount.toInt - if (arrays.length == 1) { - arrays.head.withReadablePointer(p => p.toArray.asInstanceOf[Array[T]]) - } else { - val out = new Array[T](size) - copyToArray(arrays, out, 0, size) - out - } - } - def copyToArray[B >: T](arrays: Array[CLGuardedBuffer[Any]], out: Array[B], start: Int = 0, length: Int = -1) = { - assert(elementCount == arrays.length) - val pointers = arrays.map(_.toPointer) - val size = pointers(0).getValidElements.toInt - var i = start - val sup = if (length < 0) size else min(size, start + length) - while (i < sup) { - out(i) = extract(pointers, i) - i += 1 - } - } - -} - -object CLTupleDataIO { - val builtInArities = Set(1, 2, 4, 8) -} -class CLTupleDataIO[T](ios: Array[CLDataIO[Any]], values: T => Array[Any], tuple: Array[Any] => T)(implicit override val t: ClassManifest[T]) extends CLDataIO[T] { - - assert(!ios.isEmpty) - - override lazy val pointerIO: PointerIO[T] = - error("Cannot create PointerIO for tuples !") - - override def openCLKernelArgDeclarations(nameBasis: String, argType: CLDataIO.ArgType, offset: Int): Seq[String] = - iosAndOffsets.flatMap { case (io, ioOffset) => io.openCLKernelArgDeclarations(nameBasis, argType, offset + ioOffset) } - - override def openCLKernelNthItemExprs(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, n: String): Seq[(String, List[Int])] = - iosAndOffsets.zipWithIndex.flatMap { - case ((io, ioOffset), i) => - io.openCLKernelNthItemExprs(nameBasis, argType, offset + ioOffset, n).map { - case (s, indexes) => (s, i :: indexes) - } - } - - //override def openCLIntermediateKernelNthItemExprs(argType: CLDataIO.ArgType, offset: Int, n: String): Seq[String] = - // iosAndOffsets.flatMap { case (io, ioOffset) => io.openCLIntermediateKernelNthItemExprs(argType, offset + ioOffset, n) } - - /*override def openCLTupleShuffleNthFieldExprs(argType: CLDataIO.ArgType, offset: Int, n: String, shuffleExpr: String): Seq[String] = - if (!isOpenCLTuple) - error("Type " + this + " is not an OpenCL tuple !") - else - shuffleExpr.view.map(_ match { - case 'x' => 0 - case 'y' => 1 - case 'z' => 2 - case 'w' => 3 - }).flatMap(i => { - val (io, ioOffset) = iosAndOffsets(i) - io.openCLKernelNthItemExprs(argType, offset + ioOffset, n).map(_._1) - }) - */ - override def openCLIthTupleElementNthItemExpr(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, indexes: List[Int], n: String): String = { - val (io, ioOffset) = iosAndOffsets(indexes.head) - io.openCLIthTupleElementNthItemExpr(nameBasis, argType, offset + ioOffset, indexes.tail, n) - } - - override def openCLIntermediateKernelTupleElementsExprs(expr: String): Seq[(String, List[Int])] = { - ios.zipWithIndex.flatMap { - case (io, i) => - io.openCLIntermediateKernelTupleElementsExprs(expr + "._" + (i + 1)).map { - case (x, indexes) => - (x, i :: indexes) - } - } - } - - override def elementSize = ios.map(_.elementSize).sum - override def elements: Seq[CLDataIO[Any]] = - ios.flatMap(_.elements) - - val types = ios.map(_.clType) - val uniqTypes = types.toSet - - val isOpenCLTuple = { - uniqTypes.size == 1 && - CLTupleDataIO.builtInArities.contains(ios.size) && - ios.head.isInstanceOf[CLValDataIO[_]] - } - override def clType = { - if (isOpenCLTuple) - uniqTypes.head + ios.size - else - "struct { " + types.reduceLeft(_ + "; " + _) + "; }" - } - - override def reductionType = if (isOpenCLTuple) - (ios.head.reductionType._1, ios.size) - else - super.reductionType - - override def createBuffers(length: Int)(implicit context: Context): Array[CLGuardedBuffer[Any]] = - ios.flatMap(_.createBuffers(length)) - - val (iosAndOffsets, elementCount) = { - var off = 0 - ( - ios.map(io => { - val o = off - off += io.elementCount - (io, o) - }), - off - ) - } - - override def extract(arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): CLFuture[T] = - new CLTupleFuture( - iosAndOffsets.map(p => { - val (io, ioOffset) = p - io.extract(arrays, offset + ioOffset, index) - }), - tuple - ) - - override def store(v: T, arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): Unit = - iosAndOffsets.zip(values(v)).foreach { case ((io, ioOffset), vi) => io.store(vi, arrays, offset + ioOffset, index) } - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): T = { - var i = 0 - val length = iosAndOffsets.length - val data = new Array[Any](length) - - while (i < length) { - val (io, ioOffset) = iosAndOffsets(i) - data(i) = io.extract(pointers, offset + ioOffset, index) - i += 1 - } - tuple(data) - /* - tuple(iosAndOffsets.map(p => { - val (io, ioOffset) = p - io.extract(pointers, offset + ioOffset, index) - })) - */ - } - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): T = { - var i = 0 - val length = iosAndOffsets.length - val data = new Array[Any](length) - - while (i < length) { - val (io, ioOffset) = iosAndOffsets(i) - data(i) = io.extract(arrays, offset + ioOffset, index) - i += 1 - } - tuple(data) - } - - override def store(v: T, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = { - var i = 0 - val length = iosAndOffsets.length - val vals = values(v) - while (i < length) { - val (io, ioOffset) = iosAndOffsets(i) - val vi = vals(i) - io.store(vi, pointers, offset + ioOffset, index) - i += 1 - } - //iosAndOffsets.zip(values(v)).foreach { case ((io, ioOffset), vi) => io.store(vi, pointers, offset + ioOffset, index) } - } - - override def exprs(arrayExpr: String): Seq[String] = - ios.zipWithIndex.flatMap { case (io, i) => io.exprs(arrayExpr + "._" + (i + 1)) } - - override def toString = - "(" + ios.mkString(", ") + ")" -} - -abstract class CLValDataIO[T <: AnyVal](implicit override val t: ClassManifest[T]) extends CLDataIO[T] { - - override val elementCount = 1 - - override val pointerIO: PointerIO[T] = - PointerIO.getInstance(t.erasure) - - override def elementSize = pointerIO.getTargetSize.toInt - override def elements: Seq[CLDataIO[Any]] = - Seq(this.asInstanceOf[CLDataIO[Any]]) - - /*override def openCLTupleShuffleNthFieldExprs(argType: CLDataIO.ArgType, offset: Int, n: String, shuffleExpr: String): Seq[String] = - error("Calling tuple shuffle field '" + shuffleExpr + "' on scalar type " + this)*/ - - override def openCLKernelArgDeclarations(nameBasis: String, argType: CLDataIO.ArgType, offset: Int): Seq[String] = { - Seq( - ( - argType match { - case CLDataIO.InputPointer => - "__global const " + clType + "* " + nameBasis - case CLDataIO.OutputPointer => - "__global " + clType + "* " + nameBasis - case CLDataIO.Value => - "const " + clType + " " + nameBasis - } - ) + offset - ) - } - - override def openCLKernelNthItemExprs(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, n: String) = - Seq( - ( - argType match { - case CLDataIO.Value => - nameBasis + offset - case CLDataIO.InputPointer => - nameBasis + offset + "[" + n + "]" - case CLDataIO.OutputPointer => - nameBasis + offset + "[" + n + "]" - }, - List(0) - ) - ) - - override def openCLIntermediateKernelTupleElementsExprs(expr: String): Seq[(String, List[Int])] = - Seq((expr, List(0))) - - override def openCLIthTupleElementNthItemExpr(nameBasis: String, argType: CLDataIO.ArgType, offset: Int, indexes: List[Int], n: String): String = { - if (indexes != List(0)) - error("There is only one item in this array of " + this + " (trying to access item " + indexes + ")") - openCLKernelNthItemExprs(nameBasis, argType, offset, n)(0)._1 - } - - override def clType = t.erasure.getSimpleName.toLowerCase match { - case "sizet" => "size_t" - case "boolean" => CLFilteredArray.presenceCLType - case "character" => "short" - case n => n - } - - override def toString = t.erasure.getSimpleName + " /* " + clType + "*/" - - override def createBuffers(length: Int)(implicit context: Context): Array[CLGuardedBuffer[Any]] = - Array(new CLGuardedBuffer[T](length)(context, this).asInstanceOf[CLGuardedBuffer[Any]]) - - override def extract(arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): CLFuture[T] = - arrays(offset).asInstanceOf[CLGuardedBuffer[T]].apply(index) - - //override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): T = - // pointers(offset).asInstanceOf[Pointer[T]].get(index) - - //override def store(v: T, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - // pointers(offset).asInstanceOf[Pointer[T]].set(index, v) - - override def store(v: T, arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): Unit = - arrays(offset).asInstanceOf[CLGuardedBuffer[T]].update(index, v) - - override def exprs(arrayExpr: String): Seq[String] = - Seq(arrayExpr) - - override def toArray(arrays: Array[CLGuardedBuffer[Any]]): Array[T] = { - assert(elementCount == arrays.length) - arrays(0).asInstanceOf[CLGuardedBuffer[T]].toArray - } -} - -object CLIntDataIO extends CLValDataIO[Int] { - override def reductionType = (OpenCLType.Int, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Int = - pointers(offset).getIntAtOffset(index * 4) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Int = - arrays(offset).asInstanceOf[Array[Int]](index) - - override def store(v: Int, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setIntAtOffset(index * 4, v) -} - -object CLShortDataIO extends CLValDataIO[Short] { - override def reductionType = (OpenCLType.Short, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Short = - pointers(offset).getShortAtOffset(index * 2) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Short = - arrays(offset).asInstanceOf[Array[Short]](index) - - override def store(v: Short, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setShortAtOffset(index * 2, v) -} - -object CLByteDataIO extends CLValDataIO[Byte] { - override def reductionType = (OpenCLType.Byte, 1) - - override def clType = "char" - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Byte = - pointers(offset).getByteAtOffset(index * 1) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Byte = - arrays(offset).asInstanceOf[Array[Byte]](index) - - override def store(v: Byte, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setByteAtOffset(index * 1, v) -} - -object CLBooleanDataIO extends CLValDataIO[Boolean] { - override def reductionType = (OpenCLType.Byte, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Boolean = - pointers(offset).getByteAtOffset(index * 1) != 0 - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Boolean = - arrays(offset).asInstanceOf[Array[Boolean]](index) - - override def store(v: Boolean, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setByteAtOffset(index * 1, if (v) 1 else 0) -} - -object CLCharDataIO extends CLValDataIO[Char] { - override def reductionType = (OpenCLType.Char, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Char = - pointers(offset).getCharAtOffset(index * 2) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Char = - arrays(offset).asInstanceOf[Array[Char]](index) - - override def store(v: Char, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setCharAtOffset(index * 2, v) -} - -object CLLongDataIO extends CLValDataIO[Long] { - override def reductionType = (OpenCLType.Long, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Long = - pointers(offset).getLongAtOffset(index * 8) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Long = - arrays(offset).asInstanceOf[Array[Long]](index) - - override def store(v: Long, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setLongAtOffset(index * 8, v) -} - -object CLFloatDataIO extends CLValDataIO[Float] { - override def reductionType = (OpenCLType.Float, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Float = - pointers(offset).getFloatAtOffset(index * 4) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Float = - arrays(offset).asInstanceOf[Array[Float]](index) - - override def store(v: Float, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setFloatAtOffset(index * 4, v) -} - -object CLDoubleDataIO extends CLValDataIO[Double] { - override def reductionType = (OpenCLType.Double, 1) - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Double = - pointers(offset).getDoubleAtOffset(index * 8) - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Double = - arrays(offset).asInstanceOf[Array[Double]](index) - - override def store(v: Double, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - pointers(offset).setDoubleAtOffset(index * 8, v) -} - -/* -class CLRangeDataIO(implicit val t: ClassManifest[Int]) extends CLDataIO[Int] { - - override val elementCount = 1 - - override val pointerIO: PointerIO[Int] = - PointerIO.getInstance(t.erasure) - - override def elements: Seq[CLDataIO[Any]] = - Seq(this.asInstanceOf[CLDataIO[Any]]) - - override def openCLKernelArgDeclarations(argType: CLDataIO.ArgType, offset: Int): Seq[String] = { - assert(argType != ) - Seq("int rangeLow" + offset) - } - - override def openCLKernelNthItemExprs(argType: CLDataIO.ArgType, offset: Int, n: String) = - Seq(("(rangeLow" + offset + " + " + n + ")", List(0))) - - override def openCLIntermediateKernelTupleElementsExprs(expr: String): Seq[(String, List[Int])] = - Seq((expr, List(0))) // TODO ? - - override def openCLIthTupleElementNthItemExpr(argType: CLDataIO.ArgType, offset: Int, indexes: List[Int], n: String): String = { - if (indexes != List(0)) - error("There is only one item in this array of " + this + " (trying to access item " + indexes + ")") - openCLKernelNthItemExprs(argType, offset, n)(0)._1 - } - - override def clType = "int" - - override def toString = "int range" - - override def createBuffers(length: Int)(implicit context: Context): Array[CLGuardedBuffer[Any]] = - Array(new CLGuardedBuffer[Int](2).asInstanceOf[CLGuardedBuffer[Any]]) - - override def extract(arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): CLFuture[Int] = { - val arr = arrays(offset).asInstanceOf[CLGuardedBuffer[Int]] - error("not implemented") - - } - - override def extract(pointers: Array[Pointer[Any]], offset: Int, index: Int): Int = - pointers(offset).asInstanceOf[Pointer[Int]].get(0) + index.toInt - - override def extract(arrays: Array[Array[Any]], offset: Int, index: Int): Int = - arrays(offset).asInstanceOf[Array[Int]](0) + index.toInt - - override def store(v: Int, pointers: Array[Pointer[Any]], offset: Int, index: Int): Unit = - error("Int ranges are immutable !") - - override def store(v: Int, arrays: Array[CLGuardedBuffer[Any]], offset: Int, index: Int): Unit = - error("Int ranges are immutable !") - - override def exprs(arrayExpr: String): Seq[String] = - Seq(arrayExpr) - - override def toArray(arrays: Array[CLGuardedBuffer[Any]]): Array[Int] = { - assert(elementCount == arrays.length) - val Array(low, length, by) = arrays(0).asInstanceOf[CLGuardedBuffer[Int]].toArray - (low.toInt until length.toInt).toArray - } -} -*/ diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLEventBound.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLEventBound.scala deleted file mode 100644 index 545ff8618..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLEventBound.scala +++ /dev/null @@ -1,115 +0,0 @@ -package scalacl - -package impl - -import com.nativelibs4java.opencl._ -import scala.collection.mutable.{ArrayBuilder, ListBuffer, ArrayBuffer} - -trait CLEventBoundContainer { - def eventBoundComponents: Seq[CLEventBound] - def waitFor: Unit = eventBoundComponents.foreach(_.waitFor) -} -trait CLEventBound extends CLEventBoundContainer { - override def eventBoundComponents = Seq(this) - - protected var lastWriteEvent: CLEvent = null - protected val readEvents = new ArrayBuffer[CLEvent] - - protected def releaseEvents = this.synchronized { - if (lastWriteEvent == null) { - lastWriteEvent.release - lastWriteEvent = null - } - readEvents.map(_.release) - readEvents.clear - } - - protected def allEvents = this.synchronized { - val rea = readEvents.toArray - if (lastWriteEvent == null) - rea - else - Array(lastWriteEvent) ++ rea - } - - def write(action: Array[CLEvent] => CLEvent): CLEvent = this.synchronized { - val evt = action(allEvents) - if (evt != null) { - lastWriteEvent = evt - readEvents.clear - } - lastWriteEvent - } - def read(action: Array[CLEvent] => CLEvent): CLEvent = this.synchronized { - val evt = action(if (lastWriteEvent == null) Array() else Array(lastWriteEvent)) - if (evt != null) - readEvents += evt - - evt - } - - protected def readValue[V](f: Array[CLEvent] => V): V = this.synchronized { - f(if (lastWriteEvent == null) Array() else Array(lastWriteEvent)) - } - - def readBlock[V](block: => V) = this.synchronized { - waitFor - block - } - - override def waitFor = this.synchronized { - if (lastWriteEvent != null) - readEvents += lastWriteEvent - - CLEvent.waitFor(readEvents.result:_*) - lastWriteEvent = null - readEvents.clear - //lastReadEvent = null - } -} - -object CLEventBound { - def flatten(containers: Array[CLEventBoundContainer]) = - containers.flatMap(_.eventBoundComponents) - - def syncBlock(reads: Array[CLEventBound], writes: Array[CLEventBound], action: Array[CLEvent] => CLEvent): CLEvent = { - - def recursiveSync(ebs: List[(CLEventBound, Boolean)], evts: ArrayBuilder[CLEvent]): CLEvent = { - val (eb, write) :: tail = ebs - eb synchronized { - // Whether we're reading of writing to eb, we wait for the last write to finish : - if (eb.lastWriteEvent != null) - evts += eb.lastWriteEvent - - if (write) // If writing to eb, we wait for all those reading from eb : - evts ++= eb.readEvents - - val evt = if (tail.isEmpty) - action(evts.result()) - else - recursiveSync(tail, evts) - - if (evt != null) { - if (write) { - // Flush read events, as we now have a much more blocking write event : - eb.lastWriteEvent = evt - eb.readEvents.clear - } else { - eb.readEvents += evt - } - } - evt - } - } - val lb = new ListBuffer[(CLEventBound, Boolean)] - for (eb <- reads) - lb += ((eb, false)) - for (eb <- writes) - lb += ((eb, true)) - - if (lb.isEmpty) - action(Array()) - else - recursiveSync(lb.result, Array.newBuilder[CLEvent]) - } -} \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunction.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunction.scala deleted file mode 100644 index 53aa3f65e..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunction.scala +++ /dev/null @@ -1,210 +0,0 @@ -package scalacl - -package impl - -import scala.collection._ - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ - - -trait CLRunnable { - def isOnlyInScalaSpace: Boolean - - protected def run(dims: Array[Int], args: Array[Any], eventsToWaitFor: Array[CLEvent])(implicit context: Context): CLEvent - - def run(args: Array[Any], reads: Array[CLEventBoundContainer] = null, writes: Array[CLEventBoundContainer] = null)(dims: Array[Int], groupSizes: Array[Int] = null)(implicit context: Context): Unit = { - if (dims.sum > 0) { - lazy val defaultContainers = args collect { case c: CLEventBoundContainer => c } - CLEventBound.syncBlock( - CLEventBound.flatten(Option(reads).getOrElse(defaultContainers)), - CLEventBound.flatten(Option(writes).getOrElse(defaultContainers)), - evts => { - run(dims = dims, args = args, eventsToWaitFor = evts) - } - ) - } - } -} - -import CLFunctionCode._ - -class CLFunction[A, B]( - val function: A => B, - val code: CLFunctionCode[A, B] -)( - implicit - val aIO: CLDataIO[A], - val bIO: CLDataIO[B] -) -extends (A => B) - with CLRunnable -{ - def this( - function: A => B, - outerDeclarations: Array[String], - declarations: Array[String], - expressions: Array[String], - includedSources: Array[String], - extraArgsIOs: CapturedIOs = CapturedIOs() - )(implicit aIO: CLDataIO[A], bIO: CLDataIO[B]) = { - this( - function, - if (expressions.isEmpty) null - else - new CLFunctionCode[A, B]( - buildSourceData[A, B]( - outerDeclarations, - declarations, - expressions, - includedSources, - extraArgsIOs - ) - ) - ) - } - override def isOnlyInScalaSpace = code == null - - import code._ - - def apply(arg: A): B = - if (function == null) - error("Function is not defined in Scala land !") - else - function(arg) - - def compose[C](f: CLFunction[C, A])(implicit cIO: CLDataIO[C]): CLFunction[C, B] = { - new CLFunction[C, B]( - function.compose(f.function), - code.compose(f.code) - ) - } - - def and(f: CLFunction[A, B])(implicit el: B =:= Boolean): CLFunction[A, B] = { - new CLFunction[A, B]( - a => (function(a) && f.function(a)).asInstanceOf[B], - code.and(f.code) - ) - } - - /** - * Args must be : Array(in, out, extraInputBuffers..., extraOutputBuffers..., extraScalars...) - */ - override def run(dims: Array[Int], args: Array[Any], eventsToWaitFor: Array[CLEvent])(implicit context: Context): CLEvent = - { - val in = args(0)//.asInstanceOf[CLCollection[A]] - val out = args(1)//.asInstanceOf[CLCollection[B]] - val extraArgs = args.drop(2) - - val nExtraInputBufferArgs = extraArgsIOs.inputBuffers.size - val nExtraOutputBufferArgs = extraArgsIOs.outputBuffers.size - val nExtraBufferArgs = nExtraInputBufferArgs + nExtraOutputBufferArgs - val nExtraScalarArgs = extraArgsIOs.scalars.size - - val extraInputBufferArgs: Array[CLArray[Any]] = extraArgs.take(nExtraInputBufferArgs).map(_.asInstanceOf[CLArray[Any]]) - val extraOutputBufferArgs: Array[CLArray[Any]] = extraArgs.slice(nExtraInputBufferArgs, nExtraBufferArgs).map(_.asInstanceOf[CLArray[Any]]) - val extraScalarArgs: Array[Any] = extraArgs.drop(nExtraBufferArgs) - - run(dims, in, out, extraInputBufferArgs, extraOutputBufferArgs, extraScalarArgs, eventsToWaitFor) - } - - def withCapture( - extraInputBufferArgs: Array[CLArray[Any]], - extraOutputBufferArgs: Array[CLArray[Any]], - extraScalarArgs: Array[Any] - ) = { - new CLFunction[A, B](function, code) { - override def run(dims: Array[Int], args: Array[Any], eventsToWaitFor: Array[CLEvent])(implicit context: Context): CLEvent = - { - val Array(in, out) = args - run(dims, in, out, extraInputBufferArgs, extraOutputBufferArgs, extraScalarArgs, eventsToWaitFor) - } - } - } - - protected def getActualArgs(arg: Any, skipPresenceInFilteredArray: Boolean = false): (Array[AnyRef], Array[CLGuardedBuffer[Any]]) = arg match { - case g: CLGuardedBuffer[_] => - (Array(g.buffer), Array(g.asInstanceOf[CLGuardedBuffer[Any]])) - case a: CLArray[Any] => - val bufs = a.buffers - (bufs.map(_.buffer), bufs) - case r: CLRange => - val bufs = Array(r.buffer.asInstanceOf[CLGuardedBuffer[Any]]) - (bufs.map(_.buffer), bufs) - case f: CLFilteredArray[_] => - var bufs = f.array.buffers - // prepend presence : - if (!skipPresenceInFilteredArray) - bufs = f.presence.asInstanceOf[CLGuardedBuffer[Any]] +: bufs - - (bufs.map(_.buffer), bufs) - } - - protected def getFunctionKernelNameAndSizeFromInAndOut(in: Any, out: Any) = (in, out) match { - case (in: CLArray[Any], out: CLGuardedBuffer[Any]) => // case of CLArray.filter (output to the presence array of a CLFilteredArray - ("array_array", in.length) - case (in: CLArray[Any], out: CLArray[Any]) => // CLArray.map - ("array_array", in.length) - case (in: CLRange, out: CLArray[Any]) => // CLRange.map - ("range_array", out.length) - case (in: CLRange, out: CLGuardedBuffer[_]) => // CLRange.map - ("range_array", in.length) - case (in: CLFilteredArray[_], out: CLFilteredArray[Any]) => // CLFilteredArray.map - ("filteredArray_filteredArray", in.array.length) - case _ => - error("ERROR, in = " + in + ", out = " + out) - } - - def run( - dims: Array[Int], - in: Any,//CLCollection[A], - out: Any,//CLCollection[B], - extraInputBufferArgs: Array[CLArray[Any]], - extraOutputBufferArgs: Array[CLArray[Any]], - extraScalarArgs: Array[Any], - eventsToWaitFor: Array[CLEvent] - )(implicit context: Context): CLEvent = { - - val (inArgs, readBufs) = getActualArgs(in) - val (outArgs, writeBufs) = getActualArgs(out, skipPresenceInFilteredArray = true) - - val extraInBufs = extraInputBufferArgs.flatMap(_.buffers) - val extraOutBufs = extraOutputBufferArgs.flatMap(_.buffers) - - val (kernelName, size: Int) = getFunctionKernelNameAndSizeFromInAndOut(in, out) - - val kernel = code.getKernel(context, kernelName) - assert(kernel.getFunctionName() == kernelName, "not getting the expected kernel !") - - val kernelArgs: Array[AnyRef] = - Array(size.asInstanceOf[AnyRef]) ++ - inArgs ++ - outArgs ++ - extraInBufs.map(_.buffer) ++ - extraOutBufs.map(_.buffer) ++ - extraScalarArgs.map(_.asInstanceOf[AnyRef]) - - val readBuffers: Array[CLEventBound] = readBufs ++ extraInBufs - val writeBuffers: Array[CLEventBound] = writeBufs ++ extraOutBufs - - CLEventBound.syncBlock( - readBuffers, - writeBuffers, - evts => { - kernel.synchronized { - try { - //println("kernelArgs = \n\t" + kernelArgs.map(a => a + ": " + a.getClass.getName).mkString("\n\t")) - kernel.setArgs(kernelArgs:_*) - if (verbose) - println("[ScalaCL] Enqueuing kernel " + kernelName + " with dims " + dims.mkString(", ")) - kernel.enqueueNDRange(context.queue, dims, evts ++ eventsToWaitFor:_*) - } catch { case ex => - ex.printStackTrace(System.out) - throw ex - } - } - } - ) - - } -} \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunctionCode.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunctionCode.scala deleted file mode 100644 index ab9cf4364..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFunctionCode.scala +++ /dev/null @@ -1,422 +0,0 @@ -package scalacl - -package impl - -import scala.collection._ -//import com.nativelibs4java.opencl._ - - -//import CLFunction._ -case class CapturedIOs( - inputBuffers: Array[CLDataIO[Any]] = Array(), - outputBuffers: Array[CLDataIO[Any]] = Array(), - scalars: Array[CLDataIO[Any]] = Array() -) { - lazy val isEmpty = - inputBuffers.isEmpty && outputBuffers.isEmpty && scalars.isEmpty -} - -case class SourceData( - functionName: String, - functionSource: String, - kernelsSource: String, - includedSources: Array[String], - outerDeclarations: Seq[String] -) - -object CLFunctionCode { - private var nextuid = 1 - protected def newuid = this.synchronized { - val uid = nextuid - nextuid += 1 - uid - } - def clType[T](implicit dataIO: CLDataIO[T]) = dataIO.clType - - val compositions = new mutable.HashMap[(Long, Long), CLFunctionCode[_, _]] - val ands = new mutable.HashMap[(Long, Long), CLFunctionCode[_, _]] - - protected val indexVar: String = "$i" - protected val sizeVar: String = "$size" - protected val clVarPrefix = "__cl_" - protected val indexVarName = clVarPrefix + "i" - protected val sizeVarName = clVarPrefix + "size" - - - sealed trait ArgKind - object ParallelInputValueArg extends ArgKind - object ParallelOutputValueArg extends ArgKind - object InputBufferArg extends ArgKind - object OutputBufferArg extends ArgKind - object InputScalarArg extends ArgKind - - case class ArgInfo( - io: CLDataIO[_], - kind: ArgKind - ) - trait FiberReplacementContent { - def apply(parallelIndexesExprs: Seq[String], isParallelInputARange: Boolean): String - } - trait ReplacementContent { - def apply(parallelIndexesExprs: Seq[String]): Seq[(String, List[Int])] - } - case class FiberInfo( - pattern: String, - tupleIndexes: List[Int], - replacementContent: FiberReplacementContent - ) - case class ReplacementInfo( - nameBasis: String, - //pattern: Option[String], - argInfo: ArgInfo, - //offset: Int, - kernelParamsDeclarations: Seq[String], - functionParamsDeclarations: Seq[String], - fiberInfos: Option[Seq[FiberInfo]], - replacementContent: ReplacementContent - ) - - def getReplacements(argInfos: Seq[ArgInfo]): Seq[ReplacementInfo] = { - case class ArgOffsets(fiberOffset: Int, extraArgOffset: Int) - val argsWithOffsets = argInfos.zip(argInfos.scanLeft((0, 0)) { case ((offset, extraArgs), argInfo) => - ( - offset + argInfo.io.elementCount, - extraArgs + (argInfo.kind match { - case InputBufferArg | OutputBufferArg | InputScalarArg => 1 - case _ => 0 - }) - ) - }).map { case (argInfo, (offset, extraArgs)) => (argInfo, ArgOffsets(offset, extraArgs)) } - - argsWithOffsets map { - case (argInfo, offsets) => - import CLDataIO.{ InputPointer, OutputPointer, Value } - - val (nameBasis, argTypeForKernel, argTypeForFunction, fiberInfos) = argInfo.kind match { - case ParallelInputValueArg => - val nameBasis = clVarPrefix + "in" - (nameBasis, InputPointer, Value, Some(argInfo.io.openCLIntermediateKernelTupleElementsExprs("_") map { - case (expr, tupleIndexes) => - FiberInfo(expr, tupleIndexes, new FiberReplacementContent { - override def apply(parallelIndexesExprs: Seq[String], isParallelInputARange: Boolean) = { - val Seq(i) = parallelIndexesExprs - - def getRawIthArrayElement(i: String) = - argInfo.io.openCLIthTupleElementNthItemExpr( - nameBasis, - InputPointer, - offsets.fiberOffset, - tupleIndexes, - i - ) - - if (isParallelInputARange) - "(" + - getRawIthArrayElement("0") + - " + (" + i + ") * " + - getRawIthArrayElement("2") + - ")" // buffer contains (from, to, by, inclusive). Value is (from + i * by) - else - getRawIthArrayElement(i) - } - }) - })) - case ParallelOutputValueArg => - (clVarPrefix + "out", OutputPointer, OutputPointer, None) - case _ => - val (nameBasis, argTypeForKernel, argTypeForFunction) = argInfo.kind match { - case InputBufferArg => - (clVarPrefix + "capturedIn", InputPointer, InputPointer) - case OutputBufferArg => - (clVarPrefix + "capturedOut", OutputPointer, OutputPointer) - case InputScalarArg => - (clVarPrefix + "capturedVal", Value, Value) - case _ => - null - } - - def fiberInfos(nameBasis: String) = - argInfo.io.openCLIntermediateKernelTupleElementsExprs( - "_" + (offsets.extraArgOffset + 1) - ) map { case (expr, tupleIndexes) => - FiberInfo(expr, tupleIndexes, new FiberReplacementContent { - override def apply(parallelIndexesExprs: Seq[String], isParallelInputARange: Boolean) = { - //expr - argInfo.io.openCLIthTupleElementNthItemExpr( - nameBasis, - Value, - offsets.fiberOffset, - tupleIndexes, - "0" - ) - } - }) - } - - (nameBasis, argTypeForKernel, argTypeForFunction, Some(fiberInfos(nameBasis))) - } - - ReplacementInfo( - nameBasis, - argInfo, - //offsets.fibersOffset, - kernelParamsDeclarations = - argInfo.io.openCLKernelArgDeclarations(nameBasis, argTypeForKernel, offsets.fiberOffset), - functionParamsDeclarations = - argInfo.io.openCLKernelArgDeclarations(nameBasis, argTypeForFunction, offsets.fiberOffset), - fiberInfos = fiberInfos, - new ReplacementContent { - override def apply(parallelIndexesExprs: Seq[String]) = { - val Seq(i) = parallelIndexesExprs - argInfo.io.openCLKernelNthItemExprs(nameBasis, CLDataIO.OutputPointer, offsets.fiberOffset, i) - } - } - ) - } - } - def toRxb(s: String) = { - "(^|\\b)" + - java.util.regex.Matcher.quoteReplacement(s) + - "($|\\b)" - } - - def getFibersReplacementInfos(replacementInfos: Seq[ReplacementInfo]): Seq[(ReplacementInfo, FiberInfo)] = { - replacementInfos.flatMap(ri => ri.fiberInfos.map(_.map(fi => (ri, fi)))).flatten - } - def replaceAll(s: String, isParallelInputARange: Boolean, fibersReplacementInfos: Seq[(ReplacementInfo, FiberInfo)], i: String = indexVarName): String = { - var r = s.replaceAll(toRxb(indexVar), indexVarName) - r = r.replaceAll(toRxb(sizeVar), sizeVarName) - - var sortedInfos: Seq[(ReplacementInfo, FiberInfo)] = - fibersReplacementInfos.filter(_._1.argInfo.kind != ParallelOutputValueArg). // don't replace the output - sortBy({ case (ri, fi) => -fi.pattern.length }) // replace longest patterns first... - - for ((replacementInfo, fiberInfo) <- sortedInfos) { - val x = fiberInfo.replacementContent(Seq(i), isParallelInputARange) - val expr = fiberInfo.pattern - - //println("REPLACING '" + expr + "' by '" + x + "'") - r = r.replaceAll(toRxb(expr), x) - //println("\t-> '" + r.replaceAll("\n", "\n\t") + "'") - } - - r - } - - def outputFunction(beforeParams: String, params: Seq[Seq[String]], body: Seq[Seq[String]], out: StringBuilder = new StringBuilder): StringBuilder = { - //import out.{ append => << } - out append beforeParams append '(' - var first = true - for (sub <- params; param <- sub) { - if (first) - first = false - else - out append ", " - out append param - } - out append ") {\n" - for (sub <- body; stat <- sub) - out append '\t' append stat append '\n' - - out append "}\n" - - out - } - - def buildSourceData[A, B]( - outerDeclarations: Array[String], - declarations: Array[String], - expressions: Array[String], - includedSources: Array[String], - extraArgsIOs: CapturedIOs = CapturedIOs(), - bodyPrefix: Array[String] = Array(), - bodySuffix: Array[String] = Array() - )(implicit aIO: CLDataIO[A], bIO: CLDataIO[B]): SourceData = - { - assert(!expressions.isEmpty) - - val uid = newuid - val functionName = "f" + uid - - val argInfos = - Seq( - ArgInfo(aIO, ParallelInputValueArg), - ArgInfo(bIO, ParallelOutputValueArg) - ) ++ - extraArgsIOs.inputBuffers.map(ArgInfo(_, InputBufferArg)) ++ - extraArgsIOs.outputBuffers.map(ArgInfo(_, OutputBufferArg)) ++ - extraArgsIOs.scalars.map(ArgInfo(_, InputScalarArg)) - - //println("argInfos = " + argInfos) - - val replacementInfos = getReplacements(argInfos) - val fibersReplacementInfos = getFibersReplacementInfos(replacementInfos) - //println("replacementInfos = " + replacementInfos) - - - val indexHeader = Seq("int " + indexVarName + " = get_global_id(0);") - val sizeHeader = Seq("if (" + indexVarName + " >= " + sizeVarName + ") return;") - - val outputFibersInfos = replacementInfos.filter(_.argInfo.kind == ParallelOutputValueArg) - - def getAssignments(i: String, isRange: Boolean): Seq[String] = - expressions.zip(outputFibersInfos.flatMap(_.replacementContent(Seq(i)))).map { - case (expression, (xOut, indexes)) => xOut + " = " + replaceAll(expression, isRange, fibersReplacementInfos, i) + ";" - } - - - val funDecls = declarations.map(replaceAll(_, false, fibersReplacementInfos, "0")) - //lazy val funDeclsRange = declarations.map(replaceAll(_, true, replacementInfos, "0")) - var kernelParams = replacementInfos.flatMap(_.kernelParamsDeclarations) - var functionParams = replacementInfos.flatMap(_.functionParamsDeclarations) - - val functionSource = ""/*outputFunction( - "inline void " + functionName, - Seq(functionParams), - Seq( - indexHeader, - funDecls, - getAssignments("0", false) - ) - ).toString*/ - - val presenceName = "__cl_presence" - val presenceParam = Seq("__global const " + CLFilteredArray.presenceCLType + "* " + presenceName) - val presenceHeader = Seq("if (!" + presenceName + "[" + indexVarName + "]) return;") - - val sizeParam = Seq("int " + sizeVarName) - - val kernDeclsArray = declarations.map(replaceAll(_, false, fibersReplacementInfos)) - lazy val kernDeclsRange = declarations.map(replaceAll(_, true, fibersReplacementInfos)) - - val assigntArray = getAssignments(indexVarName, false) - lazy val assigntRange = getAssignments(indexVarName, true) - - val kernelsSource = new StringBuilder - for (outerDeclaration <- outerDeclarations) - kernelsSource.append(outerDeclaration).append('\n') - - outputFunction( - "__kernel void array_array", - Seq(sizeParam, kernelParams), - Seq( - bodyPrefix, - indexHeader, - sizeHeader, - kernDeclsArray, - assigntArray, - bodySuffix - ), - kernelsSource - ) - outputFunction( - "__kernel void filteredArray_filteredArray", - Seq(sizeParam, presenceParam, kernelParams), - Seq( - bodyPrefix, - indexHeader, - sizeHeader, - presenceHeader, - kernDeclsArray, - assigntArray, - bodySuffix - ), - kernelsSource - ) - - if (aIO.t.erasure == classOf[Int]) {// || aIO.t.erasure == classOf[Integer])) { - outputFunction( - "__kernel void range_array", - Seq(sizeParam, kernelParams), - Seq( - bodyPrefix, - indexHeader, - sizeHeader, - kernDeclsRange, - assigntRange, - bodySuffix - ), - kernelsSource - ) - } - if (verbose) - println("[ScalaCL] Creating kernel with source <<<\n\t" + kernelsSource.toString.replaceAll("\n", "\n\t") + "\n>>>") - - SourceData( - functionName = functionName, - functionSource = functionSource, - kernelsSource = kernelsSource.toString, - includedSources = includedSources, - outerDeclarations = outerDeclarations - ) - } -} - -import CLFunctionCode._ - -class CLFunctionCode[A, B]( - val sourceData: SourceData, - val extraArgsIOs: CapturedIOs = CapturedIOs() -)( - implicit - val aIO: CLDataIO[A], - val bIO: CLDataIO[B] -) -extends CLCode -{ - import sourceData._ - - val uid = newuid - - val sourcesToInclude = - //if (sourceData == null) null else - includedSources ++ Array(functionSource) - - override val sources = - //if (sourceData == null) null else - sourcesToInclude ++ Array(kernelsSource) - - override val macros = Map[String, String]() - override val compilerArguments = Array[String]() - - //override def isOnlyInScalaSpace = sourceData == null - - protected def throwIfCapture(f: CLFunctionCode[_, _]) = { - if (!extraArgsIOs.isEmpty) - throw new UnsupportedOperationException("Cannot compose functions that capture external variables !") - } - - def compose[C](f: CLFunctionCode[C, A])(implicit cIO: CLDataIO[C]) = { - throwIfCapture(f) - - compositions.synchronized { - compositions.getOrElseUpdate((uid, f.uid), { - // TODO FIXME ! - new CLFunctionCode[C, B]( - sourceData = buildSourceData[C, B]( - outerDeclarations = Array(),// TODO ??? outerDeclarations ++ f.outerDeclarations, - declarations = Array(), - expressions = Array(functionName + "(" + f.sourceData.functionName + "(_))"), - includedSources = sourcesToInclude ++ f.sourcesToInclude - )(f.aIO, bIO) - ).asInstanceOf[CLFunctionCode[_, _]] - }).asInstanceOf[CLFunctionCode[C, B]] - } - } - - def and(f: CLFunctionCode[A, B]) = { - ands.synchronized { - ands.getOrElseUpdate((uid, f.uid), { - // TODO FIXME ! - new CLFunctionCode[A, B]( - sourceData = buildSourceData[A, B]( - outerDeclarations = Array(), - declarations = Array(), - expressions = Array("(" + functionName + "(_) && " + f.sourceData.functionName + "(_))"), - includedSources = sourcesToInclude ++ f.sourcesToInclude - ) - ).asInstanceOf[CLFunctionCode[_, _]] - }).asInstanceOf[CLFunctionCode[A, B]] - } - } -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFuture.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFuture.scala deleted file mode 100644 index 466c3c49b..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLFuture.scala +++ /dev/null @@ -1,34 +0,0 @@ -package scalacl - -package impl - -import com.nativelibs4java.opencl._ - -import org.bridj.Pointer -import org.bridj.Pointer._ - - -trait CLFuture[T] { - def get: T -} - -trait CLEventFuture[T] extends CLEventBound with CLFuture[T] { - protected def doGet: T - override def get = readBlock { doGet } - def apply = get -} - -case class CLInstantFuture[T](value: T) extends CLFuture[T] { - override def get = value -} -case class CLPointerFuture[T](ptr: Pointer[T], evt: CLEvent) extends CLEventFuture[T] { - //evt.waitFor - - lastWriteEvent = evt - - protected override def doGet = ptr.get -} - -class CLTupleFuture[T](ff: Array[CLFuture[Any]], tuple: Array[Any] => T) extends CLFuture[T] { - override def get = tuple(ff.map(_.get)) -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLGuardedBuffer.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLGuardedBuffer.scala deleted file mode 100644 index bd00344a8..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLGuardedBuffer.scala +++ /dev/null @@ -1,142 +0,0 @@ -package scalacl - -package impl - -import scala.collection.generic.CanBuildFrom -import com.nativelibs4java.opencl._ - -import com.nativelibs4java.opencl._ -import org.bridj.Pointer -import org.bridj.Pointer._ - -object CLGuardedBuffer { - val debugFakeClone = System.getenv("SCALACL_DEBUG_FAKE_CLONE") == "1" -} - -trait CopiableToCLArray[A] { - def copyTo(other: CLArray[A]): Unit -} -class CLGuardedBuffer[T](val buffer: CLBuffer[T])(implicit val context: Context, val dataIO: CLDataIO[T]) -extends CLEventBound -{ - implicit val t = dataIO.t - lazy val elementClass = t.erasure.asInstanceOf[Class[T]] - - def this(size: Long)(implicit context: Context, dataIO: CLDataIO[T]) = { - this(context.context.createBuffer(CLMem.Usage.InputOutput, dataIO.pointerIO, size)) - //clear - } - - def this(values: Array[T])(implicit context: Context, dataIO: CLDataIO[T]) = { - this(context.context.createBuffer(CLMem.Usage.InputOutput, { - val ptr = allocateArray(dataIO.pointerIO, values.length) - ptr.setArray(values) - ptr - }, - true - )) - } - - def clear = { - write(evts => dataIO.clear(buffer, evts:_*)) - } - def release = { - releaseEvents - buffer.release - } - - def args = Seq(buffer) - - def apply(index: Long): CLFuture[T] = { - val b: Pointer[T] = allocate(elementClass) - new CLPointerFuture[T](b, read(evts => buffer.read(context.queue, index, 1, b, false, evts:_*))) - } - - def update(values: Array[T]): CLGuardedBuffer[T] = { - val b: Pointer[T] = pointerToArray(values) - write(evts => buffer.write(context.queue, 0, b.getValidElements, b, false, evts:_*)) - this - } - - def withReadablePointer[V](f: Pointer[T] => V): V = withPointer(CLMem.MapFlags.Read, f) - def withWritablePointer[V](f: Pointer[T] => V): V = withPointer(CLMem.MapFlags.Write, f) - def withReadableWritablePointer[V](f: Pointer[T] => V): V = withPointer(CLMem.MapFlags.ReadWrite, f) - - def withReadableMappedPointer[V](f: Pointer[T] => V): Option[V] = withMappedPointer(CLMem.MapFlags.Read, f) - def withWritableMappedPointer[V](f: Pointer[T] => V): Option[V] = withMappedPointer(CLMem.MapFlags.Write, f) - def withReadableWritableMappedPointer[V](f: Pointer[T] => V): Option[V] = withMappedPointer(CLMem.MapFlags.ReadWrite, f) - - protected def withPointer[V](usage: CLMem.MapFlags, f: Pointer[T] => V): V = this synchronized { - withMappedPointer(usage, f).getOrElse { - var copied = toPointer - try { - f(copied) - } finally { - copied.release - } - } - } - - protected def withMappedPointer[V](usage: CLMem.MapFlags, f: Pointer[T] => V): Option[V] = this synchronized { - var mapped: Pointer[T] = null - try { - //println("Map...") - CLEventBound.syncBlock(Array(this), Array(), evts => { - mapped = buffer.map(context.queue, usage, evts:_*) - null - }) - //println("Map succeeded !") - Some(f(mapped)) - } catch { - case ex: CLException.MapFailure => - //println("Map failed !") - None - } finally { - if (mapped != null) - buffer.unmap(context.queue, mapped) - } - } - - def update(index: Long, value: T): Unit = { - val b: Pointer[T] = allocate(elementClass) - b.set(value) - write(evts => buffer.write(context.queue, index, 1, b, false, evts:_*)) - } - - def toPointer: Pointer[T] = - readValue(evts => buffer.read(context.queue, evts:_*)) - - def toArray: Array[T] = toPointer.getArray.asInstanceOf[Array[T]] - - val size = buffer.getElementCount - - - override def clone: CLGuardedBuffer[T] = { - // TODO allocate and copy on write, with value groups ! - if (CLGuardedBuffer.debugFakeClone) - this - else { - val out = new CLGuardedBuffer(context.context.createBuffer(CLMem.Usage.InputOutput, elementClass, size)) - copyTo(out) - out - } - } - - def copyTo(out: CLGuardedBuffer[T]): Unit = if (this ne out) { - assert(buffer.getByteCount == out.buffer.getByteCount) - CLEventBound.syncBlock(Array(this), Array(out), evts => { - buffer.copyTo(context.queue, 0, size /* * buffer.getElementSize*/, out.buffer, 0, evts:_*) - }) - } - def clone(start: Long, end: Long): CLGuardedBuffer[T] = { - val newSize = end - start - assert(newSize > 0) - assert(start > 0) - assert(end <= size) - val out = new CLGuardedBuffer(context.context.createBuffer(CLMem.Usage.InputOutput, elementClass, newSize)) - CLEventBound.syncBlock(Array(this), Array(out), evts => { - buffer.copyTo(context.queue, start, newSize, out.buffer, 0, readEvents:_*) - }) - out - } -} diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLSimpleCode.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLSimpleCode.scala deleted file mode 100644 index 660ddeac4..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/CLSimpleCode.scala +++ /dev/null @@ -1,53 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl._ - -class CLSimpleCode( - override val sources: Array[String], - override val compilerArguments: Array[String], - override val macros: Map[String, String], - val kernelName: Option[String] = None -) extends CLCode with CLRunnable { - def this(source: String) = this(Array(source), Array(), Map()) - - override def isOnlyInScalaSpace = false - - protected def flattenArgs(arg: Any): Array[AnyRef] = arg match { - case g: CLGuardedBuffer[_] => - Array(g.buffer) - case a: CLArray[Any] => - a.buffers.map(_.buffer) - case r: CLRange => - Array(r.buffer.buffer) - case f: CLFilteredArray[_] => - f.presence.buffer +: f.array.buffers - case Int | Short | Long | Byte | Char | Boolean | Double | Float => - Array(arg.asInstanceOf[AnyRef]) - } - - protected override def run(dims: Array[Int], args: Array[Any], eventsToWaitFor: Array[CLEvent])(implicit context: Context): CLEvent = { - val kernel = kernelName.map(getKernel(context, _)).getOrElse { - val (program, kernels) = getProgramAndKernels(context) - if (kernels.size != 1) - throw new RuntimeException("Expected a unique kernel in the program, found " + kernels.size + " : " + kernels.keys.mkString(", ")) - - kernels.first._2 - } - - val flatArgs = args.flatMap(flattenArgs _) - - kernel.synchronized { - try { - kernel.setArgs(flatArgs:_*) - if (verbose) - println("[ScalaCL] Enqueuing kernel " + kernel.getFunctionName + " with dims " + dims.mkString(", ")) - kernel.enqueueNDRange(context.queue, dims, eventsToWaitFor:_*) - } catch { case ex => - ex.printStackTrace(System.out) - throw ex - } - } - } -} - diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/GroupedPrefixSum.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/GroupedPrefixSum.scala deleted file mode 100644 index dda837987..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/GroupedPrefixSum.scala +++ /dev/null @@ -1,297 +0,0 @@ -package scalacl -package impl - -// Ported from http://developer.apple.com/library/mac/#samplecode/OpenCL_Parallel_Prefix_Sum_Example/ -import scala.collection._ -import com.nativelibs4java.opencl._ -import scala.math._ -import org.bridj._ -import org.bridj.Pointer._ -import com.nativelibs4java.util.IOUtils.readText -import scala.collection.JavaConversions._ - -class GroupedPrefixSum[A]( - implicit val context: Context, - val dataIO: CLDataIO[A] -) { - val source: String = readText(Platform.getClassLoader(classOf[GroupedPrefixSum[_]]).getResourceAsStream("scalacl/impl/scan_kernel.cl")) - val devices = context.getDevices - val program = context.createProgram(source) - program.defineMacro("DATA_TYPE", dataIO.clType) - - val kernels @ Array( - preScanKernel, - preScanStoreSumKernel, - preScanStoreSumNonPowerOfTwoKernel, - preScanNonPowerOfTwoKernel, - uniformAddKernel - ) = Array( - "PreScanKernel", - "PreScanStoreSumKernel", - "PreScanStoreSumNonPowerOfTwoKernel", - "PreScanNonPowerOfTwoKernel", - "UniformAddKernel" - ).map(n => program.createKernel(n)) - - val GROUP_SIZE = (Array(256) ++ kernels.flatMap(_.getWorkGroupSize.values.map(_.longValue.toInt)) ++ devices.map(_.getMaxWorkGroupSize.toInt)).min - //println("GROUP_SIZE = " + GROUP_SIZE) - - val dataSize = dataIO.elementSize - val dataClass = dataIO.t.erasure.asInstanceOf[Class[A]] - val NUM_BANKS = (16) - - private def IsPowerOfTwo(n: Int) = - ((n & (n - 1)) == 0) - - /* - private def floorPow2(n: Int) = { - var v = n - var ret = 0 - while (v != 0) { - v = v >> 1 - ret += 1 - } - ret - } //*/ - //* - // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious - private def floorLog2(n: Int) = { - var x = n - var ret = 0 - if ((x & 0xffff0000) != 0) { ret += 16; x >>= 16; } - if ((x & 0x0000ff00) != 0) { ret += 8; x >>= 8; } - if ((x & 0x000000f0) != 0) { ret += 4; x >>= 4; } - if ((x & 0x0000000c) != 0) { ret += 2; x >>= 2; } - if ((x & 0x00000002) != 0) { ret += 1; } - ret - } - private def floorPow2(n: Int) = - 1 << floorLog2(n) - //*/ - - @inline private def ceilFunc(elementCount: Int, groupSize: Int) = - max(1, ceil(elementCount / (2.0f * groupSize)).toInt) - - private def CreatePartialSumBuffers(count: Int) = { - var group_size = GROUP_SIZE - var element_count = count - - var level = 0 - - do { - val group_count = ceilFunc(element_count, group_size) - if (group_count > 1) { - level += 1 - } - element_count = group_count - - } while (element_count > 1) - - val ScanPartialSums = new Array[CLBuffer[A]](level) - - element_count = count - level = 0 - - do { - val group_count = ceilFunc(element_count, group_size) - if (group_count > 1) { - ScanPartialSums(level) = context.createBuffer(CLMem.Usage.InputOutput, dataClass, group_count) - level += 1 - } - - element_count = group_count - - } while (element_count > 1) - - ScanPartialSums - } - - private def PreScanBufferRecursive( - ScanPartialSums: Array[CLBuffer[A]], - output_data: CLBuffer[A], - input_data: CLBuffer[A], - max_group_size: Int, - max_work_item_count: Int, - element_count: Int, - level: Int): Unit = - { - val group_size = max_group_size - val group_count = ceilFunc(element_count, group_size) - var work_item_count = 0 - - if (group_count > 1) - work_item_count = group_size - else if (IsPowerOfTwo(element_count)) - work_item_count = element_count / 2 - else - work_item_count = floorPow2(element_count) - - work_item_count = if (work_item_count > max_work_item_count) max_work_item_count else work_item_count - - val element_count_per_group = work_item_count * 2 - val last_group_element_count = element_count - (group_count - 1) * element_count_per_group - var remaining_work_item_count = max(1, last_group_element_count / 2) - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - var remainder = 0 - var last_shared = 0L - - - if (last_group_element_count != element_count_per_group) { - remainder = 1 - - if (!IsPowerOfTwo(last_group_element_count)) - remaining_work_item_count = floorPow2(last_group_element_count) - - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - val padding = (2 * remaining_work_item_count) / NUM_BANKS - last_shared = dataSize * (2 * remaining_work_item_count + padding) - } - - remaining_work_item_count = if (remaining_work_item_count > max_work_item_count) max_work_item_count else remaining_work_item_count - val global = Array(max(1, group_count - remainder) * work_item_count, 1) - val local = Array(work_item_count, 1) - - val padding = element_count_per_group / NUM_BANKS - val shared = dataSize * (element_count_per_group + padding) - - val partial_sums = if (level >= ScanPartialSums.size) null else ScanPartialSums(level) - - if (group_count > 1) { - preScanStoreSumKernel.enqueueNDRange(global, local)( - output_data, - input_data, - partial_sums, - new LocalSize(shared), - 0, //group_index - 0, //base_index - work_item_count * 2 - ) - - if (remainder != 0) { - val last_global = Array(1 * remaining_work_item_count, 1) - val last_local = Array(remaining_work_item_count, 1) - - preScanStoreSumNonPowerOfTwoKernel.enqueueNDRange(last_global, last_local)( - output_data, - input_data, - partial_sums, - new LocalSize(last_shared), - group_count - 1, // group_index, - element_count - last_group_element_count, // base_index, - last_group_element_count - ) - } - - PreScanBufferRecursive(ScanPartialSums, partial_sums, partial_sums, max_group_size, max_work_item_count, group_count, level + 1) - - uniformAddKernel.enqueueNDRange(global, local)( - output_data, - partial_sums, - new LocalSize(dataSize), - 0, //group_offset - 0, //base_index - element_count - last_group_element_count - ) - - if (remainder != 0) { - val last_global = Array(1 * remaining_work_item_count, 1) - val last_local = Array(remaining_work_item_count, 1) - - uniformAddKernel.enqueueNDRange(last_global, last_local)( - output_data, - partial_sums, - new LocalSize(dataSize), - group_count - 1, //group_offset - element_count - last_group_element_count, //base_index - last_group_element_count - ) - } - } - else if (IsPowerOfTwo(element_count)) { - preScanKernel.enqueueNDRange(global, local)( - output_data, - input_data, - new LocalSize(shared), - 0, //group_index - 0, //base_index - work_item_count * 2 - ) - } - else { - preScanNonPowerOfTwoKernel.enqueueNDRange(global, local)( - output_data, - input_data, - new LocalSize(shared), - 0, //group_index - 0, //base_index - element_count - ) - } - } - - def prefixSum(input_buffer: CLBuffer[A], evtsToWaitFor: CLEvent*): (CLBuffer[A], CLEvent) = - { - val count = input_buffer.getElementCount.toInt - val output_buffer = context.createBuffer(CLMem.Usage.InputOutput, dataClass, count) - (output_buffer, prefixSum(input_buffer, output_buffer, evtsToWaitFor:_*)) - } - def prefixSum(input_buffer: CLBuffer[A], output_buffer: CLBuffer[A], evtsToWaitFor: CLEvent*): CLEvent = - { - assert(input_buffer != null, "null input buffer") - assert(output_buffer != null, "null output buffer") - - val count = input_buffer.getElementCount.toInt - assert(output_buffer.getElementCount == count, "invalid output buffer size (expected " + count + ", got " + output_buffer.getElementCount + ")") - - if (context.queue.isOutOfOrder) - CLEvent.waitFor(evtsToWaitFor:_*) // TODO use these events - - // TODO remove this - //output_buffer.write(context.queue, allocateArray(dataClass, count), true) - - var ScanPartialSums = CreatePartialSumBuffers(count) - - PreScanBufferRecursive( - ScanPartialSums, - output_buffer, - input_buffer, - GROUP_SIZE, - GROUP_SIZE, - count, - 0 - ) - - ScanPartialSums.map(_.release) - - if (context.queue.isOutOfOrder) - context.queue.finish // TODO return events ! - null - } -} - -object GroupedPrefixSum { - - private val cache = new mutable.HashMap[(Context, Class[_]), GroupedPrefixSum[_]] - def apply[A](implicit context: Context, dataIO: CLDataIO[A]) = cache synchronized { - cache.getOrElseUpdate((context, dataIO.t.erasure), new GroupedPrefixSum[A]).asInstanceOf[GroupedPrefixSum[A]] - } -/* - def main(args: Array[String]) { - implicit val context = Context.best(CPU) - val n = 10 - val inputValues = allocateInts(n).as(classOf[Int]) - for (i <- 0 until n) - inputValues(i) = i - - val scanner = GroupedPrefixSum[Int] - val inputBuffer = context.createBuffer(CLMem.Usage.InputOutput, inputValues, true) - val (outputBuffer, evt) = scanner.prefixSum(inputBuffer) - CLEvent.waitFor(evt) - - val expectedValues = (0 until n).scanLeft(0)(_ + _) - val outputValues = outputBuffer.read(context.queue) - for (i <- 0 until n) - println("At " + i + ", expected " + expectedValues(i) + ", got " + outputValues(i)) - } -*/ -} \ No newline at end of file diff --git a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/PrefixSum.scala b/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/PrefixSum.scala deleted file mode 100644 index f0825c7ce..000000000 --- a/libraries/ScalaCL/Collections/src/main/scala/scalacl/impl/PrefixSum.scala +++ /dev/null @@ -1,72 +0,0 @@ -package scalacl - -package impl - -import org.bridj.PointerIO -import org.bridj.SizeT - -private[scalacl] object PrefixSum { - - private lazy val prefixSumCodeByte = new CLSimpleCode(""" - __kernel void prefSum(int size, __global const char* in, __global int* out) { - int i = get_global_id(0); - int j; - if (i >= size) - return; - - int total = 0; - for (j = 0; j <= i; j++) - total += in[j]; - - out[i] = total; - } - """) - @deprecated("Does not perform the same sum as prefixSumInt : at position i, counts values <= i (whereas prefixSumInt counts < i)") - private[scalacl] def prefixSumByte(bitmap: CLGuardedBuffer[Boolean], output: CLGuardedBuffer[Int])(implicit context: Context) = { - val kernel = prefixSumCodeByte.getKernel(context) - kernel.synchronized { - kernel.setArgs(bitmap.size.toInt.asInstanceOf[Object], bitmap.buffer, output.buffer) - CLEventBound.syncBlock(Array(bitmap), Array(output), evts => { - kernel.enqueueNDRange(context.queue, Array(bitmap.size.toInt), evts:_*) - }) - } - } - private[scalacl] def prefixSumInt(bitmap: CLGuardedBuffer[Int], output: CLGuardedBuffer[Int])(implicit context: Context) = { - CLEventBound.syncBlock(Array(bitmap), Array(output), evts => { - GroupedPrefixSum[Int].prefixSum(bitmap.buffer, output.buffer, evts:_*) - }) - } - private lazy val copyPrefixedCode = new CLSimpleCode(""" - __kernel void copyPrefixed( - int size, - __global const int* presencePrefix, - __global const char* in, - int elementSize, - __global char* out - ) { - int i = get_global_id(0); - if (i >= size) - return; - - int prefix = presencePrefix[i + 1]; - if (!i && prefix > 0 || i && prefix > presencePrefix[i]) { - int j, inOffset = i * elementSize, outOffset = (prefix - 1) * elementSize; - for (j = 0; j < elementSize; j++) { - out[outOffset + j] = in[inOffset + j]; - } - } - } - """) - private[scalacl] def copyPrefixed[T](size: Int, presencePrefix: CLGuardedBuffer[Int], in: CLGuardedBuffer[T], out: CLGuardedBuffer[T])(implicit t: ClassManifest[T], context: Context) = { - val kernel = copyPrefixedCode.getKernel(context) - val pio = PointerIO.getInstance(t.erasure) - assert(pio != null) - kernel.synchronized { - kernel.setArgs(in.size.toInt.asInstanceOf[Object], presencePrefix.buffer, in.buffer, pio.getTargetSize.toInt.asInstanceOf[Object], out.buffer) - CLEventBound.syncBlock(Array(in, presencePrefix), Array(out), evts => { - kernel.enqueueNDRange(context.queue, Array(in.size.toInt), evts:_*) - }) - } - } -} - diff --git a/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCollectionTest.scala b/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCollectionTest.scala deleted file mode 100644 index ea7187a47..000000000 --- a/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCollectionTest.scala +++ /dev/null @@ -1,242 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package scalacl - -import impl._ - -import com.nativelibs4java.opencl._ -import org.bridj.Pointer -import org.bridj.Pointer._ - -import org.junit._ -import Assert._ - -import scala.math._ - -object CLCollectionTest { - - implicit var context: Context = Context.best(DoubleSupport) - - def rng = (0 until n).cl - def clrng = (0 until n).cl - - def cla = (0 until n).toCLArray - def a = (0 until n).toArray - - val rand = new java.util.Random(System.nanoTime) - def aRand = (0 until n).map(_ => rand.nextFloat).toArray - def claRand = aRand.toCLArray - - val extVal = 10 - - var f: Int => Boolean = _ - var fScalarCapture: Int => Int = _ - var fArrayCapture: Int => Int = _ - var m: Int => Int = _ - var m2: Int => (Int, Int) = _ - var m2join: ((Int, Int)) => Int = _ - - val n = 10 - val samples = n - - def same[V](b: Traversable[V], a: CLIndexedSeq[V])(implicit v: ClassManifest[V]) { - val aa = a.toArray.take(samples).toSeq - val bb = b.toArray.take(samples).toSeq - - if (!(aa == bb)) { - println("aa = " + aa) - //println("a = " + a) - a match { - case fa: CLFilteredArray[V] => - println("aa.presence = " + fa.presence.toArray.take(samples).toSeq) - println("aa.updatedPresencePrefixSum = " + fa.updatedPresencePrefixSum.toArray.take(samples).toSeq) - case _ => - } - println("bb = " + bb) - assert(false) - } - - assertEquals(bb, aa) - } - - @BeforeClass - def setUp: Unit = { - //context = new Context - - //cla = (0 until n).toCLArray - //a = (0 until n).toArray - - f = ( - (x: Int) => (exp(x).toInt % 2) == 0, - Array("(((int)exp((float)_)) % 2) == 0") - ): CLFunction[Int, Boolean] - - fScalarCapture = - ( - ( - (x: Int) => x * extVal - x - extVal, - Array("_ * _1 - _ - _1"), - impl.CapturedIOs( - Array(), - Array(), - Array(IntCLDataIO.asInstanceOf[CLDataIO[Any]]) - ) - ): CLFunction[Int, Int] - ) - - m = ( - (x: Int) => (x * 2 * exp(x)).toInt, - Array("(int)(_ * 2 * exp((float)_))") - ): CLFunction[Int, Int] - - m2 = ( - (x: Int) => (x, x * 2), - Array("_", "_ * 2") - ): CLFunction[Int, (Int, Int)] - - m2join = ( - (p: (Int, Int)) => p._1 + 2 * p._2, - Array("_._1 + 2 * _._2") - ): CLFunction[(Int, Int), Int] - - } - - @AfterClass - def tearDown: Unit = { - //context.release - } -} - -class CLCollectionTest { - - import CLCollectionTest._ - - @Test - def testMapScalarCapture { - val fCapt = fScalarCapture.withCapture( - Array(), - Array(), - Array(extVal) - ) - same(a.map(fCapt), cla.map(fCapt)) - } - @Test - def testMapArrayCapture { - val rg = (0 until n).map(_ * 10).toCLArray - val f: CLFunction[Int, Int] = - ( - (x: Int) => rg(x) - x, - Array("_1[_] - _"), - impl.CapturedIOs( - Array(IntCLDataIO.asInstanceOf[CLDataIO[Any]]), - Array(), - Array() - ) - ) - - val fCapt = f.withCapture( - Array(rg.asInstanceOf[CLArray[Any]]), - Array(), - Array() - ) - same(a.map(fCapt), cla.map(fCapt)) - } - - - @Test - def testSimpleFilter { - same(a.filter(f), cla.filter(f).toCLArray) - //context.queue.finish - } - @Test - def testSimpleMap { - same(a.map(m), cla.map(m)) - //context.queue.finish - } - - @Test - def testTupleMap { - same(a.map(m2), cla.map(m2)) - //context.queue.finish - } - - @Test - def testFilterMap { - same(a.filter(f).map(m), cla.filter(f).map(m)) - //context.queue.finish - } - @Test - def testFilterMapTuple2Result { - same(a.filter(f).map(m2), cla.filter(f).map(m2)) - //context.queue.finish - } - - @Test - def testFilterMapTuple2Arg { - same(a.filter(f).map(m2).map(m2join), cla.filter(f).map(m2).map(m2join)) - //context.queue.finish - } - - @Test - def testToString { - assertEquals("CLArray()", CLArray[Int]().toString) - assertEquals("CLArray(1, 2)", CLArray(1, 2).toString) - assertEquals("CLFilteredArray()", CLArray(1, 2).filter(_ => false).toString) - assertEquals("CLFilteredArray(1, 2)", CLArray(1, 2).filter(_ => true).toString) - } - - @Test - def testRangeMap { - same(rng.map(m), clrng.map(m)) - //context.queue.finish - } - - /* - Code from old protocl.Example : - - - val a = Array(1, 2, 3) - - implicit val context = new Context(JavaCL.createBestContext) - - val tup2 = new CLArray[(Float, Float)](3) - var i = 0 - val ff2: ((Float, Float)) => (Float, Float) = { case (x, y) => i += 1; val f = i.toFloat; (f, f * f) } - val mapTup2 = tup2.map(ff2) - println("mapTup2 = " + mapTup2.toSeq) - equals(Seq((1.0,1.0), (2.0,4.0), (3.0,9.0)), mapTup2.toSeq) - val mapTup22 = mapTup2.mapFun(CLFun[(Float, Float), Float](Seq("_._1 + _._2"))) - println("mapTup22 = " + mapTup22.toSeq) - equals(Seq(2f, 6f, 12f), mapTup22) - - - val tup3 = new CLArray[(Float, Float, Float)](3) - i = 0 - val ff3: ((Float, Float, Float)) => (Float, Float, Float) = { case (x, y, z) => i += 1; val f = i.toFloat; (f, f * f, f * f * f) } - val mapTup3 = tup3.map(ff3) - println("mapTup3 = " + mapTup3.toSeq) - equals(Seq((1.0,1.0,1.0), (2.0,4.0,8.0), (3.0,9.0,27.0)), mapTup3.toSeq) - - - var cla = new CLArray[Int](10) - val mapped = cla.map((x: Int) => x + 10) - - val clMapped = mapped.mapFun(CLFunSeq[Int, Int](Seq("int v = _ + $i;"), Seq("v * (v - 1)"))) - - println("original = " + cla.toArray.toSeq) - println("mapped = " + mapped.toArray.toSeq) - println("clMapped = " + clMapped.toArray.toSeq) - - val filtered = clMapped.filterFun(CLFun[Int, Boolean](Seq("(_ % 10) == 0"))) - filtered.waitFor - println("filtered = " + filtered.buffers(0).toArray.toSeq) - val arr: Array[Boolean] = filtered.presence.toArray.asInstanceOf[Array[Boolean]] - val arrB: Array[Byte] = filtered.presence.buffer.as(classOf[Byte]).read(context.queue).getBytes(filtered.buffersSize.toInt) - val packed = filtered.toCLArray - val pref = filtered.updatedPresencePrefixSum.toArray - val filteredSize = filtered.size - */ -} diff --git a/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCustomCodeTest.scala b/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCustomCodeTest.scala deleted file mode 100644 index dba3845d1..000000000 --- a/libraries/ScalaCL/Collections/src/test/scala/scalacl/CLCustomCodeTest.scala +++ /dev/null @@ -1,44 +0,0 @@ -package scalacl - -import impl._ - -import com.nativelibs4java.opencl._ -import org.bridj.Pointer -import org.bridj.Pointer._ - -import org.junit._ -import Assert._ - -import scala.math._ - -class CLCustomCodeTest { - - @Test - def testSinCos = { - import scalacl._ - implicit val context = Context.best(CPU) - val n = 100 - val f = 0.5f - val sinCosOutputs: CLArray[Float] = new CLArray[Float](2 * n) - val sinCosCode = customCode(""" - __kernel void sinCos(__global float2* outputs, float f) { - int i = get_global_id(0); - float c, s = sincos(i * f, &c); - outputs[i] = (float2)(s, c); - } - """) - sinCosCode.execute( - args = Array(sinCosOutputs, f), - writes = Array(sinCosOutputs), - globalSizes = Array(n) - ) - val resCL = sinCosOutputs.toArray - - val resJava = (0 until n).flatMap(i => { - val x = i * f - Array(sin(x).toFloat, cos(x).toFloat) - }).toArray - - assertArrayEquals(resJava, resCL, 0.00001f) - } -} diff --git a/libraries/ScalaCL/Collections/src/test/scala/scalacl/FilterTest.scala b/libraries/ScalaCL/Collections/src/test/scala/scalacl/FilterTest.scala deleted file mode 100644 index 5549ba716..000000000 --- a/libraries/ScalaCL/Collections/src/test/scala/scalacl/FilterTest.scala +++ /dev/null @@ -1,68 +0,0 @@ -package scalacl - -import impl._ - -import org.junit._ -import Assert._ - -import scala.math._ -import com.nativelibs4java.opencl._ - -class FilterTest { - - @Test - def testFilterPreferablyOnCPU = - testFilter(Context.best(CPU)) - - @Test - def testFilterPreferablyOnGPU = - testFilter(Context.best(GPU)) - - def testFilter(implicit context: Context) = { - val filt = ( - (x: Int) => (x % 2) == 0, - Array("(_ % 2) == 0") - ): CLFunction[Int, Boolean] - - for (dim <- 1 until 1000) { - //for (offset <- 0 to 1) { - val openclArray = (0 until dim).toCLArray.filter(filt).toArray.toSeq - val openclRangePre: CLIndexedSeq[Int] = (0 until dim).cl.filter(filt) - val openclRange = openclRangePre.toArray.toSeq - val scala = (0 until dim).toArray.filter(filt).toArray.toSeq - if (openclArray != scala) { - //println("\tExpected : " + scala) - //println("\t Found : " + opencl) - assertEquals("Different result for dim = " + dim + " !", scala, openclArray) - } - assertEquals("Different result between range and array filters for dim = " + dim + " !", openclArray, openclRange) - } - } - @Test - def testFilterSumPreferablyOnCPU = - testFilterSum(Context.best(CPU)) - - @Test - def testFilterSumPreferablyOnGPU = - testFilterSum(Context.best(GPU)) - - def testFilterSum(implicit context: Context) = { - val filt = ( - (x: Int) => (x % 2) == 0, - Array("(_ % 2) == 0") - ): CLFunction[Int, Boolean] - - for (dim <- Seq(1, 3, 5, 100, 1000000)) { - val openclArray = (0 until dim).toCLArray.filter(filt).sum - val openclRangePre: CLIndexedSeq[Int] = (0 until dim).cl.filter(filt) - val openclRange = openclRangePre.sum - val scala = (0 until dim).toArray.filter(filt).sum - if (openclArray != scala) { - //println("\tExpected : " + scala) - //println("\t Found : " + opencl) - assertEquals("Different result for dim = " + dim + " !", scala, openclArray) - } - assertEquals("Different result between range and array filtered sums for dim = " + dim + " !", openclArray, openclRange) - } - } -} diff --git a/libraries/ScalaCL/Collections/src/test/scala/scalacl/ReductionTest.scala b/libraries/ScalaCL/Collections/src/test/scala/scalacl/ReductionTest.scala deleted file mode 100644 index 428494651..000000000 --- a/libraries/ScalaCL/Collections/src/test/scala/scalacl/ReductionTest.scala +++ /dev/null @@ -1,35 +0,0 @@ - -package scalacl - -import impl._ - -import com.nativelibs4java.opencl._ -import org.bridj.Pointer -import org.bridj.Pointer._ - -import org.junit._ -import Assert._ - -import scala.math._ - -class ReductionTest { - - import CLCollectionTest._ - - @Test - def testMinMaxSumProduct { - val aR = aRand - val claR = aR.cl - //val claR = claRand - - //val aR = (0 to 5).map(i => pow(10, i).toFloat) - //val claR = aR.cl - - assertEquals("sum", aR.sum, claR.sum, 0) - assertEquals("product", aR.product, claR.product, 0) - - assertEquals("min", aR.min, claR.min, 0) - assertEquals("max", aR.max, claR.max, 0) - - } -} diff --git a/libraries/ScalaCL/Plugin/.gitignore b/libraries/ScalaCL/Plugin/.gitignore deleted file mode 100644 index 765db939d..000000000 --- a/libraries/ScalaCL/Plugin/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -target -project/boot -project/target -*~ -out -tmpTestClassesNormal -tmpTestClassesOptimized -*.perf.properties -test.scala -test2.scala diff --git a/libraries/ScalaCL/Plugin/ABOUT b/libraries/ScalaCL/Plugin/ABOUT deleted file mode 100644 index 3f24f1ae0..000000000 --- a/libraries/ScalaCL/Plugin/ABOUT +++ /dev/null @@ -1,33 +0,0 @@ - - ScalaCL Plugin is a compiler plugin that makes your programs faster. - It optimizes general Scala constructs and ScalaCL / OpenCL programs in particular. - -Website: - http://scalacl.googlecode.com/ - -Author: - Olivier Chafik - http://ochafik.free.fr/blog/ - http://twitter.com/ochafik - -Current general optimizations include rewrites of inline ranges, List[T] and Array[T] instances into equivalent while loops : -- Array.tabulate -- foldLeft / reduceLeft / scanLeft (and for Array[T], also the -right variants) -- sum, min, max -- map -- forall, exists, count -- filter, filterNot -- takeWhile, dropWhile (except for Range) - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCollection[T].map and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- CLCollection.foreach -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list diff --git a/libraries/ScalaCL/Plugin/CHANGELOG b/libraries/ScalaCL/Plugin/CHANGELOG deleted file mode 100644 index bd1d43691..000000000 --- a/libraries/ScalaCL/Plugin/CHANGELOG +++ /dev/null @@ -1,24 +0,0 @@ -ScalaCL 0.2-SNAPSHOT -- ScalaCL Compiler Plugin changes : - - runs silently (unless SCALACL_VERBOSE=1 is set) - - added the following rewrites : - - filter / filterNot - - takeWhile / dropWhile - - forall - - exists - - count -- ScalaCL Collections released : - - CLArray behaves just like Array (new CLArray[T](size), CLArray(a, b, c...)) - - .cl method on any Seq[T] creates a CLCollection[T] (a CLRange for Range.cl, otherwise a CLArray[T]) - - scalacl.Context : Context.best, Context.best(DoubleSupport, GPU), Context.platforms, Context(device1, device2)... - - accelerated map, filter, zip, zipWithIndex operations (when compiled with ScalaCL Compiler Plugin) - - CLCode allows hand-written OpenCL code to be run on collections - -ScalaCL 0.1 -- rewrites target Array and inline ranges (x to y by z) -- rewrite the following calls to equivalent while loops : - - foreach - - foldLeft / foldRight - - scanLeft / scanRight - - reduceLeft / reduceRight - - sum, min, max diff --git a/libraries/ScalaCL/Plugin/LICENSE b/libraries/ScalaCL/Plugin/LICENSE deleted file mode 100644 index a8db4c0ce..000000000 --- a/libraries/ScalaCL/Plugin/LICENSE +++ /dev/null @@ -1,31 +0,0 @@ - - ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - http://scalacl.googlecode.com/ - - Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Olivier Chafik nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - - diff --git a/libraries/ScalaCL/Plugin/README b/libraries/ScalaCL/Plugin/README deleted file mode 100644 index 98548cb37..000000000 --- a/libraries/ScalaCL/Plugin/README +++ /dev/null @@ -1,17 +0,0 @@ -= Project = - -Project home : -http://code.google.com/p/scalacl/ - -= Compiling = - -To compile, test and package ScalaCL Plugin : -mvn clean install - -To compile only : -mvn compile -Dmaven.test.skip=true - -= Using = - -Please see : -http://code.google.com/p/scalacl/wiki/ScalaCLPlugin diff --git a/libraries/ScalaCL/Plugin/build.sbt b/libraries/ScalaCL/Plugin/build.sbt deleted file mode 100644 index 85bfa606e..000000000 --- a/libraries/ScalaCL/Plugin/build.sbt +++ /dev/null @@ -1,24 +0,0 @@ -name := "scalacl-compiler-plugin" - -mainClass := Some("scalacl.plugin.Compile") - -version := "0.3-SNAPSHOT" - -//fork := true - -organization := "com.nativelibs4java" - -//scalaHome := Some(file("/Users/ochafik/bin/scala-2.10.0.r25286-b20110715023800")) -//scalaHome := Some(file("/Users/ochafik/bin/scala-2.9.0.final")) - -scalaVersion := "2.9.1" - -resolvers += "Sonatype OSS Snapshots Repository" at "http://oss.sonatype.org/content/groups/public/" - -resolvers += "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - -libraryDependencies ++= Seq( - "com.nativelibs4java" % "scalaxy" % "0.3-SNAPSHOT", - "com.nativelibs4java" % "scalacl" % "0.3-SNAPSHOT", - "com.novocode" % "junit-interface" % "0.5" % "test->default" -) diff --git a/libraries/ScalaCL/Plugin/compileTest b/libraries/ScalaCL/Plugin/compileTest deleted file mode 100755 index ca891f6f7..000000000 --- a/libraries/ScalaCL/Plugin/compileTest +++ /dev/null @@ -1 +0,0 @@ -SCALACL_TRACE=1 mvn scala:run -DmainClass=scalacl.plugin.Compile "-DaddArgs=Test.scala|-Xprint:scalacl-stream" || exit 1 diff --git a/libraries/ScalaCL/Plugin/examples/Toto.scala b/libraries/ScalaCL/Plugin/examples/Toto.scala deleted file mode 100644 index 309e35f6e..000000000 --- a/libraries/ScalaCL/Plugin/examples/Toto.scala +++ /dev/null @@ -1,127 +0,0 @@ -/* -SCALACL_VERBOSE=1 sbt '~run examples/Toto.scala -d examples/classes -classpath ../Collections/target/scalacl-0.3-SNAPSHOT-shaded.jar' - --Xprint:scalacl-functionstransform", - "-Xprint:typer", - "-classpath", "../ScalaCL2/target/scalacl-0.2-SNAPSHOT-shaded.jar" - -*/ -object Toto { - def main(args: Array[String]) { - //new scala.collection.mutable.ArrayBuilder.ofRef[Array[Int]] - //for ((i, j) <- Array(1 -> 1, 2 -> 2)) println(i, j) - - //Seq(1, 2, 3).zipWithIndex map { case (a, i) => a + i } - - import scalacl._ - import scala.math._ - implicit val context = Context.best(CPU) - val n = 10 * args(0).toInt - - println((0 to 10).map(_ * n - n)) - println((0 to 10).toCLArray.map(_ * n - n)) - - /* - case class Matrix(data: CLArray[Float], rows: Int, columns: Int) { - def this(rows: Int, columns: Int) = - this(new CLArray[Float](rows * columns), rows, columns) - def this(n: Int) = - this(n, n) - } - - def sq(a: Matrix, b: Matrix, out: Matrix) = { - assert(a.columns == b.rows) - assert(a.rows == out.rows) - assert(b.columns == out.columns) - for (i <- 0 until a.rows; j <- 0 until b.columns) { - // TODO chain map and sum (to avoid creating a builder here !) - //out.data(i * out.columns + j) = (0 until a.columns).map(k => { - // a.data(i * a.columns + k) * b.data(k * b.columns + j) - //}).sum - var sum = 0f - for (k <- 0 until a.columns) { - sum += a.data(i * a.columns + k) * b.data(k * b.columns + j) - } - out.data(i * out.columns + j) = sum - } - } - - val a = new Matrix(n) - val b = new Matrix(n) - val out = new Matrix(n) - - sq(a, b, out) - - println(out.data.toArray) - - */ - /* - import impl._ - - val array = CLArray(1, 2, 3, 4) - val initTotal = 10 - - println(array.map(v => { - var total = 0//initTotal - for (i <- -5 until 5 by 2) { - total += (if (cos(v * i) < 0) (i * v) else (i - v)) - if ((total % 2) == 0) - total += 1 - } - total - })) - - array.map(v => { - def sq(x: Int) = x * x - (v, sq(v)) - }) - - // Map to / from tuples, zip(WithIndex) : - array.zip(array.map(_ * 2f)).zipWithIndex.map(t => { - val ((a, b), i) = t - (exp(a / 1000.0f).toFloat + b + i, a) - }) - - // Same : - array.zip(array.map(_ * 2f)).zipWithIndex map { - case ((a, b), i) => - (exp(a / 1000.0f).toFloat + b + i, a) - } - - array.map(v => { - var total = 0 - for (i <- 0 until 5) { - total += 0//if (cos(v * i) < 0) (i * v) else (i - v) - } - total - }) - */ - - /* - array.map(v => { - - def someFun(x: Int) = // becomes a top-level function inside the OpenCL kernel - exp(x / 1000).toInt - - var pair @ (init, foo) = { // tuples will be flattened in the OpenCL kernel - val d = v - 10 // unless they match an OpenCL tuple type like int2 - (d * d, 1 / d) - } - var sum = init + 1.0 - for (i <- 0 until 10; if (i % 2) != 0) { - sum += cos(v) * i + someFun(pair._2 - foo) - } - (sum, foo) - }) - */ - - //val ((a, b), i) = ((1, 2), 3) - /* - Array(1, 2, 3).map(_.toDouble) - List(1, 2, 3).map(_.toDouble) - (0 until 2).map(_.toDouble) - - val a: Set[Int] = List(1).map(_ + 1)(collection.breakOut) - */ - } -} diff --git a/libraries/ScalaCL/Plugin/mmult.scala b/libraries/ScalaCL/Plugin/mmult.scala deleted file mode 100644 index fe24fc2c6..000000000 --- a/libraries/ScalaCL/Plugin/mmult.scala +++ /dev/null @@ -1,44 +0,0 @@ - -object LinAlg -{ - type Matrix = - Array[Array[Double]] - - @inline - def columns(m: Matrix): Int = - m(0).length - - @inline - def rows(m: Matrix): Int = - m.length - - @inline - def multiply(a: Matrix, b: Matrix): Matrix = { - val aRows = rows(a) - val aCols = columns(a) - val bCols = columns(b) - Array.tabulate[Double](aRows, bCols)((i, j) => { - (0 until aCols).map(k => a(i)(k) * b(k)(j)).sum - }) - } - - def describe(m: Matrix) = - "[\n" + m.map("\t[ \t" + _.mkString(",\t") + "\t ]").mkString(",\n") + "\n]" -} - -object TestLinAlg extends App -{ - import LinAlg._ - - val m = 3 - val n = 4 - val o = 5 - val a = Array.tabulate[Double](m, n)(_ + _) // a(i)(j) = i + j - val b = Array.tabulate[Double](n, o)(_ - _) // b(i)(j) = i - j - val ab = multiply(a, b) - - assert(rows(a) == rows(ab)) - assert(columns(b) == columns(ab)) - - println(describe(ab)) -} diff --git a/libraries/ScalaCL/Plugin/nbactions.xml b/libraries/ScalaCL/Plugin/nbactions.xml deleted file mode 100644 index 9d6f91c8a..000000000 --- a/libraries/ScalaCL/Plugin/nbactions.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - run - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/branches/OpenCL-BridJ/libraries/OpenCL/ScalaCLPlugin - runtime - -classpath %classpath scalacl.Compile Test.scala -classpath /Users/ochafik/nativelibs4javaBridJed/OpenCL/ScalaCL2/target/scalacl-0.2-SNAPSHOT-shaded.jar - java - - - - debug - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/branches/OpenCL-BridJ/libraries/OpenCL/ScalaCLPlugin - runtime - -Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath scalacl.Compile Test.scala -classpath /Users/ochafik/nativelibs4javaBridJed/OpenCL/ScalaCL2/target/scalacl-0.2-SNAPSHOT-shaded.jar - true - java - - - - profile - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - /Users/ochafik/Prog/Java/versionedSources/nativelibs4java/branches/OpenCL-BridJ/libraries/OpenCL/ScalaCLPlugin - ${profiler.args} -classpath %classpath scalacl.Compile Test.scala -classpath /Users/ochafik/nativelibs4javaBridJed/OpenCL/ScalaCL2/target/scalacl-0.2-SNAPSHOT-shaded.jar - profile - ${profiler.java} - - - diff --git a/libraries/ScalaCL/Plugin/pom.xml b/libraries/ScalaCL/Plugin/pom.xml deleted file mode 100644 index ec4626a85..000000000 --- a/libraries/ScalaCL/Plugin/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - scalacl-compiler-plugin - ScalaCL Compiler Plugin - http://code.google.com/p/scalacl/ - jar - - -ScalaCL provides data structures that leverage the OpenCL library to execute operations on GPUs. -This plugin transforms some Scala functions into OpenCL kernels so they can effectively execute in the OpenCL land instead of in the JVM. -It will also soon feature some limited OpenCL-backed autovectorization. -For more info, please visit http://code.google.com/p/scalacl - - - - com.nativelibs4java - scalacl-parent - 0.3-SNAPSHOT - .. - - - - false - - - - - com.nativelibs4java - scalacl - shaded - - - com.nativelibs4java - scalaxy - - - com.nativelibs4java - scalaxy - test-jar - test - - - org.scala-lang - scala-compiler - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - com.nativelibs4java - maven-velocity-plugin - - ${basedir}/src/main/resources - - - - - - - - diff --git a/libraries/ScalaCL/Plugin/project-old/build.properties b/libraries/ScalaCL/Plugin/project-old/build.properties deleted file mode 100644 index 5d5891682..000000000 --- a/libraries/ScalaCL/Plugin/project-old/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -#Project properties -#Tue Oct 26 01:13:22 CEST 2010 -project.organization=com.nativelibs4java.opencl -project.name=scalacl-compiler-plugin -sbt.version=0.7.5.RC0 -project.version=0.2.Beta14 -build.scala.versions=2.9.0.1 -project.initialize=false diff --git a/libraries/ScalaCL/Plugin/project-old/build/ScalaCLPluginProject.scala b/libraries/ScalaCL/Plugin/project-old/build/ScalaCLPluginProject.scala deleted file mode 100644 index a20173472..000000000 --- a/libraries/ScalaCL/Plugin/project-old/build/ScalaCLPluginProject.scala +++ /dev/null @@ -1,22 +0,0 @@ -import sbt._ -import reaktor.scct.ScctProject - -class ScalaCLPluginProject(info: ProjectInfo) extends DefaultProject(info) -with ScctProject -with IdeaProject -{ - //override def name = "scalacl-compiler-plugin" - override def watchPaths = super.watchPaths +++ Path.fromFile("examples") - - override def filterScalaJars = false - override def compileOptions = super.compileOptions ++ - compileOptions("-optimise") - - val nativelibs4javaRepo = "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - //val scalacl = compilerPlugin("com.nativelibs4java" % "scalacl-compiler-plugin" % "1.0-SNAPSHOT") - - //val BuSwing = "com.nativelibs4java" % "buswing_2.8.0" % "0.1.1-SNAPSHOT" - val junitInterface = "com.novocode" % "junit-interface" % "0.5" % "test->default" - val scalaCompiler = "org.scala-lang" % "scala-compiler" % buildScalaVersion - val scalaLibrary = "org.scala-lang" % "scala-library" % buildScalaVersion -} diff --git a/libraries/ScalaCL/Plugin/project-old/plugins/Plugins.scala b/libraries/ScalaCL/Plugin/project-old/plugins/Plugins.scala deleted file mode 100644 index 73d17d1cb..000000000 --- a/libraries/ScalaCL/Plugin/project-old/plugins/Plugins.scala +++ /dev/null @@ -1,9 +0,0 @@ -import sbt._ -class Plugins(info: ProjectInfo) extends PluginDefinition(info) { - val scctRepo = "scct-repo" at "http://mtkopone.github.com/scct/maven-repo/" - lazy val scctPlugin = "reaktor" % "sbt-scct-for-2.8" % "0.1-SNAPSHOT" - - val sbtIdeaRepo = "sbt-idea-repo" at "http://mpeltonen.github.com/maven/" - val sbtIdea = "com.github.mpeltonen" % "sbt-idea-plugin" % "0.1-SNAPSHOT" -} - diff --git a/libraries/ScalaCL/Plugin/project-old/plugins/project/build.properties b/libraries/ScalaCL/Plugin/project-old/plugins/project/build.properties deleted file mode 100644 index 141ad5ada..000000000 --- a/libraries/ScalaCL/Plugin/project-old/plugins/project/build.properties +++ /dev/null @@ -1,3 +0,0 @@ -#Project properties -#Thu May 12 22:55:38 CEST 2011 -plugin.uptodate=true diff --git a/libraries/ScalaCL/Plugin/project/build.properties b/libraries/ScalaCL/Plugin/project/build.properties deleted file mode 100644 index f2ccdfa37..000000000 --- a/libraries/ScalaCL/Plugin/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.11.0 diff --git a/libraries/ScalaCL/Plugin/scalac-bugs.scala b/libraries/ScalaCL/Plugin/scalac-bugs.scala deleted file mode 100644 index 03a599b37..000000000 --- a/libraries/ScalaCL/Plugin/scalac-bugs.scala +++ /dev/null @@ -1,7 +0,0 @@ -class Test { - val out = collection.mutable.ArrayBuffer[Int]() - val item: Int = 0 - if (item != 0) - out.+=(item) // triggers a "silent" reference to BoxedUnit.UNIT -} -//:javap -c Test diff --git a/libraries/ScalaCL/Plugin/scalacl b/libraries/ScalaCL/Plugin/scalacl deleted file mode 100755 index 7a5fadff0..000000000 --- a/libraries/ScalaCL/Plugin/scalacl +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -export SCALACL_TRACE=1 -export SCALACL_VERBOSE=1 -export SCALACL_STREAM=1 - - -SCALA_LIB_DIR=project/boot/scala-2.9.0/lib -#SCALA_LIB_DIR=$SCALA_HOME/lib - -COMPILER_JAR=$SCALA_LIB_DIR/scala-compiler.jar -LIBRARY_JAR=$SCALA_LIB_DIR/scala-library.jar - -SCALACL_JAR=../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar - -CLASSES_DIR=target/classes -#CLASSES_DIR=target/scala-2.9.0.final/classes - -COMPILE_CLASS=scalacl.plugin.Compile - - - -mvn scala:run -DmainClass=scalacl.plugin.Compile "-DaddArgs=$1|-cp|$SCALACL_JAR" -o || exit 1 - -#scala -cp $COMPILER_JAR:$SCALACL_JAR:$CLASSES_DIR $COMPILE_CLASS "$@" - -java -cp $COMPILER_JAR:$LIBRARY_JAR:$SCALACL_JAR:$CLASSES_DIR $COMPILE_CLASS "$@" diff --git a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iml b/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iml deleted file mode 100644 index 8db8435c6..000000000 --- a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.ipr b/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.ipr deleted file mode 100644 index 2defa7129..000000000 --- a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.ipr +++ /dev/null @@ -1,367 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.6 - - - - - - - - - diff --git a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iws b/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iws deleted file mode 100644 index 0d01ffa29..000000000 --- a/libraries/ScalaCL/Plugin/scalacl-compiler-plugin.iws +++ /dev/null @@ -1,656 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Plugin DevKit - - - - - Abstraction issues - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - - - 1321220711595 - 1321220711595 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Plugin/src/main/resources/scalac-plugin.xml b/libraries/ScalaCL/Plugin/src/main/resources/scalac-plugin.xml deleted file mode 100644 index 09df9b5a6..000000000 --- a/libraries/ScalaCL/Plugin/src/main/resources/scalac-plugin.xml +++ /dev/null @@ -1,4 +0,0 @@ - - scalacl-compiler-plugin-0.3-SNAPSHOT - scalacl.plugin.ScalaCLPlugin - diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101005.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101005.advert deleted file mode 100644 index c40a337c0..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101005.advert +++ /dev/null @@ -1,24 +0,0 @@ - - scalacl-compiler-plugin1.0-20101005ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101005.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006-3.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006-3.advert deleted file mode 100644 index 6d47e31ae..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006-3.advert +++ /dev/null @@ -1,27 +0,0 @@ - - scalacl-compiler-plugin1.0-20101006-3ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops -- Rewrite of Array[T].foldLeft / foldRight into while loops -- Rewrite of Array[T].reduceLeft / reduceRight into while loops -- Rewrite of Array[T].scanLeft / scanRight into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101006-3.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006.advert deleted file mode 100644 index 4e81ee869..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006.advert +++ /dev/null @@ -1,27 +0,0 @@ - - scalacl-compiler-plugin1.0-20101006ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops -- Rewrite of Array[T].foldLeft / foldRight into while loops -- Rewrite of Array[T].reduceLeft / reduceRight into while loops -- Rewrite of Array[T].scanLeft / scanRight into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101006.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006_2.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006_2.advert deleted file mode 100644 index bda933341..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101006_2.advert +++ /dev/null @@ -1,27 +0,0 @@ - - scalacl-compiler-plugin1.0-20101006_2ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops -- Rewrite of Array[T].foldLeft / foldRight into while loops -- Rewrite of Array[T].reduceLeft / reduceRight into while loops -- Rewrite of Array[T].scanLeft / scanRight into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101006_2.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-1.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-1.advert deleted file mode 100644 index c41230898..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-1.advert +++ /dev/null @@ -1,27 +0,0 @@ - - scalacl-compiler-plugin1.0-20101013-1ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops -- Rewrite of Array[T].foldLeft / foldRight into while loops -- Rewrite of Array[T].reduceLeft / reduceRight into while loops -- Rewrite of Array[T].scanLeft / scanRight into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101013-1.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-2.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-2.advert deleted file mode 100644 index 7801c48f8..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-20101013-2.advert +++ /dev/null @@ -1,27 +0,0 @@ - - scalacl-compiler-plugin1.0-20101013-2ScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops -- Rewrite of Array[T].foldLeft / foldRight into while loops -- Rewrite of Array[T].reduceLeft / reduceRight into while loops -- Rewrite of Array[T].scanLeft / scanRight into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-20101013-2.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-SNAPSHOT.advert b/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-SNAPSHOT.advert deleted file mode 100644 index e45097bf7..000000000 --- a/libraries/ScalaCL/Plugin/src/main/sbaz/scalacl-compiler-plugin-1.0-SNAPSHOT.advert +++ /dev/null @@ -1,24 +0,0 @@ - - scalacl-compiler-plugin1.0-SNAPSHOTScalaCL Plugin is a compiler plugin that optimizes general Scala programs and ScalaCL / OpenCL programs in particular. -(see http://scalacl.googlecode.com/) -Author: Olivier Chafik <olivier.chafik@gmail.com> - -Current general optimizations include : -- Rewrite of int range foreach loops into faster while loops -- Rewrite of Array[T].foreach into while loops (for T being primitive or AnyRef) -- Rewrite of Array[T].map into while loops - -Current ScalaCL / OpenCL-specific optimizations include : -- Transforming Scala functions given to CLCol[T].map, foreach and filter into OpenCL kernels (supports only limited inline lambdas) - -More optimizations are scheduled, such as : -- Autovectorization of ScalaCL loops -- Auto-ScalaCL-ization of general code (upon explicit demand via a compiler option, as this introduces runtime dependency on ScalaCL) -- Support for external references in ScalaCL functions, including external calls (when target is invariant and can be converted to OpenCL) - -Please use NativeLibs4Java's user group and bug-tracker for feedback or help about ScalaCL and its compiler plugin : -http://groups.google.fr/group/nativelibs4java/ -http://code.google.com/p/nativelibs4java/issues/list - - http://nativelibs4java.sourceforge.net/sbaz/scalacl/scalacl-compiler-plugin-1.0-SNAPSHOT.sbp - \ No newline at end of file diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLCodeAnalysis.scala b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLCodeAnalysis.scala deleted file mode 100644 index 08a5b6c28..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLCodeAnalysis.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl ; package plugin -import com.nativelibs4java.scalaxy._ -import common._ -import pluginBase._ -import components._ - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} -import scala.tools.nsc.typechecker.Analyzer -import scala.tools.nsc.typechecker.Contexts -import scala.Predef._ - -trait CLCodeAnalysis -extends CodeAnalysis - with CLPluginNames -{ - this: PluginComponent with WithOptions => - - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed} // methods to type trees - import CODE._ - - import gen._ - import scala.tools.nsc.symtab.Flags._ - import analyzer.{SearchResult, ImplicitSearch} - - override protected def createSideEffectsEvaluator(tree: Tree, cached: Boolean = true, preKnownSymbols: Set[Symbol] = Set()) = { - //println("Creating CL-modified SideEffectsEvaluator") - new SideEffectsEvaluator(tree, cached, preKnownSymbols) { - override protected def isSideEffectFreeMethod(target: Tree, symbol: MethodSymbol): Boolean = { - val name = symbol.name - symbol.owner == CLArrayClass && { - name == (applyName: Name) || - name == (updateName: Name) - } || - super.isSideEffectFreeMethod(target, symbol) - } - } - } -} diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLPluginNames.scala b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLPluginNames.scala deleted file mode 100644 index d08d0db47..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/CLPluginNames.scala +++ /dev/null @@ -1,26 +0,0 @@ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.Global -import reflect.NameTransformer -; -trait CLPluginNames extends PluginNames { - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - val ScalaCLPackage = M("scalacl") - val ScalaCLPackageClass = ScalaCLPackage.tpe.typeSymbol - val CLDataIOClass = C("scalacl.impl.CLDataIO") - val CLArrayClass = C("scalacl.CLArray") - //val CLArrayModule = getModule("scalacl.CLArray") - val CLFunctionClass = C("scalacl.impl.CLFunction") - val CLRangeClass = C("scalacl.CLRange") - val CLCollectionClass = C("scalacl.CLCollection") - val CLFilteredArrayClass = C("scalacl.CLFilteredArray") - val scalacl_ = N("scalacl") - val getCachedFunctionName = N("getCachedFunction") - val Function2CLFunctionName = N("Function2CLFunction") - val withCaptureName = N("withCapture") -} diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/OpenCLConverter.scala b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/OpenCLConverter.scala deleted file mode 100644 index 30ef17290..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/OpenCLConverter.scala +++ /dev/null @@ -1,305 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl ; package plugin -import com.nativelibs4java.scalaxy._ -import common._ -import pluginBase._ -import components._ - -import scala.collection.immutable.Stack -import scala.reflect.NameTransformer -import scala.reflect.generic.{Names, Trees, Types, Constants, Universe} -import scala.tools.nsc.Global -import scala.tools.nsc.symtab.Flags._ -import scala.tools.nsc.plugins.PluginComponent - -trait OpenCLConverter -extends MiscMatchers - with CodeFlattening -{ - this: PluginComponent with WithOptions => - - val global: Global - import global._ - import definitions._ - - def nodeToStringNoComment(tree: Tree): String - - var openclLabelIds = new Ids - - var placeHolderRefs = new Stack[String] - - def valueCode(v: String) = FlatCode[String](Seq(), Seq(), Seq(v)) - def emptyCode = FlatCode[String](Seq(), Seq(), Seq()) - def statementCode(s: String) = FlatCode[String](Seq(), Seq(s), Seq()) - def convert(body: Tree): FlatCode[String] = { - def cast(expr: Tree, clType: String) = - convert(expr).mapEachValue(v => Seq("((" + clType + ")" + v + ")")) - - /* - def convertForeach(from: Tree, to: Tree, isUntil: Boolean, by: Tree, function: Tree) = { - val Function(List(vd @ ValDef(paramMods, paramName, tpt, rhs)), body) = function - val id = openclLabelIds.next - val iVar = "iVar$" + id - val nVal = "nVal$" + id - - out("int ", iVar, ";\n") - out("const int ", nVal, " = ", to, ";\n") - out("for (", iVar, " = ", from, "; ", iVar, " ", if (isUntil) "<" else "<=", " ", nVal, "; ", iVar, " += ", by, ") {\n") - doConvertExpr(argNames + (vd.symbol -> iVar), body, false, conversion, b)._1 - out("\n}") - }*/ - body match { - case TupleCreation(tupleArgs) =>//Apply(TypeApply(Select(TupleObject(), applyName()), tupleTypes), tupleArgs) if isTopLevel => - tupleArgs.map(convert).reduceLeft(_ ++ _) - case Literal(Constant(value)) => - if (value == ()) - emptyCode - else - valueCode(value.toString) - case Ident(name) => - valueCode(name.toString) - - case If(condition, then, otherwise) => - // val (a, b) = if ({ val d = 0 ; d != 0 }) (1, d) else (2, 0) - // -> - // val d = 0 - // val condition = d != 0 - // val a = if (condition) 1 else 2 - // val b = if (condition) d else 0 - val FlatCode(dc, sc, Seq(vc)) = convert(condition) - val fct @ FlatCode(Seq(), st, vt) = convert(then) - val fco @ FlatCode(Seq(), so, vo) = convert(otherwise) - - def newIf(t: String, o: String, isValue: Boolean) = - if (isValue) - "((" + vc + ") ? (" + t + ") : (" + o + "))" - else - "if (" + vc + ") {\n" + t + "\n} else {\n" + o + "\n}\n" - - val (rs, rv) = (st, so) match { - case (Seq(), Seq()) if !vt.isEmpty && !vo.isEmpty => - ( - Seq(), - vt.zip(vo).map { case (t, o) => newIf(t, o, true) } // pure (cond ? then : otherwise) form, possibly with tuple values - ) - case _ => - ( - Seq(newIf((st ++ vt).mkString("\n"), (so ++ vo).mkString("\n"), false)), - Seq() - ) - } - FlatCode[String]( - dc, - sc ++ rs, - rv - ) - case Apply(Select(target, applyName()), List(singleArg)) => - merge(Seq(target, singleArg).map(convert):_*) { case Seq(t, a) => Seq(t + "[" + a + "]") } - case Apply(Select(target, updateName()), List(index, value)) => - merge(Seq(target, index, value).map(convert):_*) { case Seq(t, i, v) => Seq(t + "[" + i + "] = " + v) } - case Assign(lhs, rhs) => - merge(Seq(lhs, rhs).map(convert):_*) { case Seq(l, r) => Seq(l + " = " + r + ";") } - case Typed(expr, tpt) => - val t = convertTpe(tpt.tpe) - convert(expr).mapValues(_.map(v => "((" + t + ")" + v + ")")) - case DefDef(mods, name, tparams, vparamss, tpt, body) => - val b = new StringBuilder - b ++= convertTpe(body.tpe) + " " + name + "(" - var first = true - for (param <- vparamss.flatten) { - if (first) - first = false - else - b ++= ", " - b ++= constPref(param.mods) + convertTpe(param.tpt.tpe) + " " + param.name - } - b ++= ") {\n" - val convBody = convert(body) - convBody.statements.foreach(b ++= _) - if (!convBody.values.isEmpty) { - val Seq(ret) = convBody.values - b ++= "return " + ret + ";" - } - b ++= "\n}" - FlatCode[String]( - convBody.outerDefinitions :+ b.toString, - Seq(), - Seq() - ) - case vd @ ValDef(paramMods, paramName, tpt: TypeTree, rhs) => - val convValue = convert(rhs) - FlatCode[String]( - convValue.outerDefinitions, - convValue.statements ++ - Seq( - constPref(paramMods) + convertTpt(tpt) + " " + paramName + ( - if (rhs != EmptyTree) { - val Seq(value) = convValue.values - " = " + value - } else - "" - ) + ";" - ), - Seq() - ) - //case Typed(expr, tpe) => - // out(expr) - case Match(ma @ Ident(matchName), List(CaseDef(pat, guard, body))) => - //for () - //x0$1 match { - // case (_1: Long,_2: Float)(Long, Float)((i @ _), (c @ _)) => i.+(c) - //} - //Match(Ident("x0$1"), List(CaseDef(Apply(TypeTree(), List(Bind(i, Ident("_")), Bind(c, Ident("_"))), EmptyTree Apply(Select(Ident("i"), "$plus"), List(Ident("c") - convert(body) - case Select(expr, toSizeTName()) => cast(expr, "size_t") - case Select(expr, toLongName()) => cast(expr, "long") - case Select(expr, toIntName()) => cast(expr, "int") - case Select(expr, toShortName()) => cast(expr, "short") - case Select(expr, toByteName()) => cast(expr, "char") - case Select(expr, toCharName()) => cast(expr, "short") - case Select(expr, toDoubleName()) => cast(expr, "double") - case Select(expr, toFloatName()) => cast(expr, "float") - case ScalaMathFunction(functionType, funName, args) => - convertMathFunction(functionType, funName, args) - case Apply(s @ Select(left, name), args) => - val List(right) = args - NameTransformer.decode(name.toString) match { - case op @ ("+" | "-" | "*" | "/" | "%" | "^" | "^^" | "&" | "&&" | "|" | "||" | "<<" | ">>" | "==" | "<" | ">" | "<=" | ">=" | "!=") => - merge(Seq(left, right).map(convert):_*) { - case Seq(l, r) => Seq("(" + l + " " + op + " " + r + ")") - //case e => - // throw new RuntimeException("ugh : " + e + ", op = " + op + ", body = " + body + ", left = " + left + ", right = " + right) - } - case n if isPackageReference(left, "scala.math") => - convertMathFunction(s.tpe, name, args) - //merge(Seq(right).map(convert):_*) { case Seq(v) => Seq(n + "(" + v + ")") } - case n => - println(nodeToStringNoComment(body)) - throw new RuntimeException("[ScalaCL] Unhandled method name in Scala -> OpenCL conversion : " + name + "\n\tleft = " + left + ",\n\targs = " + args) - valueCode("/* Error: failed to convert " + body + " */") - } - case s @ Select(expr, fun) => - convert(expr).mapEachValue(v => { - val fn = fun.toString - if (fn.matches("_\\d+")) { - Seq(v + "." + fn) - } else { - throw new RuntimeException("Unknown function " + s) - Seq("/* Error: failed to convert " + body + " */") - } - }) - case WhileLoop(condition, content) => - val FlatCode(dcont, scont, vcont) = content.map(convert).reduceLeft(_ >> _) - val FlatCode(dcond, scond, Seq(vcond)) = convert(condition) - FlatCode[String]( - dcond ++ dcont, - scond ++ - Seq( - "while (" + vcond + ") {\n" + - (scont ++ vcont).mkString("\n") + "\n" + - "}" - ), - Seq() - ) - case Apply(target, args) => - merge((target :: args).map(convert):_*)(seq => { - val t :: a = seq.toList - Seq(t + "(" + a.mkString(", ") + ")") - }) - case Block(statements, Literal(Constant(empty))) => - assert(empty == (), "Valued blocks should have been flattened in a previous phase !") - statements.map(convert).map(_.noValues).reduceLeft(_ >> _) - case _ => - //println(nodeToStringNoComment(body)) - throw new RuntimeException("Failed to convert " + body.getClass.getName + ": \n" + body + " : \n" + nodeToStringNoComment(body)) - valueCode("/* Error: failed to convert " + body + " */") - } - } - def convertMathFunction(functionType: Type, funName: Name, args: List[Tree]) = { - var outers = Seq[String]()//"#include ") - val hasDoubleParam = args.exists(_.tpe == DoubleClass.tpe) - if (hasDoubleParam) - outers ++= Seq("#pragma OPENCL EXTENSION cl_khr_fp64: enable") - - val normalizedArgs = args.map(_ match { - case Select(a, toDoubleName()) => a - case arg => arg - }) - val convArgs = normalizedArgs.map(convert) - - assert(convArgs.forall(_.statements.isEmpty), convArgs) - FlatCode[String]( - convArgs.flatMap(_.outerDefinitions) ++ outers, - convArgs.flatMap(_.statements), - Seq( - funName + "(" + - convArgs.zip(normalizedArgs).map({ case (convArg, normalizedArg) => - assert(convArg.statements.isEmpty, convArg) - val Seq(value) = convArg.values - //"(" + convertTpe(normalizedArg.tpe) + ")" + value - functionType match { - case _ //MethodType(List(param), resultType) - if normalizedArg.tpe != DoubleClass.tpe => - "(float)" + value - case _ => - "(" + convertTpe(normalizedArg.tpe) + ")" + value - } - }).mkString(", ") + - ")" - ) - ) - } - def constPref(mods: Modifiers) = - (if (mods.hasFlag(MUTABLE)) "" else "const ") - - def convertTpt(tpt: TypeTree) = convertTpe(tpt.tpe) - def convertTpe(tpe: Type) = { - if (tpe == null) { - throw new RuntimeException("Null type cannot be converted to OpenCL !") - "?" - } else if (tpe == NoType) - "void" - else - tpe.toString match { - case "Int" => "int" - case "Long" => "long" - case "Short" => "short" - case "Char" => "short" - case "Byte" => "char" - case "Float" => "float" - case "Double" => "double" - case "Boolean" => "char" - case "org.bridj.SizeT" => "size_t" - case _ => throw new RuntimeException("Cannot convert unknown type " + tpe + " to OpenCL") - } - } -} diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala deleted file mode 100644 index 656bcbaea..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala +++ /dev/null @@ -1,601 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl ; package plugin -import com.nativelibs4java.scalaxy._ -import common._ -import pluginBase._ -import components._ - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} -import scala.tools.nsc.typechecker.Analyzer -import scala.tools.nsc.typechecker.Contexts -import scala.Predef._ - -//import scala.tools.nsc.typechecker.Contexts._ - -object ScalaCLFunctionsTransformComponent { - val runsAfter = List[String]( - "namer", - //LoopsTransformComponent.phaseName, - StreamTransformComponent.phaseName - ) - val runsBefore = List[String]( - "refchecks" - ) - val phaseName = "scalacl-functionstransform" -} - -class ScalaCLFunctionsTransformComponent(val global: Global, val options: PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - with MiscMatchers - with TreeBuilders - with TraversalOps - with OpenCLConverter - with WithOptions - with CodeFlattening - with TupleAnalysis - with CLCodeAnalysis - with WorkaroundsForOtherPhases - with CLPluginNames -{ - import global._ - import global.definitions._ - import gen._ - import CODE._ - import scala.tools.nsc.symtab.Flags._ - import typer.typed - import analyzer.{SearchResult, ImplicitSearch, UnTyper} - - override val runsAfter = ScalaCLFunctionsTransformComponent.runsAfter - override val runsBefore = ScalaCLFunctionsTransformComponent.runsBefore - override val phaseName = ScalaCLFunctionsTransformComponent.phaseName - - import impl._ - - def getDataIOByTupleInfo(ti: TupleInfo): CLDataIO[Any] = { - //println("ti.tpe = " + ti.tpe + ", ti.components = " + ti.components) - if (ti.components.size <= 1) - getDataIO(ti.tpe) - else - new CLTupleDataIO[Any](ios = ti.components.toArray.map(getDataIOByTupleInfo _), null, null) // TODO - } - - def getDataIO(tpe: Type): CLDataIO[Any] = { - //println("getDataIO(" + tpe + ")") - val dataIO = tpe.typeSymbol match { - case IntClass => CLIntDataIO - case ShortClass => CLShortDataIO - case ByteClass => CLByteDataIO - case CharClass => CLCharDataIO - case LongClass => CLLongDataIO - case BooleanClass => CLBooleanDataIO - case FloatClass => CLFloatDataIO - case DoubleClass => CLDoubleDataIO - case _ => { - try { - val tupleInfo = getTupleInfo(tpe) - val tupleDataIO = getDataIOByTupleInfo(tupleInfo) - //println("ScalaCLFunctionsTransform: dataIO=" + tupleDataIO.toString + " tupleInfo=" + tupleInfo.toString) - tupleDataIO - } catch { case e => - println("ScalaCLFunctionsTransform: Exception getting CLDataIO for tuple. e=" + e.getStackTraceString) - throw e - } - } - } - dataIO.asInstanceOf[CLDataIO[Any]] - } - - def newTransformer(unit: CompilationUnit) = new TypingTransformer(unit) { - var currentClassName: Name = null - - def createImplicitDataIO(context: analyzer.Context, tree: Tree, tpe: Type) = { - val applicableViews: List[SearchResult] = - new ImplicitSearch(tree, tpe, isView = false, context.makeImplicit(reportAmbiguousErrors = false)).allImplicits - for (view <- applicableViews) { - - } - null: Tree - } - - /** - * Remove all symbols from the trees, because old symbols from before the unique renaming will preempt on renamed Ident names when printing the tree out to C code. - * Hit Java verifier exceptions (Scala compiler bug) when letting this function definition where it's used, so lifted it up manually :-S - */ - private def removeSymbolsExceptParamSymbolAsUnderscore(symbolReplacements: Map[Symbol, String], t: Tree) = { - - def replace(tree: Tree) = { - //paramSymbol: Symbol - symbolReplacements.get(tree.symbol) match { - case Some(rep) => - treeCopy.Ident(tree, N(rep)) - case None => - tree.setSymbol(NoSymbol) // to make renaming effective - super.transform(tree) - } - } - - val trans = new Transformer { - override def transform(tree: Tree) = tree match { - case s @ Select(This(targetClass), name) if tree.hasSymbol => - //println("Replacing name=" + name + " with _X using This(..)") - replace(tree) - case s @ Select(Select(target, target2), name) if tree.hasSymbol => - //println("Replacing name=" + name + " with _X using Select(..)") - replace(tree) - case Ident(name) if tree.hasSymbol => - //println("Replacing name=" + name + " with _X using Ident(..)") - replace(tree) - case _ => - //println("NOT Replacing anything! tree=" + tree) - super.transform(tree) - } - } - trans transform t - } - - /* - lazy val scalaCLContexts = { - import com.nativelibs4java.opencl._ - JavaCL.listPlatforms.flatMap(_.listAllDevices(true).flatMap(device => { - try { - Some(new Context(JavaCL.createContext(null, device))) - } catch { - case ex => - ex.printStackTrace - None - } - })) - }.toArray - */ - - private lazy val duplicator = new Transformer { - override val treeCopy = new StrictTreeCopier - } - - val primitiveTypeSymbols = Set(IntClass, LongClass, ShortClass, ByteClass, BooleanClass, DoubleClass, FloatClass, CharClass) - - def canCaptureSymbol(s: Symbol) = { - //(System.getenv("SCALACL_CAPTURE_VARIABLES") != null) && - s.owner == CLArrayClass || // TODO check / refine / warn - s.isValue && s.isStable && !s.isMutable && - s.isInstanceOf[TermSymbol] && //s.isEffectivelyFinal && // this rules out captured fields ! - { - val tpe = normalize(s.tpe) match { - case NullaryMethodType(result) => - result - case tpe => - tpe - } - - tpe == IntClass.tpe || - tpe == ShortClass.tpe || - tpe == LongClass.tpe || - tpe == ByteClass.tpe || - tpe == DoubleClass.tpe || - tpe == FloatClass.tpe || - tpe == CharClass.tpe || - (tpe match { // tpe == CLArrayClass.tpe - case TypeRef(_, CLArrayClass, List(_)) => - true - case _ => - false - }) - } - } - - def getDataIOImplicit(tpe: Type, context: analyzer.Context, enclosingTree: Tree): (Tree, CLDataIO[Any]) = { - //println("getDataIOImplicit(" + tpe + ", ...) ; UnitClass.tpe = " + UnitClass.tpe) - if (isUnit(tpe)) - null - else { - val dataIOTpe = appliedType(CLDataIOClass.tpe, List(tpe)) - var ioTree = analyzer.inferImplicit(enclosingTree, dataIOTpe, false, false, context).tree - if (ioTree == null) - null - else { - val dataIO = getDataIO(tpe) - (ioTree, dataIO) - } - } - } - def conversionError(pos: Position, msg: String) = { - unit.error(pos, msg) - throw new UnsupportedOperationException("Conversion error : " + msg) - } - - case class Capture(symbol: Symbol, io: (Tree, CLDataIO[Any]), isArray: Boolean, arg: Tree) - - val anyCLDataIOTpe = TypeRef(NoPrefix, CLDataIOClass, List(WildcardType)) - val anyCLArrayTpe = TypeRef(NoPrefix, CLArrayClass, List(WildcardType)) - - def getCaptures(f: Tree, context: analyzer.Context, enclosingTree: Tree): (Seq[Capture], Boolean) = { - val externalSymbolInfo = - getUnknownSymbolInfo(f, t => t.symbol != NoSymbol && { - //println("Examining t = " + t ) - t.symbol match { - case s: MethodSymbol => - !(s.owner == CLArrayClass && s.toString == "method apply") && - !primitiveTypeSymbols.contains(s.owner) && - !(s.owner == ScalaMathCommonClass && s.toString.startsWith("method ")) && - !s.toString.matches("value _\\d+") && - !s.toString.matches("method to(Double|Int|Float|Long|Short|Byte|Boolean|Char)") && - !(s.toString == "method apply" && s.owner != null && s.owner.toString.matches("object Tuple\\d+")) // TODO cleanup hack - case s: ModuleSymbol => - false - case s: TermSymbol => - println("TermSymbol: " + s + " t.isInstanceOf[Ident] = " + t.isInstanceOf[Ident] + " t.isInstanceOf[Select] = " + t.isInstanceOf[Select]) - t.isInstanceOf[Ident] || t.isInstanceOf[Select] - case s => - println("Unmatched symbol: " + s) - false - } - }) - - val externalRefsBySymbol = externalSymbolInfo.unknownReferences.groupBy(_.symbol) - val externalSymbols = externalRefsBySymbol.keys.toSet - - val (capturableSymbols, nonCapturableSymbols) = - externalSymbols.partition(canCaptureSymbol) - - for (s <- nonCapturableSymbols) yield { - val details = - if (options.verbose) - "\nDetails about symbol '" + s + "' (" + s.getClass.getName + ") :\n\t" + - Map( - "tpe" -> { - val t = normalize(s.tpe) - t + " (" + t.getClass.getName + ")" - }, - "owner" -> s.owner, - "isMutable" -> s.isMutable, - "isFinal" -> s.isFinal, - "isEffectivelyFinal" -> s.isEffectivelyFinal, - "isStable" -> s.isStable, - "isConstant" -> s.isConstant, - "isValue" -> s.isValue, - "isVariable" -> s.isVariable, - "isModuleVar" -> s.isModuleVar, - "isLocal" -> s.isLocal, - "isValueParameter" -> s.isValueParameter, - "isCapturedVariable" -> s.isCapturedVariable, - "isLocalDummy" -> s.isLocalDummy, - "isErroneous" -> s.isErroneous, - "isOuterField" -> s.isOuterField, - "isOuterAccessor" -> s.isOuterAccessor - ).map({ case (n, v) => n + ":\t" + v }).mkString("\n\t") - else - "" - - val refs = externalRefsBySymbol(s) - for (ref <- refs) { - unit.error(ref.pos, "Cannot capture this external symbol (can only capture final AnyVal or CLArray values)." + details) - } - } - - val captures = for (s <- capturableSymbols) yield { - val refs = externalRefsBySymbol(s) - val (rawTpe: Type, isArray: Boolean) = normalize(s.tpe) match { - case TypeRef(_, CLArrayClass, List(tpe)) => - (tpe, true) - case NullaryMethodType(result) => - result match { - case TypeRef(_, CLArrayClass, List(tpe)) => - (tpe, true) - case _ => - (result, false) - } - case _ => - (s.tpe, false) - } - val tpe = normalize(rawTpe) - - var io = if (isUnit(tpe)) null else { - val io = getDataIOImplicit(tpe, context, enclosingTree) - if (io == null) { - for (ref <- refs) - unit.error(ref.pos, "Cannot infer CLDataIO instance for type " + tpe + " of captured " + (if (isArray) "array" else "") + " variable !") - } - io - } - val arg = ident(s, N(refs.first.toString)) - Capture(symbol = s, io = io, isArray = isArray, arg = arg) - } - - (captures.toSeq, nonCapturableSymbols.isEmpty) - } - - def convertFunctionToCLFunction(originalFunction: Tree): Tree = { - val f = duplicator transform originalFunction - - //println("originalFunction = " + originalFunction) - - val context = localTyper.context1 - - val (captures, succeeded) = getCaptures(f, context, originalFunction) - //println("captures = " + captures) - - if (!succeeded) { - // Failure ! - originalFunction - } else { - val extraInputBufferArgsIOs = Seq[(Tree, CLDataIO[Any])]() // TODO put here the ios for arrays that are used in read-only mode - val extraOutputBufferArgsIOs = captures.filter(_.isArray).map(_.io) - val extraScalarArgsIOs = captures.filter(!_.isArray).map(_.io) - - val extraInputBufferArgs = Seq[Tree]() // TODO put here the ios for arrays that are used in read-only mode - - val (capturedOutputBuffers, capturedScalars) = captures.partition(_.isArray) - val extraOutputBufferArgs = capturedOutputBuffers.map(_.arg.AS(anyCLArrayTpe)) - val extraScalarArgs = capturedScalars.map(_.arg) - - assert(f.id != originalFunction.id) - var Function(List(uniqueParam), body) = f - val renamed = renameDefinedSymbolsUniquely(body, unit) - val tupleAnalyzer = new TupleAnalyzer(renamed) - val flattener = new TuplesAndBlockFlattener(tupleAnalyzer) - val flattened = flattener.flattenTuplesAndBlocksWithInputSymbol(renamed, uniqueParam.symbol, uniqueParam.name, currentOwner)(unit) - - /* - if (options.verbose) - println("Flattened tuples and blocks : \n\t" + - flattened.outerDefinitions.mkString("\n").replaceAll("\n", "\n\t") + - "\n\t" + uniqueParam + " => {\n\t\t" + - flattened.statements.mkString("\n").replaceAll("\n", "\n\t\t") + - "\n\t\t(\n\t\t\t" + - flattened.values.mkString("\n").replaceAll("\n", "\n\t\t\t") + - "\n\t\t)\n\t}" - ) - */ - - // Symbols replacement map : replace function param by "_" and captured symbols by "_1", "_2"... - val symsMap = - Map(uniqueParam.symbol -> "_") ++ - ((capturedOutputBuffers ++ capturedScalars).zipWithIndex.map { case (c, i) => c.symbol -> ("_" + (i + 1)) }) - - //println("symsMap = " + symsMap) - - def convertCode(tree: Tree) = - convert(removeSymbolsExceptParamSymbolAsUnderscore(symsMap/*uniqueParam.symbol*/, tree)) - - val Array(convDefs, convStats, convVals) = Array(flattened.outerDefinitions, flattened.statements, flattened.values).map(_ map convertCode) - - val outerDefinitions = - Seq(convDefs, convStats, convVals).flatMap(_.flatMap(_.outerDefinitions)).distinct.toArray.sortBy(_.startsWith("#")) - - val statements = - Seq(convStats, convVals).flatMap(_.flatMap(_.statements)) - - val values: Seq[String] = - convVals.flatMap(_.values) - - //println("Renamed defined symbols uniquely : " + renamed) - val sourceTpe = uniqueParam.symbol.tpe - val mappedTpe = body.tpe - val Array( - sourceDataIO, - mappedDataIO - ) = Array( - sourceTpe, - mappedTpe - ).map(tpe => getDataIOImplicit(tpe, context, originalFunction)) - - //val (statements, values) = convertExpr(Map(uniqueParam.symbol -> "_"), body) - val uniqueSignature = Literal(Constant( - ( - Array( - originalFunction.symbol.outerSource, originalFunction.symbol.tag + "|" + originalFunction.pos, - sourceTpe, mappedTpe - ) ++ - outerDefinitions ++ - statements ++ - values - ).map(_.toString).mkString("|") - )) - val uniqueId = uniqueSignature.hashCode // TODO !!! - - if (options.verbose) { - def indent(t: Any) = - "\t" + t.toString.replaceAll("\n", "\n\t") - - println( - ( - Array( - "[scalacl] Converted <<<", - indent(body), - ">>> to <<<" - ) ++ - outerDefinitions.map(indent) ++ - statements.map(indent) ++ - Array( - indent("(" + values.mkString(", ") + ")"), - ">>>" - ) - ).mkString("\n") - ) - } - - /* - val sourceData = { - val aIO = sourceDataIO._2 - val bIO = mappedDataIO._2 - //println("aIO = " + aIO + ", bIO = " + bIO) - CLFunctionCode.buildSourceData[Any, Any]( - outerDeclarations = outerDefinitions, - declarations = statements.toArray, - expressions = values.toArray, - includedSources = Array(), - extraArgsIOs = CapturedIOs( - extraInputBufferArgsIOs.toArray.map(_._2), - extraOutputBufferArgsIOs.toArray.map(_._2), - extraScalarArgsIOs.toArray.map(_._2) - ) - )(aIO, bIO) - } - - //println("sourceData = " + sourceData) - */ - - /* - if (System.getenv("SCALACL_VERIFY") != "0") { - val errors = scalaCLContexts.flatMap(context => { - try { - val f = new impl.CLFunction[Int, Int](null, outerDefinitions, statements, values, Seq()) - f.compile(context) - // TODO illegal access : f.release(context) - None - } catch { case ex => Some((context.context.getDevices()(0), ex)) } - }) - - - if (errors.length > 0) - throw new RuntimeException("Failed to compile the OpenCL kernel with some of the available devices :\n" + (errors.map { case (device, ex) => "Device " + device + " : " + ex }).mkString("\n")) - else if (options.verbose) - println("Program successfully compiled on " + scalaCLContexts.size + " available device(s)") - } - */ - val getCachedFunctionSym = ScalaCLPackage.tpe member getCachedFunctionName - val clFunction = - typed { - Apply( - Apply( - TypeApply( - Select( - Ident(scalacl_) setSymbol ScalaCLPackage, - getCachedFunctionName - ), - List(TypeTree(sourceTpe), TypeTree(mappedTpe)) - ).setSymbol(getCachedFunctionSym), - List( - newInt(uniqueId), - originalFunction, - newArrayApply(TypeTree(StringClass.tpe), outerDefinitions.map(d => Literal(Constant(d))):_*), - newArrayApply(TypeTree(StringClass.tpe), statements.map(s => Literal(Constant(s))):_*), - newArrayApply(TypeTree(StringClass.tpe), values.map(value => Literal(Constant(value))):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraInputBufferArgsIOs.map(_._1):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraOutputBufferArgsIOs.filter(_ != null).map(_._1):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraScalarArgsIOs.filter(_ != null).map(_._1):_*) - ) - ).setSymbol(getCachedFunctionSym), - List( - sourceDataIO._1, - Option(mappedDataIO).map(_._1).getOrElse(newNull(anyCLDataIOTpe)) - ) - ).setSymbol(getCachedFunctionSym) - } - - if (captures.isEmpty) - clFunction - else - typed { - val withCaptureSym = CLFunctionClass.tpe member withCaptureName - Apply( - Select( - clFunction, - withCaptureName - ).setSymbol(withCaptureSym), - List( - newArrayApply(TypeTree(anyCLArrayTpe), extraInputBufferArgs:_*), - newArrayApply(TypeTree(anyCLArrayTpe), extraOutputBufferArgs:_*), - newArrayApply(TypeTree(AnyClass.tpe), extraScalarArgs:_*) - ) - ).setSymbol(withCaptureSym) - } - } - } - override def transform(tree: Tree): Tree = { - if (!shouldOptimize(tree)) - super.transform(tree) - else { - try { - tree match { - case TraversalOp(traversalOp) if traversalOp.op.f != null => - import traversalOp._ - val colTpe = normalize(collection.tpe) - //if (colTpe <:< CLCollectionClass.tpe) { - //println("colTpe = " + colTpe) - //println("colTpe.typeSymbol.typeConstructor = " + colTpe.typeSymbol.typeConstructor) - //println("colTpe.typeSymbol.typeConstructor == CLArray = " + (colTpe.typeSymbol.typeConstructor == CLArrayClass.tpe)) - val colTpeStr = colTpe.toString - - if (colTpeStr.contains("scalacl.") || colTpeStr.contains("CLArray")) { // TODO - //println("OpenCL colTpe ; op = " + op) - op match { - case opType @ (TraversalOps.MapOp(_, _, _) | TraversalOps.ForeachOp(_, _) | TraversalOps.FilterOp(_, _, false)) => - msg(unit, tree.pos, "associated equivalent OpenCL source to " + colTpe + "." + op + "'s function argument.") { - val clFunction = convertFunctionToCLFunction(op.f) - replaceOccurrences(super.transform(tree), Map(), Map(), Map(op.f -> (() => clFunction)), unit) - } - case _ => - if (verbose) - println("Operation " + op + " on " + colTpeStr + " is not optimized by ScalaCL yet") - super.transform(tree) - } - } else { - super.transform(tree) - } - case - Apply( - Apply( - TypeApply( - Select( - tg, - Function2CLFunctionName() - ), - List(typeFrom, typeTo) - ), - List(f) - ), - List(ioFrom, ioTo) - ) if isPackageReference(tg, "scalacl") => - msg(unit, tree.pos, "transformed Scala function to a CLFunction.") { - val clFunction = convertFunctionToCLFunction(f) - clFunction.tpe = tree.tpe - clFunction - //replaceOccurrences(super.transform(tree), Map(), Map(), Map(f -> (() => clFunction)), unit) - } - case _ => - super.transform(tree) - } - } catch { - case ex => - ex.printStackTrace - super.transform(tree) - } - } - } - } -} diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala.bug b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala.bug deleted file mode 100644 index bd3c5395c..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLFunctionsTransformComponent.scala.bug +++ /dev/null @@ -1,570 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl ; package plugin - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} -import scala.tools.nsc.typechecker.Analyzer -import scala.tools.nsc.typechecker.Contexts -import scala.Predef._ - -//import scala.tools.nsc.typechecker.Contexts._ - -object ScalaCLFunctionsTransformComponent { - val runsAfter = List[String]( - "namer", - LoopsTransformComponent.phaseName, - StreamTransformComponent.phaseName - ) - val runsBefore = List[String]( - "refchecks" - ) - val phaseName = "scalacl-functionstransform" -} - -class ScalaCLFunctionsTransformComponent(val global: Global, val options: ScalaCLPlugin.PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - with MiscMatchers - with TreeBuilders - with TraversalOps - with OpenCLConverter - with WithOptions - with CodeFlattening - with TupleAnalysis - with CodeAnalysis - with WorkaroundsForOtherPhases -{ - import global._ - import global.definitions._ - import gen._ - import CODE._ - import scala.tools.nsc.symtab.Flags._ - import typer.typed - import analyzer.{SearchResult, ImplicitSearch, UnTyper} - - override val runsAfter = ScalaCLFunctionsTransformComponent.runsAfter - override val runsBefore = ScalaCLFunctionsTransformComponent.runsBefore - override val phaseName = ScalaCLFunctionsTransformComponent.phaseName - - import impl._ - - val ScalaCLPackage = getModule("scalacl") - val ScalaCLPackageClass = ScalaCLPackage.tpe.typeSymbol - - - def tryOrNull[V <: AnyRef](v: => V): V = - try { v } catch { case _ => null.asInstanceOf[V] } - - val CLDataIOClass = C("scalacl.impl.CLDataIO") - val CLArrayClass = C("scalacl.CLArray") - val CLArrayModule = M("scalacl.CLArray") - val CLFunctionClass = C("scalacl.impl.CLFunction") - val CLRangeClass = C("scalacl.CLRange") - val CLCollectionClass = C("scalacl.CLCollection") - val CLFilteredArrayClass = C("scalacl.CLFilteredArray") - - val scalacl_ = N("scalacl") - val getCachedFunctionName = N("getCachedFunction") - val Function2CLFunctionName = N("Function2CLFunction") - val withCaptureName = N("withCapture") - - def getDataIOByTupleInfo(ti: TupleInfo): CLDataIO[Any] = { - if (ti.components.size == 1) - getDataIO(ti.tpe) - else - new CLTupleDataIO[Any](ios = ti.components.toArray.map(getDataIOByTupleInfo _), null, null) // TODO - } - def getDataIO(tpe: Type): CLDataIO[Any] = { - try { - getDataIOByTupleInfo(getTupleInfo(tpe)) - } catch { case _ => - (tpe.typeSymbol match { - case IntClass => CLIntDataIO - case ShortClass => CLShortDataIO - case ByteClass => CLByteDataIO - case CharClass => CLCharDataIO - case LongClass => CLLongDataIO - case BooleanClass => CLBooleanDataIO - case FloatClass => CLFloatDataIO - case DoubleClass => CLDoubleDataIO - }).asInstanceOf[CLDataIO[Any]] - } - } - - def newTransformer(unit: CompilationUnit) = new TypingTransformer(unit) { - var currentClassName: Name = null - - def createImplicitDataIO(context: analyzer.Context, tree: Tree, tpe: Type) = { - val applicableViews: List[SearchResult] = - new ImplicitSearch(tree, tpe, isView = false, context.makeImplicit(reportAmbiguousErrors = false)).allImplicits - for (view <- applicableViews) { - - } - null: Tree - } - - /** - * Remove all symbols from the trees, because old symbols from before the unique renaming will preempt on renamed Ident names when printing the tree out to C code. - * Hit Java verifier exceptions (Scala compiler bug) when letting this function definition where it's used, so lifted it up manually :-S - */ - private def removeSymbolsExceptParamSymbolAsUnderscore(symbolReplacements: Map[Symbol, String], t: Tree) = { - val trans = new Transformer { - override def transform(tree: Tree) = tree match { - case Ident(name) if tree.hasSymbol => - //paramSymbol: Symbol - symbolReplacements.get(tree.symbol) match { - case Some(rep) => - treeCopy.Ident(tree, N(rep)) - case None => - tree.setSymbol(NoSymbol) // to make renaming effective - super.transform(tree) - } - case _ => - super.transform(tree) - } - } - trans transform t - } - - /* - lazy val scalaCLContexts = { - import com.nativelibs4java.opencl._ - JavaCL.listPlatforms.flatMap(_.listAllDevices(true).flatMap(device => { - try { - Some(new Context(JavaCL.createContext(null, device))) - } catch { - case ex => - ex.printStackTrace - None - } - })) - }.toArray - */ - - private lazy val duplicator = new Transformer { - override val treeCopy = new StrictTreeCopier - } - - val primitiveTypeSymbols = Set(IntClass, LongClass, ShortClass, ByteClass, BooleanClass, DoubleClass, FloatClass, CharClass) - - def canCaptureSymbol(s: Symbol) = { - //(System.getenv("SCALACL_CAPTURE_VARIABLES") != null) && - s.isValue && s.isStable && !s.isMutable && - s.isInstanceOf[TermSymbol] && s.isEffectivelyFinal && // this rules out captured fields ! - { - val tpe = normalize(s.tpe) match { - case NullaryMethodType(result) => - result - case tpe => - tpe - } - - tpe == IntClass.tpe || - tpe == ShortClass.tpe || - tpe == LongClass.tpe || - tpe == ByteClass.tpe || - tpe == DoubleClass.tpe || - tpe == FloatClass.tpe || - tpe == CharClass.tpe || - (tpe match { // tpe == CLArrayClass.tpe - case TypeRef(_, CLArrayClass, List(_)) => - true - case _ => - false - }) - } - } - - def getDataIOImplicit(tpe: Type, context: analyzer.Context, enclosingTree: Tree): (Tree, CLDataIO[Any]) = { - val dataIOTpe = appliedType(CLDataIOClass.tpe, List(tpe)) - var ioTree = analyzer.inferImplicit(enclosingTree, dataIOTpe, false, false, context).tree - if (ioTree == null) - null - else - (ioTree.AS(anyCLDataIOTpe), getDataIO(tpe)) - } - def conversionError(pos: Position, msg: String) = { - unit.error(pos, msg) - throw new UnsupportedOperationException("Conversion error : " + msg) - } - - case class Capture(symbol: Symbol, io: (Tree, CLDataIO[Any]), isArray: Boolean, arg: Tree) - - val anyCLDataIOTpe = TypeRef(NoPrefix, CLDataIOClass, List(AnyClass.tpe)) - val anyCLArrayTpe = TypeRef(NoPrefix, CLArrayClass, List(AnyClass.tpe)) - - def getCaptures(f: Tree, context: analyzer.Context, enclosingTree: Tree): (Seq[Capture], Boolean) = { - val externalSymbolInfo = - getUnknownSymbolInfo(f, t => t.symbol != NoSymbol && { - //println("Examining t = " + t ) - t.symbol match { - case SymbolWithOwnerAndName(_, CLArrayClass | CLArrayModule, applyName() | updateName()) => - false // not unknown - case SymbolWithOwnerAndName(_, TupleClass(), applyName() | tupleComponentName(_)) => - false - case SymbolWithOwnerAndName(_, ScalaMathCommonClass, _) => - false - case s: MethodSymbol => - if (s.owner == CLArrayClass) { - s.name match { - case applyName() | updateName() => - false - case _ => - true // unknown - } - } else { - !primitiveTypeSymbols.contains(s.owner) && - //s.owner != ScalaMathCommonClass && - //!(s.toString.matches("value _\\d+") && println("NAME FOR TUPLE COMP IS " + s.name)) && - !s.toString.matches("method to(Double|Int|Float|Long|Short|Byte|Boolean|Char)") - } - case s: ModuleSymbol => - false - case s: TermSymbol => - t.isInstanceOf[Ident] - case _ => - false - } - }) - - val externalRefsBySymbol = externalSymbolInfo.unknownReferences.groupBy(_.symbol) - val externalSymbols = externalRefsBySymbol.keys.toSet - - val (capturableSymbols, nonCapturableSymbols) = - externalSymbols.partition(canCaptureSymbol) - - for (s <- nonCapturableSymbols) yield { - val details = - if (options.verbose) - "\nDetails about symbol '" + s + "' (" + s.getClass.getName + ") :\n\t" + - Map( - "tpe" -> { - val t = normalize(s.tpe) - t + " (" + t.getClass.getName + ")" - }, - "isMutable" -> s.isMutable, - "isFinal" -> s.isFinal, - "isEffectivelyFinal" -> s.isEffectivelyFinal, - "isStable" -> s.isStable, - "isConstant" -> s.isConstant, - "isValue" -> s.isValue, - "isVariable" -> s.isVariable, - "isModuleVar" -> s.isModuleVar, - "isLocal" -> s.isLocal, - "isValueParameter" -> s.isValueParameter, - "isCapturedVariable" -> s.isCapturedVariable, - "isLocalDummy" -> s.isLocalDummy, - "isErroneous" -> s.isErroneous, - "isOuterField" -> s.isOuterField, - "isOuterAccessor" -> s.isOuterAccessor - ).map({ case (n, v) => n + ":\t" + v }).mkString("\n\t") - else - "" - - val refs = externalRefsBySymbol(s) - for (ref <- refs) { - unit.error(ref.pos, "Cannot capture this external symbol (can only capture final AnyVal or CLArray values)." + details) - } - } - - val captures = for (s <- capturableSymbols) yield { - val refs = externalRefsBySymbol(s) - val (tpe: Type, isArray: Boolean) = s.tpe match { - case TypeRef(_, CLArrayClass, List(tpe)) => - (tpe, true) - case _ => - (s.tpe, false) - } - - var io = getDataIOImplicit(tpe, context, enclosingTree) - if (io == null) { - for (ref <- refs) - unit.error(ref.pos, "Cannot infer CLDataIO instance for type " + tpe + " of captured " + (if (isArray) "array" else "") + " variable !") - } - val arg = ident(s, N(refs.first.toString)) - Capture(symbol = s, io = io, isArray = isArray, arg = arg) - } - - (captures.toSeq, nonCapturableSymbols.isEmpty) - } - - def convertFunctionToCLFunction(originalFunction: Tree): Tree = { - val f = duplicator transform originalFunction - - //println("originalFunction = " + originalFunction) - - val context = localTyper.context1 - - val (captures, succeeded) = getCaptures(f, context, originalFunction) - //println("captures = " + captures) - - if (!succeeded) { - // Failure ! - originalFunction - } else { - val extraInputBufferArgsIOs = Seq[(Tree, CLDataIO[Any])]() // TODO put here the ios for arrays that are used in read-only mode - val extraOutputBufferArgsIOs = captures.filter(_.isArray).map(_.io) - val extraScalarArgsIOs = captures.filter(!_.isArray).map(_.io) - - val extraInputBufferArgs = Seq[Tree]() // TODO put here the ios for arrays that are used in read-only mode - val extraOutputBufferArgs = captures.filter(_.isArray).map(_.arg.AS(anyCLArrayTpe)) - val extraScalarArgs = captures.filter(!_.isArray).map(_.arg) - - assert(f.id != originalFunction.id) - var Function(List(uniqueParam), body) = f - val renamed = renameDefinedSymbolsUniquely(body, unit) - val tupleAnalyzer = new TupleAnalyzer(renamed) - val flattener = new TuplesAndBlockFlattener(tupleAnalyzer) - val flattened = flattener.flattenTuplesAndBlocksWithInputSymbol(renamed, uniqueParam.symbol, uniqueParam.name, currentOwner)(unit) - - /* - if (options.verbose) - println("Flattened tuples and blocks : \n\t" + - flattened.outerDefinitions.mkString("\n").replaceAll("\n", "\n\t") + - "\n\t" + uniqueParam + " => {\n\t\t" + - flattened.statements.mkString("\n").replaceAll("\n", "\n\t\t") + - "\n\t\t(\n\t\t\t" + - flattened.values.mkString("\n").replaceAll("\n", "\n\t\t\t") + - "\n\t\t)\n\t}" - ) - */ - - // Symbols replacement map : replace function param by "_" and captured symbols by "_1", "_2"... - val symsMap = - Map(uniqueParam.symbol -> "_") ++ - (captures.zipWithIndex.map { case (c, i) => c.symbol -> ("_" + (i + 1)) }) - - //println("symsMap = " + symsMap) - - def convertCode(tree: Tree) = - convert(removeSymbolsExceptParamSymbolAsUnderscore(symsMap/*uniqueParam.symbol*/, tree)) - - val Array(convDefs, convStats, convVals) = Array(flattened.outerDefinitions, flattened.statements, flattened.values).map(_ map convertCode) - - val outerDefinitions = - Seq(convDefs, convStats, convVals).flatMap(_.flatMap(_.outerDefinitions)).distinct.toArray.sortBy(_.startsWith("#")) - - val statements = - Seq(convStats, convVals).flatMap(_.flatMap(_.statements)) - - val values: Seq[String] = - convVals.flatMap(_.values) - - //println("Renamed defined symbols uniquely : " + renamed) - val sourceTpe = uniqueParam.symbol.tpe - val mappedTpe = body.tpe - val Array( - sourceDataIO, - mappedDataIO - ) = Array( - sourceTpe, - mappedTpe - ).map(tpe => getDataIOImplicit(tpe, context, originalFunction)) - - //val (statements, values) = convertExpr(Map(uniqueParam.symbol -> "_"), body) - val uniqueSignature = Literal(Constant( - ( - Array( - originalFunction.symbol.outerSource, originalFunction.symbol.tag + "|" + originalFunction.pos, - sourceTpe, mappedTpe - ) ++ - outerDefinitions ++ - statements ++ - values - ).map(_.toString).mkString("|") - )) - val uniqueId = uniqueSignature.hashCode // TODO !!! - - if (options.verbose) { - def indent(t: Any) = - "\t" + t.toString.replaceAll("\n", "\n\t") - - println( - ( - Array( - "[scalacl] Converted <<<", - indent(body), - ">>> to <<<" - ) ++ - outerDefinitions.map(indent) ++ - statements.map(indent) ++ - Array( - indent("(" + values.mkString(", ") + ")"), - ">>>" - ) - ).mkString("\n") - ) - } - - val sourceData = { - val aIO = sourceDataIO._2 - val bIO = mappedDataIO._2 - println("aIO = " + aIO + ", bIO = " + bIO) - CLFunctionCode.buildSourceData[Any, Any]( - outerDeclarations = outerDefinitions, - declarations = statements.toArray, - expressions = values.toArray, - includedSources = Array(), - extraArgsIOs = CapturedIOs( - extraInputBufferArgsIOs.toArray.map(_._2), - extraOutputBufferArgsIOs.toArray.map(_._2), - extraScalarArgsIOs.toArray.map(_._2) - ) - )(aIO, bIO) - } - - println("sourceData = " + sourceData) - - /* - if (System.getenv("SCALACL_VERIFY") != "0") { - val errors = scalaCLContexts.flatMap(context => { - try { - val f = new impl.CLFunction[Int, Int](null, outerDefinitions, statements, values, Seq()) - f.compile(context) - // TODO illegal access : f.release(context) - None - } catch { case ex => Some((context.context.getDevices()(0), ex)) } - }) - - - if (errors.length > 0) - throw new RuntimeException("Failed to compile the OpenCL kernel with some of the available devices :\n" + (errors.map { case (device, ex) => "Device " + device + " : " + ex }).mkString("\n")) - else if (options.verbose) - println("Program successfully compiled on " + scalaCLContexts.size + " available device(s)") - } - */ - val getCachedFunctionSym = ScalaCLPackage.tpe member getCachedFunctionName - val clFunction = - typed { - Apply( - Apply( - TypeApply( - Select( - Ident(scalacl_) setSymbol ScalaCLPackage, - getCachedFunctionName - ), - List(TypeTree(sourceTpe), TypeTree(mappedTpe)) - ).setSymbol(getCachedFunctionSym), - List( - newInt(uniqueId), - originalFunction, - newArrayApply(TypeTree(StringClass.tpe), outerDefinitions.map(d => Literal(Constant(d))):_*), - newArrayApply(TypeTree(StringClass.tpe), statements.map(s => Literal(Constant(s))):_*), - newArrayApply(TypeTree(StringClass.tpe), values.map(value => Literal(Constant(value))):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraInputBufferArgsIOs.map(_._1):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraOutputBufferArgsIOs.map(_._1):_*), - newArrayApply(TypeTree(anyCLDataIOTpe), extraScalarArgsIOs.map(_._1):_*) - ) - ).setSymbol(getCachedFunctionSym), - List( - sourceDataIO._1, - mappedDataIO._1 - ) - ).setSymbol(getCachedFunctionSym) - } - - if (captures.isEmpty) - clFunction - else - typed { - val withCaptureSym = CLFunctionClass.tpe member withCaptureName - Apply( - Select( - clFunction, - withCaptureName - ).setSymbol(withCaptureSym), - List( - newArrayApply(TypeTree(anyCLArrayTpe), extraInputBufferArgs:_*), - newArrayApply(TypeTree(anyCLArrayTpe), extraOutputBufferArgs:_*), - newArrayApply(TypeTree(AnyClass.tpe), extraScalarArgs:_*) - ) - ).setSymbol(withCaptureSym) - } - } - } - override def transform(tree: Tree): Tree = { - if (!shouldOptimize(tree)) - super.transform(tree) - else { - try { - tree match { - case TraversalOp(traversalOp) if traversalOp.op.f != null => - import traversalOp._ - val colTpe = normalize(collection.tpe) - //if (colTpe <:< CLCollectionClass.tpe) { - if (colTpe.toString.startsWith("scalacl.")) { // TODO - op match { - case opType @ (TraversalOps.MapOp(_, _, _) | TraversalOps.FilterOp(_, _, false) | TraversalOps.ForeachOp(_, _)) => - msg(unit, tree.pos, "associated equivalent OpenCL source to " + colTpe + "." + op + "'s function argument.") { - val clFunction = convertFunctionToCLFunction(op.f) - replaceOccurrences(super.transform(tree), Map(), Map(), Map(op.f -> (() => clFunction)), unit) - } - case _ => - super.transform(tree) - } - } else { - super.transform(tree) - } - case - Apply( - Apply( - TypeApply( - Select( - tg, - Function2CLFunctionName() - ), - List(typeFrom, typeTo) - ), - List(f) - ), - List(ioFrom, ioTo) - ) if isPackageReference(tg, "scalacl") => - msg(unit, tree.pos, "transformed Scala function to a CLFunction.") { - val clFunction = convertFunctionToCLFunction(f) - clFunction.tpe = tree.tpe - clFunction - //replaceOccurrences(super.transform(tree), Map(), Map(), Map(f -> (() => clFunction)), unit) - } - case _ => - super.transform(tree) - } - } catch { - case ex => - super.transform(tree) - } - } - } - } -} diff --git a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLPlugin.scala b/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLPlugin.scala deleted file mode 100644 index 2724b1771..000000000 --- a/libraries/ScalaCL/Plugin/src/main/scala/scalacl/plugin/ScalaCLPlugin.scala +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl ; package plugin -import com.nativelibs4java.scalaxy._ -import plugin._ -import pluginBase._ -import components._ - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -/** - * http://www.scala-lang.org/node/140 - * http://lamp.epfl.ch/~emir/bqbase/2005/06/02/nscTutorial.html - * http://code.google.com/p/simple-build-tool/wiki/CompilerPlugins - * mvn scala:run -DmainClass=scalacl.plugin.Compile "-DaddArgs=-d|out|examples/Toto.scala|-Xprint:scalacl-functionstransform|-classpath|../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar" - * scala -cp target/scalacl-compiler-1.0-SNAPSHOT-shaded.jar scalacl.plugin.Compile -d out src/examples/BasicExample.scala - * javap -c -classpath out/ scalacl.examples.BasicExample - */ -object ScalaCLPluginDef extends PluginDef { - override val name = "ScalaCL" - override val description = - "This plugin transforms some Scala functions into OpenCL kernels (for CLCollection[T].map and filter's arguments), so they can run on a GPU." - - override def envVarPrefix = "SCALACL_" - - override def createOptions(settings: Settings): PluginOptions = - new PluginOptions(this, settings) - - override def createComponents(global: Global, options: PluginOptions): List[PluginComponent] = - List(new StreamTransformComponent(global, options) with CLCodeAnalysis) ++ - //ScalaxyPluginDef.createComponents(global, options) ++ - List( - try { - new ScalaCLFunctionsTransformComponent(global, options) - } catch { - case ex: scala.tools.nsc.MissingRequirementError => - if (options.verbose) - println("[scalacl] ScalaCL Collections library not in the classpath : won't perform Scala -> OpenCL transforms.") - //if (options.trace) - // ex.printStackTrace - null - case _ => - null // TODO - } - ) - - override def getCopyrightMessage: String = - "ScalaCL Plugin\nCopyright Olivier Chafik 2010-2012" -} - -class ScalaCLPlugin(override val global: Global) -extends PluginBase(global, ScalaCLPluginDef) - -object Compile extends CompilerMain { - override def pluginDef = ScalaCLPluginDef - override def commandName = "scalacl" -} diff --git a/libraries/ScalaCL/Plugin/src/main/velocity/scalac-plugin.xml b/libraries/ScalaCL/Plugin/src/main/velocity/scalac-plugin.xml deleted file mode 100644 index 596922fea..000000000 --- a/libraries/ScalaCL/Plugin/src/main/velocity/scalac-plugin.xml +++ /dev/null @@ -1,4 +0,0 @@ - - ${project_name}-${project_version} - scalacl.plugin.ScalaCLPlugin - diff --git a/libraries/ScalaCL/Plugin/src/test/scala/Test209.scala b/libraries/ScalaCL/Plugin/src/test/scala/Test209.scala deleted file mode 100644 index eca4d5558..000000000 --- a/libraries/ScalaCL/Plugin/src/test/scala/Test209.scala +++ /dev/null @@ -1,31 +0,0 @@ -package scalacltests - -import scalacl._ -import org.junit.{Assert, Test, Ignore} - -/** -SCALACL_VERBOSE=1 SCALACL_TRACE=1 mvn scala:run -DmainClass=scalacl.plugin.Compile "-DaddArgs=Test209.scala|-Xprint:scalacl-stream|-cp|../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar:/Users/ochafik/.m2/repository/junit/junit/4.10/junit-4.10.jar" - -SCALACL_VERBOSE=1 SCALACL_TRACE=1 scalac -Xplugin:target/scalacl-compiler-plugin-0.3-SNAPSHOT-shaded.jar -cp ../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar:/Users/ochafik/.m2/repository/junit/junit/4.10/junit-4.10.jar Test209.scala - -scala -cp .:../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar:/Users/ochafik/.m2/repository/junit/junit/4.10/junit-4.10.jar scalacltests.Test209 -*/ -class Issue209 { - private implicit val context = Context.best - println(context) - - def $mean(av : Array[CLArray[Float]]) : Array[Float] = { av.map( v => { v.sum / v.length } ) } - def mean(av : Array[Array[Float]]) : Array[Float] = { $mean(av.map(v => { v.cl })) } //-- line 11 - - @Test - def testMean() : Unit = { - val a = Array[Float](1.2F, 1.5F, 1.6F, 1.8F) - val b = Array[Float](2.2F, 2.5F, 2.6F, 2.8F) - val m = Array(a,b) - mean(m).foreach(f => println(f)) //-- line 18 - } - - def main(args: Array[String]): Unit = { - testMean() - } -} diff --git a/libraries/ScalaCL/Plugin/src/test/scala/clmult.scala b/libraries/ScalaCL/Plugin/src/test/scala/clmult.scala deleted file mode 100644 index 374cd668b..000000000 --- a/libraries/ScalaCL/Plugin/src/test/scala/clmult.scala +++ /dev/null @@ -1,57 +0,0 @@ -import scalacl._ - -object CLLinAlg { - //case class Matrix(data: CLArray[Double], rows: Int, columns: Int) - - type Matrix = - CLArray[Double] - - def newMatrix(rows: Int, cols: Int)(implicit context: Context) = - new Matrix(rows * cols) - - def fill(m: Matrix, rows: Int, cols: Int)(implicit context: Context) = { - for (idx <- (0 until (rows * cols)).cl) { - val i = idx / cols - val j = idx - i * cols - m(idx) = i - j - } - } - - def multiply(a: Matrix, aRows: Int, aCols: Int, b: Matrix, bRows: Int, bCols: Int)(implicit context: Context): Matrix = { - assert(aCols == bRows) - - val outRows = aRows - val outCols = bCols - val out = newMatrix(outRows, outCols) - for (idx <- (0 until (outRows * outCols)).cl) { - val i = idx / outCols - val j = idx - i * outCols - - out(idx) = - (0 until aCols).map( - k => a(i * aCols + k) * b(k * bCols + j) - ).sum - } - out - } -} -object CLLinAlgTest extends App { - import CLLinAlg._ - - implicit val context = Context.best - - val m = 3 - val n = 4 - val o = 5 - - val a = newMatrix(m, n) - fill(a, m, n) - val b = newMatrix(n, o) - fill(b, n, o) - - val out = multiply(a, m, n, b, n, o) - - println("a = " + a.toSeq) - println("b = " + b.toSeq) - println("out = " + out.toSeq) -} diff --git a/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/OpenCLTest.scala b/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/OpenCLTest.scala deleted file mode 100644 index adece43ef..000000000 --- a/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/OpenCLTest.scala +++ /dev/null @@ -1,195 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package scalacl ; package test -import plugin._ -import com.nativelibs4java.scalaxy._ -import plugin._ -import pluginBase._ -import components._ - -import java.io.File -import org.junit._ -import Assert._ -import scala.math._ - -object OpenCLTest { - - val stdImportsAndContext = """ - import scalacl._ - import scala.math._ - - enforceUsingOpenCL = true - implicit val context = Context.best(DoubleSupport) - """ -} - -class OpenCLTest extends ScalaCLTestUtils { - import OpenCLTest._ - - @Test - def testMath { - val cla = compileCodeWithPlugin( - stdImportsAndContext, - """ - (0 to 10).cl.map(i => cos(i).toFloat).toArray - """ - ).newInstance()().asInstanceOf[Array[Float]] - val a = - (0 to 10).map(i => cos(i).toFloat).toArray - - assertArrayEquals(a, cla, 0.00001f) - } - - - @Test - def testScalarCapture { - val cla = compileCodeWithPlugin( - stdImportsAndContext, - """ - val n = (0 to 10).sum - (0 to 10).cl.map(i => i * n + n * n * (i - 1)).toArray - """ - ).newInstance()().asInstanceOf[Array[Int]] - - val n = (0 to 10).sum - val a = - (0 to 10).map(i => i * n + n * n * (i - 1)).toArray - - assertArrayEquals(a, cla) - } - - @Test - def testArrayCapture { - val cla = compileCodeWithPlugin( - stdImportsAndContext, - """ - val arr = (0 to 10).toCLArray - (0 to 10).cl.map(i => arr(i / 2) * 2).toArray - """ - ).newInstance()().asInstanceOf[Array[Int]] - - val arr = (0 to 10).toArray - val a = - (0 to 10).map(i => arr(i / 2) * 2).toArray - - assertArrayEquals(a, cla) - } - - @Ignore - @Test - def testMatrixMult { - type Matrix = - Array[Double] - - def newMatrix(rows: Int, columns: Int) = - new Matrix(rows * columns) - - def fill(m: Matrix, rows: Int, columns: Int) = { - for (idx <- (0 until (rows * columns))) { - val i = idx / columns - val j = idx - i * columns - m(idx) = i - j - } - } - def multiply(a: Matrix, aRows: Int, aCols: Int, b: Matrix, bRows: Int, bCols: Int): Matrix = { - assert(aCols == bRows) - - val outRows = aRows - val outCols = bCols - val out = newMatrix(outRows, outCols) - for (idx <- (0 until (outRows * outCols))) { - val i = idx / outCols - val j = idx - i * outCols - - out(idx) = - (0 until aCols).map( - k => a(i * aCols + k) * b(k * bCols + j) - ).sum - } - out - } - - val clDecls = """ - type Matrix = - CLArray[Double] - - def newMatrix(rows: Int, columns: Int)(implicit context: Context) = - new Matrix(rows * columns) - - def fill(m: Matrix, rows: Int, columns: Int) = { - for (idx <- (0 until (rows * columns)).cl) { - val i = idx / columns - val j = idx - i * columns - m(idx) = i - j - } - } - - def multiply(a: Matrix, aRows: Int, aCols: Int, b: Matrix, bRows: Int, bCols: Int)(implicit context: Context): Matrix = { - assert(aCols == bRows) - - val outRows = aRows - val outCols = bCols - val out = newMatrix(outRows, outCols) - for (idx <- (0 until (outRows * outCols)).cl) { - val i = idx / outCols - val j = idx - i * outCols - - out(idx) = - (0 until aCols).map( - k => a(i * aCols + k) * b(k * bCols + j) - ).sum - } - out - } - """ - val program = """ - val m = 3 - val n = 4 - val o = 5 - - val a = newMatrix(m, n) - fill(a, m, n) - val b = newMatrix(n, o) - fill(b, n, o) - - val out = multiply(a, m, n, b, n, o) - //val out = Array.tabulate[Double](n, n)((i, j) => { - // (0 until n).map(k => a(i)(k) * b(k)(j)).sum - //}) - - (a.toSeq, b.toSeq, out.toSeq) - """ - - type ReturnType = (Seq[Double], Seq[Double], Seq[Double]) - - val clret @ (cla, clb, clout) = compileCodeWithPlugin( - stdImportsAndContext ++ - clDecls, - program - ).newInstance()().asInstanceOf[ReturnType] - - val ret @ (a, b, out) = compileCodeWithPlugin( - stdImportsAndContext ++ - clDecls.replaceAll("""\bCLArray\b""", "Array").replaceAll("""\.cl\b""", ""), - program - ).newInstance()().asInstanceOf[ReturnType] - - /* - def println(r: ReturnType, prefix: String) = { - val (a, b, out) = r - println(prefix + "a = " + a) - println(prefix + "b = " + b) - println(prefix + "out = " + out) - } - print(clret, "cl") - print(ret, "") - */ - assertArrayEquals(a.toArray, cla.toArray, 0.0001) - assertArrayEquals(b.toArray, clb.toArray, 0.0001) - assertArrayEquals(out.toArray, clout.toArray, 0.0001) - } - -} diff --git a/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/ScalaCLTestUtils.scala b/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/ScalaCLTestUtils.scala deleted file mode 100644 index 7b69633d4..000000000 --- a/libraries/ScalaCL/Plugin/src/test/scala/scalacl/test/ScalaCLTestUtils.scala +++ /dev/null @@ -1,50 +0,0 @@ -package scalacl ; package test -import plugin._ -import com.nativelibs4java.scalaxy._ -import test._ -import pluginBase._ -import components._ - -import java.io.BufferedReader -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.io.PrintWriter -import scala.collection.mutable.HashMap -import scala.concurrent.ops -import scala.io.Source - -import java.net.URI -import java.net.URLClassLoader -import javax.tools.DiagnosticCollector -import javax.tools.FileObject -import javax.tools.ForwardingJavaFileManager -import javax.tools.JavaCompiler -import javax.tools.JavaFileManager -import javax.tools.JavaFileObject -import javax.tools.ToolProvider -import org.junit.Assert._ -import scala.tools.nsc.Settings -import scala.actors.Futures._ -import Function.{tupled, untupled} - -trait ScalaCLTestUtils extends BaseTestUtils { - def pluginDef: PluginDef = - ScalaCLPluginDef - - override def getAdditionalClassPath = { - def getPath(c: Class[_]): String = { - c.getProtectionDomain.getCodeSource.getLocation.getFile - } - Some(Set( - getPath(classOf[CLArray[_]]), - getPath(classOf[com.nativelibs4java.opencl.CLBuffer[_]]), - getPath(classOf[com.nativelibs4java.opencl.library.OpenCLLibrary]), - getPath(classOf[org.bridj.BridJ]), - getPath(classOf[org.bridj.relocated.org.objectweb.asm.ClassVisitor]) - ).toSeq) - } -} diff --git a/libraries/ScalaCL/Test/.gitignore b/libraries/ScalaCL/Test/.gitignore deleted file mode 100644 index 186cc0c3e..000000000 --- a/libraries/ScalaCL/Test/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target -project/boot -project/target -*~ -project-old diff --git a/libraries/ScalaCL/Test/build.sbt b/libraries/ScalaCL/Test/build.sbt deleted file mode 100644 index 5f19cecc6..000000000 --- a/libraries/ScalaCL/Test/build.sbt +++ /dev/null @@ -1,16 +0,0 @@ -//name := "scalacl-test" - -//version := "0.3-SNAPSHOT" - -//organization := "com.nativelibs4java" - -//scalaVersion := "2.9.0" - -resolvers += "NativeLibs4Java Repository" at "http://nativelibs4java.sourceforge.net/maven/" - -libraryDependencies += "com.nativelibs4java" % "scalacl" % "0.2" - -autoCompilerPlugins := true - -addCompilerPlugin("com.nativelibs4java" % "scalacl" % "0.2") - diff --git a/libraries/ScalaCL/Test/pom.xml b/libraries/ScalaCL/Test/pom.xml deleted file mode 100644 index aa44e2cc2..000000000 --- a/libraries/ScalaCL/Test/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - 4.0.0 - com.nativelibs4java - scalacl-test - jar - 0.3-SNAPSHOT - ScalaCLv2 Test - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - ../.. - - - - - org.scala-lang - scala-library - - - com.nativelibs4java - scalacl - 0.3-SNAPSHOT - - - - - scala-tools.org - Scala-tools Maven2 Repository - http://scala-tools.org/repo-releases - - - nativelibs4java - nativelibs4java Maven2 Repository - http://nativelibs4java.sourceforge.net/maven - - - - - - org.scala-tools - maven-scala-plugin - - - - compile - testCompile - - - - - - - com.nativelibs4java - scalacl-compiler-plugin - 0.3-SNAPSHOT - - - - -optimize - - - - - - - diff --git a/libraries/ScalaCL/Test/scalacl-test.iml b/libraries/ScalaCL/Test/scalacl-test.iml deleted file mode 100644 index b338c7712..000000000 --- a/libraries/ScalaCL/Test/scalacl-test.iml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/ScalaCL/Test/src/main/scala/Cruel.scala b/libraries/ScalaCL/Test/src/main/scala/Cruel.scala deleted file mode 100644 index 4e9d9bc7d..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/Cruel.scala +++ /dev/null @@ -1,197 +0,0 @@ -object Cruel { - def cfor[@specialized T](z: T)(ok: T=>Boolean)(succ: T=>T)(f: T=>Unit) { - var i = z - while (ok(i)) { - f(i) - i = succ(i) - } - } - - def ptime[F](f: => F) = { - var t0 = System.nanoTime - val ans = f - printf("Elapsed: %.3f s\n",(System.nanoTime - t0)*1e-9) - ans - } - - def sumWhile1(n: Int) = { - var i,s = 0 - while (i < n) { - s += i - i += 1 - } - s - } - - def sumWhile3(n: Int, m: Int, l: Int) = { - var a,s = 0 - while (a < n) { - var b = 0 - while (b < m) { - var c = 0 - while (c < l) { - s += c+l*(b+m*a); - c += 1 - } - b += 1 - } - a += 1 - } - s - } - - def sumWhile5(n: Int, m: Int, l: Int, k: Int, j: Int) = { - var a,s = 0 - while (a < n) { - var b = 0 - while (b < m) { - var c = 0 - while (c < l) { - var d = 0 - while (d < k) { - var e = 0 - while (e < j) { - s += e+j*(d+k*(c+l*(b+m*a))); - e += 1 - } - d += 1 - } - c += 1 - } - b += 1 - } - a += 1 - } - s - } - - def weirdWhile(n: Int, m: Int) = { - var i,s = 0 - while (i < n) { - var j = 0 - while (j < m) { - s += j - j += 1 - } - j = 1 - while (j <= m) { - s *= j - j += 1 - } - j = 0 - while (j < m) { - s = j*j - s - j += 1 - } - j = m - while (j > 0) { - s = j*j/(1+s*s) - j -= 1 - } - j = 0 - while (j < m) { - if (j*s > j+s) s += j - else s -= j - j += 1 - } - i += 1 - } - s - } - - def sumLimit1(n: Int) = { - var s = 0 - for (i <- 0 until n) s += i - s - } - - def sumLimit3(n: Int, m: Int, l: Int) = { - var s = 0 - for (a <- 0 until n; b <- 0 until m; c <- 0 until l) { s += c+l*(b+m*a) } - s - } - - def sumLimit5(n: Int, m: Int, k: Int, j: Int, i: Int) = { - var s = 0 - for (a <- 0 until n; - b <- 0 until m; - c <- 0 until k; - d <- 0 until j; - e <- 0 until i) { - s += e + i*(d + j*(c + k*(b + m*a))) - } - s - } - - def weirdLimit(n: Int, m: Int) = { - var s = 0 - for (i <- 0 to n) { - for (j <- 0 until m) { s += j } - for (j <- 1 to m) { s *= j } - for (j <- 0 until m) { s = j*j - s } - for (j <- m to 1 by -1) { s = j*j/(1+s*s) } - for (j <- 0 until m) { if (j*s > j+s) s += j else s -= j } - } - s - } - - def sumCfor1(n: Int) = { - var s = 0 - cfor(0)(_ < n)(_ + 1) { s += _ } - s - } - - def sumCfor3(n: Int, m: Int, k: Int) = { - var s = 0 - cfor(0)(_ < n)(_ + 1)(a => { - cfor(0)(_ < m)(_ + 1)(b => { - cfor(0)(_ < k)(_ + 1) { s += _ + k*(b + a*m) } - }) - }) - s - } - - def sumCfor5(n: Int, m: Int, k: Int, j: Int, i: Int) = { - var s = 0 - cfor(0)(_ < n)(_ + 1)(a => { - cfor(0)(_ < m)(_ + 1)(b => { - cfor(0)(_ < k)(_ + 1)(c => { - cfor(0)(_ < j)(_ + 1)(d => { - cfor(0)(_ < i)(_ + 1) { s += _ + i*(d + j*(c + k*(b + a*m))) } - }) - }) - }) - }) - s - } - - def weirdCfor(n: Int, m: Int) = { - var s = 0 - cfor(0)(_ < n)(_ + 1)(_ => { - cfor(0)(_ < m)(_ + 1) { s += _ } - cfor(1)(_ <= m)(_ + 1) { s *= _ } - cfor(0)(_ < m)(_ + 1) { j => s = j*j - s } - cfor(m)(_ > 0)(_ - 1) { j => s = j*j/(1+s*s) } - cfor(0)(_ < m)(_ + 1) { j => (if (j*s > j+s) s += j else s -= j) } - }) - s - } - - def main(args: Array[String]) { - for (i <- 1 to 4) { - ptime( print(sumWhile1(1000000000) + " While1 ") ) - ptime( print(sumWhile3(1000,500,2000) + " While3 ") ) - ptime( print(sumWhile5(100,25,40,200,50) + " While5 ") ) - ptime( print(weirdWhile(100,1000000) + " While? ") ) - ptime( print(sumLimit1(1000000000) + " Limit1 ") ) - ptime( print(sumLimit3(1000,500,2000) + " Limit3 ") ) - ptime( print(sumLimit5(100,25,40,200,50) + " Limit5 ") ) - ptime( print(weirdLimit(100,1000000) + " Limit? ") ) - ptime( print(sumCfor1(1000000000) + " Cfor1 ") ) - ptime( print(sumCfor3(1000,500,2000) + " Cfor3 ") ) - ptime( print(sumCfor5(100,25,40,200,50) + " Cfor5 ") ) - ptime( print(weirdCfor(100,1000000) + " Cfor?? ") ) - println - } - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/MatrixTest.scala b/libraries/ScalaCL/Test/src/main/scala/MatrixTest.scala deleted file mode 100644 index d5263bb8b..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/MatrixTest.scala +++ /dev/null @@ -1,56 +0,0 @@ -object MatrixTest { - type Matrix = Array[Array[Double]] - /*@inline def Matrix(rows: Int, columns: Int)(f: (Int, Int) => Double): Matrix = Array.tabulate(rows, columns)(f) - @inline def Diagonal(n: Int): Matrix = Matrix(n, n, (i, j) => if (i == j) 1 else 0) - @inline def Zero(rows: Int, columns: Int): Matrix = Array.ofDim[Double](rows, columns) - @inline def rowCount(m: Matrix) = m.length - @inline def columnCount(m: Matrix) = m(0).length - */ - //Matrix(rows: Int, columns: Int, f: (Int, Int) => Double): Matrix = Array.tabulate(rows, columns)(f) - def Diagonal(n: Int): Matrix = Array.tabulate(n, n)((i, j) => if (i == j) 1 else 0) - def Zero(rows: Int, columns: Int): Matrix = Array.ofDim[Double](rows, columns) - @inline def rowCount(m: Matrix) = m.length - @inline def columnCount(m: Matrix) = m(0).length - - def mmult(a: Matrix, b: Matrix): Matrix = - Array.tabulate(rowCount(a), columnCount(b))((i, j) => (0 until columnCount(a)).map(k => a(i)(k) * b(k)(j)).sum) - - def madd(a: Matrix, b: Matrix): Matrix = - Array.tabulate(rowCount(a), columnCount(a))((i, j) => a(i)(j) + b(i)(j)) - - def main(args: Array[String]): Unit = { - val start = System.nanoTime - val n = if (args.length == 0) - 1000 - else - args(0).toInt - - /* - val a = Array.tabulate[Double](n, n)(_ + _) - val b = Array.tabulate[Double](n, n)(_ + _) - - val o = mmult(a, b) - */ - - val a = Array.tabulate(n, n)((i, j) => (i + j) * 1.0) - val b = Array.tabulate(n, n)((i, j) => (i + j) * 1.0) - val o = Array.ofDim[Double](n, n) - for (i <- 0 until n; j <- 0 until n) { - var tot = 0.0 - for (k <- 0 until n) - tot += a(i)(k) * b(k)(j) - - o(i)(j) = tot - } - - val timeNano = System.nanoTime - start - val timeMillisStr = ((timeNano / 10000) / 100.0).toString - val random = new java.util.Random(start) - System.err.println("Total time (milliseconds) :") - System.err.println(timeMillisStr) - def rand = (random.nextDouble * o.length).toInt - System.err.println("Random value = " + o(rand)(rand)) - System.err.println("Last value = " + o(o.length - 1)(o.length - 1)) - System.out.println(timeMillisStr) - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/TestIntRangeLoops.scala b/libraries/ScalaCL/Test/src/main/scala/TestIntRangeLoops.scala deleted file mode 100644 index 509cc3a03..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/TestIntRangeLoops.scala +++ /dev/null @@ -1,62 +0,0 @@ -/** Run with : - * - * ./test - * mvn scala:compile && scala -cp target/classes Test - * mvn scala:compile && scala -cp target\classes Test - * javap -c -classpath target\classes Test$ - */ -object TestIntRangeLoops { - import TestUtils._ - - def main(args: Array[String]): Unit = { - val name = if (args.isEmpty) "Normal" else args(0) - val m = 10 - val n = 10 - val o = 30 - val mn = m * n - val mno = m * n * o - def test1_mno = { - var t = 0.0 - for (i <- 0 until mno) - t += i / 10 - t - } - def test2_mn_o = { - var t = 0.0 - for (i <- 0 until mn) - for (j <- 0 until o) - t += (i + j) / 10 - t - } - def test3_mno = { - var t = 0.0 - for (i <- 0 until n) - for (j <- 0 until m) - for (k <- 0 until o) - t += (i + j + k) / 10 - t - } - def test4_mnom = { - var t = 0.0 - for (i <- 0 until n) - for (j <- 0 until m) - for (k <- 0 until o) - for (l <- 0 until m) - t += (i + j + k + l) / 10 - t - } - val (cold1, warm1) = tst(mno) { test1_mno } - val (cold2, warm2) = tst(mno) { test2_mn_o } - val (cold3, warm3) = tst(mno) { test3_mno } - val (cold4, warm4) = tst(mno * m) { test4_mnom } - - println(Array(name, "Cold", 1, cold1).mkString("\t")); - println(Array(name, "Cold", 2, cold2).mkString("\t")); - println(Array(name, "Cold", 3, cold3).mkString("\t")); - println(Array(name, "Cold", 4, cold4).mkString("\t")); - println(Array(name, "Warm", 1, warm1).mkString("\t")); - println(Array(name, "Warm", 2, warm2).mkString("\t")); - println(Array(name, "Warm", 3, warm3).mkString("\t")); - println(Array(name, "Warm", 4, warm4).mkString("\t")); - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/TestListForeach.scala b/libraries/ScalaCL/Test/src/main/scala/TestListForeach.scala deleted file mode 100644 index 8504851de..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/TestListForeach.scala +++ /dev/null @@ -1,94 +0,0 @@ -/// USE -optimise when compiling the code : the difference between List.foreach and while is then much bigger ! -/// scalac -optimise TestListForeach.scala && scala TestListForeach -object TestListForeach { - /* - import TestUtils._ - val arrLen = 100 - val a = Array.tabulate(arrLen) { i => i.toString } - val list = a.toList - def testListForeach = { - var tot = 0 - for (v <- list) - tot += v.length - tot - } - def testListWhile = { - var tot = 0 - var l = list - while (!l.isEmpty) { - val v = l.head - tot += v.length - l = l.tail - } - tot - } - val (coldForeach, warmForeach) = tst(arrLen) { testListForeach } - val (coldWhile, warmWhile) = tst(arrLen) { testListWhile } - println(Array("Foreach", "Cold", coldForeach).mkString("\t")); - println(Array("Foreach", "Warm", warmForeach).mkString("\t")); - println(Array("While", "Cold", coldWhile).mkString("\t")); - println(Array("While", "Warm", warmWhile).mkString("\t")); - - */ - def time(loops: Int, n: Int)(b: => Unit): Double = { - val start = System.nanoTime - for (i <- 0 until loops) - b - val time = System.nanoTime - start - val nsPerItem = time / (loops * (n: Double)) - nsPerItem - } - def main(args: Array[String]): Unit = { - for (n <- Array(100000, 10000, 1000, 100, 10, 5, 4, 3, 2, 1).toList) { - val list = (0 until n).toList - - def testForeach = { - var tot = 0L - for (v <- list) - tot += v - tot - } - - def testWhile = { - var tot = 0L - var l = list - - //while (l.isInstanceOf[::[_]]) { - while (!l.isEmpty) { - val item = l.head - tot += item - l = l.tail - } - tot - } - def tst(loops: Int, n: Int, runs: Int) = { - val res = for (i <- 0 until runs) yield { - val fe = time(loops, n) { testForeach } - val wh = time(loops, n) { testWhile } - (wh, fe) - } - val whs = res.map(_._1) - val fes = res.map(_._2) - (whs.sum / whs.size, fes.sum / fes.size) - } - - val nRuns = 20 - val coldLoops = 500 - assert(testForeach == testWhile) - val (coldWhile, coldForeach) = tst(coldLoops, n, nRuns) - - val warmupLoops = 2500 - tst(warmupLoops, n, 1) - - val warmLoops = 500 - val (warmWhile, warmForeach) = tst(warmLoops, n, nRuns) - - println("Foreach (n = " + n + ")\t: \tCold = " + coldForeach + " ns \t\t\tWarm = " +warmForeach + " ns") - println(" While (n = " + n + ")\t: \tCold = " + coldWhile + " ns \t\t\tWarm = " +warmWhile + " ns") - def fmt(d: Double) = ((d * 100).toLong / 100.0).toString - println(" Gain (n = " + n + ")\t: \t x " + fmt(coldForeach / coldWhile) + "\t\t\t x " + fmt(warmForeach / warmWhile)) - - println() - } - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/TestMatrix.scala b/libraries/ScalaCL/Test/src/main/scala/TestMatrix.scala deleted file mode 100644 index 05c9a05f6..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/TestMatrix.scala +++ /dev/null @@ -1,49 +0,0 @@ -/** Run with : - * - * ./test - * mvn scala:compile && scala -cp target/classes Test - * mvn scala:compile && scala -cp target\classes Test - * javap -c -classpath target\classes Test$ - */ -object TestMatrix { - import TestUtils._ - - def main(args: Array[String]): Unit = { - val name = if (args.isEmpty) "Normal" else args(0) - val m = 10 - val n = 10 - val o = 30 - val mn = m * n - val mno = m * n * o - - - def multMatrix( - a: Array[Array[Double]], aRows: Int, aColumns: Int, - b: Array[Array[Double]], bRows: Int, bColumns: Int, - out: Array[Array[Double]]) = { - - for (i <- 0 until aRows) { - val outi = out(i) - for (j <- 0 until bColumns) { - var tot = 0.0 - val ai = a(i) - for (k <- 0 until aColumns) - tot += ai(k) * b(k)(j) - outi(j) = tot - } - } - } - - val a = new Array[Array[Double]](m).map(_ => new Array[Double](n)) - val b = new Array[Array[Double]](n).map(_ => new Array[Double](o)) - val out = new Array[Array[Double]](m).map(_ => new Array[Double](o)) - def testMat = { - multMatrix(a, m, n, b, n, o, out) - } - val (coldMat, warmMat) = tst(mno) { testMat } - println(Array(name, "Cold", "mat", coldMat).mkString("\t")); - println(Array(name, "Warm", "mat", warmMat).mkString("\t")); - - - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/TestUtils.scala b/libraries/ScalaCL/Test/src/main/scala/TestUtils.scala deleted file mode 100644 index 09335ed4f..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/TestUtils.scala +++ /dev/null @@ -1,27 +0,0 @@ - -object TestUtils { - def time[V](title: String, n: Long, loops: Int)(b: => V): Double = { - val startTime = System.nanoTime - var i = 0 - while (i < loops) { - b - i += 1 - } - val time = System.nanoTime - startTime - val timePerLoop = time / loops - val timePerItem = timePerLoop / n.toDouble - //System.err.println("Time[" + title + "] = " + (time / 1000000L) + " milliseconds (" + (timePerLoop / 1000L) + " microseconds per iteration, " + timePerItem + " nanoseconds per item)") - if (title != null) - System.err.println("Time[" + title + "] = " + timePerItem + " nanoseconds per item)") - - timePerItem - } - def tst(count: Long)(b: => Unit) = { - // Run cold code - val cold = time("Cold", count, 1000) { b } - // Finish warmup : (1000 + 3000 > hotspot threshold both in server and client modes) - time(null, count, 3000) { b } - val warm = time("Warm", count, 10000) { b } - (cold, warm) - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/fannkuch.scala b/libraries/ScalaCL/Test/src/main/scala/fannkuch.scala deleted file mode 100644 index 4c04e8c2f..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/fannkuch.scala +++ /dev/null @@ -1,160 +0,0 @@ -/* For loop benchmark modifed from: - - The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - - conversion to Scala by Rex Kerr - from Java version by Oleg Mazurov and Isaac Gouy -*/ - -object fannkuch { - def fannWhile(n: Int): Int = { - val perm1 = Array.range(0,n) - val perm, count = new Array[Int](n) - var f, i, k, r, flips, nperm, checksum = 0 - - r = n - while (r>0) { - i = 0 - while (r != 1) { count(r-1) = r; r -= 1 } - while (i < n) { perm(i) = perm1(i); i += 1 } - - // Count flips and update max and checksum - f = 0 - k = perm(0) - while (k != 0) { - i = 0 - while (2*i < k) { - val t = perm(i); perm(i) = perm(k-i); perm(k-i) = t - i += 1 - } - k = perm(0) - f += 1 - } - if (f>flips) flips = f - if ((nperm&0x1)==0) checksum += f - else checksum -= f - - // Use incremental change to generate another permutation - var go = true - while (go) { - if (r == n) return flips - - val p0 = perm1(0) - i = 0 - while (i < r) { - val j = i+1 - perm1(i) = perm1(j) - i = j - } - perm1(r) = p0 - - count(r) -= 1 - if (count(r) > 0) go = false - else r += 1 - } - nperm += 1 - } - flips - } - - def fannLimit(n: Int): Int = { - val perm1 = Array.range(0,n) - val perm, count = new Array[Int](n) - var f, i, k, r, flips, nperm, checksum = 0 - - r = n - while (r>0) { - for (i <- 0 until n) { perm(i) = perm1(i) } - while (r != 1) { count(r-1) = r; r -= 1 } - - // Count flips and update max and checksum - f = 0 - k = perm(0) - while (k != 0) { - for (i <- 0 until (k+1)/2) { - val t = perm(i); perm(i) = perm(k-i); perm(k-i) = t - } - k = perm(0) - f += 1 - } - if (f>flips) flips = f - if ((nperm&0x1)==0) checksum += f - else checksum -= f - - // Use incremental change to generate another permutation - var go = true - while (go) { - if (r == n) return flips - - val p0 = perm1(0) - for (i <- 0 until r) { perm1(i) = perm1(i+1) } - perm1(r) = p0 - - count(r) -= 1 - if (count(r) > 0) go = false - else r += 1 - } - nperm += 1 - } - flips - } - - def fannRange(n: Int): Int = { - val perm1 = Array.range(0,n) - val perm, count = new Array[Int](n) - var f, i, k, r, flips, nperm, checksum = 0 - - r = n - while (r>0) { - for (i <- 0 until n) { perm(i) = perm1(i) } - while (r != 1) { count(r-1) = r; r -= 1 } - - // Count flips and update max and checksum - f = 0 - k = perm(0) - while (k != 0) { - for (i <- 0 until (k+1)/2) { - val t = perm(i); perm(i) = perm(k-i); perm(k-i) = t - } - k = perm(0) - f += 1 - } - if (f>flips) flips = f - if ((nperm&0x1)==0) checksum += f - else checksum -= f - - // Use incremental change to generate another permutation - var go = true - while (go) { - if (r == n) return flips - - val p0 = perm1(0) - for (i <- 0 until r) { perm1(i) = perm1(i+1) } - perm1(r) = p0 - - count(r) -= 1 - if (count(r) > 0) go = false - else r += 1 - } - nperm += 1 - } - flips - } - - def ptime[F](f: => F): F = { - val t0 = System.nanoTime - val ans = f - printf("Elapsed: %.3f s\n",(System.nanoTime-t0)*1e-9) - ans - } - - def main(args: Array[String]) { - val n = (if (args.length > 0) args(0).toInt else 10) - for (i <- 0 to 2) { - ptime( print("While Pfannkuchen("+n+") = "+fannWhile(n)+". ") ) - ptime( print("Limit PFannkuchen("+n+") = "+fannLimit(n)+". ") ) - ptime( print("Range PFannkuchen("+n+") = "+fannRange(n)+". ") ) - } - } -} diff --git a/libraries/ScalaCL/Test/src/main/scala/nbody.scala b/libraries/ScalaCL/Test/src/main/scala/nbody.scala deleted file mode 100644 index 54c3ed0a7..000000000 --- a/libraries/ScalaCL/Test/src/main/scala/nbody.scala +++ /dev/null @@ -1,219 +0,0 @@ -/* Benchmark modified from: - - The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - contributed by Isaac Gouy - modified by Meiko Rachimow - modified by Olivier Chafik - updated for 2.8 by Rex Kerr -*/ -/* -sbt clean compile && JAVA_OPTS="-Xmx3G" scala -cp target/scala_2.8.0/classes/ nbody -DISABLE_SCALACL_PLUGIN=1 sbt clean compile && JAVA_OPTS="-Xmx3G" scala -cp target/scala_2.8.0/classes/ nbody - -*/ -import math._ - -object nbody { - def runWhile(n: Int) { - val josys = new JovianSystem - val e0 = josys.energy - var i = 0 - while (i < n) { josys.advanceWhile(0.01); i += 1 } - printf("While Energy: %.9f; change: %.9f. ",e0,(josys.energy - e0)) - } - - def runLimit(n: Int) { - val josys = new JovianSystem - val e0 = josys.energy - for (i <- 1 to n) { josys.advanceLimit(0.01) } - printf("Limit Energy: %.9f; change: %.9f. ",e0,(josys.energy - e0)) - } - - def runRange(n: Int) { - val josys = new JovianSystem - val e0 = josys.energy - for (i <- 0 until n) { josys.advanceRange(0.01) } - printf("Range Energy: %.9f; change: %.9f. ",e0,(josys.energy - e0)) - } - - def ptime[F](f: => F): F = { - val t0 = System.nanoTime - val ans = f - printf("Elapsed: %.3f s\n",(System.nanoTime-t0)*1e-9) - ans - } - - def main(args: Array[String]) = { - val n = try { args(0).toInt } catch { case _ => 2000000 } - for (i <- 1 to 3) { - ptime( runWhile(n) ) - ptime( runLimit(n) ) - ptime( runRange(n) ) - } - } -} - - -abstract class NBodySystem { - - def energy() = { - var e = 0.0 - for (i <- 0 until bodies.length) { - e += 0.5 * bodies(i).mass * bodies(i).speedSq - - for (j <- i+1 until bodies.length) { - val dx = bodies(i).x - bodies(j).x - val dy = bodies(i).y - bodies(j).y - val dz = bodies(i).z - bodies(j).z - val distance = sqrt(dx*dx + dy*dy + dz*dz) - e -= (bodies(i).mass * bodies(j).mass) / distance - } - } - e - } - - def advanceWhile(dt: Double) = { - var i = 0 - while (i < bodies.length){ - var j = i+1 - while (j < bodies.length){ - val dx = bodies(i).x - bodies(j).x - val dy = bodies(i).y - bodies(j).y - val dz = bodies(i).z - bodies(j).z - - val distance = sqrt(dx*dx + dy*dy + dz*dz) - val mag = dt / (distance * distance * distance) - - bodies(i).advance(dx,dy,dz,-bodies(j).mass*mag) - bodies(j).advance(dx,dy,dz,bodies(i).mass*mag) - - j += 1 - } - i += 1 - } - - i = 0 - while (i < bodies.length){ - bodies(i).move(dt) - i += 1 - } - } - - def advanceLimit(dt: Double) = { - for (i <- 0 until bodies.length ; j <- i+1 until bodies.length) { - val bi = bodies(i) - val bj = bodies(j) - val dx = bi.x - bj.x - val dy = bi.y - bj.y - val dz = bi.z - bj.z - - val distance = sqrt(dx*dx + dy*dy + dz*dz) - val mag = dt / (distance * distance * distance) - - bi.advance(dx,dy,dz,-bj.mass*mag) - bj.advance(dx,dy,dz,bi.mass*mag) - } - bodies.foreach(_.move(dt)) - } - - def advanceRange(dt: Double) = { - for (i <- 0 until bodies.length) { - for (j <- i+1 until bodies.length) { - val dx = bodies(i).x - bodies(j).x - val dy = bodies(i).y - bodies(j).y - val dz = bodies(i).z - bodies(j).z - - val distance = sqrt(dx*dx + dy*dy + dz*dz) - val mag = dt / (distance * distance * distance) - - bodies(i).advance(dx,dy,dz,-bodies(j).mass*mag) - bodies(j).advance(dx,dy,dz,bodies(i).mass*mag) - } - } - - for (i <- 0 until bodies.length) { bodies(i).move(dt) } - } - - protected val bodies: Array[Body] - - class Body(){ - var x,y,z = 0.0 - var vx,vy,vz = 0.0 - var mass = 0.0 - def speedSq = vx*vx + vy*vy + vz*vz - @inline def move(dt: Double) { - x += dt*vx - y += dt*vy - z += dt*vz - } - @inline def advance(dx: Double, dy: Double, dz: Double, delta: Double) { - vx += dx*delta - vy += dy*delta - vz += dz*delta - } - } -} - -class JovianSystem extends NBodySystem { - protected val bodies = initialValues - - private def initialValues() = { - val SOLAR_MASS = 4 * Pi * Pi - val DAYS_PER_YEAR = 365.24 - - val sun = new Body - sun.mass = SOLAR_MASS - - val jupiter = new Body - jupiter.x = 4.84143144246472090e+00 - jupiter.y = -1.16032004402742839e+00 - jupiter.z = -1.03622044471123109e-01 - jupiter.vx = 1.66007664274403694e-03 * DAYS_PER_YEAR - jupiter.vy = 7.69901118419740425e-03 * DAYS_PER_YEAR - jupiter.vz = -6.90460016972063023e-05 * DAYS_PER_YEAR - jupiter.mass = 9.54791938424326609e-04 * SOLAR_MASS - - val saturn = new Body - saturn.x = 8.34336671824457987e+00 - saturn.y = 4.12479856412430479e+00 - saturn.z = -4.03523417114321381e-01 - saturn.vx = -2.76742510726862411e-03 * DAYS_PER_YEAR - saturn.vy = 4.99852801234917238e-03 * DAYS_PER_YEAR - saturn.vz = 2.30417297573763929e-05 * DAYS_PER_YEAR - saturn.mass = 2.85885980666130812e-04 * SOLAR_MASS - - val uranus = new Body - uranus.x = 1.28943695621391310e+01 - uranus.y = -1.51111514016986312e+01 - uranus.z = -2.23307578892655734e-01 - uranus.vx = 2.96460137564761618e-03 * DAYS_PER_YEAR - uranus.vy = 2.37847173959480950e-03 * DAYS_PER_YEAR - uranus.vz = -2.96589568540237556e-05 * DAYS_PER_YEAR - uranus.mass = 4.36624404335156298e-05 * SOLAR_MASS - - val neptune = new Body - neptune.x = 1.53796971148509165e+01 - neptune.y = -2.59193146099879641e+01 - neptune.z = 1.79258772950371181e-01 - neptune.vx = 2.68067772490389322e-03 * DAYS_PER_YEAR - neptune.vy = 1.62824170038242295e-03 * DAYS_PER_YEAR - neptune.vz = -9.51592254519715870e-05 * DAYS_PER_YEAR - neptune.mass = 5.15138902046611451e-05 * SOLAR_MASS - - - val initialValues = Array ( sun, jupiter, saturn, uranus, neptune ) - - var px = 0.0; var py = 0.0; var pz = 0.0; - for (b <- initialValues){ - px += (b.vx * b.mass) - py += (b.vy * b.mass) - pz += (b.vz * b.mass) - } - sun.vx = -px / SOLAR_MASS - sun.vy = -py / SOLAR_MASS - sun.vz = -pz / SOLAR_MASS - - initialValues - } -} diff --git a/libraries/ScalaCL/Test/test b/libraries/ScalaCL/Test/test deleted file mode 100755 index 55fcf7142..000000000 --- a/libraries/ScalaCL/Test/test +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -OUT_FILE=out.txt - -rm "$OUT_FILE" - -LOOPS=10 - -DISABLE_SCALACL_PLUGIN=1 mvn clean scala:compile || exit 1 -for (( c = 1; c <= $LOOPS; c++ )) ; do - echo "Run $c / $LOOPS without ScalaCL's optimizing plugin" - scala -cp target/classes Test Normal >> "$OUT_FILE" ; -done - -mvn clean scala:compile || exit 1 -for (( c = 1; c <= $LOOPS; c++ )) ; do - echo "Run $c / $LOOPS with ScalaCL's optimizing plugin" - scala -cp target/classes Test Optimized >> "$OUT_FILE" ; -done - diff --git a/libraries/ScalaCL/Test/test.cmd b/libraries/ScalaCL/Test/test.cmd deleted file mode 100644 index b415358e2..000000000 --- a/libraries/ScalaCL/Test/test.cmd +++ /dev/null @@ -1,23 +0,0 @@ -@echo off -setlocal enabledelayedexpansion - -call mvn clean scala:compile || goto :eof - -set NAME=%~1 -set OUT_FILE=%~2 -if "%OUT_FILE%" == "" set OUT_FILE=out.txt - -echo Think of deleting "%OUT_FILE%" from time to time -rem del "%OUT_FILE%" - -set LOOPS=10 -for /L %%L IN (1, 1, %LOOPS%) do ( - echo Run %%L / %LOOPS% - call :runTest -) - -goto :eof - -:runTest -call scala -cp target\classes Test %NAME% >> "%OUT_FILE%" -goto :eof diff --git a/libraries/ScalaCL/pom.xml b/libraries/ScalaCL/pom.xml deleted file mode 100644 index f8668d06d..000000000 --- a/libraries/ScalaCL/pom.xml +++ /dev/null @@ -1,136 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - scalacl-parent - 0.3-SNAPSHOT - pom - ScalaCL Parent Project - 2011 - http://code.google.com/p/scalacl - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - Collections - Plugin - Test - - - - 1.0-SNAPSHOT - 0.3-SNAPSHOT - - - - - - com.nativelibs4java - javacl - ${javacl.version} - - - com.nativelibs4java - scalaxy - ${scalaxy.version} - - - com.nativelibs4java - scalaxy - test-jar - ${scalaxy.version} - - - org.scala-lang - scala-compiler - ${scala.version} - provided - - - - com.nativelibs4java - scalacl - ${project.version} - - - com.nativelibs4java - scalacl - shaded - ${project.version} - - - com.nativelibs4java - scalacl-compiler-plugin - ${project.version} - - - com.nativelibs4java - scalacl-test - ${project.version} - - - - - - - - com.nativelibs4java - maven-javacl-plugin - ${project.version} - - - - compile - - - - - - - - - - org.scala-tools - maven-scala-plugin - - - - - - - - - - - com.nativelibs4java - javacl - - - - org.scala-lang - scala-library - - - - - - - - org.scala-tools - maven-scala-plugin - ${scala.version} - - - - - - diff --git a/libraries/ScalaCL3/.gitignore b/libraries/ScalaCL3/.gitignore deleted file mode 100644 index 16d3c4dbb..000000000 --- a/libraries/ScalaCL3/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.cache diff --git a/libraries/ScalaCL3/README.md b/libraries/ScalaCL3/README.md deleted file mode 100644 index 102e05d1a..000000000 --- a/libraries/ScalaCL3/README.md +++ /dev/null @@ -1,69 +0,0 @@ -ScalaCL... v3 (yeah, yet another rewrite from scratch FTW!) - -NOT FUNCTIONAL YET, WORK IN PROGRESS (see [ScalaCL](https://code.google.com/p/scalacl/) if you want something that _works_). - -Features of the new design: -- Much better asynchronicity support (now requires OpenCL 1.1), and much better performance in general -- Support for captures of constants *and* OpenCL arrays -- Support for lazy clones for fast zipping -- Kernels are now fully specialized on static types and generated at compile-time (allows much faster startup and caching at runtime) -- ScalaCL Collections no longer fit in regular Scala Collections, to avoid silent data transfers / conversions when using unaccelerated methods (syntax stays the same, though) -- No more CLRange: expecting compiler to do its job - -TODO: -- Implement missing DataIO[T], including ASM-optimized case classes -- Catch up with compiler plugin: - - Auto-vectorize for loops - - Provide static types to OpenCL conversion - - Create top-level objects for kernels code -- Plug some v2 code back (filtered array compaction, reduceSymmetric, parallel sums...) -- Benchmarks! - -Example that will eventually work: - - import scalacl._ - - case class Matrix(data: CLArray[Float], rows: Int, columns: Int)(implicit context: Context) { - def this(rows: Int, columns: Int) = - this(new CLArray[Float](rows * columns), rows, columns) - def this(n: Int) = - this(n, n) - - def putProduct(a: Matrix, b: Matrix): Unit = { - assert(a.columns == b.rows) - assert(a.rows == rows) - assert(b.columns == columns) - - kernel { - // This block will either be converted to an OpenCL kernel or cause compilation error - for (i <- 0 until rows; j <- 0 until columns) { - data(i * columns + j) = (0 until a.columns).map(k => { - a.data(i * a.columns + k) * b.data(k * b.columns + j) - }).sum - } - } - } - - def putSum(a: Matrix, b: Matrix): Unit = { - assert(a.columns == b.columns && a.columns == columns) - assert(a.rows == b.rows && a.rows == rows) - - kernel { - for (i <- 0 until rows; j <- 0 until columns) { - val offset = i * columns + j - data(offset) = a.data(offset) + b.data(offset) - } - } - } - } - - implicit val context = Context.best - - val n = 10 - val a = new Matrix(n) - val b = new Matrix(n) - val out = new Matrix(n) - - out.putProduct(a, b) - - println(out.data) diff --git a/libraries/ScalaCL3/copyDeps b/libraries/ScalaCL3/copyDeps deleted file mode 100755 index 9c8113641..000000000 --- a/libraries/ScalaCL3/copyDeps +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -NL4J_HOME=/Users/ochafik/github/nativelibs4java2/libraries - -rm -fR lib -mkdir lib - -cp $NL4J_HOME/OpenCL/JavaCL/target/javacl-1.0-SNAPSHOT-shaded.jar lib - -#cp $NL4J_HOME/BridJ/target/bridj-0.6.2-SNAPSHOT.jar lib -#cp $NL4J_HOME/OpenCL/JavaCL/target/javacl-1.0-SNAPSHOT.jar lib -#cp $NL4J_HOME/OpenCL/Core/target/javacl-core-1.0-SNAPSHOT.jar lib -#cp $NL4J_HOME/OpenCL/OpenCL4Java/target/opencl4java-1.0-SNAPSHOT.jar lib diff --git a/libraries/ScalaCL3/lib/javacl-1.0-SNAPSHOT-shaded.jar b/libraries/ScalaCL3/lib/javacl-1.0-SNAPSHOT-shaded.jar deleted file mode 100644 index 6a7134a96..000000000 Binary files a/libraries/ScalaCL3/lib/javacl-1.0-SNAPSHOT-shaded.jar and /dev/null differ diff --git a/libraries/ScalaCL3/project/ScalaCLBuild.scala b/libraries/ScalaCL3/project/ScalaCLBuild.scala deleted file mode 100644 index 4d962fc62..000000000 --- a/libraries/ScalaCL3/project/ScalaCLBuild.scala +++ /dev/null @@ -1,33 +0,0 @@ -import sbt._ -import Keys._ - -object ScalaCLBuild extends Build { - val sharedSettings = Defaults.defaultSettings ++ Seq( - organization := "com.nativelibs4java", - version := "0.3-SNAPSHOT", - - scalaVersion := "2.10.0-M4", - scalacOptions ++= Seq( - //"-Xlog-free-terms", - //"-unchecked", - //"-Ymacro-debug" - ), - - resolvers += "Sonatype OSS Repository" at "http://oss.sonatype.org/content/repositories/snapshots", - - libraryDependencies ++= Seq( - //"com.nativelibs4java" % "javacl" % "1.0-SNAPSHOT", - "com.novocode" % "junit-interface" % "0.5" % "test->default" - ), - - libraryDependencies <+= (scalaVersion)("org.scala-lang" % "scala-compiler" % _) - ) - - lazy val root = Project( - id = "ScalaCL", - base = file("."), - settings = sharedSettings ++ Seq( - name := "scalacl" - ) - ) -} diff --git a/libraries/ScalaCL3/project/build.properties b/libraries/ScalaCL3/project/build.properties deleted file mode 100644 index d4832d043..000000000 --- a/libraries/ScalaCL3/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.12.0-RC3 diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/CLArray.scala b/libraries/ScalaCL3/src/main/scala/scalacl/CLArray.scala deleted file mode 100644 index 4c486655a..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/CLArray.scala +++ /dev/null @@ -1,93 +0,0 @@ -package scalacl -import scalacl.impl._ -import com.nativelibs4java.opencl.CLMem -import scala.collection.mutable.ArrayBuffer -import com.nativelibs4java.opencl.CLEvent -import org.bridj.Pointer - -import language.experimental.macros - -object CLArray { - def apply[T](values: T*)(implicit io: DataIO[T], context: Context, m: ClassManifest[T]) = { - val valuesArray = values.toArray - val length = valuesArray.length - new CLArray[T](length, io.allocateBuffers(length, valuesArray)) - } -} - -class CLArray[T]( - val length: Long, - protected val buffers: Array[ScheduledBuffer[_]] -)( - implicit io: DataIO[T], - val context: Context, - m: ClassManifest[T] -) -extends ScheduledBufferComposite -{ - def this(length: Long)(implicit io: DataIO[T], context: Context, m: ClassManifest[T]) = { - this(length, io.allocateBuffers(length)) - } - - def apply(index: Long): T = error("not implemented") - def update(index: Long, value: T): Unit = error("not implemented") - - override def clone: CLArray[T] = - new CLArray[T](length, buffers.map(_.clone)) - - override def foreachBuffer(f: ScheduledBuffer[_] => Unit): Unit = - buffers.foreach(f) - - override def toString = - toArray.mkString("CLArray[" + io.typeString + "](", ", ", ")") - - def toPointer(implicit io: ScalarDataIO[T]): Pointer[T] = { - val p: Pointer[T] = Pointer.allocateArray(io.pointerIO, length) - val Array(buffer: ScheduledBuffer[T]) = buffers - buffer.read(p) - p - } - def toArray: Array[T] = - io.toArray(length.toInt, buffers) - - def toSeq: Seq[T] = - toArray.toSeq - - def foreach(f: T => Unit): Unit = macro CLArrayMacros.foreachImpl[T] - private[scalacl] def foreach(f: CLFunction[T, Unit]): Unit = - execute(f, null) - - def map[U](f: T => U)(implicit io2: DataIO[U], m2: ClassManifest[U]): CLArray[U] = macro CLArrayMacros.mapImpl[T, U] - private[scalacl] def map[U](f: CLFunction[T, U])(implicit io2: DataIO[U], m2: ClassManifest[U]): CLArray[U] = { - val output = new CLArray[U](length) - execute(f, output) - output - } - - private def execute[U](f: CLFunction[T, U], output: CLArray[U]): Unit = { - val clf = f.asInstanceOf[CLFunction[T, U]] - val params = KernelExecutionParameters(Array(length)) - clf.apply(context, params, this, output) - } - - def filter(f: T => Boolean): CLFilteredArray[T] = macro CLArrayMacros.filterImpl[T] - private[scalacl] def filter(f: CLFunction[T, Boolean]): CLFilteredArray[T] = { - val presenceMask = new CLArray[Boolean](length) - execute(f, presenceMask) - new CLFilteredArray[T](this.clone, presenceMask) - } - - def reduce(f: (T, T) => T): T = error("not implemented") - - def zip[U](col: CLArray[U])(implicit m2: ClassManifest[U], io: DataIO[(T, U)]): CLArray[(T, U)] = - new CLArray[(T, U)](length, buffers.clone ++ col.buffers.clone) - - def zipWithIndex: CLArray[(T, Int)] = error("not implemented") - - def copyTo(pointer: Pointer[T]): Unit = error("not implemented") - - def sum: T = error("not implemented") - def product: T = error("not implemented") - def min: T = error("not implemented") - def max: T = error("not implemented") -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/CLFilteredArray.scala b/libraries/ScalaCL3/src/main/scala/scalacl/CLFilteredArray.scala deleted file mode 100644 index 233d10b32..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/CLFilteredArray.scala +++ /dev/null @@ -1,22 +0,0 @@ -package scalacl - -import scalacl.impl.ScheduledBuffer -import scalacl.impl.DataIO -import scalacl.impl.ScheduledBufferComposite -import scalacl.impl.DefaultScheduledData - -case class CLFilteredArray[T](array: CLArray[T], presenceMask: CLArray[Boolean])(implicit io: DataIO[T], context: Context) - extends ScheduledBufferComposite { - - override def foreachBuffer(f: ScheduledBuffer[_] => Unit): Unit = { - array.foreachBuffer(f) - presenceMask.foreachBuffer(f) - } - - def map[U](f: T => U): CLFilteredArray[U] = error("not implemented") - def compact: CLArray[T] = error("not implemented") - - def toCLArray = compact - - override def toString = "(" + array + ", " + presenceMask + ")" -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/Context.scala b/libraries/ScalaCL3/src/main/scala/scalacl/Context.scala deleted file mode 100644 index 436e181e5..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/Context.scala +++ /dev/null @@ -1,26 +0,0 @@ -package scalacl - -import com.nativelibs4java.opencl.CLContext -import com.nativelibs4java.opencl.CLQueue -import com.nativelibs4java.opencl.JavaCL -import com.nativelibs4java.opencl.CLDevice -import com.nativelibs4java.opencl.CLPlatform -import scalacl.impl.Kernel -import com.nativelibs4java.opencl.CLKernel -import scalacl.impl.ConcurrentCache - -/** - * ScalaCL context, which gathers an OpenCL context and a command queue. - */ -class Context(val context: CLContext, val queue: CLQueue) { - private[scalacl] val kernels = new ConcurrentCache[Kernel, CLKernel] -} - -object Context { - def best = { - val context = JavaCL.createBestContext(CLPlatform.DeviceFeature.GPU) - val queue = context.createDefaultOutOfOrderQueueIfPossible - println("queue: " + queue + " (" + queue.getProperties + ")") - new Context(context, queue) - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLArrayMacros.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLArrayMacros.scala deleted file mode 100644 index 44a3dd712..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLArrayMacros.scala +++ /dev/null @@ -1,29 +0,0 @@ -package scalacl -package impl - -import scala.reflect.makro.Context -import language.experimental.macros - -private[scalacl] object CLArrayMacros { - def foreachImpl[T: c.TypeTag](c: Context)(f: c.Expr[T => Unit]): c.Expr[Unit] = { - val ff = CLFunctionMacros.convertFunction(c)(f) // TODO pass static input + output collection type - c.reify { - val input = c.prefix.asInstanceOf[c.Expr[CLArray[T]]].splice - input.foreach(ff.splice) - } - } - def mapImpl[T: c.TypeTag, U: c.TypeTag](c: Context)(f: c.Expr[T => U])(io2: c.Expr[DataIO[U]], m2: c.Expr[ClassManifest[U]]): c.Expr[CLArray[U]] = { - val ff = CLFunctionMacros.convertFunction(c)(f) // TODO pass static input + output collection type - c.reify { - val input = c.prefix.asInstanceOf[c.Expr[CLArray[T]]].splice - input.map(ff.splice)(io2.splice, m2.splice) - } - } - def filterImpl[T: c.TypeTag](c: Context)(f: c.Expr[T => Boolean]): c.Expr[CLFilteredArray[T]] = { - val ff = CLFunctionMacros.convertFunction(c)(f) // TODO pass static input + output collection type - c.reify { - val input = c.prefix.asInstanceOf[c.Expr[CLArray[T]]].splice - input.filter(ff.splice) - } - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunction.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunction.scala deleted file mode 100644 index 658b6222c..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunction.scala +++ /dev/null @@ -1,35 +0,0 @@ -package scalacl.impl - -import java.util.concurrent.atomic.AtomicLong -import scala.collection.mutable.ArrayBuffer -import com.nativelibs4java.opencl.CLQueue -import scalacl.CLArray -import scalacl.Context - -case class Captures( - inputs: Array[CLArray[_]] = Array(), - outputs: Array[CLArray[_]] = Array(), - constants: Array[AnyRef] = Array()) - -case class CLFunction[U, V](f: U => V, kernel: Kernel, captures: Captures = Captures()) - extends Function1[U, V] { - - def apply(u: U) = f(u) - - def apply(context: Context, params: KernelExecutionParameters, input: CLArray[U], output: CLArray[V]) = { - ScheduledData.schedule( - if (input == null) captures.inputs else captures.inputs :+ input, - if (output == null) captures.outputs else captures.outputs :+ output, - eventsToWaitFor => { - val args = new ArrayBuffer[AnyRef] - - input.foreachBuffer(args += _.buffer) - captures.inputs.foreach(_.foreachBuffer(args += _.buffer)) - output.foreachBuffer(args += _.buffer) - captures.outputs.foreach(_.foreachBuffer(args += _.buffer)) - args ++= captures.constants - kernel.enqueue(context, params, args.toArray, eventsToWaitFor) - }) - - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunctionMacros.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunctionMacros.scala deleted file mode 100644 index bc419c6af..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CLFunctionMacros.scala +++ /dev/null @@ -1,38 +0,0 @@ -package scalacl -package impl - -import scala.reflect.makro.Context -import language.experimental.macros - -private[impl] object CLFunctionMacros -{ - private val random = new java.util.Random(System.currentTimeMillis) - - /// These ids are not necessarily unique, but their values should be dispersed well - private def nextKernelId = random.nextLong - - private[impl] def convertFunction[T: c.TypeTag, U: c.TypeTag](c: Context)(f: c.Expr[T => U]): c.Expr[CLFunction[T, U]] = { - import c.universe._ - - val Function(List(param), body) = c.typeCheck(f.tree) - - val outName = newTermName(c.fresh("out")) - - val code = CodeConversion.convertCode(c)( - Assign(Ident(outName), body), - dimensionallyIteratedInput = Some(param.symbol), - dimensionallyIteratedOutput = Some(outName), - dimensionRangeIndexes = None, - dimensionRangeOffsets = None, - dimensionRangeSteps = None, - capturedInputs = Seq(), - capturedOutputs = Seq(), - capturedConstants = Seq() - ) - val src = c.Expr[String](Literal(Constant(code))) - val id = c.Expr[Long](Literal(Constant(nextKernelId))) - c.reify { - new CLFunction[T, U](f.splice, new Kernel(id.splice, src.splice)) - } - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CodeConversion.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/CodeConversion.scala deleted file mode 100644 index 73791b1f6..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/CodeConversion.scala +++ /dev/null @@ -1,30 +0,0 @@ -package scalacl -package impl - -import scala.reflect.makro.Context - -private[impl] object CodeConversion { - def convertCode(c: Context)( - code: c.universe.Tree, - dimensionallyIteratedInput: Option[c.universe.Symbol], - dimensionallyIteratedOutput: Option[c.universe.Name], - dimensionRangeIndexes: Option[Seq[c.universe.Symbol]], - dimensionRangeOffsets: Option[Seq[c.universe.Symbol]], - dimensionRangeSteps: Option[Seq[c.universe.Symbol]], - capturedInputs: Seq[c.universe.Symbol], - capturedOutputs: Seq[c.universe.Symbol], - capturedConstants: Seq[c.universe.Symbol]): String = - { - val converter = new OpenCLConverter { - override val global = c.universe - } - - val tree = code.asInstanceOf[converter.global.Tree] - - val symbols = converter.getExternalSymbols(tree) - println(symbols) - val flat = converter.convert(tree) - println(flat) - "kernel void TODO() {}" // TODO - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConcurrentCache.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConcurrentCache.scala deleted file mode 100644 index 06f7f5125..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConcurrentCache.scala +++ /dev/null @@ -1,26 +0,0 @@ -package scalacl.impl - -/** - * Simple concurrent cache with support for costly extra values discarding - */ -class ConcurrentCache[K, V <: AnyRef] { - private val map = new java.util.concurrent.ConcurrentHashMap[K, V] - - def apply(key: K, discardValue: V => Unit)(initialValue: => V) = { - val value = map.get(key) - if (value != null) { - value - } else { - val newValue = initialValue - val oldValue = map.putIfAbsent(key, newValue) - if (oldValue eq null) { - newValue - } else { - discardValue(newValue) - oldValue - } - } - } - def clear = - map.clear -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConversionNames.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConversionNames.scala deleted file mode 100644 index 1bde30928..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ConversionNames.scala +++ /dev/null @@ -1,143 +0,0 @@ -package scalacl -package impl - -import reflect.NameTransformer - -trait ConversionNames { - val global: reflect.api.Universe - import global._ - import definitions._ - - class N(val s: String) { - def unapply(n: Name): Boolean = n.toString == s - } - object N { - def apply(s: String) = new N(s) - } - implicit def N2Name(n: N) = newTermName(n.s) - - val addAssignName = N(NameTransformer.encode("+=")) - val toArrayName = N("toArray") - val toListName = N("toList") - val toSeqName = N("toSeq") - val toSetName = N("toSet") - val toIndexedSeqName = N("toIndexedSeq") - val toVectorName = N("toVector") - val toMapName = N("toMap") - val resultName = N("result") - val scalaName = N("scala") - val ArrayName = N("Array") - val intWrapperName = N("intWrapper") - val tabulateName = N("tabulate") - val toName = N("to") - val byName = N("by") - val withFilterName = N("withFilter") - val untilName = N("until") - val isEmptyName = N("isEmpty") - val sumName = N("sum") - val productName = N("product") - val minName = N("min") - val maxName = N("max") - val headName = N("head") - val tailName = N("tail") - val foreachName = N("foreach") - val foldLeftName = N("foldLeft") - val foldRightName = N("foldRight") - val zipWithIndexName = N("zipWithIndex") - val zipName = N("zip") - val reverseName = N("reverse") - val reduceLeftName = N("reduceLeft") - val reduceRightName = N("reduceRight") - val scanLeftName = N("scanLeft") - val scanRightName = N("scanRight") - val mapName = N("map") - val collectName = N("collect") - val canBuildFromName = N("canBuildFrom") - val filterName = N("filter") - val filterNotName = N("filterNot") - val takeWhileName = N("takeWhile") - val dropWhileName = N("dropWhile") - val countName = N("count") - val forallName = N("forall") - val existsName = N("exists") - val findName = N("find") - val updateName = N("update") - val toSizeTName = N("toSizeT") - val toLongName = N("toLong") - val toIntName = N("toInt") - val toShortName = N("toShort") - val toByteName = N("toByte") - val toCharName = N("toChar") - val toDoubleName = N("toDouble") - val toFloatName = N("toFloat") - val mathName = N("math") - val packageName = N("package") - val applyName = N("apply") - val thisName = N("this") - val superName = N("super") - - /* - def C(name: String) = definitions.getClass(name) - def M(name: String) = definitions.getModule(name) - - lazy val ScalaReflectPackage = M("scala.reflect") - lazy val ScalaCollectionPackage = M("scala.collection") - lazy val ScalaMathPackage = M("scala.math") - lazy val ScalaMathPackageClass = ScalaMathPackage.tpe.typeSymbol - lazy val ScalaMathCommonClass = C("scala.MathCommon") - - lazy val SeqModule = M("scala.collection.Seq") - lazy val SeqClass = C("scala.collection.Seq") - lazy val SetModule = M("scala.collection.Set") - lazy val SetClass = C("scala.collection.Set") - lazy val VectorClass = C("scala.collection.Set") - lazy val ListClass = C("scala.List") - lazy val ImmutableListClass = C("scala.collection.immutable.List") - lazy val NonEmptyListClass = C("scala.collection.immutable.$colon$colon") - lazy val IndexedSeqModule = M("scala.collection.IndexedSeq") - lazy val IndexedSeqClass = C("scala.collection.IndexedSeq") - lazy val OptionModule = M("scala.Option") - lazy val OptionClass = C("scala.Option") - lazy val SomeModule = M("scala.Some") - lazy val NoneModule = M("scala.None") - lazy val StringOpsClass = C("scala.collection.immutable.StringOps") - - lazy val VectorBuilderClass = C("scala.collection.immutable.VectorBuilder") - lazy val ListBufferClass = C("scala.collection.mutable.ListBuffer") - lazy val ArrayBufferClass = C("scala.collection.mutable.ArrayBuffer") - lazy val WrappedArrayBuilderClass = C("scala.collection.mutable.WrappedArrayBuilder") - lazy val RefArrayBuilderClass = C("scala.collection.mutable.ArrayBuilder.ofRef") - lazy val RefArrayOpsClass = C("scala.collection.mutable.ArrayOps.ofRef") - lazy val SetBuilderClass = C("scala.collection.mutable.SetBuilder") - - lazy val RichWrappers: Set[Symbol] = - Array("Byte", "Short", "Int", "Char", "Long", "Float", "Double", "Boolean"). - map(n => C("scala.runtime.Rich" + n)).toSet - - lazy val CanBuildFromClass = C("scala.collection.generic.CanBuildFrom") - - lazy val ArrayIndexOutOfBoundsExceptionClass = C("java.lang.ArrayIndexOutOfBoundsException") - - lazy val primArrayNames = Array( - (IntClass.tpe, "ofInt"), - (LongClass.tpe, "ofLong"), - (ShortClass.tpe, "ofShort"), - (ByteClass.tpe, "ofByte"), - (CharClass.tpe, "ofChar"), - (BooleanClass.tpe, "ofBoolean"), - (FloatClass.tpe, "ofFloat"), - (DoubleClass.tpe, "ofDouble"), - (UnitClass.tpe, "ofUnit") - ) - - lazy val primArrayBuilderClasses = primArrayNames.map { - case (sym, n) => - (sym, C("scala.collection.mutable.ArrayBuilder." + n)) - } toMap - - lazy val primArrayOpsClasses = primArrayNames.map { - case (sym, n) => - (sym, C("scala.collection.mutable.ArrayOps." + n)) - } toMap - */ -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/DataIO.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/DataIO.scala deleted file mode 100644 index 08cae5780..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/DataIO.scala +++ /dev/null @@ -1,34 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl.{ CLMem, CLEvent } -import org.bridj.{ Pointer, PointerIO } -import scala.collection.mutable.ArrayBuffer - -private[scalacl] trait DataIO[T] { - private[scalacl] def typeString: String - private[scalacl] def bufferCount: Int - private[scalacl] def foreachScalar(f: ScalarDataIO[_] => Unit): Unit - private[scalacl] def allocateBuffers(length: Long)(implicit context: Context): Array[ScheduledBuffer[_]] = { - val buffers = new ArrayBuffer[ScheduledBuffer[_]] - allocateBuffers(length, buffers) - buffers.toArray - } - - private[scalacl] def toArray(length: Int, buffers: Array[ScheduledBuffer[_]]): Array[T] - - private[scalacl] def allocateBuffers(length: Long, values: Array[T])(implicit context: Context, m: ClassManifest[T]): Array[ScheduledBuffer[_]] = { - val pointersBuf = new ArrayBuffer[Pointer[_]] - foreachScalar(io => pointersBuf += Pointer.allocateArray(io.pointerIO, length)) - - val pointers = pointersBuf.toArray - for (i <- 0 until length.toInt) { - set(i, pointers, 0, values(i)) - } - - pointers.map(pointer => new ScheduledBuffer(context.context.createBuffer(CLMem.Usage.InputOutput, pointer))) - } - private[scalacl] def allocateBuffers(length: Long, out: ArrayBuffer[ScheduledBuffer[_]])(implicit context: Context): Unit - private[scalacl] def get(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int): T - private[scalacl] def set(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int, value: T): Unit -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/DefaultScheduledData.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/DefaultScheduledData.scala deleted file mode 100644 index 9cc8a6941..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/DefaultScheduledData.scala +++ /dev/null @@ -1,71 +0,0 @@ -package scalacl.impl -import com.nativelibs4java.opencl._ -import java.util.concurrent.locks._ -import collection.mutable.ArrayBuffer - -private[scalacl] trait DefaultScheduledData extends ScheduledData { - private val scheduleLock = new ReentrantLock - - private def locked[V](block: => V): V = { - scheduleLock.lock - try { - block - } finally { - scheduleLock.unlock - } - } - override def finish = { - val events = new ArrayBuffer[CLEvent] - locked { - if (dataWrite != null) - events += dataWrite - events ++= dataReads - } - CLEvent.waitFor(events.toArray: _*) - locked { - events.foreach(doEventCompleted(_)) - } - } - private def doEventCompleted(event: CLEvent) { - if (event.equals(dataWrite)) { - dataWrite = null - dataReads.clear - } else { - dataReads -= event - } - } - def eventCompleted(event: CLEvent): Unit = { - locked { - doEventCompleted(event) - } - } - def startRead(out: ArrayBuffer[CLEvent]) = { - scheduleLock.lock - if (dataWrite != null) - out += dataWrite - this - } - - def startWrite(out: ArrayBuffer[CLEvent]) = { - scheduleLock.lock - out ++= dataReads - if (dataWrite != null) - out += dataWrite - this - } - - def endRead(event: CLEvent): Unit = { - if (event != null) - dataReads += event - scheduleLock.unlock - } - - def endWrite(event: CLEvent): Unit = { - if (event != null) - dataWrite = event - scheduleLock.unlock - } - - private var dataWrite: CLEvent = _ - private val dataReads = new ArrayBuffer[CLEvent] -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/FlatCode.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/FlatCode.scala deleted file mode 100644 index d382771f3..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/FlatCode.scala +++ /dev/null @@ -1,49 +0,0 @@ -package scalacl -package impl - -object FlatCodes { - - def merge[T](fcs: FlatCode[T]*)(f: Seq[T] => Seq[T]) = - fcs.reduceLeft(_ ++ _).mapValues(f) - -} -case class FlatCode[T]( - /// External functions that are referenced by statements and / or values - outerDefinitions: Seq[T], - /// List of variable definitions and other instructions (if statements, do / while loops...) - statements: Seq[T], - /// Final values of the code in a "flattened tuple" style - values: Seq[T] -) { - def mapEachValue(f: T => Seq[T]): FlatCode[T] = - copy(values = values.flatMap(f)) - - def mapValues(f: Seq[T] => Seq[T]): FlatCode[T] = - copy(values = f(values)) - - def ++(fc: FlatCode[T]) = - FlatCode(outerDefinitions ++ fc.outerDefinitions, statements ++ fc.statements, values ++ fc.values) - - def >>(fc: FlatCode[T]) = - FlatCode(outerDefinitions ++ fc.outerDefinitions, statements ++ fc.statements ++ values, fc.values) - - def noValues = - FlatCode(outerDefinitions, statements ++ values, Seq()) - - def addOuters(outerDefs: Seq[T]) = - copy(outerDefinitions = outerDefinitions ++ outerDefs) - - def addStatements(stats: Seq[T]) = - copy(statements = statements ++ stats) - - def printDebug(name: String = "") = { - def pt(seq: Seq[T]) = println("\t" + seq.map(_.toString.replaceAll("\n", "\n\t")).mkString("\n\t")) - println("FlatCode(" + name + "):") - pt(outerDefinitions) - println("\t--") - pt(statements) - println("\t--") - pt(values) - } -} - diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/Kernel.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/Kernel.scala deleted file mode 100644 index ddac2e39c..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/Kernel.scala +++ /dev/null @@ -1,41 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl._ -import java.util.concurrent.locks._ -import collection.mutable.ArrayBuffer - -private[scalacl] case class KernelExecutionParameters( - globalSizes: Array[Long], - localSizes: Array[Long] = null, - globalOffsets: Array[Long] = null) { - def this(uniqueSize: Long) = this(Array(uniqueSize)) -} - -/** - * Thin wrapper for OpenCL kernel sources, which can act as a fast cache key for the corresponding CLKernel - */ -class Kernel(protected val id: Long, protected val sources: String) { - def getKernel(context: Context): CLKernel = { - context.kernels(this, _.release) { - val Array(k) = context.context.createProgram(sources).createKernels - k - } - } - def enqueue(context: Context, params: KernelExecutionParameters, args: Array[AnyRef], eventsToWaitFor: Array[CLEvent]): CLEvent = { - var kernel = getKernel(context) - kernel synchronized { - kernel.setArgs(args: _*) - kernel.enqueueNDRange(context.queue, params.globalOffsets, params.globalSizes, params.localSizes, eventsToWaitFor: _*) - } - } - - override def equals(o: Any) = o.isInstanceOf[Kernel] && { - val k = o.asInstanceOf[Kernel] - id == k.id && (sources eq k.sources) // identity test: assume interned strings coming from class resources! - } - - override def hashCode = id.hashCode - - override def toString = "Kernel(" + sources + ")" -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelMacros.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelMacros.scala deleted file mode 100644 index e5a86de98..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelMacros.scala +++ /dev/null @@ -1,16 +0,0 @@ -package scalacl.impl - -import language.experimental.macros - -import reflect.makro.Context - -object KernelMacros { - def kernelImpl(c: Context)(block: c.Expr[Unit])(context: c.Expr[scalacl.Context]): c.Expr[Unit] = { - c.reify { - {} - } - } - def taskImpl(c: Context)(block: c.Expr[Unit])(context: c.Expr[scalacl.Context]): c.Expr[Unit] = { - kernelImpl(c)(block)(context) - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelSymbolsAnalysis.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelSymbolsAnalysis.scala deleted file mode 100644 index add4a596f..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/KernelSymbolsAnalysis.scala +++ /dev/null @@ -1,98 +0,0 @@ -package scalacl -package impl - -import scala.collection.immutable.Stack -import scala.reflect.NameTransformer - -sealed trait SymbolKind -object SymbolKind { - case object Array extends SymbolKind - case object Constant extends SymbolKind - case object ConvertiblePredefined extends SymbolKind - case object Other extends SymbolKind -} - -sealed trait UsageKind { - def merge(usage: UsageKind): UsageKind -} -object UsageKind { - case object Input extends UsageKind { - override def merge(usage: UsageKind) = - if (usage == Input) Input - else InputOutput - } - case object Output extends UsageKind { - override def merge(usage: UsageKind) = - if (usage == Output) Output - else InputOutput - } - case object InputOutput extends UsageKind { - override def merge(usage: UsageKind) = - this - } -} - -trait KernelSymbolsAnalysis -extends ConversionNames -with MiscMatchers -{ - val global: reflect.api.Universe - import global._ - import definitions._ - - import collection._ - - case class KernelSymbols( - symbolKinds: mutable.HashMap[Symbol, SymbolKind] = new mutable.HashMap[Symbol, SymbolKind], - symbolUsages: mutable.HashMap[Symbol, UsageKind] = new mutable.HashMap[Symbol, UsageKind], - localSymbols: mutable.HashSet[Symbol] = new mutable.HashSet[Symbol] - ) { - def declareSymbolUsage(symbol: Symbol, usage: UsageKind): Unit = { - if (symbol == NoSymbol) { - // TODO error("Cannot declare usage of NoSymbol!") - } else { - val symbolKind = getKind(symbol) - if (symbolKind == SymbolKind.Other) - error("Cannot handle usage of symbol " + symbol) - - symbolUsages.get(symbol) match { - case Some(u) => - symbolUsages(symbol) = u.merge(usage) - case None => - symbolUsages(symbol) = usage - } - } - } - def getKind(symbol: Symbol): SymbolKind = { - // TODO - SymbolKind.Array - } - } - - def getExternalSymbols(tree: Tree, knownSymbols: Set[Symbol] = Set()): KernelSymbols = { - - val symbols = new KernelSymbols - - new Traverser { - override def traverse(tree: Tree) = tree match { - case Ident(n) => - symbols.declareSymbolUsage(tree.symbol, UsageKind.Input) - case Apply(Select(target, updateName()), List(index, value)) => - symbols.declareSymbolUsage(target.symbol, UsageKind.Output) - super.traverse(index) - super.traverse(value) - case Apply(Select(target, applyName()), List(index)) => - symbols.declareSymbolUsage(target.symbol, UsageKind.Output) - super.traverse(index) - case ValDef(_, _, _, _) => - symbols.localSymbols += tree.symbol - super.traverse(tree) - - case _ => - super.traverse(tree) - } - }.traverse(tree) - - symbols - } -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/MiscMatchers.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/MiscMatchers.scala deleted file mode 100644 index 14729d8d9..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/MiscMatchers.scala +++ /dev/null @@ -1,31 +0,0 @@ -package scalacl -package impl - -trait MiscMatchers { - val global: reflect.api.Universe - import global._ - - object WhileLoop { - def unapply(tree: Tree) = tree match { - case - LabelDef( - lab, - List(), - If( - condition, - Block( - content, - Apply( - Ident(lab2), - List() - ) - ), - Literal(Constant(())) - ) - ) if (lab == lab2) => - Some(condition, content) - case _ => - None - } - } -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/OpenCLConverter.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/OpenCLConverter.scala deleted file mode 100644 index a8b094d58..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/OpenCLConverter.scala +++ /dev/null @@ -1,311 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl -package impl - -import scala.collection.immutable.Stack -import scala.reflect.NameTransformer - -trait OpenCLConverter -extends ConversionNames -with MiscMatchers -with KernelSymbolsAnalysis -{ - val global: reflect.api.Universe - import global._ - import definitions._ - - //import global.FlagValues._ - import FlatCodes.merge - - def nodeToStringNoComment(tree: Tree): String = tree.toString // TODO - - class Ids(start: Long = 1) { - private var nx = start - def next = this.synchronized { - val v = nx - nx += 1 - v - } - } - - var openclLabelIds = new Ids - - var placeHolderRefs = new Stack[String] - - def valueCode(v: String) = FlatCode[String](Seq(), Seq(), Seq(v)) - def emptyCode = FlatCode[String](Seq(), Seq(), Seq()) - def statementCode(s: String) = FlatCode[String](Seq(), Seq(s), Seq()) - def convert(body: Tree): FlatCode[String] = { - def cast(expr: Tree, clType: String) = - convert(expr).mapEachValue(v => Seq("((" + clType + ")" + v + ")")) - - /* - def convertForeach(from: Tree, to: Tree, isUntil: Boolean, by: Tree, function: Tree) = { - val Function(List(vd @ ValDef(paramMods, paramName, tpt, rhs)), body) = function - val id = openclLabelIds.next - val iVar = "iVar$" + id - val nVal = "nVal$" + id - - out("int ", iVar, ";\n") - out("const int ", nVal, " = ", to, ";\n") - out("for (", iVar, " = ", from, "; ", iVar, " ", if (isUntil) "<" else "<=", " ", nVal, "; ", iVar, " += ", by, ") {\n") - doConvertExpr(argNames + (vd.symbol -> iVar), body, false, conversion, b)._1 - out("\n}") - }*/ - body match { - //case TupleCreation(tupleArgs) =>//Apply(TypeApply(Select(TupleObject(), applyName()), tupleTypes), tupleArgs) if isTopLevel => - // tupleArgs.map(convert).reduceLeft(_ ++ _) - case Literal(Constant(value)) => - if (value == ()) - emptyCode - else - valueCode(value.toString) - case Ident(name) => - valueCode(name.toString) - - case If(condition, then, otherwise) => - // val (a, b) = if ({ val d = 0 ; d != 0 }) (1, d) else (2, 0) - // -> - // val d = 0 - // val condition = d != 0 - // val a = if (condition) 1 else 2 - // val b = if (condition) d else 0 - val FlatCode(dc, sc, Seq(vc)) = convert(condition) - val fct @ FlatCode(Seq(), st, vt) = convert(then) - val fco @ FlatCode(Seq(), so, vo) = convert(otherwise) - - def newIf(t: String, o: String, isValue: Boolean) = - if (isValue) - "((" + vc + ") ? (" + t + ") : (" + o + "))" - else - "if (" + vc + ") {\n" + t + "\n} else {\n" + o + "\n}\n" - - val (rs, rv) = (st, so) match { - case (Seq(), Seq()) if !vt.isEmpty && !vo.isEmpty => - ( - Seq(), - vt.zip(vo).map { case (t, o) => newIf(t, o, true) } // pure (cond ? then : otherwise) form, possibly with tuple values - ) - case _ => - ( - Seq(newIf((st ++ vt).mkString("\n"), (so ++ vo).mkString("\n"), false)), - Seq() - ) - } - FlatCode[String]( - dc, - sc ++ rs, - rv - ) - case Apply(Select(target, applyName()), List(singleArg)) => - merge(Seq(target, singleArg).map(convert):_*) { case Seq(t, a) => Seq(t + "[" + a + "]") } - case Apply(Select(target, updateName()), List(index, value)) => - merge(Seq(target, index, value).map(convert):_*) { case Seq(t, i, v) => Seq(t + "[" + i + "] = " + v) } - case Assign(lhs, rhs) => - merge(Seq(lhs, rhs).map(convert):_*) { case Seq(l, r) => Seq(l + " = " + r + ";") } - case Typed(expr, tpt) => - val t = convertTpe(tpt.tpe) - convert(expr).mapValues(_.map(v => "((" + t + ")" + v + ")")) - case DefDef(mods, name, tparams, vparamss, tpt, body) => - val b = new StringBuilder - b ++= convertTpe(body.tpe) + " " + name + "(" - var first = true - for (param <- vparamss.flatten) { - if (first) - first = false - else - b ++= ", " - b ++= constPref(param.mods) + convertTpe(param.tpt.tpe) + " " + param.name - } - b ++= ") {\n" - val convBody = convert(body) - convBody.statements.foreach(b ++= _) - if (!convBody.values.isEmpty) { - val Seq(ret) = convBody.values - b ++= "return " + ret + ";" - } - b ++= "\n}" - FlatCode[String]( - convBody.outerDefinitions :+ b.toString, - Seq(), - Seq() - ) - case vd @ ValDef(paramMods, paramName, tpt: TypeTree, rhs) => - val convValue = convert(rhs) - FlatCode[String]( - convValue.outerDefinitions, - convValue.statements ++ - Seq( - constPref(paramMods) + convertTpt(tpt) + " " + paramName + ( - if (rhs != EmptyTree) { - val Seq(value) = convValue.values - " = " + value - } else - "" - ) + ";" - ), - Seq() - ) - //case Typed(expr, tpe) => - // out(expr) - case Match(ma @ Ident(matchName), List(CaseDef(pat, guard, body))) => - //for () - //x0$1 match { - // case (_1: Long,_2: Float)(Long, Float)((i @ _), (c @ _)) => i.+(c) - //} - //Match(Ident("x0$1"), List(CaseDef(Apply(TypeTree(), List(Bind(i, Ident("_")), Bind(c, Ident("_"))), EmptyTree Apply(Select(Ident("i"), "$plus"), List(Ident("c") - convert(body) - case Select(expr, toSizeTName()) => cast(expr, "size_t") - case Select(expr, toLongName()) => cast(expr, "long") - case Select(expr, toIntName()) => cast(expr, "int") - case Select(expr, toShortName()) => cast(expr, "short") - case Select(expr, toByteName()) => cast(expr, "char") - case Select(expr, toCharName()) => cast(expr, "short") - case Select(expr, toDoubleName()) => cast(expr, "double") - case Select(expr, toFloatName()) => cast(expr, "float") - // TODO - //case ScalaMathFunction(functionType, funName, args) => - // convertMathFunction(functionType, funName, args) - case Apply(s @ Select(left, name), args) => - val List(right) = args - NameTransformer.decode(name.toString) match { - case op @ ("+" | "-" | "*" | "/" | "%" | "^" | "^^" | "&" | "&&" | "|" | "||" | "<<" | ">>" | "==" | "<" | ">" | "<=" | ">=" | "!=") => - merge(Seq(left, right).map(convert):_*) { - case Seq(l, r) => Seq("(" + l + " " + op + " " + r + ")") - //case e => - // throw new RuntimeException("ugh : " + e + ", op = " + op + ", body = " + body + ", left = " + left + ", right = " + right) - } - // TODO - //case n if isPackageReference(left, "scala.math") => - // convertMathFunction(s.tpe, name, args) - //merge(Seq(right).map(convert):_*) { case Seq(v) => Seq(n + "(" + v + ")") } - case n => - println(nodeToStringNoComment(body)) - throw new RuntimeException("[ScalaCL] Unhandled method name in Scala -> OpenCL conversion : " + name + "\n\tleft = " + left + ",\n\targs = " + args) - valueCode("/* Error: failed to convert " + body + " */") - } - case s @ Select(expr, fun) => - convert(expr).mapEachValue(v => { - val fn = fun.toString - if (fn.matches("_\\d+")) { - Seq(v + "." + fn) - } else { - throw new RuntimeException("Unknown function " + s) - Seq("/* Error: failed to convert " + body + " */") - } - }) - case WhileLoop(condition, content) => - val FlatCode(dcont, scont, vcont) = content.map(convert).reduceLeft(_ >> _) - val FlatCode(dcond, scond, Seq(vcond)) = convert(condition) - FlatCode[String]( - dcond ++ dcont, - scond ++ - Seq( - "while (" + vcond + ") {\n" + - (scont ++ vcont).mkString("\n") + "\n" + - "}" - ), - Seq() - ) - case Apply(target, args) => - merge((target :: args).map(convert):_*)(seq => { - val t :: a = seq.toList - Seq(t + "(" + a.mkString(", ") + ")") - }) - case Block(statements, Literal(Constant(empty))) => - assert(empty == (), "Valued blocks should have been flattened in a previous phase !") - statements.map(convert).map(_.noValues).reduceLeft(_ >> _) - case _ => - //println(nodeToStringNoComment(body)) - throw new RuntimeException("Failed to convert " + body.getClass.getName + ": \n" + body + " : \n" + nodeToStringNoComment(body)) - valueCode("/* Error: failed to convert " + body + " */") - } - } - def convertMathFunction(functionType: Type, funName: Name, args: List[Tree]) = { - var outers = Seq[String]()//"#include ") - val hasDoubleParam = args.exists(_.tpe == DoubleClass.asType) - if (hasDoubleParam) - outers ++= Seq("#pragma OPENCL EXTENSION cl_khr_fp64: enable") - - val normalizedArgs = args.map(_ match { - case Select(a, toDoubleName()) => a - case arg => arg - }) - val convArgs = normalizedArgs.map(convert) - - assert(convArgs.forall(_.statements.isEmpty), convArgs) - FlatCode[String]( - convArgs.flatMap(_.outerDefinitions) ++ outers, - convArgs.flatMap(_.statements), - Seq( - funName + "(" + - convArgs.zip(normalizedArgs).map({ case (convArg, normalizedArg) => - assert(convArg.statements.isEmpty, convArg) - val Seq(value) = convArg.values - //"(" + convertTpe(normalizedArg.tpe) + ")" + value - functionType match { - case _ //MethodType(List(param), resultType) - if normalizedArg.tpe != DoubleClass.asType => - "(float)" + value - case _ => - "(" + convertTpe(normalizedArg.tpe) + ")" + value - } - }).mkString(", ") + - ")" - ) - ) - } - def constPref(mods: Modifiers) = - (if (mods.hasFlag(Flag.MUTABLE)) "" else "const ") - - def convertTpt(tpt: TypeTree) = convertTpe(tpt.tpe) - def convertTpe(tpe: Type) = { - if (tpe == null) { - throw new RuntimeException("Null type cannot be converted to OpenCL !") - "?" - } else if (tpe == NoType) - "void" - else - tpe.toString match { - case "Int" => "int" - case "Long" => "long" - case "Short" => "short" - case "Char" => "short" - case "Byte" => "char" - case "Float" => "float" - case "Double" => "double" - case "Boolean" => "char" - case "org.bridj.SizeT" => "size_t" - case _ => throw new RuntimeException("Cannot convert unknown type " + tpe + " to OpenCL") - } - } -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScalarDataIO.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScalarDataIO.scala deleted file mode 100644 index 1909f1177..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScalarDataIO.scala +++ /dev/null @@ -1,53 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl.CLMem -import org.bridj.{ Pointer, PointerIO } -import scala.collection.mutable.ArrayBuffer - -abstract class ScalarDataIO[T : Manifest](io: PointerIO[_]) extends DataIO[T] { - override val typeString = implicitly[ClassManifest[T]].erasure.getSimpleName - override def bufferCount = 1 - - private[scalacl] val pointerIO: PointerIO[T] = io.asInstanceOf[PointerIO[T]] - - private[scalacl] def foreachScalar(f: ScalarDataIO[_] => Unit): Unit = - f(this) - - override def toArray(length: Int, buffers: Array[ScheduledBuffer[_]]): Array[T] = { - val Array(buffer: ScheduledBuffer[T]) = buffers - buffer.read().getArray.asInstanceOf[Array[T]] - } - - override def allocateBuffers(length: Long, values: Array[T])(implicit context: Context, m: ClassManifest[T]): Array[ScheduledBuffer[_]] = { - val pointer = Pointer.pointerToArray[T](values) - Array(new ScheduledBuffer(context.context.createBuffer(CLMem.Usage.InputOutput, pointer))) - } - private[scalacl] def allocateBuffer(length: Long)(implicit context: Context) = - context.context.createBuffer(CLMem.Usage.InputOutput, pointerIO, length) - - override def allocateBuffers(length: Long, out: ArrayBuffer[ScheduledBuffer[_]])(implicit context: Context) = { - out += new ScheduledBuffer(allocateBuffer(length)) - } -} - -object IntDataIO extends ScalarDataIO[Int](PointerIO.getIntInstance) { - override def get(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int) = - buffers(bufferOffset).getIntAtOffset(index * 4) - override def set(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int, value: Int) = - buffers(bufferOffset).setIntAtOffset(index * 4, value) -} - -object FloatDataIO extends ScalarDataIO[Float](PointerIO.getFloatInstance) { - override def get(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int) = - buffers(bufferOffset).getFloatAtOffset(index * 4) - override def set(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int, value: Float) = - buffers(bufferOffset).setFloatAtOffset(index * 4, value) -} - -object BooleanDataIO extends ScalarDataIO[Boolean](PointerIO.getBooleanInstance) { - override def get(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int) = - buffers(bufferOffset).getByteAtOffset(index * 1) != 0 - override def set(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int, value: Boolean) = - buffers(bufferOffset).setByteAtOffset(index * 1, (if (value) 1 else 0).asInstanceOf[Byte]) -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBuffer.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBuffer.scala deleted file mode 100644 index 28aee6528..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBuffer.scala +++ /dev/null @@ -1,98 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl.CLBuffer -import scala.collection.mutable.ArrayBuffer -import com.nativelibs4java.opencl.CLEvent -import org.bridj.Pointer -import com.nativelibs4java.opencl.CLMem - -/* - -ScheduledBuffer: -- shallowClones: ArrayBuffer[ScheduledBuffer] -- cloneModel: ScheduledBuffer - - */ - -private[scalacl] class ScheduledBuffer[T](initialBuffer: CLBuffer[T])(implicit context: Context) extends DefaultScheduledData { - - private var buffer_ = initialBuffer - private var lazyClones = new ArrayBuffer[ScheduledBuffer[T]] - private var lazyCloneModel: ScheduledBuffer[T] = _ - - def buffer = buffer_ - - def release = this synchronized { - if (lazyCloneModel == null) - buffer.release - } - override def clone: ScheduledBuffer[T] = this synchronized { - if (lazyCloneModel != null) { - lazyCloneModel.clone - } else { - val c = new ScheduledBuffer(buffer) - c.lazyCloneModel = this - lazyClones += c - c - } - } - - def performClone = this synchronized { - if (lazyCloneModel != null) { - lazyCloneModel synchronized { - buffer_ = context.context.createBuffer(CLMem.Usage.InputOutput, initialBuffer.getIO, initialBuffer.getElementCount) - lazyCloneModel.lazyClones -= this - lazyCloneModel = null - ScheduledData.schedule( - Array(lazyCloneModel), - Array(this), - eventsToWaitFor => initialBuffer.copyTo(context.queue, buffer, eventsToWaitFor: _*)) - } - } - } - - override def startWrite(out: ArrayBuffer[CLEvent]) = this synchronized { - performClone - lazyClones.toArray.foreach(_.performClone) - super.startWrite(out) - } - - def write(in: Pointer[T]): Unit = { - ScheduledData.schedule( - Array(), - Array(this), - eventsToWaitFor => buffer.write(context.queue, in, false, eventsToWaitFor: _*) - ) - } - def read(): Pointer[T] = { - val queue = context.queue - val p = buffer.allocateCompatibleMemory(queue.getDevice) - - val event = ScheduledData.schedule( - Array(this), - Array[ScheduledData](), - eventsToWaitFor => buffer.read(queue, p, true, eventsToWaitFor: _*)) - p - } - def read(out: ArrayBuffer[CLEvent]): Pointer[T] = { - val queue = context.queue - val p = buffer.allocateCompatibleMemory(queue.getDevice) - - val event = ScheduledData.schedule( - Array(this), - Array[ScheduledData](), - eventsToWaitFor => buffer.read(queue, p, false, eventsToWaitFor: _*)) - if (out != null) - out += event - p - } - - def read(p: Pointer[T]): Unit = { - val event = ScheduledData.schedule( - Array(this), - Array(), - eventsToWaitFor => buffer.read(context.queue, p, false, eventsToWaitFor: _*)) - event.waitFor - } -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBufferComposite.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBufferComposite.scala deleted file mode 100644 index 9c0a24406..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledBufferComposite.scala +++ /dev/null @@ -1,34 +0,0 @@ -package scalacl.impl - -import scala.collection.mutable.ArrayBuffer -import com.nativelibs4java.opencl.CLEvent - -private[scalacl] trait ScheduledBufferComposite extends ScheduledData { - - def foreachBuffer(f: ScheduledBuffer[_] => Unit): Unit - - def finish = - foreachBuffer(_.finish) - - def release = - foreachBuffer(_.release) - - def eventCompleted(event: CLEvent): Unit = - foreachBuffer(_.eventCompleted(event)) - - def startRead(out: ArrayBuffer[CLEvent]): ScheduledData = { - foreachBuffer(_.startRead(out)) - this - } - - def startWrite(out: ArrayBuffer[CLEvent]): ScheduledData = { - foreachBuffer(_.startWrite(out)) - this - } - - def endRead(event: CLEvent): Unit = - foreachBuffer(_.endRead(event)) - - def endWrite(event: CLEvent): Unit = - foreachBuffer(_.endWrite(event)) -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledData.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledData.scala deleted file mode 100644 index dc53a3050..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/ScheduledData.scala +++ /dev/null @@ -1,44 +0,0 @@ -package scalacl.impl -import com.nativelibs4java.opencl._ -import java.util.concurrent.locks._ -import collection.mutable.ArrayBuffer - -private[scalacl] object ScheduledData { - def schedule[S1 <: ScheduledData, S2 <: ScheduledData]( - inputs: Array[S1], - outputs: Array[S2], - operation: Array[CLEvent] => CLEvent): CLEvent = { - - val nData = inputs.length + outputs.length - val eventsToWaitFor = new ArrayBuffer[CLEvent](nData) - - inputs.foreach(_.startRead(eventsToWaitFor)) - outputs.foreach(_.startWrite(eventsToWaitFor)) - - var event: CLEvent = null - try { - event = operation(eventsToWaitFor.toArray) - if (event != null) - event.setCompletionCallback(new CLEvent.EventCallback { - override def callback(status: Int) = { - // println("completed") - inputs.foreach(_.eventCompleted(event)) - outputs.foreach(_.eventCompleted(event)) - } - }) - event - } finally { - inputs.foreach(_.endRead(event)) - outputs.foreach(_.endWrite(event)) - } - } -} - -private[scalacl] trait ScheduledData { - def finish: Unit - def eventCompleted(event: CLEvent): Unit - def startRead(out: ArrayBuffer[CLEvent]): ScheduledData - def startWrite(out: ArrayBuffer[CLEvent]): ScheduledData - def endRead(event: CLEvent): Unit - def endWrite(event: CLEvent): Unit -} diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/impl/TupleDataIO.scala b/libraries/ScalaCL3/src/main/scala/scalacl/impl/TupleDataIO.scala deleted file mode 100644 index 66bcea757..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/impl/TupleDataIO.scala +++ /dev/null @@ -1,43 +0,0 @@ -package scalacl -package impl - -import com.nativelibs4java.opencl.{ CLMem, CLEvent } -import org.bridj.{ Pointer, PointerIO } -import scala.collection.mutable.ArrayBuffer - -private[impl] abstract class TupleDataIO[T : Manifest] extends DataIO[T] { - - override def toArray(length: Int, buffers: Array[ScheduledBuffer[_]]): Array[T] = { - val eventsToWaitFor = new ArrayBuffer[CLEvent] - val pointers = buffers.map(_.read(eventsToWaitFor).withoutValidityInformation) // unsafe, but faster - CLEvent.waitFor(eventsToWaitFor.toArray: _*) - (0 until length.toInt).par.map(i => get(i, pointers, 0)).toArray // TODO check - } -} -class Tuple2DataIO[T1 : Manifest : DataIO, T2 : Manifest : DataIO] - extends TupleDataIO[(T1, T2)] { - val io1 = implicitly[DataIO[T1]] - val io2 = implicitly[DataIO[T2]] - - override def typeString = "(" + io1.typeString + ", " + io2.typeString + ")" - override val bufferCount = io1.bufferCount + io2.bufferCount - def foreachScalar(f: ScalarDataIO[_] => Unit): Unit = { - io1.foreachScalar(f) - io2.foreachScalar(f) - } - override def allocateBuffers(length: Long, out: ArrayBuffer[ScheduledBuffer[_]])(implicit context: Context) = { - io1.allocateBuffers(length, out) - io2.allocateBuffers(length, out) - } - override def get(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int) = { - val v1 = io1.get(index, buffers, bufferOffset) - val v2 = io2.get(index, buffers, bufferOffset + io1.bufferCount) - (v1, v2) - } - - override def set(index: Long, buffers: Array[Pointer[_]], bufferOffset: Int, value: (T1, T2)) = { - val (v1, v2) = value - io1.set(index, buffers, bufferOffset, v1) - io2.set(index, buffers, bufferOffset + io1.bufferCount, v2) - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/main/scala/scalacl/package.scala b/libraries/ScalaCL3/src/main/scala/scalacl/package.scala deleted file mode 100644 index d092c2df0..000000000 --- a/libraries/ScalaCL3/src/main/scala/scalacl/package.scala +++ /dev/null @@ -1,18 +0,0 @@ -import com.nativelibs4java.opencl.CLMem - -import language.experimental.macros - -package object scalacl { - import impl._ - - implicit val intDataIO = IntDataIO - implicit val floatDataIO = FloatDataIO - implicit val booleanDataIO = BooleanDataIO - implicit def tuple2DataIO[T1 : Manifest : DataIO, T2 : Manifest : DataIO] = { - new Tuple2DataIO[T1, T2] - } - - def kernel(block: Unit)(implicit context: Context): Unit = macro KernelMacros.kernelImpl - - def task(block: Unit)(implicit context: Context): Unit = macro KernelMacros.taskImpl -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/test/scala/scalacl/KernelTest.scala b/libraries/ScalaCL3/src/test/scala/scalacl/KernelTest.scala deleted file mode 100644 index c14bf7b5f..000000000 --- a/libraries/ScalaCL3/src/test/scala/scalacl/KernelTest.scala +++ /dev/null @@ -1,25 +0,0 @@ -package scalacl -import impl._ - -import org.junit._ -import Assert._ - -class KernelTest { - @Test - def testEquality { - val sources = "aa" - same(new Kernel(1, sources), new Kernel(1, sources)) - diff(new Kernel(1, sources), new Kernel(2, sources), false) - diff(new Kernel(1, sources), new Kernel(1, "a" + ('b' - 1)), true) - } - - def same(a: AnyRef, b: AnyRef) = { - assertEquals(a.hashCode, b.hashCode) - assertEquals(a, b) - } - - def diff(a: AnyRef, b: AnyRef, sameHC: Boolean) = { - assertTrue(sameHC ^ (a.hashCode != b.hashCode)) - assertFalse(a.equals(b)) - } -} diff --git a/libraries/ScalaCL3/src/test/scala/scalacl/MatrixTest.scala b/libraries/ScalaCL3/src/test/scala/scalacl/MatrixTest.scala deleted file mode 100644 index df4450d05..000000000 --- a/libraries/ScalaCL3/src/test/scala/scalacl/MatrixTest.scala +++ /dev/null @@ -1,50 +0,0 @@ -package scalacl -import org.junit._ -import Assert._ - -class MatrixTest { - - case class Matrix(data: CLArray[Float], rows: Int, columns: Int)(implicit context: Context) { - def this(rows: Int, columns: Int)(implicit context: Context) = - this(new CLArray[Float](rows * columns), rows, columns) - def this(n: Int)(implicit context: Context) = - this(n, n) - } - - def mult(a: Matrix, b: Matrix, out: Matrix)(implicit context: Context) = - { - assert(a.columns == b.rows) - assert(a.rows == out.rows) - assert(b.columns == out.columns) - - kernel { - // This block will either be converted to an OpenCL kernel or cause compilation error - // It captures out.data, a.data and b.data - for (i <- 0 until a.rows; j <- 0 until b.columns) { - // TODO chain map and sum (to avoid creating a builder here !) - //out.data(i * out.columns + j) = (0 until a.columns).map(k => { - // a.data(i * a.columns + k) * b.data(k * b.columns + j) - //}).sum - var sum = 0f - for (k <- 0 until a.columns) { - sum += a.data(i * a.columns + k) * b.data(k * b.columns + j) - } - out.data(i * out.columns + j) = sum - } - } - } - - @Test - def testMatrix { - implicit val context = Context.best - - val n = 10 - val a = new Matrix(n) - val b = new Matrix(n) - val out = new Matrix(n) - - mult(a, b, out) - - println(out.data) - } -} \ No newline at end of file diff --git a/libraries/ScalaCL3/src/test/scala/scalacl/SimpleTest.scala b/libraries/ScalaCL3/src/test/scala/scalacl/SimpleTest.scala deleted file mode 100644 index c90629219..000000000 --- a/libraries/ScalaCL3/src/test/scala/scalacl/SimpleTest.scala +++ /dev/null @@ -1,73 +0,0 @@ -package scalacl - -import scalacl._ - -import com.nativelibs4java.opencl.CLMem -import scalacl.impl.Kernel -import scalacl.impl.CLFunction -import scalacl.impl.Captures - -import org.junit._ -import Assert._ - -/* - -kernel void f(global float*a, int dim1Offset, int dim1Step) { - int i = dim1Offset + global_index(0) * dim1Step; -} - - */ - -class SimpleTest { - @Test - def testSimpleArray { - implicit val context = Context.best - val factor = 20.5f - val trans = new CLFunction[Int, Int](v => (v * factor).toInt, new Kernel(1, """ -kernel void f(global const int* input, global int* output, float factor) { - int i = get_global_id(0); - if (i >= get_global_size(0)) - return; - output[i] = (int)(input[i] * factor); -} -"""), Captures(constants = Array(factor.asInstanceOf[AnyRef]))) - val pred = new CLFunction[Int, Boolean](v => v % 2 == 0, new Kernel(2, """ -kernel void f(global const int* input, global char* output) { - int i = get_global_id(0); - if (i >= get_global_size(0)) - return; - output[i] = input[i] % 2 == 0; -} -""")) - val values = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val a = CLArray[Int](values: _*) - //val a = new CLArray[Int](1000000) - println(a) - - def doit(print: Boolean, check: Boolean = false) { - val b = a.map(trans) - val fil = a.map(pred) - if (print) { - println(b) - println(fil) - } - if (check) { - assertEquals(values.map(trans).toSeq, b.toArray.toSeq) - } - // b.finish - context.queue.finish - b.release - } - - doit(true) - for (i <- 0 until 10) { - val start = System.nanoTime - doit(false) - val timeMicros = (System.nanoTime - start) / 1000 - println((timeMicros / 1000.0) + " milliseconds") - } - - val f = 0.2f - a.map(x => x * 2 * f) - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/TODO b/libraries/Scalaxy/TODO deleted file mode 100644 index c89410a90..000000000 --- a/libraries/Scalaxy/TODO +++ /dev/null @@ -1,34 +0,0 @@ -- add Immutable trait for case classes, and enforce it with the compiler plugin - -> error on var fields - -- coding guidelines : wrapping POJOs vs. pimps - -> write a guide - -- warn about dependent typing (?) - -> in some circumstances, can use reflection - -- warn about numeric code without azavea's specialized-numeric - -- warn if appears to switch (named-)argument names with same type or similar, suggest to use named args (hamming distance ? subword ?) : - def f(a: Int, b: Int) - f(b, a) - -> rationale: potential error - -- warn if any public method does not define return value - -> rationale: readability, early surprises - -- warn about Unit vals - -> rationale: confusing, favours tricks of returning Unit instead of value - -- warn about structural types / type refinements { def some: Unit } usage (call site ?) - -> rationale: speed - -- warn about weird (unicode) method names - -> rationale: readability - -- warn about non-local returns - -> rationale: speed issues - -- warn about intermediate collections (excluding views) - -> cf. ScalaCL - diff --git a/libraries/Scalaxy/build.sbt b/libraries/Scalaxy/build.sbt deleted file mode 100644 index c757fb23c..000000000 --- a/libraries/Scalaxy/build.sbt +++ /dev/null @@ -1,19 +0,0 @@ -name := "scalaxy" - -mainClass := Some("com.nativelibs4java.scalaxy.plugin.Compile") - -version := "0.3-SNAPSHOT" - -organization := "com.nativelibs4java" - -//scalaHome := Some(file("/Users/ochafik/bin/scala-2.9.0.final")) - -scalaVersion := "2.9.2" - -resolvers += "Sonatype OSS Snapshots Repository" at "http://oss.sonatype.org/content/groups/public/" - -libraryDependencies ++= Seq( - "org.scala-lang" % "scala-compiler" % "2.9.1", - "org.scala-lang" % "scala-library" % "2.9.1", - "com.novocode" % "junit-interface" % "0.5" % "test->default" -) diff --git a/libraries/Scalaxy/examples/Test.scala b/libraries/Scalaxy/examples/Test.scala deleted file mode 100644 index 155bbef1c..000000000 --- a/libraries/Scalaxy/examples/Test.scala +++ /dev/null @@ -1,8 +0,0 @@ -class Test { - //val a = Array(1, 2) ; - //val r: Array[Array[Int]] = a.map(xx => a.map(x => { def f = x ; f })) - //List(Array(1,2), Array(3,4)).toArray.map(_.toSeq).toSeq - //val a = Array(1, 2) ; val r: Array[(Int, Int)] = for (v <- a) yield (v, v) - //val r: IndexedSeq[Int] = (0 until 100).filter(_ != 50) - (0 until 100).filter(_ != 50) -} diff --git a/libraries/Scalaxy/instrumentation/InstrumentationTransformComponent.scala b/libraries/Scalaxy/instrumentation/InstrumentationTransformComponent.scala deleted file mode 100644 index 2664ca9f6..000000000 --- a/libraries/Scalaxy/instrumentation/InstrumentationTransformComponent.scala +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package scalacl.instrumentation - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} - -import scalacl._ - -/* -set SCALACL_INSTRUMENT=1 -mvn scala:run -DmainClass=scalacl.Compile "-DaddArgs=t.scala|-Xprint:scalacl-instrument" -*/ -object InstrumentationTransformComponent { - val runsAfter = List[String]( - "namer" - ) - val phaseName = "scalacl-instrument" -} -class InstrumentationTransformComponent(val global: Global, val options: ScalaCLPlugin.PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - with MiscMatchers - with TreeBuilders - with WithOptions -{ - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed, atOwner} // methods to type trees - - override val runsAfter = InstrumentationTransformComponent.runsAfter - override val phaseName = InstrumentationTransformComponent.phaseName - - val ids = new LogIds - val logClassName = "scalacl.instrumentation.Log" - val LogClass = definitions.getClass(logClassName) - val LogModule = definitions.getModule(logClassName) - val logApplyMethod = LogModule.tpe member "apply" - val logEnterMethod = LogClass.tpe member "enter" - val logExitMethod = LogClass.tpe member "exit" - - def newTransformer(unit: CompilationUnit) = new TypingTransformer(unit) { - var currentClassName: Name = null - - override def transform(tree: Tree): Tree = tree match { - case block: Block => - val pos = tree.pos - val logId = LogId(currentOwner.ownerChain.mkString(","), pos.source.file.path, pos.line, pos.offset.getOrElse(-1)) - msg(unit, pos, "instrumented " + logId) { - val id = ids(logId) - val logVar = newVariable(unit, "log", currentOwner, tree.pos, false, - Apply( - Select( - TypeTree(LogModule.tpe), - N("apply") - ).setSymbol(logApplyMethod).setType(LogClass.tpe), - Nil - ).setType(LogClass.tpe) - ) - typed { - treeCopy.Block( - tree, - List( - logVar.definition, - Apply( - typed { Select( // sym=method enter, sym.owner=class Log, sym.tpe=(id: Long)Unit, tpe=(id: Long)Unit, tpe.sym= - logVar(), - N("enter") - ).setSymbol(logEnterMethod) }, - List(newLong(id)) - ).setSymbol(logEnterMethod).setType(UnitClass.tpe) - ), - Try( - super.transform(block), - Nil, - Apply( - typed { Select( // sym=method enter, sym.owner=class Log, sym.tpe=(id: Long)Unit, tpe=(id: Long)Unit, tpe.sym= - logVar(), - N("exit") - ).setSymbol(logExitMethod) }, - List(newLong(id)) - ).setSymbol(logExitMethod).setType(UnitClass.tpe) - ) - ) - } - } - case _ => - super.transform(tree) - } - } -} diff --git a/libraries/Scalaxy/instrumentation/Log.scala b/libraries/Scalaxy/instrumentation/Log.scala deleted file mode 100644 index 15607f0be..000000000 --- a/libraries/Scalaxy/instrumentation/Log.scala +++ /dev/null @@ -1,76 +0,0 @@ -package scalacl.instrumentation - -import java.io._ -import scala.collection.mutable.ArrayBuffer -class Log { - private val arrays = new ArrayBuffer[Array[Long]] - private var currentArray: Array[Long] = _ - private val arraySize = 1024 - private var currentSize = 0 - - @inline private def nextArray = { - val a = new Array[Long](arraySize << 1) - currentArray = a - arrays += a - a - } - nextArray - - def enter(id: Long) = log(id, true) - def exit(id: Long) = log(id, false) - - @inline private def log(id: Long, isEnter: Boolean): Unit = { - if (currentSize >= arraySize) { - nextArray - } - val a = currentArray - val offset = currentSize << 1 - a(offset) = id - val t = System.nanoTime - a(offset + 1) = (if (isEnter) -t else t) - currentSize += 1 - } - - def dump(dir: File) { - val f = new File(dir, "thread-" + Thread.currentThread.getId) - println("Writing '" + f + "'...") - val out = new PrintStream(f) - def line(values: Any*) = out.println(values.mkString("\t")) - line("Id", "Nano Time") - try { - arrays.foreach(a => { - for (i <- 0 until (if (a == currentArray) currentSize else arraySize)) { - val offset = i << 1 - line(a(offset), a(offset + 1)) - } - }) - } finally { - out.close - } - } -} -object Log { - private val logs = new ArrayBuffer[Log] - private val local = new ThreadLocal[Log] { - override def initialValue = { - val log = new Log - logs synchronized { - logs += log - } - log - } - } - Runtime.getRuntime.addShutdownHook(new Thread { - override def run { - var dirProp = System.getProperty("scalacl.log.dir", System.getenv("SCALACL_LOG_DIR")) - if (dirProp == null) - dirProp = "logs" - - val dir = new File(dirProp) - dir.mkdirs - logs.foreach(_.dump(dir)) - println("Finished writing log dumps") - } - }) - def apply(): Log = local.get -} diff --git a/libraries/Scalaxy/instrumentation/LogIds.scala b/libraries/Scalaxy/instrumentation/LogIds.scala deleted file mode 100644 index af4e053bd..000000000 --- a/libraries/Scalaxy/instrumentation/LogIds.scala +++ /dev/null @@ -1,36 +0,0 @@ -package scalacl.instrumentation - -import java.io._ - -case class LogId(qualifiedName: String, source: String, line: Int, offset: Int) - -class LogIds { - import scala.collection.mutable.HashMap - private var nextId = 1L - private val ids = new HashMap[LogId, Long] - def apply(id: LogId) = ids.getOrElseUpdate(id, this synchronized { - val id = nextId - nextId += 1 - id - }) - Runtime.getRuntime.addShutdownHook(new Thread { - override def run { - var fileProp = System.getProperty("scalacl.log.ids.file", System.getenv("SCALACL_LOG_IDS_FILE")) - if (fileProp == null) - fileProp = "log.ids.properties" - - val file = new File(fileProp).getAbsoluteFile - file.getParentFile.mkdirs - val out = new PrintStream(file) - def line(values: Any*) = out.println(values.mkString("\t")) - line("Id", "Qualified Name", "Source File", "Line", "Offset") - try { - for ((logId, id) <- ids) - line(id, logId.qualifiedName, logId.source, logId.line, logId.offset) - } finally { - out.close - } - println("Finished writing log ids") - } - }) -} diff --git a/libraries/Scalaxy/out.txt b/libraries/Scalaxy/out.txt deleted file mode 100644 index 27fa09ac6..000000000 --- a/libraries/Scalaxy/out.txt +++ /dev/null @@ -1,2138 +0,0 @@ -[INFO] Scanning for projects... -[WARNING] -[WARNING] Some problems were encountered while building the effective model for com.nativelibs4java:scalace:jar:0.3-SNAPSHOT -[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ com.nativelibs4java:nativelibs4java-parent:1.7-SNAPSHOT, /Users/ochafik/github/nativelibs4java/libraries/pom.xml, line 153, column 12 -[WARNING] -[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. -[WARNING] -[WARNING] For this reason, future Maven versions might no longer support building such malformed projects. -[WARNING] -[INFO] -[INFO] ------------------------------------------------------------------------ -[INFO] Building Scalace 0.3-SNAPSHOT -[INFO] ------------------------------------------------------------------------ -[INFO] -[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ scalace --- -[INFO] Deleting /Users/ochafik/github/nativelibs4java/libraries/Scalace/target -[INFO] -[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ scalace --- -[INFO] -[INFO] --- maven-velocity-plugin:0.7-SNAPSHOT:generate (default) @ scalace --- -Velocity root path = /Users/ochafik/github/nativelibs4java/libraries/Scalace/src -[INFO] Found 1 files in '/Users/ochafik/github/nativelibs4java/libraries/Scalace/src/main/velocity'... -[INFO] Executing template 'scalac-plugin.xml'... -[INFO] Got properties : {project_name=scalace, project_version=0.3-SNAPSHOT} -[INFO] Got property : project_name = scalace -[INFO] Got property : project_version = 0.3-SNAPSHOT -Velocity root path = /Users/ochafik/github/nativelibs4java/libraries/Scalace/src -[INFO] Found 0 files in '/Users/ochafik/github/nativelibs4java/libraries/Scalace/src/test/velocity'... -[INFO] -[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ scalace --- -[INFO] Using 'UTF-8' encoding to copy filtered resources. -[INFO] skip non existing resourceDirectory /Users/ochafik/github/nativelibs4java/libraries/Scalace/src/main/resources -[INFO] -[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ scalace --- -[INFO] Nothing to compile - all classes are up to date -[INFO] -[INFO] --- maven-scala-plugin:2.9.1:compile (default) @ scalace --- -[ERROR] /Users/ochafik/github/nativelibs4java/libraries/Scalace/src/main/java -[ERROR] /Users/ochafik/github/nativelibs4java/libraries/Scalace/target/generated-sources/main -[ERROR] /Users/ochafik/github/nativelibs4java/libraries/Scalace/src/main/scala -[INFO] Compiling 24 source files to /Users/ochafik/github/nativelibs4java/libraries/Scalace/target/classes -[WARNING] warning: there were 9 deprecation warnings; re-run with -deprecation for details -[WARNING] warning: there were 8 unchecked warnings; re-run with -unchecked for details -[WARNING] two warnings found -[INFO] -[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ scalace --- -[INFO] Using 'UTF-8' encoding to copy filtered resources. -[INFO] Copying 1 resource -[INFO] -[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ scalace --- -[INFO] No sources to compile -[INFO] -[INFO] --- maven-scala-plugin:2.9.1:testCompile (default) @ scalace --- -[ERROR] /Users/ochafik/github/nativelibs4java/libraries/Scalace/src/test/java -[ERROR] /Users/ochafik/github/nativelibs4java/libraries/Scalace/src/test/java/../scala -[INFO] Compiling 19 source files to /Users/ochafik/github/nativelibs4java/libraries/Scalace/target/test-classes -[WARNING] warning: there were 3 deprecation warnings; re-run with -deprecation for details -[WARNING] one warning found -[INFO] -[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ scalace --- -[INFO] Surefire report directory: /Users/ochafik/github/nativelibs4java/libraries/Scalace/target/surefire-reports - -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running com.nativelibs4java.scalace.test.AllOrSome2WhileTest -Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 12.049 sec -Running com.nativelibs4java.scalace.test.ArrayChainedPerformanceTest -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 2, cold] OK (2.695214105793451x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 2, warm] OK (1.7841409691629957x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 10, cold] OK (1.8837209302325582x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 10, warm] OK (1.9671361502347418x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 1000, cold] OK (7.628571428571429x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 1000, warm] OK (3.466666666666667x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 100000, cold] OK (13.374662031672461x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 100000, warm] OK (48.5218253968254x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 2, cold] OK (7.153543307086614x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 2, warm] OK (1.7107843137254901x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 10, cold] OK (1.814569536423841x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 10, warm] OK (2.1908396946564888x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 1000, cold] OK (5.002873563218391x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 1000, warm] OK (4.571428571428571x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 100000, cold] OK (13.839403247038174x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 100000, warm] OK (53.53061224489796x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 2, cold] OK (3.4975728155339807x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 2, warm] OK (2.0961538461538463x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 10, cold] OK (1.4457831325301205x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 10, warm] OK (2.18x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 1000, cold] OK (2.379204892966361x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 1000, warm] OK (2.763888888888889x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 100000, cold] OK (3.025333064190553x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 100000, warm] OK (9.126965408805031x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 2, cold] OK (3.9582172701949863x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 2, warm] OK (2.1094890510948905x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 10, cold] OK (1.212686567164179x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 10, warm] OK (2.6869565217391305x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 1000, cold] OK (2.7269565217391305x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 1000, warm] OK (4.026041666666667x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 100000, cold] OK (3.3425103852732754x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 100000, warm] OK (9.484994640943194x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 2, cold] OK (5.114197530864198x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 2, warm] OK (2.1714285714285713x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 10, cold] OK (1.7385892116182573x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 10, warm] OK (2.5714285714285716x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 1000, cold] OK (3.2323580034423407x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 1000, warm] OK (3.9702380952380953x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 100000, cold] OK (5.289802681126676x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 100000, warm] OK (24.82982616651418x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 2, cold] OK (5.185185185185185x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 2, warm] OK (1.905109489051095x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 10, cold] OK (1.7276595744680852x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 10, warm] OK (2.360655737704918x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 1000, cold] OK (2.924646781789639x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 1000, warm] OK (4.591240875912408x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 100000, cold] OK (4.733997155049787x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 100000, warm] OK (15.413480885311872x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 2, cold] OK (9.69811320754717x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 2, warm] OK (3.15702479338843x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 10, cold] OK (1.8564593301435406x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 10, warm] OK (1.702127659574468x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 1000, cold] OK (3.5427046263345194x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 1000, warm] OK (3.92258064516129x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 100000, cold] OK (7.603458676855017x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 100000, warm] OK (18.738072054527752x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 2, cold] OK (5.2585227272727275x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 2, warm] OK (3.212121212121212x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 10, cold] OK (1.5x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 10, warm] OK (2.5405405405405403x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 1000, cold] OK (5.15727002967359x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 1000, warm] OK (4.170542635658915x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 100000, cold] OK (9.97269100951212x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 100000, warm] OK (25.675233644859812x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 2, cold] OK (5.672727272727273x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 2, warm] OK (2.5213675213675213x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 10, cold] OK (1.2982456140350878x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 10, warm] OK (1.7857142857142858x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 1000, cold] OK (2.8231827111984282x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 1000, warm] OK (5.380165289256198x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 100000, cold] OK (3.2520333791063694x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 100000, warm] OK (13.539480949751518x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 2, cold] OK (7.117154811715481x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 2, warm] OK (1.64375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 10, cold] OK (1.902061855670103x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 10, warm] OK (1.704225352112676x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 1000, cold] OK (3.2169625246548326x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 1000, warm] OK (4.088757396449704x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 100000, cold] OK (6.458161582852432x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 100000, warm] OK (27.718074656188605x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 2, cold] OK (5.584375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 2, warm] OK (1.9435483870967742x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 10, cold] OK (1.425x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 10, warm] OK (1.7925925925925925x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 1000, cold] OK (2.8945454545454545x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 1000, warm] OK (4.141935483870967x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 100000, cold] OK (3.898738918716444x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 100000, warm] OK (11.867165575304023x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 2, cold] OK (6.404651162790698x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 2, warm] OK (1.7884615384615385x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 10, cold] OK (2.0789473684210527x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 10, warm] OK (2.020979020979021x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 1000, cold] OK (3.871900826446281x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 1000, warm] OK (3.776315789473684x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 100000, cold] OK (7.49133924799324x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 100000, warm] OK (20.86907020872865x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 2, cold] OK (8.091743119266056x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 2, warm] OK (1.9555555555555555x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 10, cold] OK (1.7357512953367875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 10, warm] OK (1.9130434782608696x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 1000, cold] OK (3.5806451612903225x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 1000, warm] OK (4.7407407407407405x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 100000, cold] OK (6.959973166368515x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 100000, warm] OK (23.50873786407767x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 2, cold] OK (7.5625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 2, warm] OK (1.9647887323943662x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 10, cold] OK (1.813953488372093x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 10, warm] OK (2.625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 1000, cold] OK (3.892857142857143x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 1000, warm] OK (5.341269841269841x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 100000, cold] OK (7.928817451205511x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 100000, warm] OK (25.026258205689278x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 2, cold] OK (8.71875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 2, warm] OK (2.0956521739130434x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 10, cold] OK (2.027027027027027x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 10, warm] OK (2.115107913669065x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 1000, cold] OK (3.5135135135135136x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 1000, warm] OK (3.8366013071895426x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 100000, cold] OK (5.959052978847273x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 100000, warm] OK (27.17031070195627x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 2, cold] OK (5.224806201550388x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 2, warm] OK (2.046153846153846x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 10, cold] OK (1.565217391304348x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 10, warm] OK (2.4473684210526314x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 1000, cold] OK (3.3098106712564546x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 1000, warm] OK (5.107913669064748x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 100000, cold] OK (4.713623612635687x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 100000, warm] OK (13.80908626850434x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 2, cold] OK (0.9608750525872949x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 2, warm] OK (1.43801652892562x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 10, cold] OK (1.158974358974359x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 10, warm] OK (1.1258278145695364x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 1000, cold] OK (1.4835377663008393x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 1000, warm] OK (1.5670731707317074x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 100000, cold] ERROR: only 0.8986917793257445x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 100000, warm] OK (2.3353966070609813x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 2, cold] OK (9.567164179104477x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 2, warm] OK (1.8968253968253967x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.702020202020202x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.8699186991869918x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 1000, cold] OK (4.508333333333334x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 1000, warm] OK (3.6706586826347305x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 100000, cold] OK (6.389227642276423x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 100000, warm] OK (22.87869822485207x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 2, cold] OK (1.6115173674588665x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 2, warm] OK (1.8211920529801324x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 10, cold] OK (1.226148409893993x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 10, warm] OK (1.5870967741935484x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 1000, cold] OK (1.6785046728971962x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 1000, warm] OK (2.865979381443299x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 100000, cold] OK (1.337447033898305x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 100000, warm] OK (5.516573176950535x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 2, cold] OK (7.493449781659389x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.8503937007874016x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 10, cold] OK (1.8663793103448276x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 10, warm] OK (2.053030303030303x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 1000, cold] OK (3.113680154142582x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 1000, warm] OK (4.669064748201439x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 100000, cold] OK (6.340385421030582x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 100000, warm] OK (30.269377382465056x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 2, cold] OK (1.6957383548067393x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 2, warm] OK (1.375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 10, cold] OK (1.0466472303206997x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 10, warm] OK (1.5917159763313609x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 1000, cold] OK (1.84x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 1000, warm] OK (2.105839416058394x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 100000, cold] OK (2.6387462558836114x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 100000, warm] OK (5.195060483870968x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 2, cold] OK (2.898843930635838x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 2, warm] OK (1.1895424836601307x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 10, cold] OK (1.0093896713615023x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 10, warm] OK (1.272108843537415x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 1000, cold] OK (1.46677471636953x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 1000, warm] OK (2.4496644295302015x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 100000, cold] OK (1.7560933147632312x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 100000, warm] OK (9.077201447527141x faster, expected > 0.95x) - -Tests run: 22, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 237.764 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.ArrayForeach2WhileTest -Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.727 sec -Running com.nativelibs4java.scalace.test.ArrayMap2WhileTest -Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 19.769 sec -Running com.nativelibs4java.scalace.test.ArrayPerformanceTest -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 2, cold] OK (5.262886597938144x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 2, warm] OK (1.6048387096774193x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 10, cold] OK (1.5904255319148937x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 10, warm] OK (1.2658227848101267x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 1000, cold] OK (2.966867469879518x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 1000, warm] OK (1.8591549295774648x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 100000, cold] OK (2.5949470252648736x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForall, n = 100000, warm] OK (13.109137055837563x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 2, cold] OK (4.744186046511628x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 2, warm] OK (2.4315068493150687x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 10, cold] OK (1.4522613065326633x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 10, warm] OK (1.9444444444444444x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 1000, cold] OK (2.6628895184135977x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 1000, warm] OK (2.906474820143885x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 100000, cold] OK (2.2724888539207972x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleExists, n = 100000, warm] OK (11.405825242718446x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 2, cold] OK (1.1306990881458967x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 2, warm] OK (1.2713178294573644x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 10, cold] OK (1.1014492753623188x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 10, warm] OK (1.7241379310344827x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 1000, cold] ERROR: only 0.5845410628019324x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 1000, warm] OK (1.4014598540145986x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 100000, cold] ERROR: only 0.15493683939159578x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToArray, n = 100000, warm] ERROR: only 0.20473372781065088x faster (expected >= 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 2, cold] OK (1.099041533546326x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 2, warm] OK (1.3307692307692307x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 10, cold] ERROR: only 0.9304347826086956x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 10, warm] OK (1.2074074074074075x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 1000, cold] ERROR: only 0.7145015105740181x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 1000, warm] OK (1.3674242424242424x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 100000, cold] OK (1.3048114764504253x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleToList, n = 100000, warm] OK (2.727476530755219x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 2, cold] OK (2.8287461773700304x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 2, warm] OK (1.546218487394958x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 10, cold] OK (1.1839622641509433x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 10, warm] OK (1.609375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 1000, cold] OK (1.8298969072164948x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 1000, warm] OK (3.287769784172662x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 100000, cold] OK (1.8439256376999569x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilter, n = 100000, warm] OK (6.8897097625329815x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 2, cold] OK (3.197278911564626x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 2, warm] OK (1.4696969696969697x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 10, cold] OK (1.2876712328767124x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 10, warm] OK (1.5528455284552845x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 1000, cold] OK (1.926905132192846x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 1000, warm] OK (3.456953642384106x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 100000, cold] OK (2.2247448979591837x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFilterNot, n = 100000, warm] OK (7.843455497382199x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 2, cold] OK (4.962790697674419x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 2, warm] OK (1.534351145038168x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 10, cold] OK (1.4232804232804233x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 10, warm] OK (1.4736842105263157x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 1000, cold] OK (3.7724867724867726x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 1000, warm] OK (3.096296296296296x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 100000, cold] OK (3.138680203045685x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleCount, n = 100000, warm] OK (12.639285714285714x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 2, cold] OK (2.67027027027027x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 2, warm] OK (1.803030303030303x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 10, cold] OK (1.3377777777777777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 10, warm] OK (1.7058823529411764x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 1000, cold] OK (1.5819672131147542x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 1000, warm] OK (2.8962962962962964x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 100000, cold] OK (2.141542002301496x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleTakeWhile, n = 100000, warm] OK (5.695724597445864x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 2, cold] OK (3.207547169811321x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 2, warm] OK (1.8045112781954886x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 10, cold] OK (1.3623853211009174x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 10, warm] OK (1.624113475177305x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 1000, cold] OK (1.4375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 1000, warm] OK (3.097902097902098x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 100000, cold] OK (1.7793696275071633x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleDropWhile, n = 100000, warm] OK (5.89043381535039x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 2, cold] OK (5.619289340101523x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 2, warm] OK (1.4785714285714286x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 10, cold] OK (1.2901554404145077x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 10, warm] OK (1.4661654135338347x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 1000, cold] OK (2.0975103734439835x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 1000, warm] OK (2.2125984251968505x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 100000, cold] OK (2.976881872004511x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleForeach, n = 100000, warm] OK (15.0x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 2, cold] OK (2.8369905956112853x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 2, warm] OK (1.381294964028777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 10, cold] OK (1.47x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 10, warm] OK (1.6343283582089552x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 1000, cold] OK (2.3707865168539324x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 1000, warm] OK (4.050420168067227x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 100000, cold] OK (3.4009122006841506x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMap, n = 100000, warm] OK (14.85385500575374x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 2, cold] OK (1.861904761904762x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 2, warm] OK (1.3636363636363635x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 10, cold] OK (1.24x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 10, warm] OK (1.4878048780487805x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 1000, cold] OK (1.464705882352941x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 1000, warm] OK (2.7480916030534353x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 100000, cold] OK (2.3408646534868565x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleSum, n = 100000, warm] OK (17.940630797773654x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 2, cold] OK (2.0765027322404372x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 2, warm] OK (1.5258620689655173x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 10, cold] OK (1.198019801980198x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 10, warm] OK (1.5446428571428572x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 1000, cold] ERROR: only 0.9485981308411215x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 1000, warm] OK (2.7132867132867133x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 100000, cold] OK (2.321402304486394x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleProduct, n = 100000, warm] OK (15.894480519480519x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 2, cold] OK (1.7096774193548387x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 2, warm] OK (1.5572519083969465x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 10, cold] OK (1.3112244897959184x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 10, warm] OK (1.507462686567164x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 1000, cold] OK (1.3154761904761905x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 1000, warm] OK (2.12x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 100000, cold] OK (1.9474504564684925x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMin, n = 100000, warm] OK (13.4992x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 2, cold] OK (1.7815533980582525x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 2, warm] OK (1.4924242424242424x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 10, cold] OK (1.0138248847926268x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 10, warm] OK (2.3576642335766422x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 1000, cold] OK (1.0694444444444444x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 1000, warm] OK (3.116788321167883x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 100000, cold] OK (1.8241525423728813x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleMax, n = 100000, warm] OK (14.739208633093526x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 2, cold] OK (3.731707317073171x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 2, warm] OK (2.1545454545454548x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 10, cold] OK (1.6132075471698113x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 10, warm] OK (1.7364341085271318x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 1000, cold] OK (2.9628865979381445x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 1000, warm] OK (2.610294117647059x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 100000, cold] OK (4.311451342281879x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanLeft, n = 100000, warm] OK (15.152912621359222x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 2, cold] OK (1.389413988657845x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 2, warm] OK (1.0494699646643109x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 10, cold] OK (1.0x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 10, warm] OK (1.053231939163498x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 1000, cold] OK (0.9657072872014697x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 1000, warm] ERROR: only 0.9408866995073891x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 100000, cold] ERROR: only 0.7776826755428753x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleScanRight, n = 100000, warm] OK (0.9967305193444272x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 2, cold] OK (4.3053097345132745x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 2, warm] OK (1.328x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.1616161616161615x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.421875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 1000, cold] OK (1.8727272727272728x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 1000, warm] OK (2.422818791946309x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 100000, cold] OK (3.1990790899241603x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldLeft, n = 100000, warm] OK (16.163120567375888x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 2, cold] OK (0.9602510460251046x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 2, warm] OK (1.0056179775280898x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 10, cold] OK (1.0074906367041199x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 10, warm] OK (0.958974358974359x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 1000, cold] ERROR: only 0.9458483754512635x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 1000, warm] OK (1.0425531914893618x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 100000, cold] ERROR: only 0.9454238106737503x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleFoldRight, n = 100000, warm] ERROR: only 0.9483644228169775x faster (expected >= 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 2, cold] OK (5.414364640883978x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.362962962962963x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 10, cold] OK (1.3798882681564246x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 10, warm] OK (1.4409448818897639x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 1000, cold] OK (2.2686915887850465x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 1000, warm] OK (3.0763358778625953x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 100000, cold] OK (2.904066985645933x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceLeft, n = 100000, warm] OK (17.512014787430683x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 2, cold] OK (0.9616122840690979x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 2, warm] ERROR: only 0.9052631578947369x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 10, cold] OK (1.0076923076923077x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 10, warm] OK (1.1412429378531073x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 1000, cold] ERROR: only 0.8518057285180572x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 1000, warm] ERROR: only 0.8952702702702703x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 100000, cold] OK (1.0053651593123836x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleReduceRight, n = 100000, warm] OK (0.980715221868564x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 2, cold] OK (2.7663817663817665x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 2, warm] OK (1.147887323943662x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 10, cold] OK (1.1473214285714286x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 10, warm] OK (1.2810457516339868x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 1000, cold] OK (2.1049723756906076x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 1000, warm] OK (2.6466666666666665x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 100000, cold] OK (1.4524339360222531x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ArrayPerformanceTest.simpleArrayTabulate, n = 100000, warm] OK (9.34610630407911x faster, expected > 0.95x) - -Tests run: 22, Failures: 6, Errors: 0, Skipped: 0, Time elapsed: 246.593 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.Filter2WhileTest -EXPECTED : - Compiled from "simplePrimitiveArrayFilter.scala" - public class simplePrimitiveArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: getstatic ; //Field scala/Array$.MODULE$:Lscala/Array$; - 3: iconst_1 - 4: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 7: iconst_3 - 8: newarray int - 10: dup - 11: iconst_0 - 12: iconst_2 - 13: iastore - 14: dup - 15: iconst_1 - 16: iconst_3 - 17: iastore - 18: dup - 19: iconst_2 - 20: iconst_4 - 21: iastore - 22: invokevirtual ; //Method scala/Predef$.wrapIntArray:([I)Lscala/collection/mutable/WrappedArray; - 25: invokevirtual ; //Method scala/Array$.apply:(ILscala/collection/Seq;)[I - 28: astore_1 - 29: aload_1 - 30: astore_3 - 31: aload_3 - 32: arraylength - 33: istore_2 - 34: iconst_0 - 35: istore 5 - 37: new ; //class scala/collection/mutable/ArrayBuilder$ofInt - 40: dup - 41: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofInt."":()V - 44: astore 6 - 46: iload 5 - 48: iload_2 - 49: if_icmpge 87 - 52: aload_3 - 53: iload 5 - 55: iaload - 56: istore 4 - 58: iload 4 - 60: iconst_0 - 61: if_icmpeq 74 - 64: aload 6 - 66: iload 4 - 68: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.$plus$eq:(I)Lscala/collection/mutable/ArrayBuilder$ofInt; - 71: goto 77 - 74: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 77: pop - 78: iload 5 - 80: iconst_1 - 81: iadd - 82: istore 5 - 84: goto 46 - 87: aload 6 - 89: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.result:()[I - 92: pop - 93: return - - public simplePrimitiveArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "simplePrimitiveArrayFilter.scala" - public class simplePrimitiveArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: getstatic ; //Field scala/Array$.MODULE$:Lscala/Array$; - 3: iconst_1 - 4: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 7: iconst_3 - 8: newarray int - 10: dup - 11: iconst_0 - 12: iconst_2 - 13: iastore - 14: dup - 15: iconst_1 - 16: iconst_3 - 17: iastore - 18: dup - 19: iconst_2 - 20: iconst_4 - 21: iastore - 22: invokevirtual ; //Method scala/Predef$.wrapIntArray:([I)Lscala/collection/mutable/WrappedArray; - 25: invokevirtual ; //Method scala/Array$.apply:(ILscala/collection/Seq;)[I - 28: astore_1 - 29: aload_1 - 30: astore_3 - 31: aload_3 - 32: arraylength - 33: istore_2 - 34: iconst_0 - 35: istore 5 - 37: new ; //class scala/collection/mutable/ArrayBuilder$ofInt - 40: dup - 41: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofInt."":()V - 44: astore 6 - 46: iload 5 - 48: iload_2 - 49: if_icmpge 81 - 52: aload_3 - 53: iload 5 - 55: iaload - 56: istore 4 - 58: iload 4 - 60: iconst_0 - 61: if_icmpeq 72 - 64: aload 6 - 66: iload 4 - 68: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.$plus$eq:(I)Lscala/collection/mutable/ArrayBuilder$ofInt; - 71: pop - 72: iload 5 - 74: iconst_1 - 75: iadd - 76: istore 5 - 78: goto 46 - 81: aload 6 - 83: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.result:()[I - 86: pop - 87: return - - public simplePrimitiveArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -EXPECTED : - Compiled from "simpleRefArrayFilter.scala" - public class simpleRefArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_4 - 1: anewarray ; //class java/lang/String - 4: dup - 5: iconst_0 - 6: ldc ; //String 1 - 8: aastore - 9: dup - 10: iconst_1 - 11: ldc ; //String 2 - 13: aastore - 14: dup - 15: iconst_2 - 16: ldc ; //String 3 - 18: aastore - 19: dup - 20: iconst_3 - 21: ldc ; //String 4 - 23: aastore - 24: checkcast ; //class "[Ljava/lang/Object;" - 27: checkcast ; //class "[Ljava/lang/String;" - 30: astore_1 - 31: aload_1 - 32: astore_3 - 33: aload_3 - 34: arraylength - 35: istore_2 - 36: iconst_0 - 37: istore 5 - 39: new ; //class scala/collection/mutable/ArrayBuilder$ofRef - 42: dup - 43: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 46: ldc ; //class java/lang/String - 48: invokevirtual ; //Method scala/reflect/Manifest$.classType:(Ljava/lang/Class;)Lscala/reflect/Manifest; - 51: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofRef."":(Lscala/reflect/Manifest;)V - 54: astore 6 - 56: iload 5 - 58: iload_2 - 59: if_icmpge 114 - 62: aload_3 - 63: iload 5 - 65: aaload - 66: astore 4 - 68: aload 4 - 70: dup - 71: ifnonnull 83 - 74: pop - 75: ldc ; //String - 77: ifnull 91 - 80: goto 97 - 83: ldc ; //String - 85: invokevirtual ; //Method java/lang/Object.equals:(Ljava/lang/Object;)Z - 88: ifeq 97 - 91: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 94: goto 104 - 97: aload 6 - 99: aload 4 - 101: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 104: pop - 105: iload 5 - 107: iconst_1 - 108: iadd - 109: istore 5 - 111: goto 56 - 114: aload 6 - 116: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 119: pop - 120: return - - public simpleRefArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "simpleRefArrayFilter.scala" - public class simpleRefArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_4 - 1: anewarray ; //class java/lang/String - 4: dup - 5: iconst_0 - 6: ldc ; //String 1 - 8: aastore - 9: dup - 10: iconst_1 - 11: ldc ; //String 2 - 13: aastore - 14: dup - 15: iconst_2 - 16: ldc ; //String 3 - 18: aastore - 19: dup - 20: iconst_3 - 21: ldc ; //String 4 - 23: aastore - 24: checkcast ; //class "[Ljava/lang/Object;" - 27: checkcast ; //class "[Ljava/lang/String;" - 30: astore_1 - 31: aload_1 - 32: astore_3 - 33: aload_3 - 34: arraylength - 35: istore_2 - 36: iconst_0 - 37: istore 5 - 39: new ; //class scala/collection/mutable/ArrayBuilder$ofRef - 42: dup - 43: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 46: ldc ; //class java/lang/String - 48: invokevirtual ; //Method scala/reflect/Manifest$.classType:(Ljava/lang/Class;)Lscala/reflect/Manifest; - 51: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofRef."":(Lscala/reflect/Manifest;)V - 54: astore 6 - 56: iload 5 - 58: iload_2 - 59: if_icmpge 108 - 62: aload_3 - 63: iload 5 - 65: aaload - 66: astore 4 - 68: aload 4 - 70: dup - 71: ifnonnull 83 - 74: pop - 75: ldc ; //String - 77: ifnull 99 - 80: goto 91 - 83: ldc ; //String - 85: invokevirtual ; //Method java/lang/Object.equals:(Ljava/lang/Object;)Z - 88: ifne 99 - 91: aload 6 - 93: aload 4 - 95: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 98: pop - 99: iload 5 - 101: iconst_1 - 102: iadd - 103: istore 5 - 105: goto 56 - 108: aload 6 - 110: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 113: pop - 114: return - - public simpleRefArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -EXPECTED : - Compiled from "tupleArrayFilter.scala" - public class tupleArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_3 - 1: anewarray ; //class scala/Tuple2 - 4: dup - 5: iconst_0 - 6: new ; //class scala/Tuple2$mcII$sp - 9: dup - 10: iconst_1 - 11: iconst_2 - 12: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 15: aastore - 16: dup - 17: iconst_1 - 18: new ; //class scala/Tuple2$mcII$sp - 21: dup - 22: bipush 10 - 24: bipush 20 - 26: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 29: aastore - 30: dup - 31: iconst_2 - 32: new ; //class scala/Tuple2$mcII$sp - 35: dup - 36: bipush 100 - 38: sipush 200 - 41: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 44: aastore - 45: checkcast ; //class "[Ljava/lang/Object;" - 48: checkcast ; //class "[Lscala/Tuple2;" - 51: astore_1 - 52: aload_1 - 53: astore_3 - 54: aload_3 - 55: arraylength - 56: istore_2 - 57: iconst_0 - 58: istore 5 - 60: new ; //class scala/collection/mutable/ArrayBuilder$ofRef - 63: dup - 64: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 67: ldc ; //class scala/Tuple2 - 69: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 72: invokevirtual ; //Method scala/reflect/Manifest$.Int:()Lscala/reflect/AnyValManifest; - 75: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 78: iconst_1 - 79: anewarray ; //class scala/reflect/OptManifest - 82: dup - 83: iconst_0 - 84: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 87: invokevirtual ; //Method scala/reflect/Manifest$.Int:()Lscala/reflect/AnyValManifest; - 90: aastore - 91: checkcast ; //class "[Ljava/lang/Object;" - 94: invokevirtual ; //Method scala/Predef$.wrapRefArray:([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray; - 97: invokevirtual ; //Method scala/reflect/Manifest$.classType:(Ljava/lang/Class;Lscala/reflect/OptManifest;Lscala/collection/Seq;)Lscala/reflect/Manifest; - 100: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofRef."":(Lscala/reflect/Manifest;)V - 103: astore 6 - 105: iload 5 - 107: iload_2 - 108: if_icmpge 150 - 111: aload_3 - 112: iload 5 - 114: aaload - 115: astore 4 - 117: aload 4 - 119: invokevirtual ; //Method scala/Tuple2._1$mcI$sp:()I - 122: bipush 30 - 124: if_icmpge 137 - 127: aload 6 - 129: aload 4 - 131: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 134: goto 140 - 137: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 140: pop - 141: iload 5 - 143: iconst_1 - 144: iadd - 145: istore 5 - 147: goto 105 - 150: aload 6 - 152: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 155: pop - 156: return - - public tupleArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "tupleArrayFilter.scala" - public class tupleArrayFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_3 - 1: anewarray ; //class scala/Tuple2 - 4: dup - 5: iconst_0 - 6: new ; //class scala/Tuple2$mcII$sp - 9: dup - 10: iconst_1 - 11: iconst_2 - 12: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 15: aastore - 16: dup - 17: iconst_1 - 18: new ; //class scala/Tuple2$mcII$sp - 21: dup - 22: bipush 10 - 24: bipush 20 - 26: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 29: aastore - 30: dup - 31: iconst_2 - 32: new ; //class scala/Tuple2$mcII$sp - 35: dup - 36: bipush 100 - 38: sipush 200 - 41: invokespecial ; //Method scala/Tuple2$mcII$sp."":(II)V - 44: aastore - 45: checkcast ; //class "[Ljava/lang/Object;" - 48: checkcast ; //class "[Lscala/Tuple2;" - 51: astore_1 - 52: aload_1 - 53: astore_3 - 54: aload_3 - 55: arraylength - 56: istore_2 - 57: iconst_0 - 58: istore 5 - 60: new ; //class scala/collection/mutable/ArrayBuilder$ofRef - 63: dup - 64: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 67: ldc ; //class scala/Tuple2 - 69: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 72: invokevirtual ; //Method scala/reflect/Manifest$.Int:()Lscala/reflect/AnyValManifest; - 75: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 78: iconst_1 - 79: anewarray ; //class scala/reflect/OptManifest - 82: dup - 83: iconst_0 - 84: getstatic ; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$; - 87: invokevirtual ; //Method scala/reflect/Manifest$.Int:()Lscala/reflect/AnyValManifest; - 90: aastore - 91: checkcast ; //class "[Ljava/lang/Object;" - 94: invokevirtual ; //Method scala/Predef$.wrapRefArray:([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray; - 97: invokevirtual ; //Method scala/reflect/Manifest$.classType:(Ljava/lang/Class;Lscala/reflect/OptManifest;Lscala/collection/Seq;)Lscala/reflect/Manifest; - 100: invokespecial ; //Method scala/collection/mutable/ArrayBuilder$ofRef."":(Lscala/reflect/Manifest;)V - 103: astore 6 - 105: iload 5 - 107: iload_2 - 108: if_icmpge 144 - 111: aload_3 - 112: iload 5 - 114: aaload - 115: astore 4 - 117: aload 4 - 119: invokevirtual ; //Method scala/Tuple2._1$mcI$sp:()I - 122: bipush 30 - 124: if_icmpge 135 - 127: aload 6 - 129: aload 4 - 131: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 134: pop - 135: iload 5 - 137: iconst_1 - 138: iadd - 139: istore 5 - 141: goto 105 - 144: aload 6 - 146: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 149: pop - 150: return - - public tupleArrayFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -Tests run: 4, Failures: 3, Errors: 0, Skipped: 0, Time elapsed: 4.527 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.Fold2WhileTest -EXPECTED : - Compiled from "simpleFoldRight.scala" - public class simpleFoldRight extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: bipush 10 - 2: newarray double - 4: astore_1 - 5: aload_1 - 6: astore_2 - 7: aload_2 - 8: arraylength - 9: istore_3 - 10: iload_3 - 11: istore 4 - 13: iload 4 - 15: iconst_0 - 16: if_icmple 28 - 19: iload 4 - 21: iconst_1 - 22: isub - 23: istore 4 - 25: goto 13 - 28: return - - public simpleFoldRight(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "simpleFoldRight.scala" - public class simpleFoldRight extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: bipush 10 - 2: newarray double - 4: astore_1 - 5: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 8: aload_1 - 9: invokevirtual ; //Method scala/Predef$.doubleArrayOps:([D)Lscala/collection/mutable/ArrayOps; - 12: dconst_0 - 13: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToDouble:(D)Ljava/lang/Double; - 16: new ; //class simpleFoldRight$$anonfun$1 - 19: dup - 20: aload_0 - 21: invokespecial ; //Method simpleFoldRight$$anonfun$1."":(LsimpleFoldRight;)V - 24: invokeinterface , 3; //InterfaceMethod scala/collection/IndexedSeqOptimized.foldRight:(Ljava/lang/Object;Lscala/Function2;)Ljava/lang/Object; - 29: pop - 30: return - - public simpleFoldRight(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 3.032 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.IntRangeForeach2WhileTest -EXPECTED : - Compiled from "simpleRangeFilter.scala" - public class simpleRangeFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_0 - 1: istore_2 - 2: new ; //class scala/collection/immutable/VectorBuilder - 5: dup - 6: invokespecial ; //Method scala/collection/immutable/VectorBuilder."":()V - 9: astore_3 - 10: iload_2 - 11: bipush 100 - 13: if_icmpge 46 - 16: iload_2 - 17: istore_1 - 18: iload_1 - 19: bipush 50 - 21: if_icmpeq 35 - 24: aload_3 - 25: iload_1 - 26: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer; - 29: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.$plus$eq:(Ljava/lang/Object;)Lscala/collection/immutable/VectorBuilder; - 32: goto 38 - 35: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 38: pop - 39: iload_2 - 40: iconst_1 - 41: iadd - 42: istore_2 - 43: goto 10 - 46: aload_3 - 47: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.result:()Lscala/collection/immutable/Vector; - 50: pop - 51: return - - public simpleRangeFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "simpleRangeFilter.scala" - public class simpleRangeFilter extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: iconst_0 - 1: istore_2 - 2: new ; //class scala/collection/immutable/VectorBuilder - 5: dup - 6: invokespecial ; //Method scala/collection/immutable/VectorBuilder."":()V - 9: astore_3 - 10: iload_2 - 11: bipush 100 - 13: if_icmpge 40 - 16: iload_2 - 17: istore_1 - 18: iload_1 - 19: bipush 50 - 21: if_icmpeq 33 - 24: aload_3 - 25: iload_1 - 26: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer; - 29: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.$plus$eq:(Ljava/lang/Object;)Lscala/collection/immutable/VectorBuilder; - 32: pop - 33: iload_2 - 34: iconst_1 - 35: iadd - 36: istore_2 - 37: goto 10 - 40: aload_3 - 41: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.result:()Lscala/collection/immutable/Vector; - 44: pop - 45: return - - public simpleRangeFilter(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -Tests run: 11, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 18.569 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.ListChainedPerformanceTest -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 2, cold] OK (5.501587301587302x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 2, warm] ERROR: only 0.6036036036036037x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 10, cold] OK (1.123456790123457x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 10, warm] OK (1.152542372881356x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 1000, cold] OK (2.734653465346535x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 1000, warm] OK (2.8609271523178808x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 100000, cold] OK (3.459527824620573x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 100000, warm] OK (10.59349593495935x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 2, cold] OK (5.65886287625418x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 2, warm] OK (1.3986013986013985x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 10, cold] OK (1.1891891891891893x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 10, warm] OK (1.616x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 1000, cold] OK (2.633744855967078x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 1000, warm] OK (3.265151515151515x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 100000, cold] OK (3.508349146110057x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 100000, warm] OK (10.44029244516653x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 2, cold] OK (3.5831202046035804x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 2, warm] OK (1.640625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 10, cold] OK (1.0436363636363637x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 10, warm] OK (1.5037593984962405x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 1000, cold] OK (1.2296601441812565x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 1000, warm] OK (2.1497584541062804x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 100000, cold] OK (1.3447770567301653x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 100000, warm] OK (3.3111404087013843x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 2, cold] OK (3.575x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 2, warm] OK (1.330827067669173x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 10, cold] OK (1.140625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 10, warm] OK (1.6036036036036037x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 1000, cold] OK (1.1524390243902438x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 1000, warm] OK (2.023696682464455x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 100000, cold] OK (1.008468595624559x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 100000, warm] OK (1.9675253708040594x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 2, cold] OK (5.754716981132075x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 2, warm] OK (1.606837606837607x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 10, cold] ERROR: only 0.9446494464944649x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 10, warm] OK (1.7459016393442623x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 1000, cold] OK (1.7623873873873874x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 1000, warm] OK (2.4486486486486485x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 100000, cold] OK (1.9760151085930122x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 100000, warm] OK (3.528567832871885x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 2, cold] OK (4.5570291777188325x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 2, warm] OK (1.523076923076923x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 10, cold] OK (1.2781954887218046x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 10, warm] OK (1.4462809917355373x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 1000, cold] OK (1.4827586206896552x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 1000, warm] OK (1.815217391304348x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 100000, cold] OK (1.5180429623318932x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 100000, warm] OK (2.946443239691145x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 2, cold] OK (6.689230769230769x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 2, warm] OK (1.375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 10, cold] OK (1.3347457627118644x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 10, warm] OK (1.75x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 1000, cold] OK (2.181712962962963x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 1000, warm] OK (2.1559633027522938x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 100000, cold] OK (3.33373063170441x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 100000, warm] OK (3.6200212426978227x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 2, cold] OK (4.558265582655826x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 2, warm] ERROR: only 0.5862068965517241x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 10, cold] OK (1.2925764192139737x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 10, warm] ERROR: only 0.923469387755102x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 1000, cold] OK (3.323529411764706x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 1000, warm] OK (2.883720930232558x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 100000, cold] OK (3.059930795847751x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 100000, warm] OK (7.715126545026486x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 2, cold] OK (4.72543352601156x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 2, warm] OK (1.5333333333333334x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 10, cold] ERROR: only 0.9033333333333333x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 10, warm] OK (1.448x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 1000, cold] OK (1.5975855130784709x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 1000, warm] OK (2.2233502538071064x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 100000, cold] OK (1.38530990727184x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 100000, warm] OK (2.4362698261035733x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 2, cold] OK (5.295819935691318x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 2, warm] OK (1.5869565217391304x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 10, cold] OK (1.5159817351598173x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 10, warm] OK (1.5073529411764706x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 1000, cold] OK (1.6618705035971224x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 1000, warm] OK (1.9188034188034189x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 100000, cold] OK (2.3289765175011077x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 100000, warm] OK (3.672067901234568x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 2, cold] OK (4.502923976608187x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 2, warm] OK (1.416x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 10, cold] OK (1.23109243697479x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 10, warm] OK (1.6666666666666667x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 1000, cold] OK (1.4682926829268292x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 1000, warm] OK (2.1272727272727274x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 100000, cold] OK (1.3974670059773924x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 100000, warm] OK (2.7570671378091873x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 2, cold] OK (4.215873015873016x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 2, warm] OK (1.782258064516129x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 10, cold] OK (1.420353982300885x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 10, warm] OK (1.3098591549295775x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 1000, cold] OK (1.43024494142705x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 1000, warm] OK (1.7956521739130435x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 100000, cold] OK (2.391414432040511x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 100000, warm] OK (3.9362962962962964x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 2, cold] OK (5.714788732394366x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 2, warm] OK (1.6131386861313868x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 10, cold] OK (1.3738738738738738x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 10, warm] OK (1.0476190476190477x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 1000, cold] OK (1.515625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 1000, warm] OK (2.144186046511628x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 100000, cold] OK (2.1961989938513136x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 100000, warm] OK (3.7569444444444446x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 2, cold] OK (3.742857142857143x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 2, warm] OK (1.7727272727272727x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 10, cold] OK (1.2217391304347827x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 10, warm] OK (1.6417910447761195x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 1000, cold] OK (1.3326592517694642x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 1000, warm] OK (2.343137254901961x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 100000, cold] OK (2.2029220779220777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 100000, warm] OK (3.790623335109217x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 2, cold] OK (4.27639751552795x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 2, warm] OK (1.4685314685314685x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 10, cold] OK (1.2531120331950207x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 10, warm] OK (1.5887096774193548x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 1000, cold] OK (1.4939226519337017x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 1000, warm] OK (1.550420168067227x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 100000, cold] OK (2.081578947368421x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 100000, warm] OK (3.60025641025641x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 2, cold] OK (3.874186550976139x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 2, warm] OK (1.5813953488372092x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 10, cold] OK (1.5019455252918288x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 10, warm] OK (2.1219512195121952x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 1000, cold] OK (1.4780564263322884x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 1000, warm] OK (1.9868995633187774x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 100000, cold] OK (1.9547169811320755x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 100000, warm] OK (3.254095238095238x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 2, cold] OK (5.305555555555555x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 2, warm] OK (1.6589147286821706x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.317391304347826x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.3x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 1000, cold] OK (1.6714727085478889x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 1000, warm] OK (2.1083743842364533x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 100000, cold] OK (2.7639525320173894x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 100000, warm] OK (3.826481715006305x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 2, cold] OK (5.836734693877551x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.5648854961832062x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 10, cold] OK (1.2477064220183487x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 10, warm] OK (1.7076923076923076x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 1000, cold] OK (1.604898828541001x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 1000, warm] OK (2.1036036036036037x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 100000, cold] OK (2.6840849439274637x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 100000, warm] OK (3.990193407790793x faster, expected > 0.95x) - -Tests run: 18, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 213.418 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.ListLoopsRewriteTest -Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec -Running com.nativelibs4java.scalace.test.ListPerformanceTest -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 2, cold] OK (1.0263157894736843x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 2, warm] OK (0.9821428571428571x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 10, cold] OK (1.1415929203539823x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 10, warm] ERROR: only 0.9352941176470588x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 1000, cold] OK (1.014684287812041x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 1000, warm] OK (0.9859154929577465x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 100000, cold] ERROR: only 0.9442573887018332x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForall, n = 100000, warm] OK (1.0209222886421863x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 2, cold] OK (1.0804721030042919x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 2, warm] OK (1.0536912751677852x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 10, cold] OK (1.0186915887850467x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 10, warm] OK (1.051948051948052x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 1000, cold] ERROR: only 0.9490254872563718x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 1000, warm] OK (1.09375x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 100000, cold] OK (1.0113613308987623x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleExists, n = 100000, warm] OK (1.0512820512820513x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 2, cold] ERROR: only 0.6779661016949152x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 2, warm] OK (0.9588235294117647x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 10, cold] OK (0.9551020408163265x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 10, warm] ERROR: only 0.8641304347826086x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 1000, cold] ERROR: only 0.9244712990936556x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 1000, warm] ERROR: only 0.9046153846153846x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 100000, cold] ERROR: only 0.92644666511736x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToArray, n = 100000, warm] OK (1.0027023375219566x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 2, cold] OK (1.0673076923076923x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 2, warm] OK (1.0909090909090908x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 10, cold] OK (1.0564971751412429x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 10, warm] OK (0.9523809523809523x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 1000, cold] OK (0.9558011049723757x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 1000, warm] OK (1.0x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 100000, cold] OK (1.0134357005758157x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleToList, n = 100000, warm] OK (0.950354609929078x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 2, cold] OK (1.381151832460733x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 2, warm] OK (1.0368098159509203x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 10, cold] ERROR: only 0.9135802469135802x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 10, warm] OK (1.1x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 1000, cold] ERROR: only 0.9477064220183486x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 1000, warm] ERROR: only 0.8985074626865671x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 100000, cold] ERROR: only 0.926497277676951x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilter, n = 100000, warm] OK (1.0482900337589902x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 2, cold] OK (0.9849785407725322x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 2, warm] OK (1.0440251572327044x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 10, cold] ERROR: only 0.8417508417508418x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 10, warm] ERROR: only 0.9302325581395349x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 1000, cold] OK (1.0643171806167402x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 1000, warm] ERROR: only 0.8885448916408669x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 100000, cold] OK (1.0116381590548404x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFilterNot, n = 100000, warm] OK (0.9896230410842863x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 2, cold] ERROR: only 0.5024711696869851x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 2, warm] ERROR: only 0.8941176470588236x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 10, cold] OK (0.9859649122807017x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 10, warm] OK (1.0849673202614378x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 1000, cold] OK (1.0806223479490806x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 1000, warm] OK (0.9623430962343096x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 100000, cold] OK (0.9812909260991581x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleCount, n = 100000, warm] ERROR: only 0.9387071851661086x faster (expected >= 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 2, cold] OK (1.0299785867237687x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 2, warm] OK (1.0742857142857143x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 10, cold] OK (1.0711111111111111x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 10, warm] ERROR: only 0.9457831325301205x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 1000, cold] OK (0.95x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 1000, warm] OK (0.9736842105263158x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 100000, cold] OK (0.9680981595092024x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleTakeWhile, n = 100000, warm] OK (0.9832695984703633x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 2, cold] OK (1.2059732234809475x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 2, warm] OK (0.9753086419753086x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 10, cold] OK (1.1271186440677967x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 10, warm] ERROR: only 0.9202453987730062x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 1000, cold] OK (1.0783410138248848x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 1000, warm] OK (1.1055276381909547x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 100000, cold] ERROR: only 0.9308250048990789x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleDropWhile, n = 100000, warm] OK (0.9868583162217659x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 2, cold] ERROR: only 0.836873406966865x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 2, warm] OK (1.1437125748502994x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 10, cold] OK (1.1284046692607004x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 10, warm] OK (1.0797546012269938x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 1000, cold] OK (0.964562569213732x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 1000, warm] OK (1.0901960784313725x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 100000, cold] OK (1.0316465863453814x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleForeach, n = 100000, warm] OK (1.0637688082159065x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 2, cold] OK (1.0113052415210688x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 2, warm] OK (0.9746835443037974x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 10, cold] OK (1.0887096774193548x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 10, warm] ERROR: only 0.9016393442622951x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 1000, cold] OK (0.9640102827763496x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 1000, warm] OK (1.2387543252595157x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 100000, cold] OK (1.0071942446043165x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMap, n = 100000, warm] OK (1.0010543580131208x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 2, cold] OK (0.9611111111111111x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 2, warm] OK (1.0164835164835164x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 10, cold] OK (1.1478260869565218x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 10, warm] OK (0.9787234042553191x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 1000, cold] OK (1.2145110410094637x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 1000, warm] OK (0.9808917197452229x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 100000, cold] OK (1.1536355859709153x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleSum, n = 100000, warm] OK (0.9950018511662347x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 2, cold] OK (1.27217125382263x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 2, warm] OK (0.9611111111111111x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 10, cold] OK (1.045267489711934x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 10, warm] OK (1.0691489361702127x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 1000, cold] OK (1.2032258064516128x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 1000, warm] OK (1.126923076923077x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 100000, cold] OK (1.0789818454052031x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleProduct, n = 100000, warm] ERROR: only 0.9365898617511521x faster (expected >= 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 2, cold] OK (1.2444444444444445x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 2, warm] ERROR: only 0.9162303664921466x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 10, cold] ERROR: only 0.9461538461538461x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 10, warm] OK (1.0235294117647058x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 1000, cold] OK (1.050314465408805x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 1000, warm] OK (1.0x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 100000, cold] OK (1.0245973008271658x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMin, n = 100000, warm] OK (1.0034965034965035x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 2, cold] OK (1.0597014925373134x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 2, warm] ERROR: only 0.9212121212121213x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 10, cold] OK (0.9912280701754386x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 10, warm] OK (1.0773480662983426x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 1000, cold] ERROR: only 0.8673469387755102x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 1000, warm] OK (1.0111940298507462x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 100000, cold] OK (1.0135345018859552x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleMax, n = 100000, warm] OK (0.9547491039426523x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 2, cold] OK (1.0629441624365483x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 2, warm] OK (1.7246376811594204x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 10, cold] ERROR: only 0.8422619047619048x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 10, warm] ERROR: only 0.9426229508196722x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 1000, cold] OK (1.1335820895522388x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 1000, warm] OK (1.0154241645244215x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 100000, cold] ERROR: only 0.38989774330042315x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleScanLeft, n = 100000, warm] OK (1.0377577021079454x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 2, cold] OK (1.010351966873706x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 2, warm] ERROR: only 0.927710843373494x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.0088105726872247x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.00625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 1000, cold] OK (1.0438047559449313x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 1000, warm] OK (1.0136054421768708x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 100000, cold] ERROR: only 0.8653730142770963x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleFoldLeft, n = 100000, warm] OK (0.9869491204842066x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 2, cold] OK (1.0593406593406594x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.0240963855421688x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 10, cold] OK (0.9620253164556962x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 10, warm] ERROR: only 0.9392265193370166x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 1000, cold] OK (1.029040404040404x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 1000, warm] ERROR: only 0.9027237354085603x faster (expected >= 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 100000, cold] OK (1.13902352523939x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.ListPerformanceTest.simpleReduceLeft, n = 100000, warm] OK (1.0052044609665427x faster, expected > 0.95x) - -Tests run: 18, Failures: 16, Errors: 0, Skipped: 0, Time elapsed: 212.661 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.MatrixPerformanceTest -[com.nativelibs4java.scalace.test.MatrixPerformanceTest.simpleMatrixTest, n = 100, cold] OK (1.5895293324060469x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.MatrixPerformanceTest.simpleMatrixTest, n = 100, warm] OK (31.5961210051232x faster, expected > 0.95x) - -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.007 sec -Running com.nativelibs4java.scalace.test.NoChangeTest -Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.334 sec -Running com.nativelibs4java.scalace.test.PastBugsTest -Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.536 sec -Running com.nativelibs4java.scalace.test.RangeChainedPerformanceTest -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 2, cold] OK (10.215686274509803x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 2, warm] OK (2.0277777777777777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 10, cold] OK (1.9345794392523366x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 10, warm] OK (2.106060606060606x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 1000, cold] OK (5.6075949367088604x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 1000, warm] OK (3.5107913669064748x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 100000, cold] OK (9.998633879781421x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForall, n = 100000, warm] OK (38.468513853904284x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 2, cold] OK (9.242718446601941x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 2, warm] OK (1.9647887323943662x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 10, cold] OK (2.053658536585366x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 10, warm] OK (2.4126984126984126x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 1000, cold] OK (7.0168776371308015x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 1000, warm] OK (3.406015037593985x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 100000, cold] OK (9.45929203539823x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleExists, n = 100000, warm] OK (35.45396145610278x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 2, cold] OK (5.976539589442815x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 2, warm] OK (2.371900826446281x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 10, cold] OK (1.7598425196850394x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 10, warm] OK (2.347826086956522x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 1000, cold] OK (2.8473282442748094x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 1000, warm] OK (4.147058823529412x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 100000, cold] OK (3.305074257425743x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToArray, n = 100000, warm] OK (8.163807415605977x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 2, cold] OK (4.586538461538462x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 2, warm] OK (2.146153846153846x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 10, cold] OK (1.8151658767772512x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 10, warm] OK (2.3934426229508197x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 1000, cold] OK (2.825x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 1000, warm] OK (3.788732394366197x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 100000, cold] OK (2.6222121486854033x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleToList, n = 100000, warm] OK (6.416363636363636x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 2, cold] OK (6.496296296296296x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 2, warm] OK (3.008771929824561x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 10, cold] OK (1.653061224489796x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 10, warm] OK (2.0x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 1000, cold] OK (2.7864077669902914x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 1000, warm] OK (3.871794871794872x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 100000, cold] OK (4.533244680851064x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilter, n = 100000, warm] OK (18.424912689173457x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 2, cold] OK (5.252225519287834x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 2, warm] OK (2.1746031746031744x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 10, cold] OK (1.588235294117647x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 10, warm] OK (2.456x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 1000, cold] OK (2.5014044943820224x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 1000, warm] OK (3.0114285714285716x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 100000, cold] OK (3.19015032533094x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFilterNot, n = 100000, warm] OK (8.837837837837839x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 2, cold] OK (9.536458333333334x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 2, warm] OK (1.9921875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 10, cold] OK (1.8829268292682926x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 10, warm] OK (1.9776119402985075x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 1000, cold] OK (4.103448275862069x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 1000, warm] OK (3.047945205479452x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 100000, cold] OK (5.70006801178871x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleCount, n = 100000, warm] OK (20.00925925925926x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 2, cold] OK (5.65625x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 2, warm] OK (1.950354609929078x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 10, cold] OK (1.5x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 10, warm] OK (1.8357142857142856x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 1000, cold] OK (4.18848167539267x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 1000, warm] OK (4.25984251968504x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 100000, cold] OK (6.644300518134715x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleTakeWhile, n = 100000, warm] OK (15.48663101604278x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 2, cold] OK (7.633663366336633x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 2, warm] OK (2.3140495867768593x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 10, cold] OK (1.169054441260745x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 10, warm] OK (2.274193548387097x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 1000, cold] OK (3.408348457350272x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 1000, warm] OK (3.2111111111111112x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 100000, cold] OK (3.142107284598643x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleDropWhile, n = 100000, warm] OK (8.846632124352332x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 2, cold] OK (9.030303030303031x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 2, warm] OK (1.6496815286624205x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 10, cold] OK (1.94x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 10, warm] OK (2.0324675324675323x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 1000, cold] OK (3.1613508442776737x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 1000, warm] OK (2.6875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 100000, cold] OK (5.178760654227137x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleForeach, n = 100000, warm] OK (16.460251046025103x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 2, cold] OK (4.809659090909091x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 2, warm] OK (1.6923076923076923x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 10, cold] OK (1.5458515283842795x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 10, warm] OK (1.5985915492957747x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 1000, cold] OK (2.782131661442006x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 1000, warm] OK (3.8358208955223883x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 100000, cold] OK (4.065713500137476x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleMap, n = 100000, warm] OK (9.626488095238095x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 2, cold] OK (5.45398773006135x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 2, warm] OK (2.1707317073170733x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 10, cold] OK (1.63013698630137x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 10, warm] OK (2.0277777777777777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 1000, cold] OK (3.5459662288930582x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 1000, warm] OK (4.026315789473684x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 100000, cold] OK (3.158275748601514x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleScanLeft, n = 100000, warm] OK (8.071659731853906x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 2, cold] OK (9.097435897435897x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 2, warm] OK (1.7633587786259541x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.5792079207920793x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.9754098360655739x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 1000, cold] OK (3.9042316258351892x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 1000, warm] OK (4.27972027972028x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 100000, cold] OK (5.889409559512652x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleFoldLeft, n = 100000, warm] OK (23.903713892709767x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 2, cold] OK (12.763440860215054x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.9583333333333333x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 10, cold] OK (1.811659192825112x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 10, warm] OK (2.452991452991453x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 1000, cold] OK (4.366812227074236x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 1000, warm] OK (5.468253968253968x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 100000, cold] OK (6.655824508320726x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.simpleReduceLeft, n = 100000, warm] OK (16.782340862423x faster, expected > 0.95x) - -Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 164.05 sec -Running com.nativelibs4java.scalace.test.RangePerformanceTest -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 2, cold] OK (5.271844660194175x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 2, warm] OK (1.646153846153846x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 10, cold] OK (1.4299065420560748x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 10, warm] OK (2.1818181818181817x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 1000, cold] OK (2.819095477386935x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 1000, warm] OK (2.2635135135135136x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 100000, cold] OK (5.011526370939574x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForall, n = 100000, warm] OK (24.585714285714285x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 2, cold] OK (5.28643216080402x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 2, warm] OK (1.4785714285714286x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 10, cold] OK (1.6057142857142856x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 10, warm] OK (1.7753623188405796x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 1000, cold] OK (2.145348837209302x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 1000, warm] OK (2.0x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 100000, cold] OK (3.891025641025641x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleExists, n = 100000, warm] OK (22.88888888888889x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 2, cold] OK (2.797142857142857x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 2, warm] OK (1.2575757575757576x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 10, cold] OK (1.1101321585903083x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 10, warm] OK (1.62015503875969x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 1000, cold] OK (1.7320872274143302x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 1000, warm] OK (2.911602209944751x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 100000, cold] OK (1.2778315585672797x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilter, n = 100000, warm] OK (4.118334179786694x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 2, cold] OK (3.383177570093458x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 2, warm] OK (1.4137931034482758x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 10, cold] OK (1.1487603305785123x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 10, warm] OK (1.5539568345323742x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 1000, cold] OK (2.011686143572621x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 1000, warm] OK (2.8120805369127515x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 100000, cold] OK (1.6991786447638604x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFilterNot, n = 100000, warm] OK (5.176529588766299x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 2, cold] OK (4.611650485436893x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 2, warm] OK (1.3767123287671232x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 10, cold] OK (1.421875x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 10, warm] OK (1.3591549295774648x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 1000, cold] OK (2.935420743639922x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 1000, warm] OK (2.0779220779220777x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 100000, cold] OK (2.486195472114854x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleCount, n = 100000, warm] OK (6.089285714285714x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 2, cold] OK (1.7272727272727273x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 2, warm] OK (1.0939597315436242x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 10, cold] OK (1.1791044776119404x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 10, warm] OK (1.9342105263157894x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 1000, cold] OK (1.3698296836982968x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 1000, warm] OK (1.0063291139240507x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 100000, cold] OK (1.217311795184395x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleForeach, n = 100000, warm] OK (2.159250585480094x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 2, cold] OK (3.5170068027210886x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 2, warm] OK (1.6343283582089552x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 10, cold] OK (1.2488262910798122x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 10, warm] OK (2.2905405405405403x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 1000, cold] OK (1.3756097560975609x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 1000, warm] OK (1.9533678756476685x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 100000, cold] OK (1.7511510387422795x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleMap, n = 100000, warm] OK (3.7480916030534353x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 2, cold] OK (3.1517857142857144x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 2, warm] OK (1.9398496240601504x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 10, cold] OK (1.4232365145228216x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 10, warm] OK (1.6462585034013606x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 1000, cold] OK (2.041322314049587x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 1000, warm] OK (2.405128205128205x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 100000, cold] OK (1.5928785100839524x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleScanLeft, n = 100000, warm] OK (2.5828891257995736x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 2, cold] OK (5.130653266331659x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 2, warm] OK (1.3722627737226278x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 10, cold] OK (1.6756756756756757x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 10, warm] OK (1.4755244755244756x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 1000, cold] OK (2.0870712401055407x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 1000, warm] OK (2.4130434782608696x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 100000, cold] OK (4.389703375383566x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleFoldLeft, n = 100000, warm] OK (25.063444108761328x faster, expected > 0.95x) - -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 2, cold] OK (5.767195767195767x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 2, warm] OK (1.457142857142857x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 10, cold] OK (1.5902439024390245x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 10, warm] OK (1.8248175182481752x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 1000, cold] OK (3.792452830188679x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 1000, warm] OK (2.5x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 100000, cold] OK (2.5995180722891567x faster, expected > 0.95x) -[com.nativelibs4java.scalace.test.RangePerformanceTest.simpleReduceLeft, n = 100000, warm] OK (20.5906432748538x faster, expected > 0.95x) - -Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 116.122 sec -Running com.nativelibs4java.scalace.test.Reduce2WhileTest -EXPECTED : - Compiled from "simpleReduceRight.scala" - public class simpleReduceRight extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: bipush 10 - 2: newarray double - 4: astore_1 - 5: aload_1 - 6: astore_2 - 7: aload_2 - 8: arraylength - 9: istore_3 - 10: iload_3 - 11: istore 4 - 13: iconst_0 - 14: istore 5 - 16: iload 4 - 18: iconst_0 - 19: if_icmple 42 - 22: iload 4 - 24: iconst_1 - 25: isub - 26: istore 4 - 28: iload 5 - 30: ifeq 36 - 33: goto 16 - 36: iconst_1 - 37: istore 5 - 39: goto 16 - 42: iload 5 - 44: ifeq 48 - 47: return - 48: new ; //class java/lang/ArrayIndexOutOfBoundsException - 51: dup - 52: iconst_0 - 53: invokespecial ; //Method java/lang/ArrayIndexOutOfBoundsException."":(I)V - 56: athrow - - public simpleReduceRight(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -FOUND : - Compiled from "simpleReduceRight.scala" - public class simpleReduceRight extends java.lang.Object implements scala.ScalaObject{ - public void invoke(); - Code: - 0: bipush 10 - 2: newarray double - 4: astore_1 - 5: getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 8: aload_1 - 9: invokevirtual ; //Method scala/Predef$.doubleArrayOps:([D)Lscala/collection/mutable/ArrayOps; - 12: new ; //class simpleReduceRight$$anonfun$1 - 15: dup - 16: aload_0 - 17: invokespecial ; //Method simpleReduceRight$$anonfun$1."":(LsimpleReduceRight;)V - 20: invokeinterface , 2; //InterfaceMethod scala/collection/IndexedSeqOptimized.reduceRight:(Lscala/Function2;)Ljava/lang/Object; - 25: pop - 26: return - - public simpleReduceRight(); - Code: - 0: aload_0 - 1: invokespecial ; //Method java/lang/Object."":()V - 4: return - - } - - -Tests run: 6, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 9.604 sec <<< FAILURE! -Running com.nativelibs4java.scalace.test.Scan2WhileTest -Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.36 sec -Running com.nativelibs4java.scalace.test.SideEffectsTest -Tests run: 4, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.954 sec <<< FAILURE! - -Results : - -Failed tests: - simpleScanRight(com.nativelibs4java.scalace.test.ArrayChainedPerformanceTest): ERROR: only 0.8986917793257445x faster (expected >= 0.95x) - simpleToArray(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.5845410628019324x faster (expected >= 0.95x) -ERROR: only 0.15493683939159578x faster (expected >= 0.95x) -ERROR: only 0.20473372781065088x faster (expected >= 0.95x) - simpleToList(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.9304347826086956x faster (expected >= 0.95x) -ERROR: only 0.7145015105740181x faster (expected >= 0.95x) - simpleProduct(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.9485981308411215x faster (expected >= 0.95x) - simpleScanRight(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.9408866995073891x faster (expected >= 0.95x) -ERROR: only 0.7776826755428753x faster (expected >= 0.95x) - simpleFoldRight(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.9458483754512635x faster (expected >= 0.95x) -ERROR: only 0.9454238106737503x faster (expected >= 0.95x) -ERROR: only 0.9483644228169775x faster (expected >= 0.95x) - simpleReduceRight(com.nativelibs4java.scalace.test.ArrayPerformanceTest): ERROR: only 0.9052631578947369x faster (expected >= 0.95x) -ERROR: only 0.8518057285180572x faster (expected >= 0.95x) -ERROR: only 0.8952702702702703x faster (expected >= 0.95x) - simplePrimitiveArrayFilter(com.nativelibs4java.scalace.test.Filter2WhileTest): expected:<...2 - 49: if_icmpge 8[7 - 52: aload_3 - 53: iload 5 - 55: iaload - 56: istore 4 - 58: iload 4 - 60: iconst_0 - 61: if_icmpeq 74 - 64: aload 6 - 66: iload 4 - 68: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.$plus$eq:(I)Lscala/collection/mutable/ArrayBuilder$ofInt; - 71: goto 77 - 74: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 77: pop - 78: iload 5 - 80: iconst_1 - 81: iadd - 82: istore 5 - 84: goto 46 - 87: aload 6 - 89: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.result:()[I - 92: pop - 93]: return - -public sim...> but was:<...2 - 49: if_icmpge 8[1 - 52: aload_3 - 53: iload 5 - 55: iaload - 56: istore 4 - 58: iload 4 - 60: iconst_0 - 61: if_icmpeq 72 - 64: aload 6 - 66: iload 4 - 68: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.$plus$eq:(I)Lscala/collection/mutable/ArrayBuilder$ofInt; - 71: pop - 72: iload 5 - 74: iconst_1 - 75: iadd - 76: istore 5 - 78: goto 46 - 81: aload 6 - 83: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofInt.result:()[I - 86: pop - 87]: return - -public sim...> - simpleRefArrayFilter(com.nativelibs4java.scalace.test.Filter2WhileTest): expected:<...2 - 59: if_icmpge 1[14 - 62: aload_3 - 63: iload 5 - 65: aaload - 66: astore 4 - 68: aload 4 - 70: dup - 71: ifnonnull 83 - 74: pop - 75: ldc ; //String - 77: ifnull 91 - 80: goto 97 - 83: ldc ; //String - 85: invokevirtual ; //Method java/lang/Object.equals:(Ljava/lang/Object;)Z - 88: ifeq 97 - 91: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 94: goto 104 - 97: aload 6 - 99: aload 4 - 101: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 104: pop - 105: iload 5 - 107: iconst_1 - 108: iadd - 109: istore 5 - 111: goto 56 - 114: aload 6 - 116: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 119: pop - 120]: return - -public sim...> but was:<...2 - 59: if_icmpge 1[08 - 62: aload_3 - 63: iload 5 - 65: aaload - 66: astore 4 - 68: aload 4 - 70: dup - 71: ifnonnull 83 - 74: pop - 75: ldc ; //String - 77: ifnull 99 - 80: goto 91 - 83: ldc ; //String - 85: invokevirtual ; //Method java/lang/Object.equals:(Ljava/lang/Object;)Z - 88: ifne 99 - 91: aload 6 - 93: aload 4 - 95: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 98: pop - 99: iload 5 - 101: iconst_1 - 102: iadd - 103: istore 5 - 105: goto 56 - 108: aload 6 - 110: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 113: pop - 114]: return - -public sim...> - tupleArrayFilter(com.nativelibs4java.scalace.test.Filter2WhileTest): expected:<... - 108: if_icmpge 1[50 - 111: aload_3 - 112: iload 5 - 114: aaload - 115: astore 4 - 117: aload 4 - 119: invokevirtual ; //Method scala/Tuple2._1$mcI$sp:()I - 122: bipush 30 - 124: if_icmpge 137 - 127: aload 6 - 129: aload 4 - 131: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 134: goto 140 - 137: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 140: pop - 141: iload 5 - 143: iconst_1 - 144: iadd - 145: istore 5 - 147: goto 105 - 150: aload 6 - 152: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 155: pop - 156]: return - -public tup...> but was:<... - 108: if_icmpge 1[44 - 111: aload_3 - 112: iload 5 - 114: aaload - 115: astore 4 - 117: aload 4 - 119: invokevirtual ; //Method scala/Tuple2._1$mcI$sp:()I - 122: bipush 30 - 124: if_icmpge 135 - 127: aload 6 - 129: aload 4 - 131: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuilder$ofRef; - 134: pop - 135: iload 5 - 137: iconst_1 - 138: iadd - 139: istore 5 - 141: goto 105 - 144: aload 6 - 146: invokevirtual ; //Method scala/collection/mutable/ArrayBuilder$ofRef.result:()[Ljava/lang/Object; - 149: pop - 150]: return - -public tup...> - simpleFoldRight(com.nativelibs4java.scalace.test.Fold2WhileTest): expected:<... 4: astore_1 - 5: [aload_1 - 6: astore_2 - 7: aload_2 - 8: arraylength - 9: istore_3 - 10: iload_3 - 11: istore 4 - 13: iload 4 - 15: iconst_0 - 16: if_icmple 28 - 19: iload 4 - 21: iconst_1 - 22: isub - 23: istore 4 - 25: goto 13 - 28]: return - -public sim...> but was:<... 4: astore_1 - 5: [getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 8: aload_1 - 9: invokevirtual ; //Method scala/Predef$.doubleArrayOps:([D)Lscala/collection/mutable/ArrayOps; - 12: dconst_0 - 13: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToDouble:(D)Ljava/lang/Double; - 16: new ; //class simpleFoldRight$$anonfun$1 - 19: dup - 20: aload_0 - 21: invokespecial ; //Method simpleFoldRight$$anonfun$1."":(LsimpleFoldRight;)V - 24: invokeinterface , 3; //InterfaceMethod scala/collection/IndexedSeqOptimized.foldRight:(Ljava/lang/Object;Lscala/Function2;)Ljava/lang/Object; - 29: pop - 30]: return - -public sim...> - simpleRangeFilter(com.nativelibs4java.scalace.test.IntRangeForeach2WhileTest): expected:<...0 - 13: if_icmpge 4[6 - 16: iload_2 - 17: istore_1 - 18: iload_1 - 19: bipush 50 - 21: if_icmpeq 35 - 24: aload_3 - 25: iload_1 - 26: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer; - 29: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.$plus$eq:(Ljava/lang/Object;)Lscala/collection/immutable/VectorBuilder; - 32: goto 38 - 35: getstatic ; //Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; - 38: pop - 39: iload_2 - 40: iconst_1 - 41: iadd - 42: istore_2 - 43: goto 10 - 46: aload_3 - 47: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.result:()Lscala/collection/immutable/Vector; - 50: pop - 51]: return - -public sim...> but was:<...0 - 13: if_icmpge 4[0 - 16: iload_2 - 17: istore_1 - 18: iload_1 - 19: bipush 50 - 21: if_icmpeq 33 - 24: aload_3 - 25: iload_1 - 26: invokestatic ; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer; - 29: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.$plus$eq:(Ljava/lang/Object;)Lscala/collection/immutable/VectorBuilder; - 32: pop - 33: iload_2 - 34: iconst_1 - 35: iadd - 36: istore_2 - 37: goto 10 - 40: aload_3 - 41: invokevirtual ; //Method scala/collection/immutable/VectorBuilder.result:()Lscala/collection/immutable/Vector; - 44: pop - 45]: return - -public sim...> - simpleForall(com.nativelibs4java.scalace.test.ListChainedPerformanceTest): ERROR: only 0.6036036036036037x faster (expected >= 0.95x) - simpleFilter(com.nativelibs4java.scalace.test.ListChainedPerformanceTest): ERROR: only 0.9446494464944649x faster (expected >= 0.95x) - simpleTakeWhile(com.nativelibs4java.scalace.test.ListChainedPerformanceTest): ERROR: only 0.5862068965517241x faster (expected >= 0.95x) -ERROR: only 0.923469387755102x faster (expected >= 0.95x) - simpleDropWhile(com.nativelibs4java.scalace.test.ListChainedPerformanceTest): ERROR: only 0.9033333333333333x faster (expected >= 0.95x) - simpleForall(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9352941176470588x faster (expected >= 0.95x) -ERROR: only 0.9442573887018332x faster (expected >= 0.95x) - simpleExists(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9490254872563718x faster (expected >= 0.95x) - simpleToArray(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.6779661016949152x faster (expected >= 0.95x) -ERROR: only 0.8641304347826086x faster (expected >= 0.95x) -ERROR: only 0.9244712990936556x faster (expected >= 0.95x) -ERROR: only 0.9046153846153846x faster (expected >= 0.95x) -ERROR: only 0.92644666511736x faster (expected >= 0.95x) - simpleFilter(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9135802469135802x faster (expected >= 0.95x) -ERROR: only 0.9477064220183486x faster (expected >= 0.95x) -ERROR: only 0.8985074626865671x faster (expected >= 0.95x) -ERROR: only 0.926497277676951x faster (expected >= 0.95x) - simpleFilterNot(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.8417508417508418x faster (expected >= 0.95x) -ERROR: only 0.9302325581395349x faster (expected >= 0.95x) -ERROR: only 0.8885448916408669x faster (expected >= 0.95x) - simpleCount(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.5024711696869851x faster (expected >= 0.95x) -ERROR: only 0.8941176470588236x faster (expected >= 0.95x) -ERROR: only 0.9387071851661086x faster (expected >= 0.95x) - simpleTakeWhile(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9457831325301205x faster (expected >= 0.95x) - simpleDropWhile(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9202453987730062x faster (expected >= 0.95x) -ERROR: only 0.9308250048990789x faster (expected >= 0.95x) - simpleForeach(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.836873406966865x faster (expected >= 0.95x) - simpleMap(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9016393442622951x faster (expected >= 0.95x) - simpleProduct(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9365898617511521x faster (expected >= 0.95x) - simpleMin(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9162303664921466x faster (expected >= 0.95x) -ERROR: only 0.9461538461538461x faster (expected >= 0.95x) - simpleMax(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9212121212121213x faster (expected >= 0.95x) -ERROR: only 0.8673469387755102x faster (expected >= 0.95x) - simpleScanLeft(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.8422619047619048x faster (expected >= 0.95x) -ERROR: only 0.9426229508196722x faster (expected >= 0.95x) -ERROR: only 0.38989774330042315x faster (expected >= 0.95x) - simpleFoldLeft(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.927710843373494x faster (expected >= 0.95x) -ERROR: only 0.8653730142770963x faster (expected >= 0.95x) - simpleReduceLeft(com.nativelibs4java.scalace.test.ListPerformanceTest): ERROR: only 0.9392265193370166x faster (expected >= 0.95x) -ERROR: only 0.9027237354085603x faster (expected >= 0.95x) - simpleReduceRight(com.nativelibs4java.scalace.test.Reduce2WhileTest): expected:<... 4: astore_1 - 5: [aload_1 - 6: astore_2 - 7: aload_2 - 8: arraylength - 9: istore_3 - 10: iload_3 - 11: istore 4 - 13: iconst_0 - 14: istore 5 - 16: iload 4 - 18: iconst_0 - 19: if_icmple 42 - 22: iload 4 - 24: iconst_1 - 25: isub - 26: istore 4 - 28: iload 5 - 30: ifeq 36 - 33: goto 16 - 36: iconst_1 - 37: istore 5 - 39: goto 16 - 42: iload 5 - 44: ifeq 48 - 47: return - 48: new ; //class java/lang/ArrayIndexOutOfBoundsException - 51: dup - 52: iconst_0 - 53: invokespecial ; //Method java/lang/ArrayIndexOutOfBoundsException."":(I)V - 56: athrow] - -public simpleReduc...> but was:<... 4: astore_1 - 5: [getstatic ; //Field scala/Predef$.MODULE$:Lscala/Predef$; - 8: aload_1 - 9: invokevirtual ; //Method scala/Predef$.doubleArrayOps:([D)Lscala/collection/mutable/ArrayOps; - 12: new ; //class simpleReduceRight$$anonfun$1 - 15: dup - 16: aload_0 - 17: invokespecial ; //Method simpleReduceRight$$anonfun$1."":(LsimpleReduceRight;)V - 20: invokeinterface , 2; //InterfaceMethod scala/collection/IndexedSeqOptimized.reduceRight:(Lscala/Function2;)Ljava/lang/Object; - 25: pop - 26: return] - -public simpleReduc...> - simpleSideEffectAssignment(com.nativelibs4java.scalace.test.SideEffectsTest): Failed to analyze side-effects ! Side effects = - testOutputs = Map() expected: but was: - simpleMethodCall(com.nativelibs4java.scalace.test.SideEffectsTest): Failed to analyze side-effects ! Side effects = - testOutputs = Map() expected: but was: - -Tests run: 170, Failures: 35, Errors: 0, Skipped: 0 - -Wrote com.nativelibs4java.scalace.test.RangeChainedPerformanceTest.perf.properties -Wrote com.nativelibs4java.scalace.test.MatrixPerformanceTest.perf.properties -Wrote com.nativelibs4java.scalace.test.RangePerformanceTest.perf.properties -Wrote com.nativelibs4java.scalace.test.ListPerformanceTest.perf.properties -Wrote com.nativelibs4java.scalace.test.ArrayPerformanceTest.perf.properties -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD FAILURE -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 24:27.249s -[INFO] Finished at: Mon Jan 02 20:48:06 GMT 2012 -[INFO] Final Memory: 11M/1078M -[INFO] ------------------------------------------------------------------------ -[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.7.2:test (default-test) on project scalace: There are test failures. -[ERROR] -[ERROR] Please refer to /Users/ochafik/github/nativelibs4java/libraries/Scalace/target/surefire-reports for the individual test results. -[ERROR] -> [Help 1] -[ERROR] -[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. -[ERROR] Re-run Maven using the -X switch to enable full debug logging. -[ERROR] -[ERROR] For more information about the errors and possible solutions, please read the following articles: -[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException diff --git a/libraries/Scalaxy/pom.xml b/libraries/Scalaxy/pom.xml deleted file mode 100644 index 7186fca55..000000000 --- a/libraries/Scalaxy/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - scalaxy - Scalaxy - 0.3-SNAPSHOT - http://code.google.com/p/scalacl/ - jar - - -Scalaxy makes Scala faster and hopefully safer to use in production, through compilation optimizations and warnings. - - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - false - - - - - org.scala-lang - scala-compiler - - - org.scala-lang - scala-library - - - - - - ${basedir}/target/generated-sources/main - - - - - org.apache.maven.plugins - maven-shade-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.scala-tools - maven-scala-plugin - - - com.nativelibs4java - maven-velocity-plugin - - - - - - - - org.scala-tools - maven-scala-plugin - - - - diff --git a/libraries/Scalaxy/scalace.txt b/libraries/Scalaxy/scalace.txt deleted file mode 100644 index 6670c3db9..000000000 --- a/libraries/Scalaxy/scalace.txt +++ /dev/null @@ -1,102 +0,0 @@ -Scalace - - /\ - / \ - / \ - / \ -| | - \ / - \ / - \ / - \/ - - - _ - / \ - / \ - / \ - / \ -/ \ -\ / - \ / - \ / - \ / - \_/ - - _ - / \ - / \ - / _ \ - / / \ \ -/ \_ \ -\ \ / - \ \_/ / - \ / - \ / - \_/ - _ - / \ - / \ - / _ \ - / / \ \ -/ \_ \ -\ \ / - \ \_/ / - \ / - \ / - \_/ - - ____ - /___/ - /___/ - /___/ - - - - _________ - / \ - | A | - | ___, | - | /___, | - | /___, | - | /___, | - | | - | A | - \_________/ - - _________ - / \ - | A | - | ___ | - | /___/ | - | /___/ | - | /___/ | - | | - | A | - \_________/ - - - - _________ - / \ - | A | - | ___ | - | /___/ | - | /___/ | - | /___/ | - | | - | A | - \_________/ - _ - / \ - \_ - \ - \_/ - - - - Scal♤ce - - Scal♠ce - - diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeAnalysis.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeAnalysis.scala deleted file mode 100644 index 00ca63a0b..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeAnalysis.scala +++ /dev/null @@ -1,267 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.collection.immutable.Stack -import scala.collection.mutable.ArrayBuffer -import scala.reflect.NameTransformer -import scala.reflect.generic.{Names, Trees, Types, Constants, Universe} -import scala.tools.nsc.Global -import tools.nsc.plugins.PluginComponent - -object HasSideEffects - -trait CodeAnalysis -extends MiscMatchers - with TreeBuilders - with TupleAnalysis -{ - this: PluginComponent with WithOptions => - - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed} // methods to type trees - import CODE._ - - import gen._ - import scala.tools.nsc.symtab.Flags._ - import analyzer.{SearchResult, ImplicitSearch} - - - def getTreeChildren(tree: Tree): Seq[Tree] = { - var out = collection.mutable.ArrayBuffer[Tree]() - new Traverser { - var level = 0 - override def traverse(tree: Tree) = { - if (level == 1) - out += tree - else { - level += 1 - super.traverse(tree) - level -= 1 - } - } - }.traverse(tree) - out.toArray.toSeq - } - - abstract class Evaluator[@specialized(Boolean, Int) R](defaultValue: R, combine: (R, R) => R) - extends Traverser { - def evaluate(tree: Tree): R = - if (tree eq EmptyTree) - defaultValue - else - getTreeChildren(tree).map(evaluate(_)).foldLeft(defaultValue)(combine) - } - - abstract class BooleanEvaluator extends Evaluator[Boolean](false, _ || _) - abstract class IntEvaluator extends Evaluator[Int](0, _ + _) - abstract class SeqEvaluator extends Evaluator[Seq[Tree]](Seq(), _ ++ _) - - def filterTree[V](tree: Tree)(f: PartialFunction[Tree, V]): Seq[V] = { - val out = new ArrayBuffer[V] - new Traverser { - override def traverse(t: Tree) { - if (f.isDefinedAt(t)) - out += f(t) - super.traverse(t) - } - }.traverse(tree) - out - } - - def getSymbolDefinitions(tree: Tree): Seq[DefTree] = - filterTree(tree) { - case t: DefTree => t - } - - def getRawUnknownSymbolReferences(tree: Tree, isKnownSymbol: Symbol => Boolean, accept: Tree => Boolean): Seq[RefTree] = - filterTree(tree) { - case t: RefTree if !isKnownSymbol(t.symbol) && accept(t) => t - } - - case class SymbolsInfo( - tree: Tree, - symbolDefinitions: Seq[DefTree], - definedSymbols: Set[Symbol], - preKnownSymbols: Set[Symbol], - unknownReferences: Seq[RefTree] - ) { - //lazy val definedSymbols = symbolDefinitions.map(_.symbol).toSet - lazy val unknownReferencesBySymbol = unknownReferences.groupBy(_.symbol) - lazy val unknownSymbols = unknownReferencesBySymbol.keys.toSet - - } - - def getUnknownSymbolInfo(tree: Tree, filter: Tree => Boolean = _ => true, preKnownSymbols: Set[Symbol] = Set()): SymbolsInfo = { - val symbolDefinitions = - getSymbolDefinitions(tree) - - val definedSymbols = - symbolDefinitions.map(_.symbol).toSet - - val unknownReferences = - getRawUnknownSymbolReferences(tree, s => definedSymbols.contains(s) || preKnownSymbols.contains(s), filter) - - SymbolsInfo(tree, symbolDefinitions, definedSymbols, preKnownSymbols, unknownReferences) - } - - def isSideEffectFree(tree: Tree) = - getSideEffects(tree).isEmpty - - def getSideEffects(tree: Tree) = - createSideEffectsEvaluator(tree, cached = false).evaluate(tree) - - - protected def createSideEffectsEvaluator(tree: Tree, cached: Boolean = true, preKnownSymbols: Set[Symbol] = Set()) = { - //println("Creating original SideEffectsEvaluator") - new SideEffectsEvaluator(tree, cached, preKnownSymbols) - } - - type SideEffects = Seq[Tree] - class SideEffectsEvaluator(tree: Tree, cached: Boolean = true, preKnownSymbols: Set[Symbol] = Set()) - extends SeqEvaluator - { - protected val cache = collection.mutable.Map[Tree, SideEffects]() - - protected val symbolsInfo = - getUnknownSymbolInfo(tree, preKnownSymbols = preKnownSymbols) - - protected val unknownSymbols = - symbolsInfo.unknownSymbols - - //println("#\n# unknownSymbols = " + unknownSymbols + "\n#") - - protected def isKnownTerm(symbol: Symbol) = - symbolsInfo.definedSymbols.contains(symbol) || - !unknownSymbols.contains(symbol) - - protected def isSideEffectFreeMethod(target: Tree, symbol: MethodSymbol): Boolean = { - val owner = symbol.owner - val name = symbol.name - - symbol.isGetter || - isSideEffectFreeOwner(target.tpe.typeSymbol) || - isSideEffectFreeOwner(owner) || - owner != null && { - name == (applyName: Name) && { - ArrayClass == owner || - SeqClass == owner || - { - val ownerStr = owner.toString - ownerStr == ArrayModule.toString || - ownerStr == SeqModule.toString || - { - if (options.verbose) - println("Apply method not recognized as side-effect-free with owner " + owner + " : " + symbol) - false - } - } - } - } - } - protected def isSideEffectFreeOwner(symbol: Symbol): Boolean = { - RichWrappers.contains(symbol) || - (symbol match { - case StringClass | StringOpsClass => - true - case IntClass | ShortClass | LongClass | ByteClass | CharClass | BooleanClass | DoubleClass | IntClass => - true - case PredefModule => - true - case ScalaMathPackage | ScalaMathPackageClass | ScalaMathCommonClass => - true - case SeqClass | VectorClass | ListClass | IndexedSeqClass => - true - case _ => - //println("NOT A SIDE-EFFECT-FREE OWNER : " + symbol) - false - }) - } - def isPureCaseClass(tpe: Type) = - false // TODO - - override def evaluate(tree: Tree) = { - if (cached) - cache.getOrElseUpdate(tree, { - uncachedEvaluation(tree) - }) - else - uncachedEvaluation(tree) - } - def uncachedEvaluation(tree: Tree) = { - //println("EVALUATING " + tree) - val sym = tree.symbol - tree match { - // TODO accept accesses to non-lazy vals - case (_: New) => - //println("That was a new : " + tree) - if (isPureCaseClass(tree.tpe)) - Seq() - else - Seq(tree) - case This(_) | Select(_, nme.SELF | nme.THIS | nme.FAKE_LOCAL_THIS | nme.this_ | thisName() | superName() | nme.CONSTRUCTOR) => - //println("That was a this : " + tree) - Seq() - case Select(TupleSelect() | TreeWithType(_, TypeRef(_, ArrayClass, List(_))), applyName()) => - Seq() - case Select(target, methodName) =>//if target.symbol.isInstanceOf[MethodSymbol] => - //val msg = "That was a select (" + tree + " @ " + tree.symbol + ": " + tree.symbol.getClass.getName + ") : \n\t" + tree - //println(msg) - //global.warning(msg) - //unit.warning(tree.pos, msg) - if (isSideEffectFreeOwner(sym)) - Seq() - else if (isPureCaseClass(target.tpe)) - Seq() - else if (!sym.isInstanceOf[MethodSymbol]) - Seq(tree) - else { - val ms = sym.asInstanceOf[MethodSymbol] - if (isSideEffectFreeMethod(target, ms)) - Seq() - else - Seq(tree) - } - case Assign(lhs, rhs) => - //println("That was an assign : " + tree + " on symbol " + lhs.symbol + "\n\tSymbols info :\n\t" + symbolsInfo.toString) - if (!isKnownTerm(lhs.symbol)) - Seq(tree) - else - Seq() - case _ => - super.evaluate(tree) - } - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeFlattening.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeFlattening.scala deleted file mode 100644 index 6bca91263..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/CodeFlattening.scala +++ /dev/null @@ -1,599 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.collection.immutable.Stack -import scala.collection.mutable.ArrayBuffer -import scala.reflect.NameTransformer -import scala.reflect.generic.{Names, Trees, Types, Constants, Universe} -import scala.tools.nsc.Global -import tools.nsc.plugins.PluginComponent - -trait CodeFlattening -extends MiscMatchers - with TreeBuilders - with TupleAnalysis -{ - this: PluginComponent with WithOptions => - - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed} // methods to type trees - import CODE._ - - import gen._ - import scala.tools.nsc.symtab.Flags._ - import analyzer.{SearchResult, ImplicitSearch} - - - case class FlatCode[T]( - /// External functions that are referenced by statements and / or values - outerDefinitions: Seq[T], - /// List of variable definitions and other instructions (if statements, do / while loops...) - statements: Seq[T], - /// Final values of the code in a "flattened tuple" style - values: Seq[T] - ) { - def mapEachValue(f: T => Seq[T]): FlatCode[T] = - copy(values = values.flatMap(f)) - - def mapValues(f: Seq[T] => Seq[T]): FlatCode[T] = - copy(values = f(values)) - - def ++(fc: FlatCode[T]) = - FlatCode(outerDefinitions ++ fc.outerDefinitions, statements ++ fc.statements, values ++ fc.values) - - def >>(fc: FlatCode[T]) = - FlatCode(outerDefinitions ++ fc.outerDefinitions, statements ++ fc.statements ++ values, fc.values) - - def noValues = - FlatCode(outerDefinitions, statements ++ values, Seq()) - - def addOuters(outerDefs: Seq[T]) = - copy(outerDefinitions = outerDefinitions ++ outerDefs) - - def addStatements(stats: Seq[T]) = - copy(statements = statements ++ stats) - - def printDebug(name: String = "") = { - def pt(seq: Seq[T]) = println("\t" + seq.map(_.toString.replaceAll("\n", "\n\t")).mkString("\n\t")) - println("FlatCode(" + name + "):") - pt(outerDefinitions) - println("\t--") - pt(statements) - println("\t--") - pt(values) - } - } - - def merge[T](fcs: FlatCode[T]*)(f: Seq[T] => Seq[T]) = - fcs.reduceLeft(_ ++ _).mapValues(f) - - def EmptyFlatCode[T] = FlatCode[T](Seq(), Seq(), Seq()) - - /** - * Phases : - * - unique renaming - * - tuple cartography (map symbols and treeId to TupleSlices : x._2 will be checked against x ; if is x's symbol is mapped, the resulting slice will be composed and flattened - * - tuple + block flattening (gives (Seq[Tree], Seq[Tree]) result) - */ - // separate pass should return symbolsDefined, symbolsUsed - // DefTree vs. RefTree - - def getDefAndRefTrees(tree: Tree) = { - val defTrees = new ArrayBuffer[DefTree]() - val refTrees = new ArrayBuffer[RefTree]() - new Traverser { - override def traverse(tree: Tree): Unit = { - if (tree.hasSymbol) - tree match { - case dt: DefTree => defTrees += dt - case rt: RefTree => refTrees += rt - case _ => - } - super.traverse(tree) - } - }.traverse(tree) - (defTrees.toArray, refTrees.toArray) - } - def renameDefinedSymbolsUniquely(tree: Tree, unit: CompilationUnit) = { - import scala.collection.mutable.ArrayBuffer - - val (defTrees, refTrees) = getDefAndRefTrees(tree) - val definedSymbols = defTrees.collect { case d if d.name != null => d.symbol -> d.name } toMap - val usedIdentSymbols = refTrees.collect { case ident @ Ident(name) => ident.symbol -> name} toMap - - val outerSymbols = usedIdentSymbols.keys.toSet.diff(definedSymbols.keys.toSet) - val nameCollisions = (definedSymbols ++ usedIdentSymbols).groupBy(_._2).filter(_._2.size > 1) - val renamings = nameCollisions.flatMap(_._2) map { case (sym, name) => - val newName: Name = N(unit.fresh.newName(tree.pos, name.toString)) - (sym, newName) - } toMap - - if (renamings.isEmpty) - tree - else - new Transformer { - // TODO rename the symbols themselves ?? - override def transform(tree: Tree): Tree = { - def setAttrs(newTree: Tree) = - //newTree - newTree.setSymbol(tree.symbol).setType(tree.tpe) - - renamings.get(tree.symbol).map(newName => { - tree match { - case ValDef(mods, name, tpt, rhs) => - setAttrs(treeCopy.ValDef(tree, mods, newName, super.transform(tpt), super.transform(rhs))) - case DefDef(mods, name, tparams, vparams, tpt, rhs) => - setAttrs(treeCopy.DefDef(tree, mods, newName, tparams, vparams, super.transform(tpt), super.transform(rhs))) - case Ident(name) => - setAttrs(treeCopy.Ident(tree, newName)) - case _ => - super.transform(tree) - } - }).getOrElse(super.transform(tree)) - } - }.transform(tree) - } - - class TuplesAndBlockFlattener(val tupleAnalyzer: TupleAnalyzer) - { - import tupleAnalyzer._ - - def isOpenCLIntrinsicTuple(components: List[Type]) = { - components.size match { - case 2 | 4 | 8 | 16 => - components.distinct.size == 1 - case _ => - false - } - } - - var sliceReplacements = new scala.collection.mutable.HashMap[TupleSlice, TreeGen]() - - object NumberConversion { - def unapply(tree: Tree): Option[(Tree, String)] = tree match { - case Select(expr, n) => - Option(n) collect { - case toSizeTName() => (expr, "size_t") - case toLongName() => (expr, "long") - case toIntName() => (expr, "int") - case toShortName() => (expr, "short") - case toByteName() => (expr, "char") - case toCharName() => (expr, "short") - case toDoubleName() => (expr, "double") - case toFloatName() => (expr, "float") - } - case _ => - None - } - } - def makeValuesSideEffectFree(code: FlatCode[Tree], unit: CompilationUnit, symbolOwner: Symbol) = - { - //code /* - var hasNewStatements = false - val vals = for (value <- code.values) yield { - value match { - case Select(ScalaMathFunction(_, _, _), toFloatName()) => - // special case for non-double math : - // exp(20: Float).toFloat - (Seq(), value) - case ScalaMathFunction(_, _, _) =>//Apply(f @ Select(left, name), args) if left.toString == "scala.math.package" => - // TODO this is not fair : ScalaMathFunction should have worked here !!! - (Seq(), value) - /*case Apply(s @ Select(left, name), args) if NameTransformer.decode(name.toString) match { - case op @ ("+" | "-" | "*" | "/" | "%" | "^" | "^^" | "&" | "&&" | "|" | "||" | "<<" | ">>" | "==" | "<" | ">" | "<=" | ">=" | "!=") => - true - case n if left.toString == "scala.math.package" => - true - case _ => - false - } => - (Seq(), value)*/ - case Ident(_) | Select(_, _) | ValDef(_, _, _, _) | Literal(_) | NumberConversion(_, _) | Typed(_, _) | Apply(_, List(_)) => - // already side-effect-free (?) - (Seq(), value) - case _ if value.tpe == null || value.tpe == NoType || value.tpe == UnitClass.tpe => - (Seq(), value) - case _ => - assert(value.tpe != null, value + " (" + value.getClass.getName + " = " + nodeToString(value) + ")") - val tempVar = newVariable(unit, "tmp", symbolOwner, value.pos, false, value) - if (options.verbose) - println("Creating temp variable " + tempVar.symbol + " for " + value) - hasNewStatements = true - for (slice <- getTreeSlice(value)) - setSlice(tempVar.definition, slice) - - (Seq(tempVar.definition), tempVar()) - } - } - if (!hasNewStatements) - code - else - FlatCode[Tree]( - code.outerDefinitions, - code.statements ++ vals.flatMap(_._1), - vals.map(_._2) - ) - } - def flattenTuplesAndBlocksWithInputSymbol(tree: Tree, inputSymbol: Symbol, inputName: Name, symbolOwner: Symbol)(implicit unit: CompilationUnit): FlatCode[Tree] = { - val flattenedTypes = flattenTypes(inputSymbol.tpe) - - //setSlice(inputSymbol, TupleSlice(inputSymbol, 0, flattenedTypes.size)) - - val fiberVars = if (flattenedTypes.size == 1) { - sliceReplacements ++= Seq(TupleSlice(inputSymbol, 0, 1) -> (() => ident(inputSymbol, inputName))) - Seq() - } else { - val fiberPaths = flattenFiberPaths(inputSymbol.tpe) - //println("flattenedTypes = " + flattenedTypes) - //println("fiberPaths = " + fiberPaths) - fiberPaths.zip(flattenedTypes).zipWithIndex map { case ((path, tpe), i) => - val fiberExpr = applyFiberPath(() => { - val res = ident(inputSymbol, inputName) - setSlice(res, TupleSlice(inputSymbol, i, 1)) - res - }, path) - fiberExpr.setType(tpe) - val fiberVar = newVariable(unit, inputName + "$" + path.map(_ + 1).mkString("$"), symbolOwner, tree.pos, false, fiberExpr) - sliceReplacements ++= Seq(TupleSlice(inputSymbol, i, 1) -> fiberVar.identGen) - fiberVar - } - } - val top @ FlatCode(outerDefinitions, statements, values) = flattenTuplesAndBlocks(tree)(unit, symbolOwner) - //top.printDebug("top") - //top - //* - def lastMinuteReplace = { - val trans = new Transformer { - override def transform(tree: Tree) = - replace(super.transform(tree)) - } - trans transform _ - } - val replaced = FlatCode[Tree]( - outerDefinitions map lastMinuteReplace, - (fiberVars.map(_.definition) ++ statements) map lastMinuteReplace, - values map lastMinuteReplace - ) - //replaced.printDebug("replaced") - replaced - //*/ - /*FlatCode[Tree]( - outerDefinitions, - fiberVars.map(_.definition) ++ statements, - values - )*/ - } - def replace(tree: Tree): Tree = - replaceValues(tree) match { - case Seq(unique) => unique - case _ => tree - } - - def replaceValues(tree: Tree): Seq[Tree] = if (tree.isInstanceOf[ValDef]) Seq(tree) else try { - getTreeSlice(tree, recursive = true) match { - case Some(slice) if slice.baseSymbol != tree.symbol => - sliceReplacements.get(slice) match { - case Some(identGen) => - val ident = identGen() - //setSlice(ident, slice) - //println("Replacing " + tree + " by " + ident + " (slice = " + slice + ")") - Seq(ident) - case None => - for (i <- 0 until slice.sliceLength) yield { - val subSlice = slice.subSlice(i, 1) - val ident = subSlice.toTreeGen(tupleAnalyzer)() - //println("Replacing " + tree + " by slice ident " + ident + " (slice = " + slice + ")") - //println("Tree " + tree + " has associated slice " + slice + ", extracting subSlice " + subSlice + " = " + ident) - ident - } - } - case _ => - //println("Tree " + tree + " has no associated slice") - Seq(tree) - } - } catch { case ex => - ex.printStackTrace - Seq(tree) - } - def flattenTuplesAndBlocks(initialTree: Tree, sideEffectFree: Boolean = true)(implicit unit: CompilationUnit, symbolOwner: Symbol): FlatCode[Tree] = { - val tree = initialTree//replace(initialTree) - // If the tree is mapped to a slice and that slice is mapped to a replacement, then replace the tree by an ident to the corresponding name+symbol - val res: FlatCode[Tree] = tree match { - case i: Ident => - FlatCode[Tree](Seq(), Seq(), Seq(i)) - case Block(statements, value) => - // Flatten blocks up - statements.map(flattenTuplesAndBlocks(_).noValues).reduceLeft(_ ++ _) >> flattenTuplesAndBlocks(value) - case TupleCreation(components) => - val sub = components.map(flattenTuplesAndBlocks(_)) - FlatCode[Tree]( - sub.flatMap(_.outerDefinitions), - sub.flatMap(_.statements), - sub.flatMap(_.values) - ) - case TupleComponent(target, i) =>//if getTreeSlice(target).collect(sliceReplacements) != None => - getTreeSlice(target, recursive = true) match { - case Some(slice) => - //println("Found slice " + slice + " for tuple component " + target + " i = " + i) - sliceReplacements.get(slice) match { - case Some(rep) => - FlatCode[Tree](Seq(), Seq(), Seq(rep())) - case None => - FlatCode[Tree](Seq(), Seq(), Seq(tree)) - } - case _ => - FlatCode[Tree](Seq(), Seq(), Seq(tree)) - } - case Ident(_) | Literal(_) => - // this ident has no known replacement ! - FlatCode[Tree](Seq(), Seq(), Seq(tree)) - case s @ Select(This(targetClass), name) => { - FlatCode[Tree]( - Seq(), - Seq(), - Seq(Ident(name).setSymbol(s.symbol)) ) - } - case Select(target, name) => - val FlatCode(defs, stats, vals) = flattenTuplesAndBlocks(target, sideEffectFree = target.tpe != null) - FlatCode[Tree]( - defs, - stats, - vals.map(v => Select(v, name)) - ) - case Apply(ident @ Ident(functionName), args) => - val f = args.map(flattenTuplesAndBlocks(_)) - // TODO assign vals to new vars before the calls, to ensure a correct evaluation order ! - FlatCode[Tree]( - f.flatMap(_.outerDefinitions), - f.flatMap(_.statements), - Seq(Apply(Ident(functionName).setType(ident.tpe).setSymbol(ident.symbol), f.flatMap(_.values)).setSymbol(tree.symbol).setType(tree.tpe)) - ) - case Apply(target, args) => - /* - val convArgs = args.map(flattenTuplesAndBlocks(_, symbolOwner)) - target match { - case Select(leftOperand, name) if args.length == 1 => - NameTransformer.decode(name.toString) match { - case op @ ("+" | "-" | "*" | "/" | "%" | "^" | "&" | "|" | "==" ) => - Some(out("(", left, " ", op, " ", args(0), ")") - */ - val FlatCode(defs1, stats1, vals1) = flattenTuplesAndBlocks(target, sideEffectFree = target.tpe != null) - val argsConv = args.map(flattenTuplesAndBlocks(_)) - val tpes = flattenTypes(tree.tpe) - // TODO assign vals to new vars before the calls, to ensure a correct evaluation order ! - FlatCode[Tree]( - defs1 ++ argsConv.flatMap(_.outerDefinitions), - stats1 ++ argsConv.flatMap(_.statements), - vals1.zip(argsConv.flatMap(_.values)).zip(tpes).map { case ((v1, v2), tpe) => Apply(v1, List(v2)).setType(tpe) } - ) - case f: DefDef => - FlatCode[Tree](Seq(f), Seq(), Seq()) - case Assign(lhs, rhs) => - merge(Seq(lhs, rhs).map(flattenTuplesAndBlocks(_)):_*) { case Seq(l, r) => Seq(Assign(l, r)) } - case WhileLoop(condition, content) => - // TODO clean this up !!! - val flatCondition = flattenTuplesAndBlocks(condition) - val flatContent = content.map(flattenTuplesAndBlocks(_)).reduceLeft(_ >> _) - val Seq(flatConditionValue) = flatCondition.values - FlatCode[Tree]( - flatCondition.outerDefinitions ++ flatContent.outerDefinitions, - flatCondition.statements ++ - Seq( - whileLoop( - symbolOwner, - unit, - tree, - flatConditionValue, - Block( - (flatContent.statements ++ flatContent.values).toList, - newUnit - ) - ) - ), - Seq() - ) - case If(condition, then, otherwise) => - // val (a, b) = if ({ val d = 0 ; d != 0 }) (1, d) else (2, 0) - // -> - // val d = 0 - // val condition = d != 0 - // val a = if (condition) 1 else 2 - // val b = if (condition) d else 0 - val FlatCode(dc, sc, Seq(vc)) = flattenTuplesAndBlocks(condition) - assert(vc.tpe != null, vc) - val conditionVar = newVariable(unit, "condition", symbolOwner, tree.pos, false, vc) - - val fct @ FlatCode(Seq(), st, vt) = flattenTuplesAndBlocks(then) - val fco @ FlatCode(Seq(), so, vo) = flattenTuplesAndBlocks(otherwise) - - FlatCode[Tree]( - dc, - sc :+ conditionVar.definition, - (st, so) match { - case (Seq(), Seq()) => - vt.zip(vo).map { case (t, o) => If(conditionVar(), t, o) } // pure (cond ? then : otherwise) form, possibly with tuple values - case _ => - Seq( - If(conditionVar(), Block(st.toList ++ vt.toList, newUnit), Block(so.toList ++ vo.toList, newUnit)) - ) - } - ) - case Typed(expr, tpt) => - flattenTuplesAndBlocks(expr).mapValues(_.map(Typed(_, tpt))) - case ValDef(paramMods, paramName, tpt, rhs) => - val isVal = !paramMods.hasFlag(MUTABLE) - // val p = { - // val x = 10 - // (x, x + 2) - // } - // -> - // val x = 10 - // val p_1 = x - // val p_2 = x + 2 - val FlatCode(defs, stats, values) = flattenTuplesAndBlocks(replace(rhs))(unit, tree.symbol) - //val flatValues = values.flatMap(replaceValues) - val flattenedTypes = if (tree.tpe != NoType) { - val types = flattenTypes(tree.tpe) - assert(values.size == types.size, "values = " + values + ", flattenedTypes = " + types + ", tree = " + tree) - types - } else { - values.map(_.tpe) - } - //for ((value, i) <- values.zipWithIndex; slice <- getTreeSlice(value)) { - // setSlice(tree, slice.subSlice(i, 1)) - //} - if (flattenedTypes.size == 1) { - //assert(values.size == 1, "values = " + values + ", flattenedTypes = " + flattenedTypes + ", tree = " + tree) - val List(value) = values - val vd = ValDef(paramMods, paramName, tpt, value).setSymbol(tree.symbol).setType(tree.tpe) - //println("single vd = " + vd) - //replace(value) // TODO REMOVE THIS DEBUG LINE - FlatCode[Tree]( - defs, - stats :+ vd, - Seq() - ) - } else { - val splitSyms = //: Map[TupleSlice, (String, Symbol)] = - flattenedTypes.zipWithIndex.map({ case (tpe, i) => - val name = unit.fresh.newName(tree.pos, paramName + "_" + (i + 1)) - val sym = symbolOwner.newValue(tree.pos, name) - sym.setInfo(tpe).setFlag(SYNTHETIC | LOCAL) - (TupleSlice(tree.symbol, i, 1), (name, sym))//() => ident(sym, name)) - }) - - //println("splitSyms = " + splitSyms) - if (splitSyms.size != 1 && isVal) - sliceReplacements ++= splitSyms.map { case (slice, (name, sym)) => - val rep = ident(sym, name)//slice.toTreeGen(replace(_, false), tupleAnalyzer)() - //println("New replacement for " + slice + " = " + rep + " (but name = " + name + ", sym = " + sym + ")") - (slice, () => rep) - } - - val FlatCode(defs, stats, flattenedValues) = flattenTuplesAndBlocks(rhs)(unit, tree.symbol) - - if (isVal) - for (((splitSlice, (splitName, splitSym)), value) <- splitSyms.zip(flattenedValues)) { - for (slice <- getTreeSlice(value)) { - //println("Forwarded split slice " + slice + " from value " + value + " to split symbol " + splitSym) - setSlice(splitSym, slice) - } - } - - FlatCode[Tree]( - defs, - stats ++ splitSyms.zip(flattenedValues).zip(flattenedTypes).map({ case (((slice, (name, sym)), value), tpe) => - val vv = value - val vd = ValDef(Modifiers(0), name, TypeTree(tpe), replace(value)).setSymbol(sym).setType(tpe): Tree - //println("vd = " + vd) - vd - }), - Seq()//splitSyms.map({ case (slice, (name, sym)) => ident(sym, name) }) - ) - } - case Match(selector, List(CaseDef(pat, guard, body))) => - def extract(tree: Tree): Tree = tree match { - case Typed(expr, tpt) => extract(expr) - case Annotated(annot, arg) => extract(arg) - case _ => tree - } - getTreeSlice(selector, recursive = true).orElse(getTreeSlice(extract(selector), recursive = true)) match { - case Some(slice) => - val subMatcher = new BoundTuple(slice) - val subMatcher(m) = pat - - //val info = getTupleInfo(slice.baseSymbol.tpe) - //if (false) - for ((sym, subSlice) <- m) { - val info = getTupleInfo(sym.tpe) - val boundSlice = TupleSlice(sym, 0, info.flattenTypes.size) - val rep = subSlice.toTreeGen(tupleAnalyzer) - //setSlice(rep, subSlice) - //println("Not Adding replacement for slice " + boundSlice + " to " + rep()) - //println("Adding replacement for slice " + boundSlice + " to " + subSlice) - setSlice(sym, subSlice) - //sliceReplacements ++= Seq(boundSlice -> rep) - if (subSlice.sliceLength == 1) - sliceReplacements ++= Seq(boundSlice -> subSlice.toTreeGen(tupleAnalyzer)) - //(() => applyFiberPath(subSlice.toTreeGen(replace), path))) - } - /*for ((path, i) <- info.flattenPaths.zipWithIndex) { - val subSlice = TupleSlice(slice.baseSymbol, i, 1) - sliceReplacements ++= - Seq(subSlice -> subSlice.toTreeGen(replace(_, false), tupleAnalyzer)) - //(() => applyFiberPath(subSlice.toTreeGen(replace), path))) - }*/ - - flattenTuplesAndBlocks(body) - case _ => - if (options.verbose) { - println("selector: " + selector.getClass.getName + " = " + selector + " = " + nodeToString(selector)) - println("selector.symbol = " + selector.symbol) - println("extract(selector): " + extract(selector).getClass.getName + " = " + selector + " = " + nodeToString(extract(selector))) - println("extract(selector).symbol = " + extract(selector).symbol) - println("sliceReplacements = \n\t" + sliceReplacements.mkString("\n\t")) - } - throw new RuntimeException("Unable to connect the matched pattern with its corresponding single case") - //FlatCode[Tree](Seq(), Seq(), Seq()) - } - case EmptyTree => { - println("CodeFlattening - WARNING EmptyTree! Should this ever happen?") - FlatCode[Tree](Seq(), Seq(), Seq()) - } - case _ => - assert(false, "Case not handled in tuples and blocks flattening : " + tree + " (" + tree.getClass.getName + ") :\n\t" + nodeToString(tree)) - FlatCode[Tree](Seq(), Seq(), Seq()) - } - //res.printDebug("res") - val ret = if (sideEffectFree) - makeValuesSideEffectFree( - res, - unit, - symbolOwner - ) - else - res - - //ret.printDebug("ret") - //println("tree = \n\t" + tree.toString.replaceAll("\n", "\n\t")) - //println("res = \n\t" + res.toString.replaceAll("\n", "\n\t")) - //println("ret = \n\t" + ret.toString.replaceAll("\n", "\n\t")) - - val out = ret.mapValues(s => s.flatMap(replaceValues)) - //out.printDebug("out") - out - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/CollectionRewriters.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/CollectionRewriters.scala deleted file mode 100644 index 503b53941..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/CollectionRewriters.scala +++ /dev/null @@ -1,794 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.tools.nsc.ast.TreeDSL -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.TypingTransformers - -/** - * DEPRECATED ! DO NOT EDIT THIS FILE ANYMORE, EXCEPT FOR BUGFIXES - * ALL NEW WORK SHOULD GO IN `Stream*.scala` files ! - */ -@deprecated -trait RewritingPluginComponent { - - this: PluginComponent with TreeBuilders with TraversalOps with WorkaroundsForOtherPhases with WithOptions => - import global._ - import gen._ - import definitions._ - import typer.typed - import CODE._ - - /// describes the outside of the loop (before - statements - and after - final return value) - case class LoopOutersEnv( - aVar: VarDef, - nVar: VarDef, - outputSizeVar: VarDef - ) - /// describes the outside of the loop (before - statements - and after - final return value). Includes payload that will be visible from the inside - case class LoopOuters[Payload]( - statements: List[Tree], - finalReturnValue: Tree, - payload: Payload - ) { - def typedStatements = statements.map(typed) - def finalReturnValueOrUnit = - if (finalReturnValue == null) - newUnit - else - typed { finalReturnValue } - } - /// describes the environment available to the inside of the loop - case class LoopInnersEnv[Payload]( - aVar: VarDef, - nVar: VarDef, - iVar: VarDef, - outputIndexVar: VarDef, - itemVar: VarDef, - payload: Payload - ) - case class LoopInners( - statements: List[Tree], - extraLoopTest: Tree = null - ) - - case class CollectionBuilder( - builder: Tree, - set: (TreeGen, TreeGen, TreeGen) => Tree, - add: (TreeGen, TreeGen) => Tree, - result: TreeGen => Tree - ) { - def setOrAdd(builder: TreeGen, index: TreeGen, value: TreeGen) = - if (set != null && index != null) - set(builder, index, value) - else - add(builder, value) - } - - /* - class CollectionBuilder( - newBuilder: TreeGen, - set: (TreeGen, TreeGen, TreeGen) => Tree, - add: (TreeGen, TreeGen) => Tree, - result: TreeGen => Tree - ) { - def setOrAdd(builder: TreeGen, index: TreeGen, value: TreeGen) = - if (set != null && index != null) - set(builder, index, value) - else - add(builder, value) - } - def arrayBuilder(componentType: Type) = { - - new CollectionBuilder(...) - } - object CollectionBuilder { - def unapply(tpe: Type) = null - def unapply( - def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) - def newBuilder(pos: Position, componentType: Type, collectionType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): CollectionBuilder - - } - */ - trait CollectionRewriters { - protected var currentOwner: Symbol - val unit: CompilationUnit - - abstract sealed class CollectionType { - val supportsRightVariants: Boolean - def filters: List[Tree] = Nil - def isSafeRewrite(op: TraversalOpType) = true - def colToString(tpe: Type): String - def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) - def newBuilder(pos: Position, componentType: Type, collectionType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): CollectionBuilder - def foreach[Payload]( - tree: Tree, - array: Tree, - componentType: Type, - reverseOrder: Boolean, - skipFirst: Boolean, - outerStatements: LoopOutersEnv => LoopOuters[Payload], - innerStatements: LoopInnersEnv[Payload] => LoopInners - ): Tree - - def filteredContent(content: List[Tree], itemVar: VarDef): List[Tree] = { - filters match { - case Nil => - content - case filterFunctions: List[Tree] => - List( - If( - (filterFunctions.map { - case Func(List(filterParam), filterBody) => - replaceOccurrences( - filterBody, - Map(filterParam.symbol -> itemVar), - Map( - filterParam.symbol -> itemVar.symbol/*, - f.symbol -> currentOwner*/ - ), - Map(), - unit - ) - }).reduceLeft(boolAnd), - content match { - case a :: Nil => - a - case _ => - Block(content.dropRight(1), content.last) - }, - newUnit - ) - ) - } - } - - } - class CollectionRewriter( - val colType: CollectionType, - val tpe: Type, - val array: Tree, - val componentType: Type - ) - - object CollectionRewriter { - - //TODO def unapply(tpe: Type): Option[CollectionRewriter] = tpe.dealias.deconst match { - // case ListTree(componentType) - //} - def unapply(tree: Tree): Option[CollectionRewriter] = tree match { - case WrappedArrayTree(array, componentType) => - Some(new CollectionRewriter(ArrayRewriter, appliedType(ArrayClass.tpe, List(componentType)), array, componentType)) - case ListTree(componentType) if options.deprecated => - Some(new CollectionRewriter(ListRewriter, appliedType(ListClass.tpe, List(componentType)), tree, componentType)) - case IntRange(from, to, by, isUntil, filters) => - ( - by match { - case None => - Some(1) - case Some(Literal(Constant(v: Int))) => - Some(v) - case _ => - None - } - ) match { - case Some(byValue) => - Some(new CollectionRewriter(IntRangeRewriter(from, to, byValue, isUntil, filters), appliedType(ArrayClass.tpe, List(IntClass.tpe)), null, IntClass.tpe)) - case _ => - None - } - case _ => - None - } - } - - trait HasBufferBuilder { - def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) - def newBuilder(pos: Position, componentType: Type, collectionType: Type, knownSize: TreeGen, localTyper: analyzer.Typer) = { - val (builderTpe, builderInstance, builderResultGetter) = newBuilderInstance(componentType, knownSize, localTyper) - CollectionBuilder( - builder = builderInstance, - set = null, - add = (bufferIdentGen, itemIdentGen) => { - val addAssignMethod = (builderTpe member addAssignName).alternatives.head// filter (_.paramss.size == 1) - typed { - val bufferIdent = bufferIdentGen() - val t = Apply( - Select( - bufferIdent, - addAssignName - ).setSymbol(addAssignMethod).setType(addAssignMethod.tpe), - List(itemIdentGen()) - ).setSymbol(addAssignMethod).setType(UnitClass.tpe) - //println(nodeToString(t)) - t - } - }, - result = bufferIdentGen => { - builderResultGetter(bufferIdentGen()).setType(collectionType) - } - ) - } - } - - case class IntRangeRewriter(from: Tree, to: Tree, byValue: Int, isUntil: Boolean, filtersList: List[Tree]) - extends CollectionType - with HasBufferBuilder - with ArrayBuilderTargetRewriter - { - override val supportsRightVariants = false - override def filters: List[Tree] = filtersList - override def colToString(tpe: Type) = "Range" - override def isSafeRewrite(op: TraversalOpType) = { - import TraversalOps._ - op match { - case tco: ToCollectionOp => - tco.colType match { - case ArrayType => - options.experimental - //true - case _ => - false - } - case ScanOp(_, _, _, false) => - false - case ReduceOp(_, _, _) | MinOp(_) | MaxOp(_) => - false - case _: FilterWhileOp => - // dropWhile - false - case _ => - true - } - } - - override def newArrayBuilderInfo(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer) = { - //if (knownSize == null) - //error("should not pass here now !"); - //(appliedType(WrappedArrayBuilderClass.tpe, List(componentType)), Nil, true, true) - BuilderInfo(appliedType(VectorBuilderClass.tpe, List(componentType)), Nil, false, false, simpleBuilderResult _) - //else - // super.newArrayBuilderInfo(componentType, knownSize) - } - - /* - override def newBuilder(pos: Position, componentType: Type, collectionType: Type, knownSize: TreeGen, localTyper: analyzer.Typer) = { - val cb = if (knownSize != null) - ArrayRewriter.newBuilder(pos, componentType, collectionType, knownSize, localTyper) - else - super.newBuilder(pos, componentType, collectionType, knownSize, localTyper) - - if (knownSize == null) - cb - else - cb.copy(result = bufferIdentGen => { - val r = cb.result(bufferIdentGen) - typed { - ( - if (knownSize == null) - r - else - //mkWrapArray(mkCast(r, appliedType(ArrayClass.tpe, List(componentType))), componentType) - mkWrapArray(r, componentType) - ).DOT(N("toIndexedSeq")) - } - }) - }*/ - - override def foreach[Payload]( - tree: Tree, - collection: Tree, - componentType: Type, - reverseOrder: Boolean, - skipFirst: Boolean, - outerStatements: LoopOutersEnv => LoopOuters[Payload], - innerStatements: LoopInnersEnv[Payload] => LoopInners - ): Tree = { - val pos = tree.pos - //assert(!reverseOrder) - val fromVar = newVariable(unit, "from$", currentOwner, tree.pos, false, from.setType(IntClass.tpe)) - val toVar = newVariable(unit, "to$", currentOwner, tree.pos, false, to.setType(IntClass.tpe)) - val iVar = newVariable(unit, "i$", currentOwner, tree.pos, true, fromVar()) - val iVal = newVariable(unit, "i$val$", currentOwner, tree.pos, false, iVar()) - val nVar = newVariable(unit, "n$", currentOwner, tree.pos, false, toVar()) - - val outputSize = { - val span = intSub(toVar(), fromVar()) - val width = if (isUntil) - span - else - intAdd(span, newInt(1)) - - if (byValue == 1) - width - else - intDiv(width, newInt(byValue)) - } - val outputSizeVar = newVariable(unit, "outputSize$", currentOwner, tree.pos, false, outputSize) - val outputIndexVar = newVariable(unit, "outputIndex$", currentOwner, tree.pos, true, if (reverseOrder) intSub(outputSizeVar(), newInt(1)) else newInt(0)) - val loopOuters = outerStatements(new LoopOutersEnv( - null, - nVar, - outputSizeVar - )) - val loopInners = new LoopInnersEnv[Payload](null, nVar, iVal, outputIndexVar, iVal, loopOuters.payload) - val LoopInners(statements, extraTest) = innerStatements(loopInners) - typed { - treeCopy.Block( - tree, - List[Tree]( - fromVar.definition, - toVar.definition, - nVar.definition, - iVar.definition - ) ++ - outputSizeVar.defIfUsed ++ - outputIndexVar.defIfUsed ++ - loopOuters.typedStatements ++ - List( - whileLoop( - currentOwner, - unit, - tree, - boolAnd( - binOp( - iVar(), - IntClass.tpe.member( - if (isUntil) { - if (byValue < 0) nme.GT else nme.LT - } else { - if (byValue < 0) nme.GE else nme.LE - } - ), - nVar() - ), - extraTest - ), - typed { - Block( - iVal.definition :: - filteredContent(statements, loopInners.itemVar) ++ - outputIndexVar.ifUsed(incrementIntVar(outputIndexVar, newInt(if (reverseOrder) -1 else 1))), - incrementIntVar(iVar, newInt(byValue)) - ) - } - ) - ), - loopOuters.finalReturnValueOrUnit - ) - } - } - } - - - - case class BuilderInfo(builderType: Type, mainArgs: List[Tree], needsManifest: Boolean, manifestIsInMain: Boolean, builderResultGetter: Tree => Tree) - - trait ArrayBuilderTargetRewriter { - def newArrayBuilderInfo(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): BuilderInfo = - primArrayBuilderClasses.get(componentType) match { - case Some(t) => - BuilderInfo(t.tpe, Nil, false, false, simpleBuilderResult _) - case None => - if (componentType <:< AnyRefClass.tpe) - BuilderInfo(appliedType(RefArrayBuilderClass.tpe, List(componentType)), Nil, true, false, simpleBuilderResult _) - else - BuilderInfo(appliedType(ArrayBufferClass.tpe, List(componentType)), List(newInt(16)), false, false, (tree: Tree) => { - toArray(tree, componentType, localTyper) - }) - } - def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) = { - val BuilderInfo(builderType, mainArgs, needsManifest, manifestIsInMain, builderResultGetter) = newArrayBuilderInfo(componentType, knownSize, localTyper); - ( - builderType, - localTyper.typed { - val manifestList = if (needsManifest) { - var t = componentType - - var manifest = localTyper.findManifest(t, false).tree - if (manifest == EmptyTree) - manifest = localTyper.findManifest(normalize(t), false).tree // TODO remove me ? - assert(manifest != EmptyTree, "Empty manifest for type : " + t + " = " + normalize(t)) - - // TODO: REMOVE THIS UGLY WORKAROUND !!! - assertNoThisWithNoSymbolOuterRef(manifest, localTyper) - List(manifest) - } else - null - - val sym = builderType.typeSymbol.primaryConstructor - val args = if (needsManifest && manifestIsInMain) - manifestList - else - mainArgs - - val n = Apply( - Select( - New(TypeTree(builderType)).setSymbol(builderType.typeSymbol), - sym - ).setSymbol(sym), - args - ).setSymbol(sym) - if (needsManifest && !manifestIsInMain) - Apply( - n, - manifestList - ).setSymbol(sym) - else - n - }, - builderResultGetter - ) - } - } - case object ArrayRewriter extends CollectionType with HasBufferBuilder with ArrayBuilderTargetRewriter { - override val supportsRightVariants = true - override def colToString(tpe: Type) = tpe.toString - override def isSafeRewrite(op: TraversalOpType) = { - import TraversalOps._ - op match { - case tco: ToCollectionOp => - tco.colType match { - case ListType => - options.experimental - //true - case _ => - false - } - case ScanOp(_, _, _, false) => - false - case _ => - true - } - } - override def newBuilder(pos: Position, componentType: Type, collectionType: Type, knownSize: TreeGen, localTyper: analyzer.Typer) = { - if (knownSize != null) { - CollectionBuilder( - builder = newArray( - componentType, - knownSize() - ), - set = (bufferIdentGen, indexIdentGen, contentGen) => { - newUpdate( - pos, - bufferIdentGen(), - indexIdentGen(), - contentGen() - ) - }, - add = null, - result = bufferIdentGen => bufferIdentGen() - ) - } else - super.newBuilder(pos, componentType, collectionType, knownSize, localTyper) - } - - override def foreach[Payload]( - tree: Tree, - collection: Tree, - componentType: Type, - reverseOrder: Boolean, - skipFirst: Boolean, - outerStatements: LoopOutersEnv => LoopOuters[Payload], - innerStatements: LoopInnersEnv[Payload] => LoopInners - ): Tree = { - val pos = tree.pos - val aVar = newVariable(unit, "array$", currentOwner, pos, false, collection) - val nVar = newVariable(unit, "n$", currentOwner, pos, false, newArrayLength(aVar())) - val iVar = newVariable(unit, "i$", currentOwner, pos, true, - if (reverseOrder) { - if (skipFirst) - intSub(nVar(), newInt(1)) - else - nVar() - } else { - if (skipFirst) - newInt(1) - else - newInt(0) - } - ) - val itemVar = newVariable(unit, "item$", currentOwner, pos, false, newApply(tree.pos, aVar(), iVar())) - //val outputIndexVar = newVariable(unit, "outputIndex$", currentOwner, tree.pos, false, if (reverseOrder) intSub(outputSizeVar(), newInt(1)) else newInt(0)) - val loopOuters = outerStatements(new LoopOutersEnv(aVar, nVar, nVar)) - val loopInners = new LoopInnersEnv[Payload](aVar, nVar, iVar, outputIndexVar = null, itemVar, loopOuters.payload) - val LoopInners(statements, extraTest) = innerStatements(loopInners) - typed { - treeCopy.Block( - tree, - List( - aVar.definition, - nVar.definition, - iVar.definition - ) ++ - loopOuters.typedStatements ++ - List( - whileLoop( - currentOwner, - unit, - tree, - boolAnd( - if (reverseOrder) // while (i > 0) { i--; statements } - binOp( - iVar(), - IntClass.tpe.member(nme.GT), - newInt(0) - ) - else // while (i < n) { statements; i++ } - binOp( - iVar(), - IntClass.tpe.member(nme.LT), - nVar() - ), - extraTest - ), - typed { - val itemAndInnerStats = - itemVar.definition :: - filteredContent(statements, loopInners.itemVar) - - if (reverseOrder) - Block( - decrementIntVar(iVar, newInt(1)) :: - itemAndInnerStats, - newUnit - ) - else - Block( - itemAndInnerStats, - incrementIntVar(iVar, newInt(1)) - ) - } - ) - ), - loopOuters.finalReturnValueOrUnit - ) - } - } - } - case object ListRewriter extends CollectionType with HasBufferBuilder { - override val supportsRightVariants = false - override def colToString(tpe: Type) = tpe.toString - - override def isSafeRewrite(op: TraversalOpType) = { - import TraversalOps._ - op match { - //case Foreach(_) => - // options.experimental - case tco: ToCollectionOp => - tco.colType match { - case ArrayType => - options.experimental // slow in some cases ! - //true - case _ => - false - } - //case Map | Sum | Fold | _: AllOrSome => - // true - case ScanOp(_, _, _, false) => - false - case _: ReduceOp => - options.experimental // slow in some cases ! - case _: FoldOp => - options.experimental // slow in some cases ! - case _: ForeachOp => - options.experimental // slow in some cases ! - case _: FilterOp => - options.experimental // slow in some cases ! - case _: FilterWhileOp => - options.experimental // slow in some cases ! - case _: AllOrSomeOp => - options.experimental // slow in some cases ! - case _ => - true - } - } - - override def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) = { - val builderType = appliedType(ListBufferClass.tpe, List(componentType)) - ( - builderType, - typed { - val sym = builderType.typeSymbol.primaryConstructor - Apply( - Select( - New(TypeTree(builderType)).setSymbol(builderType.typeSymbol), - builderType.typeSymbol.primaryConstructor - ).setSymbol(sym),//.setType(sym.tpe), - Nil - ).setSymbol(sym)//.setType(builderType) - }, - simpleBuilderResult _ - ) - } - override def foreach[Payload]( - tree: Tree, - collection: Tree, - componentType: Type, - reverseOrder: Boolean, - skipFirst: Boolean, - outerStatements: LoopOutersEnv => LoopOuters[Payload], - innerStatements: LoopInnersEnv[Payload] => LoopInners - ): Tree = { - assert(!reverseOrder) - val pos = tree.pos - val colTpe = collection.tpe - val aVar = newVariable(unit, "list$", currentOwner, pos, true, collection) - val itemVar = newVariable(unit, "item$", currentOwner, pos, false, typed { - Select(aVar(), headName).setSymbol(colTpe.member(headName))//.setType(componentType) - }) - val loopOuters = outerStatements(new LoopOutersEnv(aVar, null, null)) - val loopInners = new LoopInnersEnv[Payload](aVar, null, null, null, itemVar, loopOuters.payload) - val LoopInners(statements, extraTest) = innerStatements(loopInners) - typed { - treeCopy.Block( - tree, - List( - aVar.definition - ) ++ - loopOuters.typedStatements ++ - List( - whileLoop( - currentOwner, - unit, - tree, - if ("1" == System.getenv("SCALACL_LIST_TEST_ISEMPTY")) // Safer, but 10% slower - boolAnd(boolNot(Select(aVar(), isEmptyName).setSymbol(colTpe.member(isEmptyName)).setType(BooleanClass.tpe)), extraTest) - else - boolAnd(newIsInstanceOf(aVar(), appliedType(NonEmptyListClass.typeConstructor, List(componentType))),extraTest) - //boolAnd(typed { aVar().IS(NonEmptyListClass.tpe) }/*.setType(BooleanClass.tpe)*/, extraTest), - , - typed { - val itemAndInnerStats = - itemVar.definition :: - filteredContent(statements, loopInners.itemVar) - val sym = colTpe member tailName - Block( - itemAndInnerStats,//.map(typed), - Assign( - aVar(), - Select(aVar(), tailName).setSymbol(sym).setType(sym.tpe)//.setType(colTpe) - ).setType(UnitClass.tpe) - ) - } - ) - ), - loopOuters.finalReturnValueOrUnit - ) - } - } - } - case object OptionRewriter extends CollectionType with HasBufferBuilder { - override val supportsRightVariants = false - override def colToString(tpe: Type) = tpe.toString - - override def isSafeRewrite(op: TraversalOpType) = { - import TraversalOps._ - op match { - //case Foreach(_) => - // options.experimental - case _: ToCollectionOp => - true - //case Map | Sum | Fold | _: AllOrSome => - // true - case ReduceOp(_, _, _) | FoldOp(_, _, _, _) | ScanOp(_, _, _, _) => - false - case _: ForeachOp => - options.experimental // slow in some cases ! - case _: FilterOp => - options.experimental // slow in some cases ! - case _: MapOp => - options.experimental // slow in some cases ! - case _: CollectOp => - options.experimental // slow in some cases ! - case _ => - false - } - } - - override def newBuilderInstance(componentType: Type, knownSize: TreeGen, localTyper: analyzer.Typer): (Type, Tree, Tree => Tree) = { - val builderType = appliedType(ListBufferClass.tpe, List(componentType)) - ( - builderType, - typed { - val sym = builderType.typeSymbol.primaryConstructor - Apply( - Select( - New(TypeTree(builderType)).setSymbol(builderType.typeSymbol), - builderType.typeSymbol.primaryConstructor - ).setSymbol(sym),//.setType(sym.tpe), - Nil - ).setSymbol(sym)//.setType(builderType) - }, - simpleBuilderResult _ - ) - } - override def foreach[Payload]( - tree: Tree, - collection: Tree, - componentType: Type, - reverseOrder: Boolean, - skipFirst: Boolean, - outerStatements: LoopOutersEnv => LoopOuters[Payload], - innerStatements: LoopInnersEnv[Payload] => LoopInners - ): Tree = { - assert(!reverseOrder) - val pos = tree.pos - val colTpe = collection.tpe - val aVar = newVariable(unit, "list$", currentOwner, pos, true, collection) - val itemVar = newVariable(unit, "item$", currentOwner, pos, false, typed { - Select(aVar(), headName).setSymbol(colTpe.member(headName))//.setType(componentType) - }) - val loopOuters = outerStatements(new LoopOutersEnv(aVar, null, null)) - val loopInners = new LoopInnersEnv[Payload](aVar, null, null, null, itemVar, loopOuters.payload) - val LoopInners(statements, extraTest) = innerStatements(loopInners) - typed { - treeCopy.Block( - tree, - List( - aVar.definition - ) ++ - loopOuters.typedStatements ++ - List( - whileLoop( - currentOwner, - unit, - tree, - if ("1" == System.getenv("SCALACL_LIST_TEST_ISEMPTY")) // Safer, but 10% slower - boolAnd(boolNot(Select(aVar(), isEmptyName).setSymbol(colTpe.member(isEmptyName)).setType(BooleanClass.tpe)), extraTest) - else - boolAnd(newIsInstanceOf(aVar(), appliedType(NonEmptyListClass.typeConstructor, List(componentType))),extraTest) - //boolAnd(typed { aVar().IS(NonEmptyListClass.tpe) }/*.setType(BooleanClass.tpe)*/, extraTest), - , - typed { - val itemAndInnerStats = - itemVar.definition :: - filteredContent(statements, loopInners.itemVar) - val sym = colTpe member tailName - Block( - itemAndInnerStats,//.map(typed), - Assign( - aVar(), - Select(aVar(), tailName).setSymbol(sym).setType(sym.tpe)//.setType(colTpe) - ).setType(UnitClass.tpe) - ) - } - ) - ), - loopOuters.finalReturnValueOrUnit - ) - } - } - } - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/MiscMatchers.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/MiscMatchers.scala deleted file mode 100644 index f9060a5f5..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/MiscMatchers.scala +++ /dev/null @@ -1,506 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.reflect.NameTransformer -import scala.tools.nsc.Global - -abstract sealed class ColType(name: String) { - override def toString = name -} -case object SeqType extends ColType("Seq") -case object SetType extends ColType("Set") -case object ListType extends ColType("List") -case object VectorType extends ColType("Vector") -case object ArrayType extends ColType("Array") -case object IndexedSeqType extends ColType("IndexedSeq") -case object MapType extends ColType("Map") -case object OptionType extends ColType("Option") - - -trait MiscMatchers extends PluginNames with WithOptions { - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - def isPackageReference(tree: Tree, packageName: String) = { - tree.toString.matches(packageName + ".(package|`package`)") - } - - /** Strips apply nodes looking for type application. */ - def typeArgs(tree: Tree): List[Tree] = tree match { - case Apply(fn, _) => typeArgs(fn) - case TypeApply(fn, args) => args - case AppliedTypeTree(fn, args) => args - case _ => Nil - } - /** Smashes directly nested applies down to catenate the argument lists. */ - def flattenApply(tree: Tree): List[Tree] = tree match { - case Apply(fn, args) => flattenApply(fn) ++ args - case _ => Nil - } - def flattenApplyGroups(tree: Tree): List[List[Tree]] = tree match { - case Apply(fn, args) => flattenApplyGroups(fn) :+ args - case _ => Nil - } - /** Smashes directly nested selects down to the inner tree and a list of names. */ - def flattenSelect(tree: Tree): (Tree, List[Name]) = tree match { - case Select(qual, name) => flattenSelect(qual) match { case (t, xs) => (t, xs :+ name) } - case _ => (tree, Nil) - } - /** Creates an Ident or Select from a list of names. */ - def mkSelect(names: Name*): Tree = names.toList match { - case Nil => EmptyTree - case x :: Nil => Ident(x) - case x :: xs => xs.foldLeft(Ident(x): Tree)(Select(_, _)) - } - - class Ids(start: Long = 1) { - private var nx = start - def next = this.synchronized { - val v = nx - nx += 1 - v - } - } - - object ScalaMathFunction { - /** I'm all for avoiding "magic strings" but in this case it's hard to - * see the twice-as-long identifiers as much improvement. - */ - def apply(functionName: String, args: List[Tree]) = - Apply(mkSelect("scala", "math", "package", functionName), args) - - def unapply(tree: Tree): Option[(Type, Name, List[Tree])] = tree match { - case Apply(f @ Select(left, name), args) => - if (isPackageReference(left, "scala.math")) - Some((f.tpe, name, args)) - else if (tree.symbol != NoSymbol && tree.symbol.owner == ScalaMathCommonClass) - Some((f.tpe, name, args)) - else - None - /*case - Apply( - f @ Select( - Select( - Select( - Ident(scalaName()), - mathName() - ), - packageName() - ), - funName - ), - args - ) => - Some((f.tpe, funName, args))*/ - case _ => - None - } - } - object IntRange { - def apply(from: Tree, to: Tree, by: Option[Tree], isUntil: Boolean, filters: List[Tree]) = error("not implemented") - - def unapply(tree: Tree): Option[(Tree, Tree, Option[Tree], Boolean, List[Tree])] = tree match { - case Apply(Select(Apply(Select(Predef(), intWrapperName()), List(from)), funToName @ (toName() | untilName())), List(to)) => - Option(funToName) collect { - case toName() => - (from, to, None, false, Nil) - case untilName() => - (from, to, None, true, Nil) - } - case Apply(Select(tg, n @ (byName() | withFilterName() | filterName())), List(arg)) => - tg match { - case IntRange(from, to, by, isUntil, filters) => - Option(n) collect { - case byName() if by == None => - (from, to, Some(arg), isUntil, filters) - case withFilterName() | filterName() if !options.stream => - (from, to, by, isUntil, filters :+ arg) - } - case _ => - None - } - case _ => - None - } - } - - object TreeWithSymbol { - def unapply(tree: Tree): Option[(Tree, Symbol)] = - Some(tree, tree.symbol) - } - object TreeWithType { - def unapply(tree: Tree): Option[(Tree, Type)] = - Some((tree, if (tree.tpe == null) null else normalize(tree.tpe))) - } - object SymbolWithOwnerAndName { - def unapply(sym: Symbol): Option[(Symbol, Symbol, Name)] = - Some(sym, sym.owner, sym.name) - } - object TupleClass { - def unapply(sym: Symbol): Boolean = - isTupleSymbol(sym) - } - - object tupleComponentName { - val rx = "_(\\d+)".r - def unapply(n: Name): Option[Int] = { - n.toString match { - case rx(n) => - Some(n.toInt) - case _ => - None - } - } - } - - object TupleComponent { - val rx = "_(\\d+)".r - def unapply(tree: Tree) = tree match { - /*case - TreeWithSymbol( - Select( - target, - tupleComponentName(_) - ), - SymbolWithOwnerAndName( - _, - TupleClass(), - tupleComponentName(n) - ) - ) => - Some(target, n - 1) - */ - case Select(target, tupleComponentName(n)) => - //fieldName.toString match { - // case rx(n) => - if (tree.symbol != NoSymbol && isTupleSymbol(tree.symbol.owner) || isTupleSymbol(target.tpe.typeSymbol)) { - Some(target, n - 1) - } else { - println("ISSUE with tuple target symbol \n\t" + target.symbol + "\n\t" + target.tpe.typeSymbol) - None - } - //case _ => - // None - //} - case _ => - None - } - } - object TuplePath { - def unapply(tree: Tree) = { - var lastTarget: Tree = tree - var path: List[Int] = Nil - var finished = false - while (!finished) { - lastTarget match { - case TupleComponent(target, i) => - path = i :: path - lastTarget = target - case _ => - finished = true - } - } - if (path.isEmpty) - None - else - Some((lastTarget, path)) - } - } - object WhileLoop { - def unapply(tree: Tree) = tree match { - case - LabelDef( - lab, - List(), - If( - condition, - Block( - content, - Apply( - Ident(lab2), - List() - ) - ), - Literal(Constant(())) - ) - ) if (lab == lab2) => - Some(condition, content) - case _ => - None - } - } - object TupleSelect { - def unapply(tree: Tree) = tree match { - case Select(Ident(nme.scala_), name) if name.toString.matches(""".*Tuple\d+""") => - true - case _ => - false - //name.toString.matches("""(_root_\.)?scala\.Tuple\d+""") - } - } - lazy val unitTpe = UnitClass.tpe - def isUnit(tpe: Type) = normalize(tpe) match { - case `unitTpe` | MethodType(_, `unitTpe`) => - true - case _ => - false - } - - def isTupleSymbol(sym: Symbol) = - sym.toString.matches("class Tuple\\d+") - - def isAnyVal(tpe: Type) = - tpe == IntClass.tpe || - tpe == ShortClass.tpe || - tpe == LongClass.tpe || - tpe == ByteClass.tpe || - tpe == DoubleClass.tpe || - tpe == FloatClass.tpe || - tpe == CharClass.tpe || - tpe == BooleanClass.tpe - - def getArrayType(dimensions: Int, componentType: Type): Type = dimensions match { - case 1 => - appliedType(ArrayClass.tpe, List(componentType)) - case _ => - assert(dimensions > 1) - appliedType(ArrayClass.tpe, List(getArrayType(dimensions - 1, componentType))) - } - - - object BasicTypeApply { - def unapply(tree: Tree): Option[(Tree, Name, List[Tree], Seq[List[Tree]])] = tree match { - case - Apply( - TypeApply( - Select(collection, name), - typeArgs - ), - args - ) - => - Some((collection, name, typeArgs, Seq(args))) - case Apply(BasicTypeApply(collection, name, typeArgs, args), newArgs) => - Some((collection, name, typeArgs, args :+ newArgs)) - case _ => - None - } - } - - object TupleCreation { - def unapply(tree: Tree): Option[List[Tree]] = Option(tree) collect { - case Apply(TypeApply(Select(TupleSelect(), applyName()), types), components) => - components - case Apply(tt @ TypeTree(), components) if isTupleSymbol(tree.tpe.typeSymbol) => - // TODO FIX THIS BROAD HACK !!! (test tt) - //println("tt.tpe = (" + tt.tpe + ": " + tt.tpe.getClass.getName + ")") - components - } - } - class CollectionApply(colModule: Symbol, colClass: Symbol) { - def apply(component: Tree) = error("not implemented") - def unapply(tree: Tree): Option[(List[Tree], Type)] = tree match { - case - TreeWithType( - Apply(TypeApply(Select(colObject, applyName()), List(tpe)), components), - TypeRef(_, colClass, List(componentType)) - ) - if colObject.symbol == colModule => - //normalize(tree.tpe) match { - // case TypeRef(_, colClass, List(componentType)) => - Some(components, componentType) - // case _ => - // None - //} - case _ => - None - } - } - - object OptionApply extends CollectionApply(OptionModule, OptionClass) - object ArrayApply extends CollectionApply(ArrayModule, ArrayClass) - object SeqApply extends CollectionApply(SeqModule, SeqClass) - object IndexedSeqApply extends CollectionApply(IndexedSeqModule, IndexedSeqClass) - object ListApply extends CollectionApply(ListModule, ListClass) - - def normalize(tpe: Type) = { - var t = tpe - if (t != null) { - var d = t.dealias - if (d != null) { - t = d - d = t.deconst - if (d != null) { - t = d - d = t.widen - if (d != null) - t = d - } - } - } - t - } - object OptionTree { - def apply(componentType: Type) = error("not implemented") - def unapply(tree: Tree): Option[Type] = { - if (!tree.isInstanceOf[TypeTree]) - normalize(tree.tpe) match { - case TypeRef(_, OptionClass, List(componentType)) => - //println("FOUND OPTION TREE " + tree) - Some(componentType) - case _ => - None - } - else - None - } - } - object Predef { - lazy val RefArrayOps = this("refArrayOps") - lazy val GenericArrayOps = this("genericArrayOps") - lazy val IntWrapper = this("intWrapper") - lazy val println = this("println") - - def contains(sym: Symbol) = sym.owner == PredefModule.moduleClass - def apply(name: String): Symbol = PredefModule.tpe member name - def unapply(tree: Tree): Boolean = tree.symbol == PredefModule - } - object ArrayOps { - lazy val ArrayOpsClass = definitions.getClass("scala.collection.mutable.ArrayOps") - - def unapply(tree: Tree): Option[Type] = tree match { - case TypeApply(sel, List(arg)) - if sel.symbol == Predef.RefArrayOps || sel.symbol == Predef.GenericArrayOps => - Some(arg.tpe) - case _ => tree.tpe match { - case MethodType(_, TypeRef(_, ArrayOpsClass, List(param))) - if Predef contains tree.symbol => - Some(param) - case _ => - None - } - } - } - - object WrappedArrayTree { - def unapply(tree: Tree) = tree match { - case Apply(ArrayOps(componentType), List(array)) => Some(array, componentType) - case _ => None - } - } - object ArrayTyped extends HigherTypeParameterExtractor(ArrayClass) - - class HigherTypeParameterExtractor(ColClass: Symbol) { - private def isCol(s: Symbol) = - s.tpe == ColClass.tpe || s.tpe.toString == ColClass.tpe.toString - private def isCol2(s: Symbol) = - isCol(s) || isCol(s.tpe.typeSymbol) - - def unapply(tpe: Type): Option[Type] = Option(normalize(tpe)) collect { - case TypeRef(_, ColClass, List(param)) => - param - case TypeRef(_, cc, List(param)) if isCol2(cc) =>//tree.symbol) => - param - case PolyType(Nil, TypeRef(_, cc, List(param))) if isCol2(cc) => - param - } - - def unapply(tree: Tree): Option[Type] = if (tree == null) None else { - unapply(tree.tpe) match { - case Some(s) => - Some(s) - case None => - if ((tree ne null) && (tree.symbol ne null) && tree.symbol != NoSymbol) - unapply(tree.symbol.tpe) - else - None - } - } - } - object ListTree extends HigherTypeParameterExtractor(ListClass) - - object ArrayTabulate { - /** This is the one all the other ones go through. */ - lazy val tabulateSyms = (ArrayModule.tpe member "tabulate" alternatives).toSet//filter (_.paramss.flatten.size == 3) - - def apply(componentType: Tree, lengths: List[Tree], function: Tree, manifest: Tree) = error("not implemented") - def unapply(tree: Tree): Option[(Tree, List[Tree], Tree, Tree)] = { - if (!tabulateSyms.contains(methPart(tree).symbol)) - None - else flattenApplyGroups(tree) match { - case List(lengths, List(function), List(manifest)) => - Some((typeArgs(tree).headOption getOrElse EmptyTree, lengths, function, manifest)) - case _ => - None - } - } - } - - - - object TrivialCanBuildFromArg { - private def isCanBuildFrom(tpe: Type) = - tpe != null && tpe.dealias.matches(CanBuildFromClass.tpe) - //tpe.dealias.deconst <:< CanBuildFromClass.tpe - - val n1 = N("canBuildIndexedSeqFromIndexedSeq") // ScalaCL - val n2 = N("canBuildArrayFromArray") // ScalaCL - def unapply(tree: Tree) = if (!isCanBuildFrom(tree.tpe)) None else Option(tree) collect { - case Apply(TypeApply(Select(comp, canBuildFromName()), List(resultType)), List(_)) => - (comp.symbol.companionClass, resultType) - case Apply(TypeApply(Select(comp, n1() | n2()), List(resultType)), _) => - (comp.symbol.companionClass, resultType) - case TypeApply(Select(comp, canBuildFromName()), List(resultType)) => - (comp.symbol.companionClass, resultType) - } - } - object CanBuildFromArg { - def unapply(tree: Tree) = tree match { - case TrivialCanBuildFromArg(_, _) => true - case _ => false - } - } - - object Func { - def unapply(tree: Tree): Option[(List[ValDef], Tree)] = Option(tree) collect { - case Block(List(), Func(params, body)) => - // method references def f(x: T) = y; col.map(f) (inside the .map = a block((), xx => f(xx)) - (params, body) - case Function(params, body) => - (params, body) - } - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/PluginNames.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/PluginNames.scala deleted file mode 100644 index cd60646b7..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/PluginNames.scala +++ /dev/null @@ -1,145 +0,0 @@ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.Global -import reflect.NameTransformer -; -trait PluginNames { - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - class N(val s: String) { - def unapply(n: Name): Boolean = n.toString == s - } - object N { - def apply(s: String) = new N(s) - } - implicit def N2Name(n: N) = newTermName(n.s) - - val addAssignName = N(NameTransformer.encode("+=")) - val toArrayName = N("toArray") - val toListName = N("toList") - val toSeqName = N("toSeq") - val toSetName = N("toSet") - val toIndexedSeqName = N("toIndexedSeq") - val toVectorName = N("toVector") - val toMapName = N("toMap") - val resultName = N("result") - val scalaName = N("scala") - val ArrayName = N("Array") - val intWrapperName = N("intWrapper") - val tabulateName = N("tabulate") - val toName = N("to") - val byName = N("by") - val withFilterName = N("withFilter") - val untilName = N("until") - val isEmptyName = N("isEmpty") - val sumName = N("sum") - val productName = N("product") - val minName = N("min") - val maxName = N("max") - val headName = N("head") - val tailName = N("tail") - val foreachName = N("foreach") - val foldLeftName = N("foldLeft") - val foldRightName = N("foldRight") - val zipWithIndexName = N("zipWithIndex") - val zipName = N("zip") - val reverseName = N("reverse") - val reduceLeftName = N("reduceLeft") - val reduceRightName = N("reduceRight") - val scanLeftName = N("scanLeft") - val scanRightName = N("scanRight") - val mapName = N("map") - val collectName = N("collect") - val canBuildFromName = N("canBuildFrom") - val filterName = N("filter") - val filterNotName = N("filterNot") - val takeWhileName = N("takeWhile") - val dropWhileName = N("dropWhile") - val countName = N("count") - val forallName = N("forall") - val existsName = N("exists") - val findName = N("find") - val updateName = N("update") - val toSizeTName = N("toSizeT") - val toLongName = N("toLong") - val toIntName = N("toInt") - val toShortName = N("toShort") - val toByteName = N("toByte") - val toCharName = N("toChar") - val toDoubleName = N("toDouble") - val toFloatName = N("toFloat") - val mathName = N("math") - val packageName = N("package") - val applyName = N("apply") - val thisName = N("this") - val superName = N("super") - - def C(name: String) = definitions.getClass(name) - def M(name: String) = definitions.getModule(name) - - lazy val ScalaReflectPackage = M("scala.reflect") - lazy val ScalaCollectionPackage = M("scala.collection") - lazy val ScalaMathPackage = M("scala.math") - lazy val ScalaMathPackageClass = ScalaMathPackage.tpe.typeSymbol - lazy val ScalaMathCommonClass = C("scala.MathCommon") - - lazy val SeqModule = M("scala.collection.Seq") - lazy val SeqClass = C("scala.collection.Seq") - lazy val SetModule = M("scala.collection.Set") - lazy val SetClass = C("scala.collection.Set") - lazy val VectorClass = C("scala.collection.Set") - lazy val ListClass = C("scala.List") - lazy val ImmutableListClass = C("scala.collection.immutable.List") - lazy val NonEmptyListClass = C("scala.collection.immutable.$colon$colon") - lazy val IndexedSeqModule = M("scala.collection.IndexedSeq") - lazy val IndexedSeqClass = C("scala.collection.IndexedSeq") - lazy val OptionModule = M("scala.Option") - lazy val OptionClass = C("scala.Option") - lazy val SomeModule = M("scala.Some") - lazy val NoneModule = M("scala.None") - lazy val StringOpsClass = C("scala.collection.immutable.StringOps") - - lazy val VectorBuilderClass = C("scala.collection.immutable.VectorBuilder") - lazy val ListBufferClass = C("scala.collection.mutable.ListBuffer") - lazy val ArrayBufferClass = C("scala.collection.mutable.ArrayBuffer") - lazy val WrappedArrayBuilderClass = C("scala.collection.mutable.WrappedArrayBuilder") - lazy val RefArrayBuilderClass = C("scala.collection.mutable.ArrayBuilder.ofRef") - lazy val RefArrayOpsClass = C("scala.collection.mutable.ArrayOps.ofRef") - lazy val SetBuilderClass = C("scala.collection.mutable.SetBuilder") - - lazy val RichWrappers: Set[Symbol] = - Array("Byte", "Short", "Int", "Char", "Long", "Float", "Double", "Boolean"). - map(n => C("scala.runtime.Rich" + n)).toSet - - lazy val CanBuildFromClass = C("scala.collection.generic.CanBuildFrom") - - lazy val ArrayIndexOutOfBoundsExceptionClass = C("java.lang.ArrayIndexOutOfBoundsException") - - lazy val primArrayNames = Array( - (IntClass.tpe, "ofInt"), - (LongClass.tpe, "ofLong"), - (ShortClass.tpe, "ofShort"), - (ByteClass.tpe, "ofByte"), - (CharClass.tpe, "ofChar"), - (BooleanClass.tpe, "ofBoolean"), - (FloatClass.tpe, "ofFloat"), - (DoubleClass.tpe, "ofDouble"), - (UnitClass.tpe, "ofUnit") - ) - - lazy val primArrayBuilderClasses = primArrayNames.map { - case (sym, n) => - (sym, C("scala.collection.mutable.ArrayBuilder." + n)) - } toMap - - lazy val primArrayOpsClasses = primArrayNames.map { - case (sym, n) => - (sym, C("scala.collection.mutable.ArrayOps." + n)) - } toMap - -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamOps.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamOps.scala deleted file mode 100644 index 46be5831d..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamOps.scala +++ /dev/null @@ -1,486 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: ochafik - * Date: 10/05/11 - * Time: 21:40 - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.plugins.PluginComponent -import tools.nsc.Global - -trait StreamOps extends PluginNames with Streams with StreamSinks { - this: PluginComponent with WithOptions with WorkaroundsForOtherPhases => - - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - sealed abstract class TraversalOpType { - val needsInitialValue = false - val needsFunction = false - val loopSkipsFirst = false - val f: Tree - } - - class TraversalOp( - val op: TraversalOpType, - val collection: Tree, - val resultType: Type, - val mappedCollectionType: Type, - val isLeft: Boolean, - val initialValue: Tree - ) { - override def toString = "TraversalOp(" + Array(op, collection, resultType, mappedCollectionType, isLeft, initialValue).mkString(", ") + ")" - } - - /// Matches one of the folding/scanning/reducing functions : (reduce|fold|scan)(Left|Right) - /// Matches one of the folding/scanning/reducing functions : (reduce|fold|scan)(Left|Right) - object TraversalOps { - - trait ScalarReduction extends Reductoid { - override def resultKind = ScalarResult - override def transformedValue(value: StreamValue, totalVar: VarDef, initVarOpt: Option[VarDef])(implicit loop: Loop): StreamValue = - null - } - trait SideEffectFreeScalarReduction extends ScalarReduction with SideEffectFreeStreamComponent - - trait FunctionTransformer extends StreamTransformer { - def f: Tree - override def closuresCount = 1 - override def analyzeSideEffectsOnStream(analyzer: SideEffectsAnalyzer) = - analyzer.analyzeSideEffects(tree, f) - // Initial value does not affect the stream : - // && sideEffectsAnalyzer.isSideEffectFree(initialValue) - } - trait Function1Transformer extends FunctionTransformer { - lazy val Func(List(arg), body) = f - def transformedFunc(value: StreamValue)(implicit loop: Loop) = - replaceOccurrences( - loop.transform(body), - Map( - arg.symbol -> (() => value.value()) - ), - Map(f.symbol -> loop.currentOwner), - Map(), - loop.unit - ) - } - trait Function2Reduction extends Reductoid with FunctionTransformer { - lazy val Func(List(leftParam, rightParam), body) = f - - override def updateTotalWithValue(total: TreeGen, value: TreeGen)(implicit loop: Loop): ReductionTotalUpdate = { - import loop.{ unit, currentOwner } - val result = replaceOccurrences( - loop.transform(body), - Map( - leftParam.symbol -> total, - rightParam.symbol -> value - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - //val resultVar = newVariable(unit, "res$", currentOwner, tree.pos, true, - // result - //) - //loop.inner += resultVar.definition - ReductionTotalUpdate(result)//Var()) - } - } - trait Reductoid extends StreamTransformer { - //def loopSkipsFirst: Boolean - //def isLeft: Boolean - //def initialValue: Option[Tree] - def op: String = toString - - case class ReductionTotalUpdate(newTotalValue: Tree, conditionOpt: Option[Tree] = None) - - def getInitialValue(value: StreamValue): Tree - - def providesInitialValue(value: StreamValue): Boolean = - getInitialValue(value) != null - - def hasInitialValue(value: StreamValue) = - providesInitialValue(value) || value.extraFirstValue != None - - def needsInitialValue: Boolean - - def updateTotalWithValue(total: TreeGen, value: TreeGen)(implicit loop: Loop): ReductionTotalUpdate - - def createInitialValue(value: StreamValue)(implicit loop: Loop): Tree = { - //println("value.extraFirstValue = " + value.extraFirstValue) - val iv = getInitialValue(value) - (Option(iv), value.extraFirstValue) match { - case (Some(i), Some(e)) => - updateTotalWithValue(() => i, () => e()).newTotalValue - case (None, Some(e)) => - e() - case (Some(i), None) => - i - case (None, None) => - newDefaultValue(value.tpe) - } - } - - def transformedValue(value: StreamValue, totalVar: VarDef, initVarOpt: Option[VarDef])(implicit loop: Loop): StreamValue - - def throwsIfEmpty(value: StreamValue) = needsInitialValue && !hasInitialValue(value) - - def someIf[V](cond: Boolean)(v: => V): Option[V] = - if (cond) Some(v) else None - - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - import loop.{ unit, currentOwner } - - val hasInitVal = hasInitialValue(value) - - val initVal = - if (hasInitVal) - createInitialValue(value) - else - newDefaultValue(value.tpe) - - val initVarOpt = someIf(hasInitVal || producesExtraFirstValue) { - newVariable(unit, op + "$init", currentOwner, tree.pos, false, - initVal - ) - } - val totVar = newVariable(unit, op + "$", currentOwner, tree.pos, true, - initVarOpt.map(_()).getOrElse(initVal) - ) - - val mayNotBeDefined = throwsIfEmpty(value) && needsInitialValue && !hasInitVal - - //println("op " + op + " : mayNotBeDefined = " + mayNotBeDefined + ", providesInitialValue = " + providesInitialValue + ", hasInitVal = " + hasInitVal) - - val isDefinedVarOpt = someIf(mayNotBeDefined) { - newVariable(unit, "is$" + op + "$defined", currentOwner, tree.pos, true, - newBool(false) - ) - } - - for (initVar <- initVarOpt) - loop.preOuter += initVar.definition - loop.preOuter += totVar.definition - - val ReductionTotalUpdate(newTotalValue, conditionOpt) = - updateTotalWithValue(totVar.identGen, value.value) - - val totAssign = newAssign(totVar, newTotalValue) - - val update = - conditionOpt.map(newIf(_, totAssign)).getOrElse(totAssign) - - isDefinedVarOpt match { - case Some(isDefinedVar) => - loop.preOuter += isDefinedVar.definition - - loop.inner += newIf( - boolNot(isDefinedVar()), - Block( - Assign(isDefinedVar(), newBool(true)), - newAssign(totVar, value.value()), - newUnit - ), - update - ) - - loop.postOuter += - newIf( - boolNot(isDefinedVar()), - typed { - Throw( - New( - TypeTree(ArrayIndexOutOfBoundsExceptionClass.tpe), - List(List(newInt(0))) - ) - ) - } - ) - case None => - loop.inner += update - } - - loop.postOuter += totVar() - - transformedValue( - if (producesExtraFirstValue) - value.copy(extraFirstValue = initVarOpt.map(initVar => new DefaultTupleValue(initVar))) - else - value, - totVar, - initVarOpt - ) - } - } - - case class FoldOp(tree: Tree, f: Tree, initialValue: Tree, isLeft: Boolean) extends TraversalOpType with ScalarReduction with Function2Reduction { - override def toString = "fold" + (if (isLeft) "Left" else "Right") - override val needsFunction: Boolean = true - override val needsInitialValue = true - override def getInitialValue(value: StreamValue) = initialValue - override def throwsIfEmpty(value: StreamValue) = false - - override def consumesExtraFirstValue = true - - override def order = SameOrder - } - case class ScanOp(tree: Tree, f: Tree, initialValue: Tree, isLeft: Boolean) extends TraversalOpType with Function2Reduction { - override def toString = "scan" + (if (isLeft) "Left" else "Right") - override val needsFunction: Boolean = true - override val needsInitialValue = true - override def getInitialValue(value: StreamValue) = initialValue - override def throwsIfEmpty(value: StreamValue) = false - - override def consumesExtraFirstValue = true - override def producesExtraFirstValue = true - - override def transformedValue(value: StreamValue, totalVar: VarDef, initVarOpt: Option[VarDef])(implicit loop: Loop): StreamValue = { - value.copy( - value = new DefaultTupleValue(totalVar), - extraFirstValue = initVarOpt.map(initVar => new DefaultTupleValue(initVar)) - ) - } - - override def order = SameOrder - } - case class ReduceOp(tree: Tree, f: Tree, isLeft: Boolean) extends TraversalOpType with ScalarReduction with Function2Reduction { - override def toString = "reduce" + (if (isLeft) "Left" else "Right") - override val needsFunction: Boolean = true - override val loopSkipsFirst = true - override def getInitialValue(value: StreamValue) = null - override val needsInitialValue = true - override def throwsIfEmpty(value: StreamValue) = true - - override def consumesExtraFirstValue = true - override def order = SameOrder - } - case class SumOp(tree: Tree) extends TraversalOpType with SideEffectFreeScalarReduction { - override def toString = "sum" - override val f = null - override def order = Unordered - override def getInitialValue(value: StreamValue) = newDefaultValue(value.tpe) - override val needsInitialValue = false - override def throwsIfEmpty(value: StreamValue) = true - - override def updateTotalWithValue(totIdentGen: TreeGen, valueIdentGen: TreeGen)(implicit loop: Loop): ReductionTotalUpdate = { - val totIdent = totIdentGen() - val valueIdent = valueIdentGen() - ReductionTotalUpdate(binOp(totIdent, totIdent.tpe.member(nme.PLUS), valueIdent)) - } - } - case class ProductOp(tree: Tree) extends TraversalOpType with SideEffectFreeScalarReduction { - override def toString = "product" - override val f = null - override def order = Unordered - override def getInitialValue(value: StreamValue) = newOneValue(value.tpe) - override val needsInitialValue = false - override def throwsIfEmpty(value: StreamValue) = true - - override def updateTotalWithValue(totIdentGen: TreeGen, valueIdentGen: TreeGen)(implicit loop: Loop): ReductionTotalUpdate = { - val totIdent = typed { totIdentGen() } - val valueIdent = typed { valueIdentGen() } - ReductionTotalUpdate(binOp(totIdent, totIdent.tpe.member(nme.MUL), valueIdent)) - } - } - case class CountOp(tree: Tree, f: Tree) extends TraversalOpType with Function1Transformer { - override def toString = "count" - override val needsFunction: Boolean = true - - override def order = Unordered - override def resultKind = ScalarResult - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - import loop.{ unit, currentOwner } - val countVar = newVariable(unit, "count$", currentOwner, tree.pos, true, newInt(0)) - loop.preOuter += countVar.definition - loop.inner += - newIf( - transformedFunc(value), - incrementIntVar(countVar.identGen) - ) - loop.postOuter += countVar() - null - } - } - case class MinOp(tree: Tree) extends TraversalOpType with SideEffectFreeScalarReduction { - override def toString = "min" - override val loopSkipsFirst = true - override val f = null - override def order = Unordered - override val needsInitialValue = true - override def getInitialValue(value: StreamValue) = null - - override def updateTotalWithValue(totIdentGen: TreeGen, valueIdentGen: TreeGen)(implicit loop: Loop): ReductionTotalUpdate = { - val totIdent = totIdentGen() - val valueIdent = valueIdentGen() - ReductionTotalUpdate(valueIdent, conditionOpt = Some(binOp(valueIdent, totIdent.tpe.member(nme.LT), totIdent))) - } - } - case class MaxOp(tree: Tree) extends TraversalOpType with SideEffectFreeScalarReduction { - override def toString = "max" - override val loopSkipsFirst = true - override val f = null - override def order = Unordered - override val needsInitialValue = true - override def getInitialValue(value: StreamValue) = null - - override def updateTotalWithValue(totIdentGen: TreeGen, valueIdentGen: TreeGen)(implicit loop: Loop): ReductionTotalUpdate = { - val totIdent = totIdentGen() - val valueIdent = valueIdentGen() - ReductionTotalUpdate(valueIdent, conditionOpt = Some(binOp(valueIdent, totIdent.tpe.member(nme.GT), totIdent))) - } - } - case class FilterOp(tree: Tree, f: Tree, not: Boolean) extends TraversalOpType with Function1Transformer { - override def toString = if (not) "filterNot" else "filter" - override def order = Unordered - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - val cond = transformedFunc(value) - - loop.innerIf(() => { - if (not) - boolNot(cond) - else - cond - }) - - value.withoutSizeInfo - } - } - case class FilterWhileOp(tree: Tree, f: Tree, take: Boolean) extends TraversalOpType with Function1Transformer { - override def toString = if (take) "takeWhile" else "dropWhile" - - override def order = SameOrder - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - import loop.{ unit, currentOwner } - - val passedVar = newVariable(unit, "passed$", currentOwner, tree.pos, true, newBool(false) ) - loop.preOuter += passedVar.definition - - if (take) - loop.tests += boolNot(passedVar()) - - val cond = boolNot(transformedFunc(value)) - - if (take) { - loop.inner += newAssign(passedVar, cond) - loop.innerIf(() => boolNot(passedVar())) - } else { - loop.innerIf(() => - boolOr( - passedVar(), - Block( - List( - Assign( - passedVar(), - cond - ).setType(UnitClass.tpe) - ), - passedVar() - ).setType(BooleanClass.tpe) - ) - ) - } - - value.withoutSizeInfo - } - } - case class MapOp(tree: Tree, f: Tree, canBuildFrom: Tree) extends TraversalOpType with Function1Transformer { - override def toString = "map" - override def order = Unordered - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - val mappedVar = newVariable(loop.unit, "mapped$", loop.currentOwner, loop.pos, false, transformedFunc(value)) - loop.inner += mappedVar.definition - - value.copy(value = new DefaultTupleValue(mappedVar)) - } - } - - case class CollectOp(tree: Tree, f: Tree, canBuildFrom: Tree) extends TraversalOpType { - override def toString = "collect" - } - case class UpdateAllOp(tree: Tree, f: Tree) extends TraversalOpType { - override def toString = "update" - } - case class ForeachOp(tree: Tree, f: Tree) extends TraversalOpType with Function1Transformer { - override def toString = "foreach" - override def order = SameOrder - override def resultKind = NoResult - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - loop.inner += transformedFunc(value) - null - } - } - case class AllOrSomeOp(tree: Tree, f: Tree, all: Boolean) extends TraversalOpType with Function1Transformer { - override def toString = if (all) "forall" else "exists" - - override def order = Unordered - override def resultKind = ScalarResult - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = { - import loop.{ unit, currentOwner } - - val hasTrueVar = newVariable(unit, "hasTrue$", currentOwner, tree.pos, true, newBool(all)) - val countVar = newVariable(unit, "count$", currentOwner, tree.pos, true, newInt(0)) - loop.preOuter += hasTrueVar.definition - loop.tests += ( - if (all) - hasTrueVar() - else - boolNot(hasTrueVar()) - ) - loop.inner += newAssign(hasTrueVar, transformedFunc(value)) - loop.postOuter += hasTrueVar() - null - } - } - case class FindOp(tree: Tree, f: Tree) extends TraversalOpType { - override def toString = "find" - } - case class ReverseOp(tree: Tree) extends TraversalOpType with StreamTransformer with SideEffectFreeStreamComponent { - override def toString = "reverse" - override val f = null - - override def order = ReverseOrder - - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = - value.copy(valueIndex = (value.valueIndex, value.valuesCount) match { - case (Some(i), Some(n)) => - Some(() => intSub(intSub(n(), i()), newInt(1))) - case _ => - None - }) - } - case class ZipOp(tree: Tree, zippedCollection: Tree) extends TraversalOpType { - override def toString = "zip" - override val f = null - } - - abstract class ToCollectionOp(val colType: ColType) extends TraversalOpType with StreamTransformer with SideEffectFreeStreamComponent { - override def toString = "to" + colType - override val f = null - override def transform(value: StreamValue)(implicit loop: Loop): StreamValue = - value - - override def order = SameOrder - } - // TODO - case class ToSeqOp(tree: Tree) extends ToCollectionOp(SeqType) with CanCreateVectorSink - - case class ToListOp(tree: Tree) extends ToCollectionOp(ListType) with CanCreateListSink - case class ToSetOp(tree: Tree) extends ToCollectionOp(SetType) with CanCreateSetSink - case class ToArrayOp(tree: Tree) extends ToCollectionOp(ArrayType) with CanCreateArraySink { - override def isResultWrapped = false - } - //case class ToOptionOp(tree: Tree, tpe: Type) extends ToCollectionOp(ListType) with CanCreateOptionSink // TODO !!! - case class ToVectorOp(tree: Tree) extends ToCollectionOp(VectorType) with CanCreateVectorSink - case class ToIndexedSeqOp(tree: Tree) extends ToCollectionOp(IndexedSeqType) with CanCreateVectorSink - - case class ZipWithIndexOp(tree: Tree) extends TraversalOpType { - override def toString = "zipWithIndex" - override val f = null - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSinks.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSinks.scala deleted file mode 100644 index 5ca2a2dc0..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSinks.scala +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: ochafik - * Date: 10/05/11 - * Time: 15:20 - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.plugins.PluginComponent -import tools.nsc.Global - -trait StreamSinks extends Streams { - this: PluginComponent with WithOptions with WorkaroundsForOtherPhases => - - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - def itemIdentGen(value: StreamValue)(implicit loop: Loop): IdentGen = - value.value.tuple(loop.innerContext) - - def getArrayWrapperTpe(componentType: Type) = { - primArrayOpsClasses.get(componentType) match { - case Some(t) => - t.tpe - case None => - assert(componentType <:< AnyRefClass.tpe) - appliedType(RefArrayOpsClass.tpe, List(componentType)) - } - } - trait WithResultWrapper { - def wrapResultIfNeeded(result: Tree, expectedType: Type, componentType: Type): Tree = result - } - trait WithArrayResultWrapper extends WithResultWrapper { - def isResultWrapped: Boolean// = false - def isArrayType(tpe: Type) = { - tpe match { - case TypeRef(_, ArrayClass, List(_)) => true - case _ => false - } - } - - override def wrapResultIfNeeded(result: Tree, expectedType: Type, componentType: Type) = { - typed { result } - if (//isResultWrapped || - normalize(expectedType) != normalize(result.tpe)) - {//!isArrayType(expectedType) && isArrayType(result.tpe)) { - //println("TREE TPE NEEDS ARRAY WRAPPER : isResultWrapped = " + isResultWrapped + ", expected " + normalize(expectedType) + ", got " + normalize(result.tpe)) - val opsType = getArrayWrapperTpe(componentType) - newInstance(opsType, List(result)) - } else { - //println("TREE TPE IS OK : isResultWrapped = " + isResultWrapped + ", expectedType " + expectedType + ", got " + result.tpe) - result - } - } - } - trait ArrayStreamSink extends WithArrayResultWrapper { - def tree: Tree - //def isResultWrapped: Boolean - def outputArray(expectedType: Type, value: StreamValue, index: TreeGen, size: TreeGen)(implicit loop: Loop): Unit = { - import loop.{ unit, currentOwner } - val pos = loop.pos - - val componentType = value.tpe - val hasExtraValue = value.extraFirstValue.isDefined - val a = newVariable(unit, "out", currentOwner, pos, false, - newArray( - componentType, - if (hasExtraValue) - intAdd(size(), newInt(1)) - else - size() - ) - ) - loop.preOuter += a.definition - for (v <- value.extraFirstValue) - loop.preOuter += newUpdate(pos, a(), newInt(0), v()) - - loop.inner += newUpdate( - pos, - a(), - if (hasExtraValue) - intAdd(index(), newInt(1)) - else - index(), - itemIdentGen(value)(loop)() - ) - - loop.postOuter += - wrapResultIfNeeded(a(), expectedType, componentType) - } - def output(value: StreamValue, expectedType: Type)(implicit loop: Loop): Unit = { - val Some(index) = value.valueIndex - val Some(size) = value.valuesCount - outputArray(expectedType, value, index, size) - } - } - class ArrayBuilderGen(componentType: Type, localTyper: analyzer.Typer) extends BuilderGen { - val (builderType, mainArgs, needsManifest, manifestIsInMain, _builderResultGetter) = { - primArrayBuilderClasses.get(componentType) match { - case Some(t) => - (t.tpe, Nil, false, false, simpleBuilderResult _) - case None => - if (componentType <:< AnyRefClass.tpe) - (appliedType(RefArrayBuilderClass.tpe, List(componentType)), Nil, true, false, simpleBuilderResult _) - else - (appliedType(ArrayBufferClass.tpe, List(componentType)), List(newInt(16)), false, false, (tree: Tree) => { - toArray(tree, componentType, localTyper) - }) - } - } - override def builderResultGetter = { - val g = _builderResultGetter - (tree: Tree) => { - val r = g(tree) - r.setType(appliedType(ArrayClass.tpe, List(componentType))) - } - } - - override def builderCreation = localTyper.typed { - /*val manifestList = if (needsManifest) { - var t = componentType - - var manifest = localTyper.findManifest(t, false).tree - if (manifest == EmptyTree) - manifest = localTyper.findManifest(normalize(t), false).tree // TODO remove me ? - assert(manifest != EmptyTree, "Empty manifest for type : " + t + " = " + normalize(t)) - - // TODO: REMOVE THIS UGLY WORKAROUND !!! - assertNoThisWithNoSymbolOuterRef(manifest, localTyper) - List(manifest) - } else - null - - //newInstance(builderType, Nil).setType(builderType) - - val args = if (needsManifest && manifestIsInMain) - manifestList - else - mainArgs - */ - //println("builderType = " + builderType) - //println("builderType.typeSymbol.primaryConstructor = " + builderType.typeSymbol.primaryConstructor)//nodeToString(n)) - //println("args = " + args) - //val n = newInstance(builderType, args) - //println("n = " + n) - /*val r = if (needsManifest && !manifestIsInMain) - Apply( - n, - manifestList - ).setSymbol(n.symbol) - else - n - println("r = " + r) - r*/ - newInstance(builderType, Nil) - } - } - abstract class DefaultBuilderGen(rawBuilderSym: Symbol, componentType: Type) extends BuilderGen { - val builderType = appliedType(rawBuilderSym.tpe, List(componentType)) - override def builderCreation = - newInstance(builderType, Nil) - } - class ListBuilderGen(componentType: Type) extends DefaultBuilderGen(ListBufferClass, componentType) - class VectorBuilderGen(componentType: Type) extends DefaultBuilderGen(VectorBuilderClass, componentType) - class SetBuilderGen(componentType: Type) extends BuilderGen { - private val setClass = SetClass - private val setModule = SetModule - - private val setType = appliedType(setClass.tpe, List(componentType)) - val builderType = appliedType(SetBuilderClass.tpe, List(componentType, setType)) - override def builderCreation = - newInstance(builderType, List(newApply(newSetModuleTree, applyName, List(newTypeTree(componentType)), Nil))) - } - - trait BuilderGen { - def builderResultGetter: Tree => Tree = - simpleBuilderResult _ - - def builderCreation: Tree - def builderAppend: (Tree, Tree) => Tree = - addAssign(_, _) - } - trait BuilderStreamSink extends WithResultWrapper { - def tree: Tree - //def privilegedDirection = Some(FromLeft) - def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen - def outputBuilder(expectedType: Type, value: StreamValue)(implicit loop: Loop): Unit = { - import loop.{ unit, currentOwner } - val pos = loop.pos - - //if (direction != FromLeft) - // throw new UnsupportedOperationException("TODO") - - val builderGen = createBuilderGen(value) - import builderGen._ - - val a = newVariable(unit, "out", currentOwner, pos, false, builderCreation) - loop.preOuter += a.definition - for (v <- value.extraFirstValue) - loop.preOuter += builderAppend(a(), v()) - - loop.inner += builderAppend(a(), value.value()) - - loop.postOuter += wrapResultIfNeeded(builderResultGetter(a()), expectedType, value.tpe) - } - - def output(value: StreamValue, expectedType: Type)(implicit loop: Loop): Unit = - outputBuilder(expectedType, value) - } - trait ArrayBuilderStreamSink extends BuilderStreamSink with WithArrayResultWrapper { - def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen = - new ArrayBuilderGen(value.tpe, loop.localTyper) - } - trait CanCreateArraySink extends CanCreateStreamSink { - def tree: Tree - def isResultWrapped: Boolean - - override def createStreamSink(expectedType: Type, componentType: Type, outputSize: Option[TreeGen]): StreamSink = - new StreamSink - with ArrayStreamSink - with ArrayBuilderStreamSink - { - override def isResultWrapped = CanCreateArraySink.this.isResultWrapped - override def tree = CanCreateArraySink.this.tree - - override def output(value: StreamValue, expectedType: Type)(implicit loop: Loop): Unit = { - (value.valueIndex, value.valuesCount) match { - case (Some(index), Some(size)) => - outputArray(expectedType, value, index, size) - case _ => - outputBuilder(expectedType, value) - } - } - } - } - trait CanCreateVectorSink extends CanCreateStreamSink { - def tree: Tree - - override def createStreamSink(expectedType: Type, componentType: Type, outputSize: Option[TreeGen]): StreamSink = - new StreamSink - with BuilderStreamSink - { - override def tree = CanCreateVectorSink.this.tree - - def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen = - new VectorBuilderGen(value.tpe) - } - } - trait CanCreateListSink extends CanCreateStreamSink { - def tree: Tree - - override def createStreamSink(expectedType: Type, componentType: Type, outputSize: Option[TreeGen]): StreamSink = - new StreamSink - with BuilderStreamSink - { - override def tree = CanCreateListSink.this.tree - - def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen = - new ListBuilderGen(value.tpe) - } - } - - trait CanCreateSetSink extends CanCreateStreamSink { - def tree: Tree - - override def createStreamSink(expectedType: Type, componentType: Type, outputSize: Option[TreeGen]): StreamSink = - new StreamSink - with BuilderStreamSink - { - override def tree = CanCreateSetSink.this.tree - - def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen = - new SetBuilderGen(value.tpe) - } - } - - trait CanCreateOptionSink extends CanCreateStreamSink { - def tree: Tree - override def consumesExtraFirstValue = false // TODO - - override def createStreamSink(expectedType: Type, componentType: Type, outputSize: Option[TreeGen]): StreamSink = - new StreamSink - { - override def tree = CanCreateOptionSink.this.tree - - //def createBuilderGen(value: StreamValue)(implicit loop: Loop): BuilderGen = - // new VectorBuilderGen(value.tpe) - - def output(value: StreamValue, expectedType: Type)(implicit loop: Loop): Unit = { - import loop.{ unit, currentOwner } - val pos = loop.pos - - val out = newVariable(unit, "out", currentOwner, pos, mutable = true, newNull(value.tpe)) - val presence = newVariable(unit, "hasOut", currentOwner, pos, mutable = true, newBool(false)) - loop.preOuter += out.definition - loop.preOuter += presence.definition - loop.inner += newAssign(out, value.value()) - loop.inner += newAssign(presence, newBool(true)) - - loop.postOuter += typed { - If( - presence(), - newSomeApply(value.tpe, out()), - newNoneModuleTree.setType(tree.tpe) - ) - } - } - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSources.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSources.scala deleted file mode 100644 index d39beb124..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/StreamSources.scala +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: ochafik - * Date: 10/05/11 - * Time: 15:20 - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.plugins.PluginComponent -import tools.nsc.Global - -trait StreamSources extends Streams with StreamSinks { - this: PluginComponent with WithOptions with WorkaroundsForOtherPhases => - - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - trait AbstractArrayStreamSource extends StreamSource { - def tree: Tree - def array: Tree - def componentType: Type - - override def unwrappedTree = array - override def privilegedDirection = None - def emit(direction: TraversalDirection)(implicit loop: Loop) = { - import loop.{ unit, currentOwner, transform } - val pos = array.pos - - val skipFirst = false // TODO - val reverseOrder = direction == FromRight - - val aVar = newVariable(unit, "array$", currentOwner, pos, false, transform(array)) - val nVar = newVariable(unit, "n$", currentOwner, pos, false, newArrayLength(aVar())) - val iVar = newVariable(unit, "i$", currentOwner, pos, true, - if (reverseOrder) { - if (skipFirst) - intSub(nVar(), newInt(1)) - else - nVar() - } else { - if (skipFirst) - newInt(1) - else - newInt(0) - } - ) - - val itemVar = newVariable(unit, "item$", currentOwner, pos, false, newApply(pos, aVar(), iVar())) - - loop.preOuter += aVar.definition - loop.preOuter += nVar.definition - loop.preOuter += iVar.definition - loop.tests += ( - if (reverseOrder) - binOp(iVar(), IntClass.tpe.member(nme.GT), newInt(0)) - else - binOp(iVar(), IntClass.tpe.member(nme.LT), nVar()) - ) - - loop.preInner += itemVar.definition - loop.postInner += ( - if (reverseOrder) - decrementIntVar(iVar, newInt(1)) - else - incrementIntVar(iVar, newInt(1)) - ) - new StreamValue( - value = itemVar, - valueIndex = Some(iVar), - valuesCount = Some(nVar) - ) - } - } - case class WrappedArrayStreamSource(tree: Tree, array: Tree, componentType: Type) - extends AbstractArrayStreamSource - with CanCreateArraySink - with SideEffectFreeStreamComponent - { - override def isResultWrapped = true - } - - abstract class ExplicitCollectionStreamSource(val tree: Tree, items: List[Tree], val componentType: Type) - extends AbstractArrayStreamSource { - val array = newArrayApply(newTypeTree(componentType), items:_*) - - override def analyzeSideEffectsOnStream(analyzer: SideEffectsAnalyzer) = - analyzer.analyzeSideEffects(tree, items:_*) - } - case class ListStreamSource(tree: Tree, componentType: Type) - extends StreamSource - with CanCreateListSink - with SideEffectFreeStreamComponent { - val list = tree // TODO - - override def unwrappedTree = list - override def privilegedDirection = Some(FromLeft) - def emit(direction: TraversalDirection)(implicit loop: Loop) = { - import loop.{ unit, currentOwner, transform } - assert(direction == FromLeft) - - val pos = list.pos - - val skipFirst = false // TODO - val colTpe = list.tpe - - val aVar = newVariable(unit, "list$", currentOwner, pos, true, transform(list)) - val itemVar = newVariable(unit, "item$", currentOwner, pos, false, newSelect(aVar(), headName)) - - loop.preOuter += aVar.definition - loop.tests += ( - if ("1" == System.getenv("SCALACL_LIST_TEST_ISEMPTY")) // Safer, but 10% slower - boolNot(newSelect(aVar(), isEmptyName)) - else - newIsInstanceOf(aVar(), appliedType(NonEmptyListClass.typeConstructor, List(componentType))) - ) - - loop.preInner += itemVar.definition - loop.postInner += ( - Assign( - aVar(), - newSelect(aVar(), tailName) - ).setType(UnitClass.tpe) - ) - new StreamValue(itemVar) - } - } - - case class RangeStreamSource(tree: Tree, from: Tree, to: Tree, byValue: Int, isUntil: Boolean) - extends StreamSource - with CanCreateVectorSink - with SideEffectFreeStreamComponent { - override def privilegedDirection = Some(FromLeft) - - def emit(direction: TraversalDirection)(implicit loop: Loop) = { - assert(direction == FromLeft) - import loop.{ unit, currentOwner, transform } - val pos = tree.pos - - val fromVar = newVariable(unit, "from$", currentOwner, tree.pos, false, transform(from).setType(IntClass.tpe)) - val toVar = newVariable(unit, "to$", currentOwner, tree.pos, false, transform(to).setType(IntClass.tpe)) - val itemVar = newVariable(unit, "item$", currentOwner, tree.pos, true, fromVar()) - val itemVal = newVariable(unit, "item$val$", currentOwner, tree.pos, false, itemVar()) - - val size = { - val span = intSub(toVar(), fromVar()) - val width = if (isUntil) - span - else - intAdd(span, newInt(1)) - - if (byValue == 1) - width - else - intDiv(width, newInt(byValue)) - } - val sizeVal = newVariable(unit, "outputSize$", currentOwner, tree.pos, false, size) - val iVar = newVariable(unit, "outputIndex$", currentOwner, tree.pos, true, newInt(0))//if (reverseOrder) intSub(outputSizeVar(), newInt(1)) else newInt(0)) - val iVal = newVariable(unit, "i", currentOwner, tree.pos, true, iVar())//if (reverseOrder) intSub(outputSizeVar(), newInt(1)) else newInt(0)) - - loop.preOuter += fromVar.definition - loop.preOuter += toVar.definition - loop.preOuter += itemVar.definition - loop.preOuter += (sizeVal.defIfUsed _) - loop.preOuter += (() => if (iVal.identUsed) Some(iVar.definition) else None) - loop.tests += ( - binOp( - itemVar(), - IntClass.tpe.member( - if (isUntil) { - if (byValue < 0) nme.GT else nme.LT - } else { - if (byValue < 0) nme.GE else nme.LE - } - ), - toVar() - ) - ) - loop.preInner += itemVal.definition // it's important to keep a non-mutable local reference ! - loop.preInner += (iVal.defIfUsed _) - - loop.postInner += incrementIntVar(itemVar, newInt(byValue)) - loop.postInner += (() => iVal.ifUsed { incrementIntVar(iVar, newInt(1)) }) - - new StreamValue( - value = itemVal, - valueIndex = Some(iVal), - valuesCount = Some(sizeVal) - ) - } - } - case class OptionStreamSource(tree: Tree, componentOption: Option[Tree], onlyIfNotNull: Boolean, componentType: Type) - extends StreamSource - with CanCreateOptionSink - with SideEffectFreeStreamComponent - { - def emit(direction: TraversalDirection)(implicit loop: Loop) = { - import loop.{ unit, currentOwner, transform } - val pos = tree.pos - - loop.isLoop = false - - val (valueVar: VarDef, isDefinedVar: VarDef, isAlwaysDefined: Boolean) = componentOption match { - case Some(component) => - val valueVar = newVariable(unit, "value$", currentOwner, pos, false, transform(component)) - val (isDefinedValue, isAlwaysDefined) = - if (onlyIfNotNull && !isAnyVal(component.tpe)) - component match { - case Literal(Constant(v)) => - val isAlwaysDefined = v != null - (newBool(isAlwaysDefined), isAlwaysDefined) - case _ => - (newIsNotNull(valueVar()), false) - } - else - (newBool(true), true) - val isDefinedVar = newVariable(unit, "isDefined$", currentOwner, pos, false, isDefinedValue) - loop.preOuter += valueVar.definition - (valueVar, isDefinedVar, isAlwaysDefined) - case None => - val optionVar = newVariable(unit, "option$", currentOwner, pos, false, transform(tree)) - val isDefinedVar = newVariable(unit, "isDefined$", currentOwner, pos, false, newSelect(optionVar(), N("isDefined"))) - val valueVar = newVariable(unit, "value$", currentOwner, pos, false, newSelect(optionVar(), N("get"))) - loop.preOuter += optionVar.definition - loop.preInner += valueVar.definition - (valueVar, isDefinedVar, false) - } - if (!isAlwaysDefined) { - loop.preOuter += isDefinedVar.definition - loop.tests += isDefinedVar() - } else - loop.tests += newBool(true) - - new StreamValue( - value = valueVar, - valueIndex = Some(() => newInt(0)), - valuesCount = Some(() => typed { - if (isAlwaysDefined) - newInt(1) - else - If(isDefinedVar(), newInt(1), newInt(0)) - }) - ) - } - } - - case class ArrayApplyStreamSource(override val tree: Tree, components: List[Tree], override val componentType: Type) - extends ExplicitCollectionStreamSource(tree, components, componentType) - with CanCreateArraySink - { - override def isResultWrapped = false - } - - case class SeqApplyStreamSource(override val tree: Tree, components: List[Tree], override val componentType: Type) - extends ExplicitCollectionStreamSource(tree, components, componentType) with CanCreateListSink // default Seq implementation is List - - case class IndexedSeqApplyStreamSource(override val tree: Tree, components: List[Tree], override val componentType: Type) - extends ExplicitCollectionStreamSource(tree, components, componentType) with CanCreateVectorSink // default IndexedSeq implementation is Vector - - case class ListApplyStreamSource(override val tree: Tree, components: List[Tree], override val componentType: Type) - extends ExplicitCollectionStreamSource(tree, components, componentType) with CanCreateListSink - - object StreamSource { - object By { - def unapply(treeOpt: Option[Tree]) = treeOpt match { - case None => - Some(1) - case Some(Literal(Constant(v: Int))) => - Some(v) - case _ => - None - } - } - def unapply(tree: Tree): Option[StreamSource] = Option(tree) collect { - case ArrayApply(components, componentType) => - new ArrayApplyStreamSource(tree, components, componentType) - case SeqApply(components, componentType) => - new SeqApplyStreamSource(tree, components, componentType) - case IndexedSeqApply(components, componentType) => - new IndexedSeqApplyStreamSource(tree, components, componentType) - case ListApply(components, componentType) => - new ListApplyStreamSource(tree, components, componentType) - case WrappedArrayTree(array, componentType) => - WrappedArrayStreamSource(tree, array, componentType) - case ListTree(componentType) => - ListStreamSource(tree, componentType) - case TreeWithType(_, TypeRef(_, ListClass | ImmutableListClass, List(componentType))) => - ListStreamSource(tree, componentType) - case OptionApply(List(component), componentType) => - OptionStreamSource(tree, Some(component), onlyIfNotNull = true, component.tpe) - case OptionTree(componentType) => - OptionStreamSource(tree, None, onlyIfNotNull = true, componentType) - case IntRange(from, to, By(byValue), isUntil, filters) => - assert(filters.isEmpty, "Filters are not empty !!!") - RangeStreamSource(tree, from, to, byValue, isUntil/*, filters*/) - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/Streams.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/Streams.scala deleted file mode 100644 index a37a6bee0..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/Streams.scala +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: ochafik - * Date: 10/05/11 - * Time: 15:10 - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.Global -import tools.nsc.plugins.PluginComponent - -trait Streams -extends TreeBuilders -with TupleAnalysis -with CodeAnalysis -{ - this: PluginComponent with WithOptions => - - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - trait LocalContext { - def unit: CompilationUnit - def localTyper: analyzer.Typer - def currentOwner: Symbol - def addDefinition(tree: Tree): Unit - } - case class Loop(unit: CompilationUnit, pos: Position, currentOwner: Symbol, localTyper: analyzer.Typer, transform: Tree => Tree) { - type OptTreeGen = () => Option[Tree] - class TreeGenList { - var data = Seq[Either[Tree, OptTreeGen]]() - def +=(tree: Tree) = - data ++= Seq(Left(tree)) - - def ++=(trees: Seq[Tree]) = - data ++= trees.map(Left(_)) - - def +=(treeGen: OptTreeGen) = - data ++= Seq(Right(treeGen)) - - def +=(treeGenOpt: Option[TreeGen]) = - for (treeGen <- treeGenOpt) - data ++= Seq(Right(() => Some(treeGen()))) - - def toSeq: Seq[Tree] = data flatMap(_ match { - case Left(tree) => Some(tree) - case Right(treeGen) => treeGen() - }) - def toList = toSeq.toList - } - val preOuter = new TreeGenList - val tests = new TreeGenList - - class Inners { - val pre = new TreeGenList - val core = new TreeGenList - val post = new TreeGenList - - def toList = - pre.toList ++ core.toList ++ post.toList - } - protected val rootInners = new Inners - protected var inners = rootInners - - def innerIf(cond: TreeGen) = - innerComposition(sub => { - typed { - If( - cond(), - Block(sub, EmptyTree).setType(UnitClass.tpe), - EmptyTree - ).setType(UnitClass.tpe) - } - }) - - def innerComposition(composer: List[Tree] => Tree) = { - val sub = new Inners - inners.core += (() => Some(composer(sub.toList))) - inners = sub - } - def preInner = inners.pre - def inner = inners.core - var isLoop = true - def postInner = inners.post - - //val preInner = new TreeGenList - //val inner = new TreeGenList - //val postInner = new TreeGenList - - val postOuter = new TreeGenList - - class SubContext(list: TreeGenList) extends LocalContext { - override def unit = Loop.this.unit - override def localTyper = Loop.this.localTyper - override def currentOwner = Loop.this.currentOwner - override def addDefinition(tree: Tree) = - list += tree - } - val innerContext = new SubContext(preInner) - val outerContext = new SubContext(preOuter) - - def tree: Tree = { - val postOuterSeq = postOuter.toSeq - val (postStats, postVal) = - if (postOuterSeq.isEmpty) - (Seq(), EmptyTree) - else - (postOuterSeq.dropRight(1), postOuterSeq.last) - - val cond = tests.toSeq.reduceLeft(boolAnd) - val body = Block(rootInners.toList, EmptyTree).setType(UnitClass.tpe) - val ret = Block( - preOuter.toList ++ - Seq( - if (isLoop) - whileLoop( - owner = currentOwner, - unit = unit, - pos = pos, - cond = cond, - body = body - ) - else - If(cond, body, EmptyTree).setType(UnitClass.tpe) - ) ++ - postStats, - postVal - ) - typed { ret } - } - } - trait TupleValue extends (() => Ident) { - def apply(): Ident - def tpe: Type - def elements: Seq[IdentGen] - def fibersCount: Int - def componentsCount: Int - - def tuple(implicit context: LocalContext): IdentGen = - subValue(0, fibersCount) - - def fiber(index: Int)(implicit context: LocalContext): IdentGen = - subValue(index, 1) - - def subValue(fiberOffset: Int, fiberLength: Int)(implicit context: LocalContext): IdentGen - def subTuple(fiberOffset: Int, fiberLength: Int)(implicit context: LocalContext): TupleValue - } - class DefaultTupleValue(val tpe: Type, val elements: IdentGen*) extends TupleValue { - if (elements.isEmpty && tpe != UnitClass.tpe) - throw new RuntimeException("Invalid elements with tpe " + tpe + " : " + elements.mkString(", ")) - - def this(vd: VarDef) = this(vd.tpe, vd) - - override def apply(): Ident = { - if (elements.size != 1) - throw new UnsupportedOperationException("TODO tpe " + tpe + ", elements = " + elements.mkString(", ")) - else - elements.first.apply() - } - val tupleInfo = getTupleInfo(tpe) - def fibersCount = tupleInfo.componentSize - def componentsCount = elements.size - - protected def hasOneFiber = - fibersCount == 1 && elements.size == 1 - - def subValue(fiberOffset: Int, fiberLength: Int)(implicit context: LocalContext): IdentGen = - if (fiberLength == 1 && fiberOffset == 0 && hasOneFiber) - elements(0) - else if (fiberLength == fibersCount && fiberOffset == 0 && elements.size == 1) - elements.head - else - throw new RuntimeException("not implemented : fibersCount = " + fibersCount + ", fiberOffset = " + fiberOffset + ", fiberLength = " + fiberLength + ", tpe = " + tpe + ", elements = " + elements.map(_()).mkString(", ")) - def subTuple(fiberOffset: Int, fiberLength: Int)(implicit context: LocalContext): TupleValue = - if (fiberLength == fibersCount && fiberOffset == 0) - this - else - throw new RuntimeException("not implemented") - } - - implicit def varDef2TupleValue(value: VarDef) = - new DefaultTupleValue(value.definition.tpe, value) - - case class StreamValue( - value: TupleValue, - extraFirstValue: Option[TupleValue] = None, - valueIndex: Option[TreeGen] = None, - valuesCount: Option[TreeGen] = None - ) { - def tpe = value.tpe - def withoutSizeInfo = copy(valueIndex = None, valuesCount = None) - } - - sealed trait TraversalDirection - case object FromLeft extends TraversalDirection - case object FromRight extends TraversalDirection - - sealed trait Order - case object SameOrder extends Order - case object ReverseOrder extends Order - case object Unordered extends Order - - sealed trait ResultKind - case object NoResult extends ResultKind - case object ScalarResult extends ResultKind - case object StreamResult extends ResultKind - - case class CanChainResult(canChain: Boolean, reason: Option[String]) - trait StreamChainTestable { - def consumesExtraFirstValue: Boolean = false - def producesExtraFirstValue: Boolean = false - def privilegedDirection: Option[TraversalDirection] = None - - def canChainAfter(previous: StreamChainTestable, privilegedDirection: Option[TraversalDirection]) = { - //println("previous.producesExtraFirstValue = " + previous.producesExtraFirstValue + ", this.consumesExtraFirstValue = " + consumesExtraFirstValue) - if (previous.producesExtraFirstValue && !consumesExtraFirstValue) - CanChainResult(false, Some("Operation " + this + " cannot consume the extra first value produced by " + previous)) - else if (privilegedDirection != None && privilegedDirection != this.privilegedDirection) - CanChainResult(false, Some("Operation " + this + " has a privileged direction incompatible with " + privilegedDirection)) - else - CanChainResult(true, None) - } - } - - class SideEffectsAnalyzer { - - def analyzeSideEffects(base: Tree, trees: Tree*): SideEffects = { - val flagger = createSideEffectsEvaluator(base, cached = false) - trees.map(flagger.evaluate(_)).foldLeft(sideEffectFreeAnalysis)(_ ++ _) - } - - def sideEffectFreeAnalysis: SideEffects = - Seq() - - def isSideEffectFree(analysis: SideEffects): Boolean = - analysis.isEmpty - } - trait SideEffectFreeStreamComponent extends StreamComponent { - override def analyzeSideEffectsOnStream(analyzer: SideEffectsAnalyzer) = - analyzer.sideEffectFreeAnalysis - } - - trait StreamComponent extends StreamChainTestable { - def tree: Tree - - def closuresCount = 0 - - /// Used to chain stream detection : give the unwrapped content of the tree - def unwrappedTree = tree - def analyzeSideEffectsOnStream(analyzer: SideEffectsAnalyzer): SideEffects - } - trait CanCreateStreamSink extends StreamChainTestable { - override def consumesExtraFirstValue: Boolean = true - - def createStreamSink(expectedType: Type, componentTpe: Type, outputSize: Option[TreeGen]): StreamSink - } - trait StreamSource extends StreamComponent { - def emit(direction: TraversalDirection)(implicit loop: Loop): StreamValue - } - trait StreamTransformer extends StreamComponent { - def order: Order - def reverses = false - def resultKind: ResultKind = StreamResult - - def transform(value: StreamValue)(implicit loop: Loop): StreamValue - } - trait StreamSink extends SideEffectFreeStreamComponent { - def output(value: StreamValue, expectedType: Type)(implicit loop: Loop): Unit - } - case class Stream( - source: StreamSource, - transformers: Seq[StreamTransformer] - ) - case class SideEffectFullComponent( - component: StreamComponent, - sideEffects: SideEffects, - preventedOptimizations: Boolean - ) - case class CodeWontBenefitFromOptimization(reason: String) - extends UnsupportedOperationException(reason) - - case class BrokenOperationsStreamException( - msg: String, - sourceAndOps: Seq[StreamComponent], - componentsWithSideEffects: Seq[SideEffectFullComponent] - ) extends UnsupportedOperationException(msg) - - def warnSideEffect(unit: CompilationUnit, tree: Tree) = { - unit.warning(tree.pos, "Beware of side-effects in operations streams." + (if (options.debug) " (" + tree + ")" else "")) - } - def assembleStream(stream: Stream, outerTree: Tree, transform: Tree => Tree, unit: CompilationUnit, pos: Position, currentOwner: Symbol, localTyper: analyzer.Typer): Tree = { - val Stream(source, transformers) = stream - - val sourceAndOps = source +: transformers - - val sinkCreatorOpt = - if (transformers.last.resultKind == StreamResult) - sourceAndOps.collect({ case ccss: CanCreateStreamSink => ccss }).lastOption match { - case Some(sinkCreator) => - Some(sinkCreator) - case _ => - throw new UnsupportedOperationException("Failed to find any CanCreateStreamSink instance in source ++ ops = " + sourceAndOps + " !") - } - else - None - - implicit val loop = new Loop(unit, pos, currentOwner, localTyper, transform) - var direction: Option[TraversalDirection] = None // TODO choose depending on preferred directions... - - val analyzer = new SideEffectsAnalyzer - - val brokenChain = - sourceAndOps. - map(comp => (comp, comp.analyzeSideEffectsOnStream(analyzer))). - dropWhile(_._2.isEmpty) - - val componentsWithSideEffects = brokenChain.filter(!_._2.isEmpty) - - if (brokenChain.size > 1) { - throw BrokenOperationsStreamException( - "Operations stream broken by side-effects", - sourceAndOps, - componentsWithSideEffects.zipWithIndex.map({ case ((comp, se), i) => - val prevented = i != componentsWithSideEffects.size - 1 - SideEffectFullComponent(comp, se, prevented) - }) - ) - } - if (options.veryVerbose) - for ((comp, sideEffects) <- componentsWithSideEffects; sideEffect <- sideEffects) - warnSideEffect(unit, sideEffect) - - for (Seq(a, b) <- (sourceAndOps ++ sinkCreatorOpt.toSeq).sliding(2, 1)) { - val CanChainResult(canChain, reason) = b.canChainAfter(a, direction) - if (!canChain) { - throw new UnsupportedOperationException("Cannot chain streams" + reason.map(" : " + _).getOrElse(".")) - } - direction = b.privilegedDirection.orElse(direction) - } - - var value = source.emit(direction.getOrElse(FromLeft)) - - for (transformer <- transformers) - value = transformer.transform(value) - - for (sinkCreator <- sinkCreatorOpt) { - val expectedType = outerTree.tpe//sourceAndOps.last.tree.tpe - val sink = sinkCreator.createStreamSink(expectedType, value.value.tpe, value.valuesCount) - sink.output(value, expectedType) - } - loop.tree.setType(sourceAndOps.last.tree.tpe) - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/TraversalOps.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/TraversalOps.scala deleted file mode 100644 index b5180581b..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/TraversalOps.scala +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: ochafik - * Date: 10/05/11 - * Time: 21:40 - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import tools.nsc.plugins.PluginComponent -import tools.nsc.Global - -trait TraversalOps -extends PluginNames - with StreamOps - with MiscMatchers -{ - this: PluginComponent with WithOptions with WorkaroundsForOtherPhases => - - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - - object ReduceName { - def apply(isLeft: Boolean) = error("not implemented") - def unapply(name: Name) = Option(name) collect { - case reduceLeftName() => true - case reduceRightName() => false - } - } - object ScanName { - def apply(isLeft: Boolean) = error("not implemented") - def unapply(name: Name) = Option(name) collect { - case scanLeftName() => true - case scanRightName() => false - } - } - object FoldName { - def apply(isLeft: Boolean) = error("not implemented") - def unapply(name: Name) = Option(name) collect { - case foldLeftName() => true - case foldRightName() => false - } - } - - def refineComponentType(componentType: Type, collectionTree: Tree): Type = { - collectionTree.tpe match { - case TypeRef(_, _, List(t)) => - t - case _ => - componentType - } - } - - import TraversalOps._ - - def traversalOpWithoutArg(n: Name, tree: Tree) = Option(n) collect { - case toListName() => - ToListOp(tree) - case toArrayName() => - ToArrayOp(tree) - case toSeqName() => - ToSeqOp(tree) // TODO !!! - case toIndexedSeqName() => - ToIndexedSeqOp(tree) - case toVectorName() => - ToVectorOp(tree) - //case reverseName() => - // ReverseOp(tree) // TODO !!! - case sumName() => - SumOp(tree) - case productName() => - ProductOp(tree) - case minName() => - MinOp(tree) - case maxName() => - MaxOp(tree) - } - - def basicTypeApplyTraversalOp(tree: Tree, collection: Tree, name: Name, typeArgs: List[Tree], args: Seq[List[Tree]]): Option[TraversalOp] = { - (name, typeArgs, args) match { - case // Option.map[B](f) - ( - mapName(), - List(mappedComponentType), - Seq( - List(function @ Func(List(_), _)) - ) - ) => - Some(new TraversalOp(MapOp(tree, function, null), collection, refineComponentType(mappedComponentType.tpe, tree), null, true, null)) - case // map[B, That](f)(canBuildFrom) - ( - mapName(), - List(mappedComponentType, mappedCollectionType), - Seq( - List(function @ Func(List(_), _)), - List(canBuildFrom @ CanBuildFromArg()) - ) - ) => - Some(new TraversalOp(MapOp(tree, function, canBuildFrom), collection, refineComponentType(mappedComponentType.tpe, tree), mappedCollectionType.tpe, true, null)) - case - ( - foreachName(), - List(fRetType), - Seq( - List(function) - ) - ) => - Some(new TraversalOp(ForeachOp(tree, function), collection, null, null, true, null)) - - case // scanLeft, scanRight - ( - ScanName(isLeft), - List(functionResultType, mappedArrayType), - Seq( - List(initialValue), - List(function), - List(CanBuildFromArg()) - ) - ) if isLeft => - Some(new TraversalOp(ScanOp(tree, function, initialValue, isLeft), collection, functionResultType.tpe, null, isLeft, initialValue)) - case // foldLeft, foldRight - ( - FoldName(isLeft), - List(functionResultType), - Seq( - List(initialValue), - List(function) - ) - ) if isLeft => - Some(new TraversalOp(FoldOp(tree, function, initialValue, isLeft), collection, functionResultType.tpe, null, isLeft, initialValue)) - case // toArray - ( - toArrayName(), - List(functionResultType @ TypeTree()), - Seq( - List(manifest) - ) - ) => - Some(new TraversalOp(new ToArrayOp(tree), collection, functionResultType.tpe, null, true, null)) - case // sum, product, min, max - ( - n @ (sumName() | productName() | minName() | maxName()), - List(functionResultType @ TypeTree()), - Seq( - List(isNumeric) - ) - ) => - isNumeric.toString match { - case - "math.this.Numeric.IntIsIntegral" | - "math.this.Numeric.ShortIsIntegral" | - "math.this.Numeric.LongIsIntegral" | - "math.this.Numeric.ByteIsIntegral" | - "math.this.Numeric.CharIsIntegral" | - "math.this.Numeric.FloatIsFractional" | - "math.this.Numeric.DoubleIsFractional" | - "math.this.Numeric.DoubleAsIfIntegral" | - "math.this.Ordering.Int" | - "math.this.Ordering.Short" | - "math.this.Ordering.Long" | - "math.this.Ordering.Byte" | - "math.this.Ordering.Char" | - "math.this.Ordering.Double" | - "math.this.Ordering.Float" - => - traversalOpWithoutArg(n, tree).collect { case op => new TraversalOp(op, collection, functionResultType.tpe, null, true, null) } - case _ => - None - } - case // reduceLeft, reduceRight - ( - ReduceName(isLeft), - List(functionResultType), - Seq( - List(function) - ) - ) if isLeft => - Some(new TraversalOp(ReduceOp(tree, function, isLeft), collection, functionResultType.tpe, null, isLeft, null)) - case // zip(col)(canBuildFrom) - ( - mapName(), - List(mappedComponentType, otherComponentType, mappedCollectionType), - Seq( - List(zippedCollection), - List(canBuildFrom @ CanBuildFromArg()) - ) - ) => - Some(new TraversalOp(ZipOp(tree, zippedCollection), collection, refineComponentType(mappedComponentType.tpe, tree), mappedCollectionType.tpe, true, null)) - case // zipWithIndex(canBuildFrom) - ( - zipWithIndexName(), - List(mappedComponentType, mappedCollectionType), - Seq( - List(canBuildFrom @ CanBuildFromArg()) - ) - ) => - Some(new TraversalOp(ZipWithIndexOp(tree), collection, refineComponentType(mappedComponentType.tpe, tree), mappedCollectionType.tpe, true, null)) - case _ => - None - } - } - object TraversalOp { - - def unapply(tree: Tree): Option[TraversalOp] = tree match { - case // Option.map[B](f) - BasicTypeApply( - collection, - name, - typeArgs, - args - ) => - // Having a separate matcher helps avoid "jump offset too large for 16 bits integers" errors when generating bytecode - basicTypeApplyTraversalOp(tree, collection, name, typeArgs, args) - case TypeApply(Select(collection, toSetName()), List(resultType)) => - Some(new TraversalOp(ToSetOp(tree), collection, resultType.tpe, tree.tpe, true, null)) - case // reverse, toList, toSeq, toIndexedSeq - Select(collection, n @ (reverseName() | toListName() /*| toSeqName()*/ | toIndexedSeqName() | toVectorName())) => - traversalOpWithoutArg(n, tree).collect { case op => new TraversalOp(op, collection, null, null, true, null) } - //Some(new TraversalOp(Reverse, collection, null, null, true, null)) - case // filter, filterNot, takeWhile, dropWhile, forall, exists - Apply(Select(collection, n), List(function @ Func(List(param), body))) => - ( - n match { - case withFilterName() => - //println("FOUND WITHFILTER") - collection match { - case IntRange(_, _, _, _, _) => - //println("FOUND IntRange") - Some(FilterOp(tree, function, false), collection.tpe) - case _ => - //println("FOUND None") - None - } - case filterName() => - Some(FilterOp(tree, function, false), collection.tpe) - case filterNotName() => - Some(FilterOp(tree, function, true), collection.tpe) - - case takeWhileName() => - Some(FilterWhileOp(tree, function, true), collection.tpe) - case dropWhileName() => - Some(FilterWhileOp(tree, function, false), collection.tpe) - - case forallName() => - Some(AllOrSomeOp(tree, function, true), BooleanClass.tpe) - case existsName() => - Some(AllOrSomeOp(tree, function, false), BooleanClass.tpe) - - case countName() => - Some(CountOp(tree, function), IntClass.tpe) - case updateName() => - Some(UpdateAllOp(tree, function), collection.tpe) - case _ => - None - } - ) match { - case Some((op, resType)) => - Some(new TraversalOp(op, collection, resType, null, true, null)) - case None => - None - } - case _ => - None - } - - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/TreeBuilders.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/TreeBuilders.scala deleted file mode 100644 index 8893f386d..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/TreeBuilders.scala +++ /dev/null @@ -1,550 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import java.io.File - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.ast.TreeDSL -import scala.tools.nsc.transform.TypingTransformers -import Function.tupled - -trait TreeBuilders -extends MiscMatchers - with TypingTransformers - with TreeDSL -{ - this: PluginComponent with WithOptions => - - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed, atOwner} // methods to type trees - import CODE._ - - def nodeToStringNoComment(tree: Tree) = - nodeToString(tree).replaceAll("\\s*//.*\n", "\n").replaceAll("\\s*\n\\s*", " ").replaceAll("\\(\\s+", "(").replaceAll("\\s+\\)", "") - - /// print a message only if the operation succeeded : - def msg[V](unit: CompilationUnit, pos: Position, text: => String)(v: => V): V = { - val fileLine = new File(pos.source.path).getName + ":" + pos.line - val prefix = "[scalacl] " + fileLine + " " - try { - val r = v - //unit.comment(pos, text) - if (options.verbose) { - val str = prefix + text - // Global.log(String) was removed or modified in Scala's trunk version... too bad ! - //global.log(str) - println(str) - } - r - } catch { - case ex: UnsupportedOperationException => - throw ex - case ex => - var str = - """An unexpected error occurred while attempting an optimization - Attempted optimization : '"""+ text + """' - You can skip this line with the following environment variable : - SCALACL_SKIP=""" + fileLine - - if (options.trace) { - ex.printStackTrace - str += "\n\tError : " + ex - } else { - str += """ - To display the error and help debug the ScalaCL compiler plugin, please set the following environment variable : - SCALACL_TRACE=1 - You can help by filing bugs here (with [ScalaCLPlugin] in the title) : - http://code.google.com/p/nativelibs4java/issues/entry""" - } - str = prefix + str.replaceAll("\n", "\n" + prefix) - - global.warning(str) - println(str) - - throw ex - } - } - - type TreeGen = () => Tree - - def replaceOccurrences(tree: Tree, mappingsSym: Map[Symbol, TreeGen], symbolReplacements: Map[Symbol, Symbol], treeReplacements: Map[Tree, TreeGen], unit: CompilationUnit) = { - def key(s: Symbol) = s.ownerChain.map(_.toString) - val mappings = mappingsSym.map({ case (sym, treeGen) => (key(sym), (sym, treeGen)) }) - val result = new TypingTransformer(unit) { - override def transform(tree: Tree): Tree = { - treeReplacements.get(tree).map(_()).getOrElse( - tree match { - case Ident(n) if tree.symbol != NoSymbol => - val treeKey = key(tree.symbol) - mappings.get(treeKey).map({ case (sym, treeGen) => - treeGen().setType(tree.symbol.tpe) - }).getOrElse(super.transform(tree)) - case _ => - super.transform(tree) - } - ) - } - }.transform(tree) - - for ((fromSym, toSym) <- symbolReplacements) - new ChangeOwnerTraverser(fromSym, toSym).traverse(result) - - typed { - result - } - } - - // TreeGen.mkIsInstanceOf adds an extra Apply (and does not set all symbols), which makes it apparently useless in our case(s) - def newIsInstanceOf(tree: Tree, tpe: Type) = { - try { - val tt = TypeTree(tpe) - tt.tpe = tpe - TypeApply( - Select( - tree, - N("isInstanceOf") - ).setSymbol(Any_isInstanceOf), - List(tt) - ).setSymbol(Any_isInstanceOf) - } catch { case ex => - ex.printStackTrace - throw new RuntimeException(ex) - } - } - def newApply(pos: Position, array: => Tree, index: => Tree) = { - val a = array - assert(a.tpe != null) - typed { - atPos(pos) { - //a.DOT(N("apply"))(index) - val sym = getMember(a.symbol, nme.apply).filter(_.paramss.size == 1) - Apply( - Select( - a, - N("apply") - ).setSymbol(sym), - List(index) - ).setSymbol(sym) - } - } - } - - def newSelect(target: Tree, name: Name, typeArgs: List[Tree] = Nil) = - newApply(target, name, typeArgs, null) - - def newApply(target: Tree/*, targetType: Type*/, name: Name, typeArgs: List[Tree] = Nil, args: List[Tree] = Nil) = { - val targetType = - if (target.tpe == NoType || target.tpe == null) - target.symbol.tpe - else - target.tpe - - val sym = targetType member name - typed { - val select = Select(target, name).setSymbol(sym) - if (!typeArgs.isEmpty) - Apply( - TypeApply(select, typeArgs).setSymbol(sym), - args - ) - else if (args != null) - Apply(select, args) - else - select - } - } - - def newInstance(tpe: Type, constructorArgs: List[Tree]) = { - val sym = tpe.typeSymbol.primaryConstructor - typed { - Apply( - Select( - New(TypeTree(tpe)),//.setSymbol(tpe.typeSymbol), - sym - ).setSymbol(sym), - constructorArgs - ).setSymbol(sym) - } - } - - def newCollectionApply(collectionModuleTree: => Tree, typeExpr: Tree, values: Tree*) = - newApply(collectionModuleTree, applyName, List(typeExpr), values.toList) - - def newScalaPackageTree = - Ident(N("scala")).setSymbol(ScalaPackage).setType(ScalaPackage.tpe) - - def newScalaCollectionPackageTree = - Select(newScalaPackageTree, N("collection")).setSymbol(ScalaCollectionPackage).setType(ScalaCollectionPackage.tpe) - - def newSomeModuleTree = typed { - Select(newScalaPackageTree, N("Some")).setSymbol(SomeModule) - } - - def newNoneModuleTree = typed { - Select(newScalaPackageTree, N("None")).setSymbol(NoneModule) - } - - def newSeqModuleTree = typed { - Select(newScalaCollectionPackageTree, N("Seq")).setSymbol(SeqModule) - } - - def newSetModuleTree = typed { - Select(newScalaCollectionPackageTree, N("Set")).setSymbol(SetModule) - } - - def newArrayModuleTree = typed { - Select(newScalaPackageTree, N("Array")).setSymbol(ArrayModule) - } - - def newSeqApply(typeExpr: Tree, values: Tree*) = - newApply(newSeqModuleTree, applyName, List(typeExpr), values.toList) - - def newTypeTree(tpe: Type) = - TypeTree(tpe).setType(tpe) - - def newSomeApply(tpe: Type, value: Tree) = - newApply(newSomeModuleTree, applyName, List(newTypeTree(tpe)), List(value)) - - def newArrayApply(typeExpr: Tree, values: Tree*) = - newApply(newArrayModuleTree, applyName, List(typeExpr), values.toList) - - def newArrayMulti(arrayType: Type, componentTpe: Type, lengths: => List[Tree], manifest: Tree) = - typed { - val sym = (ArrayModule.tpe member "ofDim" alternatives).filter(_.paramss.flatten.size == lengths.size + 1).head - Apply( - Apply( - TypeApply( - Select( - Ident( - ArrayModule - ), - N("ofDim") - ).setSymbol(sym), - List(TypeTree(componentTpe)) - ), - lengths - ).setSymbol(sym), - List(manifest) - ).setSymbol(sym) - } - - def newArray(componentType: Type, length: => Tree) = - newArrayWithArrayType(appliedType(ArrayClass.tpe, List(componentType)), length) - - def newArrayWithArrayType(arrayType: Type, length: => Tree) = - typed { - //NEW(TypeTree(arrayType), length) - val sym = arrayType.typeSymbol.primaryConstructor - Apply( - Select( - New(TypeTree(arrayType)),//.setSymbol(arrayType.typeSymbol), - sym - ).setSymbol(sym), - List(length) - ).setSymbol(sym) - } - - - def newUpdate(pos: Position, array: => Tree, index: => Tree, value: => Tree) = { - val a = array - assert(a.tpe != null) - val sym = getMember(a.symbol, nme.update) - typed { - atPos(pos) { - //a.DOT(N("update"))(index, value) - Apply( - Select( - a, - N("update") - ).setSymbol(sym).setType(sym.tpe), - List(index, typed { value }) - ).setSymbol(sym).setType(UnitClass.tpe) - //println(nodeToString(t)) - //treeBrowsers.create.browse(t) - } - } - } - - def binOp(a: Tree, op: Symbol, b: Tree) = typed { - assert(op != NoSymbol) - Apply(Select(a, op).setSymbol(op), List(b)).setSymbol(op) - } - - def newIsNotNull(target: Tree) = typed { - binOp(target, AnyRefClass.tpe.member(nme.NE/*N("neq")*/), newNull(target.tpe))//nme.NE) - } - - def newArrayLength(a: Tree) = - //a.DOT(nme.length) - Select(a, nme.length).setSymbol(getMember(a.symbol, nme.length)).setType(IntClass.tpe) - - def boolAnd(a: Tree, b: Tree) = typed { - if (a == null) - b - else if (b == null) - a - else - binOp(a, BooleanClass.tpe.member(nme.ZAND /* AMPAMP */), b) - } - def boolOr(a: Tree, b: Tree) = typed { - if (a == null) - b - else if (b == null) - a - else - binOp(a, BooleanClass.tpe.member(nme.ZOR), b) - } - def ident(sym: Symbol, n: Name, pos: Position = NoPosition) = { - assert(sym != NoSymbol) - val v = Ident(n) - v.symbol = sym - if (sym.hasRawInfo) - v.tpe = sym.tpe - v.pos = pos - v - } - - def boolNot(a: => Tree) = { - val sym = BooleanClass.tpe.member(nme.UNARY_!) - //Apply( - Select(a, nme.UNARY_!).setSymbol(sym).setType(BooleanClass.tpe)//, Nil).setSymbol(sym).setType(BooleanClass.tpe) - } - - def intAdd(a: => Tree, b: => Tree) = - binOp(a, IntClass.tpe.member(nme.PLUS), b) - - def intDiv(a: => Tree, b: => Tree) = - binOp(a, IntClass.tpe.member(nme.DIV), b) - - def intSub(a: => Tree, b: => Tree) = - binOp(a, IntClass.tpe.member(nme.MINUS), b) - - def newAssign(target: IdentGen, value: Tree) = - Assign(target(), value).setType(UnitClass.tpe) - - def incrementIntVar(identGen: IdentGen, value: Tree = newInt(1)) = - newAssign(identGen, intAdd(identGen(), value)) - - def decrementIntVar(identGen: IdentGen, value: Tree) = - //identGen() === intSub(identGen(), value) - Assign( - identGen(), - intSub(identGen(), value) - ).setType(UnitClass.tpe) - - def whileLoop(owner: Symbol, unit: CompilationUnit, tree: Tree, cond: Tree, body: Tree): Tree = - whileLoop(owner, unit, tree.pos, cond, body) - - def whileLoop(owner: Symbol, unit: CompilationUnit, pos: Position, cond: Tree, body: Tree): Tree = { - val lab = unit.fresh.newName(body.pos, "while$") - val labTyp = MethodType(Nil, UnitClass.tpe) - val labSym = owner.newLabel(pos, N(lab)).setInfo(labTyp).setFlag(SYNTHETIC | LOCAL) - - typed { - //body.tpe = UnitClass.tpe - LabelDef( - N(lab), - Nil, - If( - cond, - Block( - if (body == null) - Nil - else - List(body), - Apply( - ident(labSym, lab, pos), - Nil - ) - ), - newUnit - ) - ).setSymbol(labSym) - } - } - - type IdentGen = () => Ident - - private lazy val anyValTypeInfos = Seq[(Class[_], Type, AnyVal)]( - ( classOf[java.lang.Boolean], BooleanClass.tpe, false ), - ( classOf[java.lang.Integer], IntClass.tpe, 0), - ( classOf[java.lang.Long], LongClass.tpe, 0: Long), - ( classOf[java.lang.Short], ShortClass.tpe, 0: Short), - ( classOf[java.lang.Byte], ByteClass.tpe, 0: Byte), - ( classOf[java.lang.Character], CharClass.tpe, 0.asInstanceOf[Char]), - ( classOf[java.lang.Double], DoubleClass.tpe, 0.0), - ( classOf[java.lang.Float], FloatClass.tpe, 0.0f) - ) - val classToType: Map[Class[_], Type] = - (anyValTypeInfos.map { case (cls, tpe, defVal) => cls -> tpe }).toMap - - val typeToDefaultValue: Map[Type, AnyVal] = - (anyValTypeInfos.map { case (cls, tpe, defVal) => tpe -> defVal }).toMap - - def newConstant(v: Any, tpe: Type = null) = { - Literal(Constant(v)).setType( - if (tpe != null) - tpe - else if (v.isInstanceOf[String]) - StringClass.tpe - else - classToType(v.getClass) - ) - } - - def newBool(v: Boolean) = newConstant(v) - def newInt(v: Int) = newConstant(v) - def newLong(v: Long) = newConstant(v) - - def newNull(tpe: Type) = newConstant(null, tpe) - - def newDefaultValue(tpe: Type) = { - if (isAnyVal(tpe)) - newConstant(typeToDefaultValue(tpe), tpe) - else - newNull(tpe) - } - - def newOneValue(tpe: Type) = { - assert(isAnyVal(tpe)) - Literal(Constant(1: Byte)).setType(tpe) - } - - def newUnit() = - Literal(Constant()).setType(UnitClass.tpe) - - case class VarDef(rawIdentGen: IdentGen, symbol: Symbol, definition: ValDef) { - var identUsed = false - val identGen: IdentGen = () => { - identUsed = true - rawIdentGen() - } - def tpe = definition.tpe - def apply() = identGen() - - def defIfUsed = if (identUsed) Some(definition) else None - def ifUsed[V](v: => V) = if (identUsed) Some(v) else None - } - implicit def VarDev2IdentGen(vd: VarDef) = if (vd == null) null else vd.identGen - - def simpleBuilderResult(builder: Tree): Tree = typed { - val resultMethod = builder.tpe member resultName - Apply( - Select( - builder, - resultName - ).setSymbol(resultMethod),//.setType(resultMethod.tpe), - Nil - ).setSymbol(resultMethod) - } - - def addAssign(target: Tree, toAdd: Tree) = { - val sym = (target.tpe member addAssignName).alternatives.head// filter (_.paramss.size == 1) - Apply( - Select( - target, - addAssignName - ).setSymbol(sym).setType(sym.tpe), - List(toAdd) - ).setSymbol(sym).setType(UnitClass.tpe) - } - - def toArray(tree: Tree, componentType: Type, localTyper: analyzer.Typer) = typed { - val manifest = localTyper.findManifest(componentType, false).tree - assert(manifest != EmptyTree, "Failed to get manifest for " + componentType) - - val method = tree.tpe member toArrayName - Apply( - TypeApply( - Select( - tree, - toArrayName - ).setSymbol(method).setType(method.tpe), - List(TypeTree(componentType)) - ), - List(manifest) - ).setSymbol(method) - } - - def newIf(cond: Tree, thenTree: Tree, elseTree: Tree = null) = { - typed { thenTree } - if (elseTree != null) - typed { elseTree } - - If(cond, thenTree, Option(elseTree).getOrElse(EmptyTree)).setType { - if (elseTree == null) - UnitClass.tpe - else if (thenTree.tpe == elseTree.tpe) - thenTree.tpe - else - throw new RuntimeException("Mismatching types between then and else : " + thenTree.tpe + " vs. " + elseTree.tpe) - } - } - - def newVariable( - unit: CompilationUnit, - prefix: String, - symbolOwner: Symbol, - pos: Position, - mutable: Boolean, - initialValue: Tree - ): VarDef = { - typed { initialValue } - var tpe = initialValue.tpe - if (tpe.isInstanceOf[ConstantType]) - tpe = tpe.widen - val name = unit.fresh.newName(pos, prefix) - val sym = ( - if (mutable) - symbolOwner.newVariable(pos, name) - else - symbolOwner.newValue(pos, name) - ).setFlag(SYNTHETIC | LOCAL) - if (tpe != null && tpe != NoType) - sym.setInfo(tpe) - - VarDef( - () => ident(sym, name, pos), - sym, - ValDef( - Modifiers(if (mutable) MUTABLE else 0), - name, - TypeTree(tpe), - initialValue - ).setType(tpe).setSymbol(sym) - ) - } -} - diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/TuplesAnalysis.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/TuplesAnalysis.scala deleted file mode 100644 index 7d7763f61..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/TuplesAnalysis.scala +++ /dev/null @@ -1,396 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.collection.immutable.Stack -import scala.collection.mutable.ArrayBuffer -import scala.reflect.NameTransformer -import scala.reflect.generic.{Names, Trees, Types, Constants, Universe} -import scala.tools.nsc.Global -import tools.nsc.plugins.PluginComponent - -trait TupleAnalysis -extends MiscMatchers - with TreeBuilders -{ - this: PluginComponent with WithOptions => - - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed} // methods to type trees - import CODE._ - - import gen._ - import scala.tools.nsc.symtab.Flags._ - import analyzer.{SearchResult, ImplicitSearch} - - case class TupleInfo(tpe: Type, components: Seq[TupleInfo]) { - lazy val flattenTypes: Seq[Type] = { - components match { - case Seq() => - Seq(tpe) - case _ => - components.flatMap(_.flattenTypes) - } - } - lazy val flattenPaths: Seq[List[Int]] = { - components match { - case Seq() => - Seq(Nil) - case _ => - components.zipWithIndex.flatMap { case (c, i) => c.flattenPaths.map(p => i :: p) } - } - } - lazy val componentSize: Int = { - components match { - case Seq() => - 1 - case _ => - components.map(_.componentSize).sum - } - } - } - private val tupleInfos = new scala.collection.mutable.HashMap[Type, TupleInfo] - - def getTupleInfo(tpe: Type): TupleInfo = { - val actualTpe = normalize(tpe) - tupleInfos.getOrElseUpdate( - actualTpe, - if (isUnit(actualTpe)) - TupleInfo(UnitClass.tpe, Seq()) - else { - actualTpe match { - case t: TypeRef => - if (isTupleSymbol(t.sym)) - TupleInfo(t, t.args.map(getTupleInfo)) - else - TupleInfo(t, Seq()) - case NoType => - TupleInfo(NoType, Seq()) - case _ => - throw new RuntimeException("Unhandled type : " + tpe + " (" + actualTpe + ": " + actualTpe.getClass.getName + ")") - //System.exit(0) - null - } - } - ) - } - def flattenTypes(tpe: Type): Seq[Type] = - getTupleInfo(tpe).flattenTypes - - def flattenFiberPaths(tpe: Type): Seq[List[Int]] = - flattenFiberPaths(getTupleInfo(tpe)) - - def flattenFiberPaths(info: TupleInfo): Seq[List[Int]] = { - val TupleInfo(_, components) = info - if (components.isEmpty) - Seq(Nil) - else - components.map(flattenFiberPaths).zipWithIndex flatMap { - case (paths, i) => paths.map(path => i :: path) - } - } - def applyFiberPath(rootGen: TreeGen, path: List[Int]): Tree = { - def sub(invertedPath: List[Int]): Tree = invertedPath match { - case Nil => - rootGen() - case i :: rest => - val inner = applyFiberPath(rootGen, rest) - val name = N("_" + (i + 1)) - - //println("Getting member " + i + " of (" + inner + ": " + inner.tpe + ") ; invertedPath = " + invertedPath) - val info = getTupleInfo(inner.tpe) - assert(i < info.components.size, "bad path : i = " + i + ", type = " + inner.tpe + ", path = " + path + ", root = " + rootGen()) - assert(inner.tpe != null && inner.tpe != NoType, "Cannot apply tuple path on untyped tree") - val sym = inner.tpe member name - Select(inner, name).setSymbol(sym).setType(info.components(i).tpe) - } - sub(path.reverse) - } - - def getComponentOffsetAndSizeOfIthMember(tpe: Type, i: Int) = { - val TupleInfo(_, components) = getTupleInfo(tpe) - ( - components.take(i).map(_.componentSize).sum, - components(i).componentSize - ) - } - - /** - * Phases : - * - unique renaming - * - tuple cartography (map symbols and treeId to TupleSlices : x._2 will be checked against x ; if is x's symbol is mapped, the resulting slice will be composed and flattened - * - tuple + block flattening (gives (Seq[Tree], Seq[Tree]) result) - */ - // separate pass should return symbolsDefined, symbolsUsed - // DefTree vs. RefTree - - case class TupleSlice(baseSymbol: Symbol, sliceOffset: Int, sliceLength: Int) { - def subSlice(offset: Int, length: Int) = - TupleSlice(baseSymbol, sliceOffset + offset, length) - - def toTreeGen(analyzer: TupleAnalyzer): TreeGen = () => { - val info = getTupleInfo(baseSymbol.tpe) - val root: TreeGen = () => ident(baseSymbol, baseSymbol.name) - assert(sliceLength == 1) - //TupleCreation((0 until sliceLength).map(i => applyFiberPath(root, info.flattenPaths(sliceOffset + i))):_*) - val flatPaths = info.flattenPaths - assert(sliceOffset < flatPaths.size, "slice offset = " + sliceOffset + ", flat paths = " + flatPaths) - var res = applyFiberPath(root, flatPaths(sliceOffset)) - //analyzer.setSlice(res, this) - //res = replace(res) - analyzer.setSlice(res, this) - res - } - } - class BoundTuple(rootSlice: TupleSlice) { - def unapply(tree: Tree): Option[Seq[(Symbol, TupleSlice)]] = tree match { - case Bind(name, what) => - val sub = this - what match { - case Ident(_) => - //println("Found bind with name " + name) - Some(Seq(tree.symbol -> rootSlice)) - case sub(m) => - Some(m :+ (tree.symbol -> rootSlice)) - case _ => - throw new RuntimeException("Not a bound tuple : " + tree + " (" + tree.getClass.getName + ")\n\tnodes = " + nodeToString(tree)) - //System.exit(1) - None - } - case TupleCreation(components) => - //println("Found tuple creation with components " + components) - var currentOffset = 0 - val ret = new scala.collection.mutable.ArrayBuffer[(Symbol, TupleSlice)] - for ((component, i) <- components.zipWithIndex) { - val compTpes = flattenTypes(component.tpe) - val compSize = compTpes.size - val subMatcher = new BoundTuple(rootSlice.subSlice(currentOffset, compSize)) - component match { - case subMatcher(m) => - ret ++= m - case _ => - //println("Cancelling BoundTuple because of component " + component + " of type " + component.tpe + " (length " + compSize + ") at offset " + currentOffset) - return None // strict binding - } - currentOffset += compSize - } - Some(ret) - case _ => - throw new RuntimeException("Not a bound tuple : " + tree + " (" + tree.getClass.getName + ")\n\tnodes = " + nodeToString(tree)) - //System.exit(1) - None - } - } - class TupleAnalyzer(tree: Tree) { - - - var treeTupleSlices = new scala.collection.mutable.HashMap[(Int, Tree), TupleSlice]() - //private var symbolTupleSlices = new scala.collection.mutable.HashMap[Symbol, TupleSlice]() - var symbolTupleSlices = new scala.collection.mutable.HashMap[Symbol, TupleSlice]() - - def getSymbolSlice(sym: Symbol, recursive: Boolean = false): Option[TupleSlice] = { - val direct = symbolTupleSlices.get(sym) - direct match { - case Some(directSlice) if recursive && directSlice.sliceLength > 1 && directSlice.baseSymbol != sym => - getSymbolSlice(directSlice.baseSymbol, recursive).orElse(direct) - case _ => - direct - } - } - def createTupleSlice(sym: Symbol, tpe: Type) = { - val info = getTupleInfo(tpe) - //assert(info.componentSize == 1, "Invalid multi-fibers slice for symbol " + sym + " (" + info.componentSize + " fibers)") - TupleSlice(sym, 0, info.componentSize) - } - - def getTreeSlice(tree: Tree, recursive: Boolean = false): Option[TupleSlice] = { - val direct = symbolTupleSlices.get(tree.symbol).orElse(treeTupleSlices.get((tree.id, tree))) - if (recursive && direct != None) - getSymbolSlice(direct.get.baseSymbol, recursive).orElse(direct) - else - direct.orElse( - if (tree.symbol == null || - tree.symbol.getClass != classOf[TermSymbol] || // not isInstanceOf ! We don't want ModuleSymbol nor MethodSymbol here, which are both TermSymbol subclasses - tree.tpe == null || tree.tpe == NoType) - None - else { - //println("Created slice for symbol " + tree.symbol + " (tree = " + tree + ", symbol.class = " + tree.symbol.getClass.getName + ")") - Some(createTupleSlice(tree.symbol, tree.tpe)) - //None - } - ) - } - - def setSlice(sym: Symbol, slice: TupleSlice) = { - assert(sym != slice.baseSymbol, "Invalid self-slice for symbol " + sym) - //println("Setting slice " + slice + " for symbol " + sym) - symbolTupleSlices(sym) = slice - } - - def setSlice(tree: Tree, slice: TupleSlice) = { - //println("Setting slice " + slice + " for tree " + tree) - val info = getTupleInfo(slice.baseSymbol.tpe) - val n = info.flattenPaths.size - assert(slice.sliceOffset + slice.sliceLength <= n, "invalid slice for type " + tree.tpe + " : " + slice + ", flat types = " + info.flattenTypes) - treeTupleSlices((tree.id, tree)) = slice - tree match { - case vd: ValDef => - symbolTupleSlices(tree.symbol) = slice - case _ => - } - } - - // Identify trees and symbols that represent tuple slices - new Traverser { - override def traverse(tree: Tree): Unit = { - tree match { - case ValDef(mods, name, tpt, rhs) if !mods.hasFlag(MUTABLE) => - super.traverse(tree) - //println("Got valdef " + name) - val tupleInfo = getTupleInfo(rhs.tpe) - if (tupleInfo == null) { - throw new RuntimeException("No tuple info for type " + rhs.tpe + " !") - } - //setSlice(tree.symbol, TupleSlice(tree.symbol, 0, tupleInfo.componentSize)) - for (slice <- getTreeSlice(rhs, true)) { - //println("\tvaldef " + tree.symbol + " linked to rhs slice " + slice) - setSlice(tree.symbol, slice) - } - case Match(selector, cases) => - traverse(selector) - //println("Found match") - for (slice <- getTreeSlice(selector)) { - //println("\tMatch has slice " + slice) - val subMatcher = new BoundTuple(slice) - for (CaseDef(pat, guard, body) <- cases) { - pat match { - case subMatcher(m) => - //println("CaseDef has guard " + guard + " (cases = " + cases + ")") - assert(guard == EmptyTree, guard) - for ((sym, subSlice) <- m) { - //println("Binding " + sym + " to " + subSlice) - setSlice(sym, subSlice) - } - for (bodySlice <- getTreeSlice(body)) { - //println("Set body slice " + bodySlice + " for body " + body) - setSlice(tree, bodySlice) - } - case _ => - assert(false, "Case matching only supports tuples for now (TODO: add (CL)Array(...) case).") - } - } - } - cases.foreach(traverse(_)) - case TupleComponent(target, i) if target != null => - super.traverse(tree) - val (componentsOffset, componentCount) = getComponentOffsetAndSizeOfIthMember(target.tpe, i) - - //println("Identified tuple component " + i + " of " + target) - getTreeSlice(target) match { - case Some(slice) => - //println("\ttarget got slice " + slice) - setSlice(tree, TupleSlice(slice.baseSymbol, componentsOffset, componentCount)) - case _ => - //println("No tuple slice symbol info for tuple component i = " + i + " : " + target + "\n\t-> " + nodeToStringNoComment(target)) - //println("\ttree : " + nodeToStringNoComment(tree)) - } - case Typed(expr, tpt) => - super.traverse(tree) - propagateSlice(expr, tree) - case Annotated(annot, arg) => - super.traverse(tree) - propagateSlice(arg, tree) - case _ => - super.traverse(tree) - } - } - def propagateSlice(source: Tree, destination: Tree) = { - getTreeSlice(source) match { - case Some(slice) => - setSlice(destination, slice) - //println("Propagated slice " + slice + " from " + source + " to " + destination) - case _ => - } - } - }.traverse(tree) - - //println("treeTupleSlices = \n\t" + treeTupleSlices.mkString("\n\t")) - //println("symbolTupleSlices = \n\t" + symbolTupleSlices.mkString("\n\t")) - - // 1) Create unique names for unique symbols ! - // 2) Detect external references, lift them up in arguments. - // 3) Annotate code with usage : - // - symbol to Array and CLArray val : read, written, both ? - // - extern vars : forbidden - // - - // 4) Flatten tuples and blocks, function definitions arg lists, function calls args - // - // Symbol => TupleSlice - // Tree => TupleSlice - // e.g. x: ((Double, Float), Int) ; x._1._2 => TupleSlice(x, 1, 1) - // - // Tuples flattening : - // - list tuple definitions - // - explode each definition unless it's an OpenCL intrinsic : - // -> create a new symbol for each split component, - // -> map resulting TupleSlice => componentSymbol - // -> splitSymbolsTable = Map[Symbol, Seq[(TupleSlice, componentSymbol, componentName)]] - // - given a Tree, we get an exploded Seq[Tree] + pre-definitions - // e.g.: - // val a: (Int, Int) = (1, 3) - // -> val a1 = 1 - // val a2 = 3 - // val a: (Int, Int) = f(x) // special case for int2 : no change - // We need to propagate slices that are of length > 1 : - // - arr1.zip(arr2).zipWithIndex.map { case r @ (p @ (a1, a2), i) => p } map { p => p._1 } - // -> p => TupleSlice(mapArg, 0, 2) - // - val (a, b) = p // p is mapped - // -> val a = p1 // using splitSymbolsTable - // val b = p2 - // Jump over blocks : - // val p = { - // val x = 10 - // (x, x + 2) - // } - // -> - // val x = 10 - // val p1 = x - // val p2 = x + 2 - // - // Each Tree gives a list of statements + a list of split value components : - // convertTree(tree: Tree): (Seq[Tree], Seq[Tree]) - // - // - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/common/WorkaroundsForOtherPhases.scala b/libraries/Scalaxy/src/main/scala/scalaxy/common/WorkaroundsForOtherPhases.scala deleted file mode 100644 index 54b06463e..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/common/WorkaroundsForOtherPhases.scala +++ /dev/null @@ -1,142 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - * - * - * - * Contains portions of scala-2.8.0.final-sources/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala : - * NSC -- new Scala compiler - * Copyright 2005-2010 LAMP/EPFL - * @author Martin Odersky - * - */ - -package com.nativelibs4java.scalaxy ; package common -import pluginBase._ - -import scala.reflect.NameTransformer -import scala.tools.nsc.Global -import scala.tools.nsc.ast.TreeDSL - -trait WorkaroundsForOtherPhases extends TreeDSL with MiscMatchers { - val global: Global - import global._ - import definitions._ - import treeInfo.{ methPart } - import typer.typed - import CODE._ - - /** - * This code was copied from the following source from the Scala Compiler : scala-2.8.0.final-sources/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala - * To trigger the targetted "no-symbol has no owner" bug, try compiling Types.scala and Typers.scala : - * SCALACL_NO_WORKAROUND_FOR_THIS_OUTERREF_NOSYMBOL=1 SRCS=/Users/ochafik/src/scala-2.8.x scalac -bootclasspath $SRCS/build/locker/classes/library -cp $SRCS/build/locker/classes/compiler $SRCS/src/compiler/scala/tools/nsc/symtab/Types.scala $SRCS/src/compiler/scala/tools/nsc/typechecker/Typers.scala - */ - def assertNoThisWithNoSymbolOuterRef(tree: Tree, localTyper: analyzer.Typer): Unit = if ("1" == System.getenv("SCALACL_NO_WORKAROUND_FOR_THIS_OUTERREF_NOSYMBOL")) new Transformer { - protected def outerPath(base: Tree, from: Symbol, to: Symbol): Tree = { - //Console.println("outerPath from "+from+" to "+to+" at "+base+":"+base.tpe) - //assert(base.tpe.widen.baseType(from.toInterface) != NoType, ""+base.tpe.widen+" "+from.toInterface)//DEBUG - if (from == to || from.isImplClass && from.toInterface == to) base - else outerPath(outerSelect(base), from.outerClass, to) - } - def outerAccessor(clazz: Symbol): Symbol = { - val firstTry = clazz.info.decl(nme.expandedName(nme.OUTER, clazz)) - if (firstTry != NoSymbol && firstTry.outerSource == clazz) firstTry - else clazz.info.decls find (_.outerSource == clazz) getOrElse NoSymbol - } - - private def outerSelect(base: Tree): Tree = { - val outerAcc = outerAccessor(base.tpe.typeSymbol.toInterface) - val currentClass = this.currentClass //todo: !!! if this line is removed, we get a build failure that protected$currentClass need an override modifier - // outerFld is the $outer field of the current class, if the reference can - // use it (i.e. reference is allowed to be of the form this.$outer), - // otherwise it is NoSymbol - val outerFld = - if (outerAcc.owner == currentClass && - base.tpe =:= currentClass.thisType && - outerAcc.owner.isFinal) - outerField(currentClass) suchThat (_.owner == currentClass) - else - NoSymbol - val path = - if (outerFld != NoSymbol) Select(base, outerFld) - else Apply(Select(base, outerAcc), Nil) - - localTyper typed path - } - - private def outerField(clazz: Symbol): Symbol = { - val result = clazz.info.member(nme getterToLocal nme.OUTER) - assert(result != NoSymbol, "no outer field in "+clazz+clazz.info.decls+" at "+phase) - - result - } - - protected def outerValue: Tree = - if (outerParam != NoSymbol) ID(outerParam) - else outerSelect(THIS(currentClass)) - - protected var outerParam: Symbol = NoSymbol - - private def isInner(clazz: Symbol) = - !clazz.isPackageClass && !clazz.outerClass.isStaticOwner - - override def transform(tree: Tree) = { - val savedOuterParam = outerParam - try { - tree match { - case Template(_, _, _) => - outerParam = NoSymbol - case DefDef(_, _, _, vparamss, _, _) => - if (tree.symbol.isClassConstructor && isInner(tree.symbol.owner)) { - outerParam = vparamss.head.head.symbol - assert(outerParam.name startsWith nme.OUTER, outerParam.name) - } - case _ => - } - - if (tree.isInstanceOf[This]) { - val This(qual) = tree - val sym = tree.symbol - - import scala.tools.nsc._ - import symtab._ - import Flags.{ CASE => _, _ } - if (sym == currentClass || (sym hasFlag MODULE) && sym.isStatic) tree - else outerPath(outerValue, currentClass.outerClass, sym) - } - super.transform(tree) - } - finally { - outerParam = savedOuterParam - } - - } - }.transform(tree) - -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/components/MyComponent.scala b/libraries/Scalaxy/src/main/scala/scalaxy/components/MyComponent.scala deleted file mode 100644 index 0b02e46b2..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/components/MyComponent.scala +++ /dev/null @@ -1,55 +0,0 @@ - -package com.nativelibs4java.scalaxy ; package components -import common._ -import pluginBase._ - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} - -object MyComponent { - val runsAfter = List[String]( - "typer" - ) - val runsBefore = List[String]()// LoopsTransformComponent.phaseName) - val phaseName = "myphase" -} - -class MyComponent(val global: Global, val options: PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - - with MiscMatchers - with TreeBuilders - with WorkaroundsForOtherPhases - - with WithOptions -{ - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed, atOwner} // methods to type trees - - override val runsAfter = StreamTransformComponent.runsAfter - override val runsBefore = StreamTransformComponent.runsBefore - override val phaseName = StreamTransformComponent.phaseName - - def newTransformer(compilationUnit: CompilationUnit) = new TypingTransformer(compilationUnit) { - - val unit = compilationUnit - - val ofDimName = N("ofDim") - - override def transform(tree: Tree): Tree = { - tree match { - case Apply(TypeApply(Select(_, ofDimName()), List(bTypeTree)), List(firstDimTree)) => - println("FOUND SOME ARRAY OFDIM = " + tree) - super.transform(tree) - case _ => - super.transform(tree) - } - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/components/StreamTransformComponent.scala b/libraries/Scalaxy/src/main/scala/scalaxy/components/StreamTransformComponent.scala deleted file mode 100644 index a80f5958b..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/components/StreamTransformComponent.scala +++ /dev/null @@ -1,335 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package components -import common._ -import pluginBase._ - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} - -object StreamTransformComponent { - val runsAfter = List[String]( - "namer" - ) - val runsBefore = List[String]("refchecks", LoopsTransformComponent.phaseName) - val phaseName = "scalacl-stream" -} - -class StreamTransformComponent(val global: Global, val options: PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - with MiscMatchers - with TreeBuilders - with TraversalOps - with Streams - with StreamSources - with StreamOps - with StreamSinks - with WithOptions - with WorkaroundsForOtherPhases -{ - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed, atOwner} // methods to type trees - import System.getenv - - override val runsAfter = StreamTransformComponent.runsAfter - override val runsBefore = StreamTransformComponent.runsBefore - override val phaseName = StreamTransformComponent.phaseName - - def newTransformer(compilationUnit: CompilationUnit) = new TypingTransformer(compilationUnit) { - - class OpsStream(val source: StreamSource, val colTree: Tree, val ops: List[StreamTransformer]) - object OpsStream { - def unapply(tree: Tree) = { - var ops = List[StreamTransformer]() - var colTree = tree - var source: StreamSource = null - var finished = false - while (!finished) { - //println("Trying to match " + colTree) - colTree match { - case TraversalOp(traversalOp) if traversalOp.op.isInstanceOf[StreamTransformer] => - //println("found op " + traversalOp + "\n\twith collection = " + traversalOp.collection) - val trans = traversalOp.op.asInstanceOf[StreamTransformer] - if (trans.resultKind != StreamResult) - ops = List() - ops = trans :: ops - colTree = traversalOp.collection - case StreamSource(cr) => - //println("found streamSource " + cr.getClass + " (ops = " + ops + ")") - source = cr - if (colTree != cr.unwrappedTree) { - //println("Unwrapping " + colTree.tpe + " into " + cr.unwrappedTree.tpe) - colTree = cr.unwrappedTree - } else - finished = true - case _ => - //if (!ops.isEmpty) println("Finished with " + ops.size + " ops upon "+ tree + " ; source = " + source + " ; colTree = " + colTree) - finished = true - } - } - if (ops.isEmpty || source == null) - None - else - Some(new OpsStream(source, colTree, ops)) - } - } - - val unit = compilationUnit - - var matchedColTreeIds = Set[Long]() - - override def transform(tree: Tree): Tree = { - //val retryWithSmallerChain = false - //def internalTransform(tree: Tree, retryWithSmallerChain: Boolean) = transform(tree) - - internalTransform(tree) - } - - protected def internalTransform(tree: Tree, retryWithSmallerChain: Boolean = true): Tree = { - if (!shouldOptimize(tree)) - super.transform(tree) - else - try { - tree match { - case ArrayTabulate(componentType, lengths @ (firstLength :: otherLengths), f @ Func(params, body), manifest) if "0" != getenv("SCALACL_TRANSFORM_TABULATE") => - val tpe = body.tpe - val returnType = if (tpe.isInstanceOf[ConstantType]) - tpe.widen - else - tpe - - val lengthDefs = lengths.map(length => newVariable(unit, "n$", currentOwner, tree.pos, false, length.setType(IntClass.tpe))) - - msg(unit, tree.pos, "transformed Array.tabulate[" + returnType + "] into equivalent while loop") { - - def replaceTabulates(lengthDefs: List[VarDef], parentArrayIdentGen: IdentGen, params: List[ValDef], mappings: Map[Symbol, TreeGen], symbolReplacements: Map[Symbol, Symbol]): (Tree, Type) = { - - val param = params.head - val pos = tree.pos - val nVar = lengthDefs.head - val iVar = newVariable(unit, "i$", currentOwner, pos, true, newInt(0)) - val iVal = newVariable(unit, "i$val$", currentOwner, pos, false, iVar()) - - val newMappings: Map[Symbol, TreeGen] = mappings + (param.symbol -> iVal) - val newReplacements = symbolReplacements ++ Map(param.symbol -> iVal.symbol, f.symbol -> currentOwner) - - val mappedArrayTpe = getArrayType(lengthDefs.size, returnType) - - val arrayVar = if (parentArrayIdentGen == null) - newVariable(unit, "m$", currentOwner, tree.pos, false, newArrayMulti(mappedArrayTpe, returnType, lengthDefs.map(_.identGen()), manifest)) - else - VarDef(parentArrayIdentGen, null, null) - - val subArrayVar = if (lengthDefs.tail == Nil) - null - else - newVariable(unit, "subArray$", currentOwner, tree.pos, false, newApply(tree.pos, arrayVar(), iVal())) - - val (newBody, bodyType) = if (lengthDefs.tail == Nil) - ( - replaceOccurrences( - body, - newMappings, - newReplacements, - Map(), - unit - ), - returnType - ) - else - replaceTabulates( - lengthDefs.tail, - subArrayVar, - params.tail, - newMappings, - newReplacements - ) - - newBody.setType(bodyType) - - ( - super.transform { - typed { - treeCopy.Block( - tree, - ( - if (parentArrayIdentGen == null) - lengthDefs.map(_.definition) :+ arrayVar.definition - else - Nil - ) ++ - List( - iVar.definition, - whileLoop( - currentOwner, - unit, - tree, - binOp( - iVar(), - IntClass.tpe.member(nme.LT), - nVar() - ), - Block( - ( - if (lengthDefs.tail == Nil) - List( - iVal.definition, - newUpdate( - tree.pos, - arrayVar(), - iVar(), - newBody - ) - ) - else { - List( - iVal.definition, - subArrayVar.definition, - newBody - ) - } - ), - incrementIntVar(iVar, newInt(1)) - ) - ) - ), - if (parentArrayIdentGen == null) - arrayVar() - else - newUnit - ) - } - }, - mappedArrayTpe - ) - } - replaceTabulates(lengthDefs, null, params, Map(), Map())._1 - } - case OpsStream(opsStream) - if - options.stream && - //(opsStream.source ne null) && - //!opsStream.ops.isEmpty && - //(opsStream ne null) && - (opsStream.colTree ne null) && - !matchedColTreeIds.contains(opsStream.colTree.id) - => - import opsStream._ - - val txt = "Streamed ops on " + (if (source == null) "UNKNOWN COL" else source.tree.tpe) + " : " + ops/*.map(_.getClass.getName)*/.mkString(", ") - matchedColTreeIds += colTree.id - msg(unit, tree.pos, "# " + txt) { - try { - val stream = Stream(source, ops) - checkStreamWillBenefitFromOptimization(stream) - val asm = assembleStream(stream, tree, this.transform _, unit, tree.pos, currentOwner, localTyper) - //println(txt + "\n\t" + asm.toString.replaceAll("\n", "\n\t")) - //println("### TRANSFORMED : ###\n" + nodeToString(asm)) - asm - } catch { - case BrokenOperationsStreamException(msg, sourceAndOps, componentsWithSideEffects) => - unit.warning(sourceAndOps.head.tree.pos, "Cannot optimize this operations stream due to side effects") - for (SideEffectFullComponent(comp, sideEffects, preventedOptimizations) <- componentsWithSideEffects) { - for (sideEffect <- sideEffects) { - if (preventedOptimizations) - unit.warning(sideEffect.pos, "This side-effect prevents optimization of the enclosing " + comp + " operation" + - (if (options.veryVerbose) " ; node = " + nodeToString(sideEffect) else "") - ) - else if (options.veryVerbose) - warnSideEffect(unit, sideEffect) - } - //println("Side effects of " + comp + " :\n\t" + sideEffects.mkString(",\n\t")) - } - - val sub = super.transform(tree) - if (retryWithSmallerChain) - internalTransform(sub, retryWithSmallerChain = false) - else - sub - } - } - case _ => - super.transform(tree)//toMatch) - } - } catch { - case ex: CodeWontBenefitFromOptimization => - if (options.veryVerbose) - unit.warning(tree.pos, ex.toString) - super.transform(tree) - case ex => - if (options.veryVerbose) - ex.printStackTrace - super.transform(tree) - } - } - } - def checkStreamWillBenefitFromOptimization(stream: Stream): Unit = { - val Stream(source, transformers) = stream - - val sourceAndOps = source +: transformers - - import TraversalOps._ - - val closuresCount = sourceAndOps.map(_.closuresCount).sum - (transformers, closuresCount, source) match { - case (Seq(), _, _) => - throw CodeWontBenefitFromOptimization("No operations chain : " + sourceAndOps) - case (_, _, _: AbstractArrayStreamSource) if !transformers.isEmpty => - // ok to transform any stream that starts with an array - case (Seq(_), 0, _) => - throw CodeWontBenefitFromOptimization("Only one operations without closure is not enough to optimize : " + sourceAndOps) - case (Seq(_), 1, _: ListStreamSource) => - throw CodeWontBenefitFromOptimization("List operations chains need at least 2 closures to make the optimization beneficial : " + sourceAndOps) - case - ( - Seq( - _: FilterWhileOp | - _: MaxOp | - _: MinOp | - _: SumOp | - _: ProductOp | - _: ToCollectionOp - ), - 1, - _: RangeStreamSource - ) - => - throw CodeWontBenefitFromOptimization("This operations stream would not benefit from a while-loop-rewrite optimization : " + sourceAndOps) - case _ => - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/components/_doomed_LoopsTransformComponent.scala b/libraries/Scalaxy/src/main/scala/scalaxy/components/_doomed_LoopsTransformComponent.scala deleted file mode 100644 index 9995f7b70..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/components/_doomed_LoopsTransformComponent.scala +++ /dev/null @@ -1,676 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package components -import common._ -import pluginBase._ - -import scala.tools.nsc.Global - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.transform.{Transform, TypingTransformers} -import scala.tools.nsc.typechecker.Analyzer -import scala.tools.nsc.typechecker.Implicits - -import System.getenv - -/** - * DEPRECATED ! DO NOT EDIT THIS FILE ANYMORE, EXCEPT FOR BUGFIXES - * ALL NEW WORK SHOULD GO IN `Stream*.scala` files ! - */ -object LoopsTransformComponent { - val runsAfter = List[String]( - "namer" - //, OpsFuserTransformComponent.phaseName, Seq2ArrayTransformComponent.phaseName - ) - val runsBefore = List[String]("refchecks") - val phaseName = "scalacl-loopstransform" -} - - -/** - * DEPRECATED ! DO NOT EDIT THIS FILE ANYMORE, EXCEPT FOR BUGFIXES - * ALL NEW WORK SHOULD GO IN `Stream*.scala` files ! - */ -@deprecated -class LoopsTransformComponent(val global: Global, val options: PluginOptions) -extends PluginComponent - with Transform - with TypingTransformers - with MiscMatchers - with TreeBuilders - with TraversalOps - with RewritingPluginComponent - with WithOptions - with WorkaroundsForOtherPhases - with CodeAnalysis // for auto tests -{ - import global._ - import global.definitions._ - import scala.tools.nsc.symtab.Flags._ - import typer.{typed} // methods to type trees - - override val runsAfter = LoopsTransformComponent.runsAfter - override val runsBefore = LoopsTransformComponent.runsBefore - override val phaseName = LoopsTransformComponent.phaseName - - import TraversalOps._ - - def newTransformer(compilationUnit: CompilationUnit) = new TypingTransformer(compilationUnit) with CollectionRewriters { - - override val unit = compilationUnit - - override def transform(tree: Tree): Tree = { - /* - Coding style checker example: - tree match { - case DefDef(mods, name, _, _, tpt: TypeTree, body) - if tpt.pos == tree.pos && name != nme.CONSTRUCTOR && !mods.hasFlag(SYNTHETIC) => - unit.error(body.pos, "Method return type must be defined explicitely (inferred " + tpt + ")") - case _ => - } - */ - - if (options.test) { - tree match { - case dd: DefDef if !dd.symbol.isConstructor => - val sef = getSideEffects(tree) - //println("Side effects for " + tree + " :\n\t" + sef.mkString(",\n\t")) - if (!sef.isEmpty) { - type Buf = collection.mutable.ArrayBuffer[Tree] - options.testOutputs.getOrElseUpdate(HasSideEffects, new Buf).asInstanceOf[Buf] ++= sef - } - case _ => - } - } - - if (!shouldOptimize(tree)) - super.transform(tree) - else - try { - tree match { - //case TypeTree() => - // println(nodeToString(tree.symbol.tpt)) - // super.transform(tree) - case TraversalOp(traversalOp) => - - import traversalOp._ - - var leftParam: ValDef = null - var rightParam: ValDef = null - var body: Tree = null - if (op.f != null) { - op.f match { - case Func(List(leftParamExtr, rightParamExtr), bodyExtr) => - leftParam = leftParamExtr - rightParam = rightParamExtr - body = bodyExtr - case Func(List(uniqueParam), bodyExtr) => - leftParam = uniqueParam - body = bodyExtr - case _ => - return super.transform(tree) - } - } - - val accParam = if (isLeft) leftParam else rightParam - val newParam = if (isLeft) rightParam else leftParam - - collection match { - case CollectionRewriter(colRewriter) => - import colRewriter._ - if ((isLeft || colType.supportsRightVariants) && (options.experimental || colType.isSafeRewrite(op))) - msg(unit, tree.pos, "transformed " + colType.colToString(tpe) + "." + op + " into equivalent while loop.") { - super.transform( - op match { - case - ReduceOp(_, _, _) | - FoldOp(_, _, _, _) | - SumOp(_) | - MinOp(_) | - MaxOp(_) - if { - val envvar = "SCALACL_TRANSFORM_" + op.toString.toUpperCase - //if (options.verbose) - // println("[scalacl] env var = " + envvar) - "0" != getenv(envvar) - } - => - val skipFirst = op.loopSkipsFirst - colType.foreach[VarDef]( - tree, - array, - componentType, - !isLeft, - skipFirst, - env => { - assert((initialValue == null) == !op.needsInitialValue) // no initial value for reduce-like ops only - val totVar = newVariable(unit, op + "$", currentOwner, tree.pos, true, - if (initialValue == null) { - op match { - case SumOp(_) => - Literal(Constant(0: Byte)).setType(componentType) - case _ => - // Take first or last value for Reduce, Min, Max - assert(skipFirst) - newApply( - tree.pos, - env.aVar(), - if (isLeft) - newInt(0) - else - intAdd(env.nVar(), newInt(-1)) - ) - } - } else - initialValue - ) - new LoopOuters(List(totVar.definition), totVar(), payload = totVar) - }, - env => { - val totVar = env.payload - LoopInners( - List( - if (body == null) { - assert(!op.needsFunction) - val totIdent = totVar() - op match { - case SumOp(_) => - Assign(totVar(), binOp(totIdent, totIdent.tpe.member(nme.PLUS), env.itemVar())).setType(UnitClass.tpe) - case MinOp(_) => - If( - binOp(env.itemVar(), totIdent.tpe.member(nme.LT), totIdent), - Assign(totVar(), env.itemVar()).setType(UnitClass.tpe), - newUnit - ) - case MaxOp(_) => - If( - binOp(env.itemVar(), totIdent.tpe.member(nme.GT), totIdent), - Assign(totVar(), env.itemVar()).setType(UnitClass.tpe), - newUnit - ) - case _ => - throw new RuntimeException("unexpected op : " + op) - } - } else { - Assign( - totVar(), - replaceOccurrences( - body, - Map( - accParam.symbol -> totVar, - newParam.symbol -> env.itemVar - ), - Map(op.f.symbol -> currentOwner), - Map(), - unit - ) - ) - } - ) - ) - } - ) - case ScanOp(_, f, _, true) if "0" != getenv("SCALACL_TRANSFORM_SCAN") => - colType.foreach[(CollectionBuilder, VarDef, VarDef)]( - tree, - array, - componentType, - !isLeft, - false, - env => { - val cb @ CollectionBuilder(builderCreation, _, _, builderResult) = colType.newBuilder( - collection.pos, - componentType, - mappedCollectionType, - () => intAdd(env.nVar(), newInt(1)), - localTyper - ) - val builderVar = newVariable( - unit, - "builder$", - currentOwner, - tree.pos, - true, - builderCreation - ) - val totVar = newVariable(unit, "tot$", currentOwner, tree.pos, true, initialValue) - new LoopOuters( - List( - totVar.definition, - builderVar.definition, - cb.setOrAdd(builderVar, () => newInt(0), totVar) - ), - builderResult(builderVar), - payload = (cb, builderVar, totVar) - ) - }, - env => { - val (cb, builderVar, totVar) = env.payload - LoopInners( - List( - Assign( - totVar(), - replaceOccurrences( - body, - Map( - accParam.symbol -> totVar, - newParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - ).setType(UnitClass.tpe), - cb.setOrAdd( - builderVar, - () => if (isLeft) - intAdd(env.iVar(), newInt(1)) - else - intSub(env.nVar(), env.iVar()), - totVar - ) - ) - ) - } - ) - case AllOrSomeOp(_, f, all) if "0" != getenv("SCALACL_TRANSFORM_FORALL_EXISTS") => - colType.foreach[VarDef]( - tree, - array, - componentType, - false, - false, - env => { - val hasTrueVar = newVariable( - unit, - "hasTrue$", - currentOwner, - tree.pos, - true, - newBool(all) - ) - new LoopOuters( - List( - hasTrueVar.definition - ), - hasTrueVar(), - payload = hasTrueVar - ) - }, - env => { - val hasTrueVar = env.payload - LoopInners( - List( - Assign( - hasTrueVar(), - replaceOccurrences( - super.transform(body), - Map( - leftParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - ) - ), - if (all) - hasTrueVar() - else - boolNot(hasTrueVar()) - ) - } - ) - case tco: ToCollectionOp if "0" != getenv("SCALACL_TRANSFORM_TOCOLLECTION") => - val ct = tco.colType - ( - ct match { - case ListType => Some(ListRewriter) - case ArrayType => Some(ArrayRewriter) - case _ => None - } - ) match { - case Some(rewriter) => - colType.foreach[(CollectionBuilder, VarDef)]( - tree, - array, - componentType, - false, - false, - env => { - val cb @ CollectionBuilder(builderCreation, _, _, builderResult) = rewriter.newBuilder(collection.pos, componentType, null, null, localTyper) - val builderVar = newVariable( - unit, - "builder$", - currentOwner, - tree.pos, - true, - builderCreation - ) - new LoopOuters( - List( - builderVar.definition - ), - builderResult(builderVar), - payload = (cb, builderVar) - ) - }, - env => { - val (cb, builderVar) = env.payload - LoopInners( - List( - cb.add(builderVar, env.itemVar) - ) - ) - } - ) - case _ => - super.transform(tree) - } - case FilterOp(_, f, not) if "0" != getenv("SCALACL_TRANSFORM_FILTER") => - colType.foreach[(CollectionBuilder, VarDef)]( - tree, - array, - componentType, - false, - false, - env => { - val cb @ CollectionBuilder(builderCreation, _, _, builderResult) = colType.newBuilder(collection.pos, componentType, null, null, localTyper) - val builderVar = newVariable( - unit, - "builder$", - currentOwner, - tree.pos, - true, - builderCreation - ) - new LoopOuters( - List( - builderVar.definition - ), - builderResult(builderVar), - payload = (cb, builderVar) - ) - }, - env => { - val (cb, builderVar) = env.payload - val cond = replaceOccurrences( - super.transform(body), - Map( - leftParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - LoopInners( - List( - If( - if (not) - boolNot(cond) - else - cond, - cb.add(builderVar, env.itemVar), - newUnit - ) - ) - ) - } - ) - case CountOp(_, f) if "0" != getenv("SCALACL_TRANSFORM_COUNT") => - colType.foreach[(VarDef)]( - tree, - array, - componentType, - false, - false, - env => { - val countVar = newVariable( - unit, - "count$", - currentOwner, - tree.pos, - true, - newInt(0) - ) - new LoopOuters( - List( - countVar.definition - ), - countVar(), - payload = countVar - ) - }, - env => { - val countVar = env.payload - val cond = replaceOccurrences( - super.transform(body), - Map( - leftParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - LoopInners( - List( - If( - cond, - incrementIntVar(countVar, newInt(1)), - newUnit - ) - ) - ) - } - ) - case FilterWhileOp(_, f, take) if "0" != getenv("SCALACL_TRANSFORM_TAKEWHILE") => - colType.foreach[(CollectionBuilder, VarDef, VarDef)]( - tree, - array, - componentType, - false, - false, - env => { - val passedVar = newVariable( - unit, - "passed$", - currentOwner, - tree.pos, - true, - newBool(false) - ) - val cb @ CollectionBuilder(builderCreation, _, _, builderResult) = colType.newBuilder(collection.pos, componentType, null, null, localTyper) - val builderVar = newVariable( - unit, - "builder$", - currentOwner, - tree.pos, - true, - builderCreation - ) - new LoopOuters( - List( - builderVar.definition, - passedVar.definition - ), - builderResult(builderVar), - payload = (cb, passedVar, builderVar) - ) - }, - env => { - val (cb, passedVar, builderVar) = env.payload - val cond = boolNot( - replaceOccurrences( - super.transform(body), - Map( - leftParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - ) - LoopInners( - if (take) { - List( - Assign( - passedVar(), - cond - ).setType(UnitClass.tpe), - If( - boolNot(passedVar()), - cb.add(builderVar, env.itemVar), - newUnit - ) - ) - } else { - List( - If( - boolOr( - passedVar(), - Block( - List( - Assign( - passedVar(), - cond - ).setType(UnitClass.tpe) - ), - passedVar() - ).setType(BooleanClass.tpe) - ), - cb.add(builderVar, env.itemVar), - newUnit - ) - ) - }, - if (take) - boolNot(passedVar()) - else - null - ) - } - ) - - case ForeachOp(_, f) if "0" != getenv("SCALACL_TRANSFORM_FOREACH") => - val rep = super.transform( - colType.foreach[Unit]( - tree, - array, - componentType, - false, - false, - env => new LoopOuters(Nil, null, payload = ()), // no extra outer statement - env => { - val content = replaceOccurrences( - body, - Map(leftParam.symbol -> env.itemVar), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - LoopInners( - List( - content - ) - ) - } - ) - ) - //println("REP = " + rep) - //println("REP NODES = " + nodeToString(rep)) - rep - case MapOp(_, f, canBuildFrom) if "0" != getenv("SCALACL_TRANSFORM_MAP") => - colType.foreach[(CollectionBuilder, VarDef)]( - tree, - array, - componentType, - false, - false, - env => { - val cb @ CollectionBuilder(builderCreation, _, _, builderResult) = colType.newBuilder(collection.pos, resultType, tree.tpe, env.outputSizeVar, localTyper) - val builderVar = newVariable( - unit, - "builder$", - currentOwner, - tree.pos, - true, - builderCreation - ) - new LoopOuters( - List( - builderVar.definition - ), - builderResult(builderVar), - payload = (cb, builderVar) - ) - }, - env => { - val (cb, builderVar) = env.payload - val content = replaceOccurrences( - super.transform(body), - Map( - leftParam.symbol -> env.itemVar - ), - Map(f.symbol -> currentOwner), - Map(), - unit - ) - LoopInners( - // TODO !!! List(cb.setOrAdd(builderVar, env.outputIndexVar, () => content)) - List(cb.setOrAdd(builderVar, env.iVar, () => content)) - ) - } - ) - case _ => - msg(unit, tree.pos, "INFO: will soon optimize this " + tpe + "." + op + " call") { - throw new UnsupportedOperationException("not supported yet") - super.transform(tree) - } - } - ) - } - else - super.transform(tree) - case _ => - super.transform(tree) - } - case _ => - super.transform(tree) - } - } catch { - case ex => - //if (options.trace) - // ex.printStackTrace - super.transform(tree) - } - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/old/StreamOps.scala b/libraries/Scalaxy/src/main/scala/scalaxy/old/StreamOps.scala deleted file mode 100644 index 8a57dfebc..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/old/StreamOps.scala +++ /dev/null @@ -1,185 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package old ; -import common._ -import pluginBase._ - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Global - -@deprecated("Not tested for long, please re-read") -trait StreamOps extends TreeBuilders { - this: PluginComponent with WithOptions => - - val global: Global - import global._ - - type ArgTuplePath = IntPath[Int] - - class TupleField(val tuple: Tree, val fieldIndex: Int) - object TupleField { - val rx = "_(\\d+)".r - def unapply(tree: Tree) = tree match { - case Select(target, fieldName) => - fieldName.toString match { - case rx(n) => - if (target.symbol.owner.toString.matches("class Tuple\\d+")) - Some(new TupleField(target, n.toInt - 1)) - else - None - case _ => - None - } - case _ => - None - } - } - case class IntPath[T](target: T, path: List[Int]) { - def appendPath(postPath: List[Int]) = new IntPath[T](target, path ++ postPath) - def prependPath(prePath: List[Int]) = new IntPath[T](target, prePath ++ path) - def map[V](f: T => V) = new IntPath[V](f(target), path) - } - object TuplePath2 { - def unapply(tree: Tree): Option[IntPath[Tree]] = tree match { - case TupleField(tf) => - tf.tuple match { - case TuplePath2(IntPath(originalTuple, path)) => - Some(new IntPath[Tree](originalTuple, path ++ List(tf.fieldIndex))) - case _ => - Some(new IntPath[Tree](tf.tuple, List(tf.fieldIndex))) - } - case _ => - None - } - } - class ArgTuplePathsHarvester(var defs: Map[Symbol, ArgTuplePath]) extends Traverser { - override def traverse(tree: Tree) = { - tree match { - case ValDef(mods, name, tpt, TuplePath2(IntPath(target, subPath))) => - defs.get(target.symbol) match { - case Some(path) => - defs += target.symbol -> path.appendPath(subPath) - case None => - } - case _ => - } - super.traverse(tree) - } - def apply(tree: Tree) = { - this.traverse(tree) - defs - } - } - - trait StreamOp { - - val isTransform: Boolean - val isFilter: Boolean - val argSymbols: Array[Symbol] = Array() - val body: Tree = null - - def toTree(unit: CompilationUnit, currentOwner: Symbol, argsIdentGens: Map[ArgTuplePath, TreeGen], zippedIndexGen: TreeGen, resultUses: Set[ArgTuplePath]): StreamOpResult - - lazy val tupleUses: Map[Symbol, ArgTuplePath] = { - val map = argSymbols.zipWithIndex.map({ case (argSymbol, argIndex) => argSymbol -> new ArgTuplePath(argIndex, Nil) }).toMap - new ArgTuplePathsHarvester(map)(body) - } - } - case class StreamOpResult( - predefs: List[Tree], - innerContentsPre: List[Tree], - innerContentsPost: List[Tree], - resultIdentGens: Map[ArgTuplePath, TreeGen], - resultZippedIndexGen: TreeGen - ) - class FilterStreamOp(not: Boolean, arg: ValDef, override val body: Tree) extends StreamOp { - override val argSymbols = Array(arg.symbol) - override val isTransform = false - override val isFilter = true - override def toTree(unit: CompilationUnit, currentOwner: Symbol, argsIdentGens: Map[ArgTuplePath, TreeGen], zippedIndexGen: TreeGen, resultUses: Set[ArgTuplePath]) = { - null - } - } - class ZipWithIndexStreamOp(not: Boolean, arg: ValDef, override val body: Tree) extends StreamOp { - override val argSymbols = Array(arg.symbol) - override val isTransform = true - override val isFilter = false - override def toTree(unit: CompilationUnit, currentOwner: Symbol, argsIdentGens: Map[ArgTuplePath, TreeGen], zippedIndexGen: TreeGen, resultUses: Set[ArgTuplePath]) = { - val resultsIdentGens: TreeGen => Map[ArgTuplePath, TreeGen] = (g: TreeGen) => argsIdentGens.map { case (path, identGen) => (path.prependPath(List(0)), identGen) } ++ Map(new ArgTuplePath(0, List(1)) -> g) - if (zippedIndexGen != null) { - StreamOpResult(Nil, Nil, Nil, resultsIdentGens(zippedIndexGen), zippedIndexGen) - } else { - val indexVar = newVariable(unit, "index$", currentOwner, NoPosition, true, newInt(0)) - StreamOpResult( - List(indexVar.definition), - Nil, - List(incrementIntVar(indexVar, newInt(1))), - resultsIdentGens(indexVar), - indexVar - ) - } - } - } - class LinkedStreamOp(op: StreamOp, next: StreamOp) extends StreamOp { - override val isTransform = { - if (op.isTransform || next == null) - true - else - next.isTransform - } - override val isFilter = { - if (op.isFilter || next == null) - true - else - next.isFilter - } - override def toTree(unit: CompilationUnit, currentOwner: Symbol, argsIdentGens: Map[ArgTuplePath, TreeGen], zippedIndexGen: TreeGen, resultUses: Set[ArgTuplePath]): StreamOpResult = { - val res = op.toTree(unit, currentOwner, argsIdentGens, zippedIndexGen, if (next == null) resultUses else next.tupleUses.values.toSet) - if (next == null) - res - else { - val StreamOpResult(predefs, innerContents, outerContents, resultIdentGens, zippedIndexGen) = res - val StreamOpResult(nextPredefs, nextInnerContents, nextOuterContents, nextResultIdentGens, nextZippedIndexGen) = - next.toTree(unit, currentOwner, resultIdentGens, if (op.isFilter) null else zippedIndexGen, resultUses) - StreamOpResult(predefs ++ nextPredefs, innerContents ++ nextInnerContents, outerContents ++ nextOuterContents, nextResultIdentGens, nextZippedIndexGen) - } - } - override lazy val tupleUses = { - val uses = op.tupleUses - val nextUses = if (op.isTransform || next == null) - Map() - else - next.tupleUses - - uses ++ nextUses - } - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/plugin/ScalaxyPlugin.scala b/libraries/Scalaxy/src/main/scala/scalaxy/plugin/ScalaxyPlugin.scala deleted file mode 100644 index 72f471eb2..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/plugin/ScalaxyPlugin.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package plugin -import pluginBase._ -import components._ - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -/** - * http://www.scala-lang.org/node/140 - * http://lamp.epfl.ch/~emir/bqbase/2005/06/02/nscTutorial.html - * http://code.google.com/p/simple-build-tool/wiki/CompilerPlugins - - * mvn scala:run -DmainClass=com.nativelibs4java.scalaxy.plugin.Compile "-DaddArgs=-d|out|examples/Test.scala|-Xprint:scalacl-stream" - - |-classpath|../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar" - * scala -cp target/scalacl-compiler-1.0-SNAPSHOT-shaded.jar scalacl.plugin.Compile -d out src/examples/BasicExample.scala - * javap -c -classpath out/ scalacl.examples.BasicExample - */ -object ScalaxyPluginDef extends PluginDef { - override val name = "Scalaxy" - override val description = - "This plugin rewrites some Scala loop-like constructs so they execute faster (e.g. Array.map, .foreach, .filter...)." - - override def envVarPrefix = "SCALAXY_" - - //"This plugin transforms some Scala functions into OpenCL kernels (for CLCollection[T].map and filter's arguments), so they can run on a GPU.\n" + - //"It will also soon feature autovectorization of ScalaCL programs, detecting parallelizable loops and unnecessary collection creations." - - override def createOptions(settings: Settings): PluginOptions = - new PluginOptions(this, settings) - - override def createComponents(global: Global, options: PluginOptions): List[PluginComponent] = - List( - //new MyComponent(global, options), - new StreamTransformComponent(global, options), - if (!options.stream) - new LoopsTransformComponent(global, options) - else - null - ) - - override def getCopyrightMessage: String = - "Scalaxy Plugin\nCopyright Olivier Chafik 2010-2012" -} - -class ScalaxyPlugin(override val global: Global) -extends PluginBase(global, ScalaxyPluginDef) - -object Compile extends CompilerMain { - override def pluginDef = ScalaxyPluginDef - override def commandName = "scalaxy" -} - diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/CompilerMain.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/CompilerMain.scala deleted file mode 100644 index f1eea3af2..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/CompilerMain.scala +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package pluginBase - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -import scala.collection.JavaConversions._ -import java.io.BufferedReader -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.PrintWriter -import scala.concurrent.ops -import scala.io.Source -import scala.tools.nsc.CompilerCommand -import scala.tools.nsc.Global -import scala.tools.nsc.Settings -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.reporters.Reporter - -/** - * http://www.scala-lang.org/node/140 - * http://lamp.epfl.ch/~emir/bqbase/2005/06/02/nscTutorial.html - * http://code.google.com/p/simple-build-tool/wiki/CompilerPlugins - * mvn scala:run -DmainClass=scalacl.plugin.Compile "-DaddArgs=-d|out|examples/Toto.scala|-Xprint:scalacl-functionstransform|-classpath|../ScalaCL/target/scalacl-0.3-SNAPSHOT-shaded.jar" - * scala -cp target/scalacl-compiler-1.0-SNAPSHOT-shaded.jar scalacl.plugin.Compile -d out src/examples/BasicExample.scala - * javap -c -classpath out/ scalacl.examples.BasicExample - */ -object CompilerMain { - lazy val bootClassPath = { - val scalaLibraryJar = classOf[List[_]].getProtectionDomain.getCodeSource.getLocation.getFile - scalaLibraryJar - } - lazy val extraArgs = Array( - "-optimise", - //"-usejavacp", - "-bootclasspath", bootClassPath - ) -} -trait CompilerMain { - def pluginDef: PluginDef - def commandName: String - - def main(args: Array[String]) { - try { - compilerMain(args, true) - } catch { case ex => - ex.printStackTrace - throw ex - } - } - - def compilerMain(args: Array[String], enablePlugins: Boolean) = { - pluginDef.printCopyrightMessageOnce - - val settings = new Settings - - val command = new CompilerCommand((args ++ CompilerMain.extraArgs).toList, settings) { - override val cmdName = commandName - } - val pluginOptions = pluginDef.createOptions(settings) - val runner = new PluginRunner(Some(pluginDef), pluginOptions, settings, new ConsoleReporter(settings)) - val run = new runner.Run - - if (command.ok) { - run.compile(command.files) - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginBase.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginBase.scala deleted file mode 100644 index e9e5be6c0..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginBase.scala +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package pluginBase - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -import scala.collection.JavaConversions._ -import java.io.BufferedReader -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.PrintWriter -import scala.concurrent.ops -import scala.io.Source -import scala.tools.nsc.CompilerCommand -import scala.tools.nsc.Global -import scala.tools.nsc.Settings -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.reporters.Reporter - -class PluginBase(override val global: Global, pluginDef: PluginDef) extends Plugin { - override val name = pluginDef.name - override val description = pluginDef.description - - lazy val pluginOptions = try { - pluginDef.createOptions(global.settings) - } catch { case ex: NoClassDefFoundError if ex.toString.matches(""".*?\bscala/.+""") => - throw new RuntimeException("Bad Scala version for " + name + " !", ex) - } - - lazy val enabled = - !pluginOptions.explicitelyDisabled - - /*override def processOptions(options: List[String], error: String => Unit) = { - for (option <- options) { - println("Found option " + option) - // WE NEVER PASS HERE, WTF ??? - } - }*/ - override val optionsHelp: Option[String] = - Some(pluginOptions.envVarHelp) - - override val components: List[PluginComponent] = if (enabled) - pluginDef.createComponents(global, pluginOptions).filter(_ != null) - else - Nil - -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginDef.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginDef.scala deleted file mode 100644 index 39e30b798..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginDef.scala +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package pluginBase - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -import scala.collection.JavaConversions._ -import java.io.BufferedReader -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.PrintWriter -import scala.concurrent.ops -import scala.io.Source -import scala.tools.nsc.CompilerCommand -import scala.tools.nsc.Global -import scala.tools.nsc.Settings -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.reporters.Reporter - -trait PluginDef { - def name: String - def description: String - def createOptions(settings: Settings): PluginOptions - def createComponents(global: Global, options: PluginOptions): List[PluginComponent] - def getCopyrightMessage: String - def envVarPrefix: String - - lazy val printCopyrightMessageOnce: Unit = - println(getCopyrightMessage) -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginOptions.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginOptions.scala deleted file mode 100644 index 86e1e4ad2..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginOptions.scala +++ /dev/null @@ -1,185 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package pluginBase - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -class PluginOptions(pluginDef: PluginDef, settings: Settings) { - import pluginDef.envVarPrefix - - private def hasEnv(name: String, default: Boolean = false) = { - val v = System.getenv(name) - if (default) - v != "0" - else - v == "1" - } - - var test = - false - - var testOutputs = - collection.mutable.Map[Any, Any]() - - var stream = - hasEnv(envVarPrefix + "STREAM", true) - - var trace = - settings != null && settings.debug.value || - hasEnv(envVarPrefix + "TRACE") - - var veryVerbose = - hasEnv(envVarPrefix + "VERY_VERBOSE") - - var debug = - hasEnv(envVarPrefix + "DEBUG") - - var verbose = - settings != null && settings.verbose.value || - veryVerbose || - hasEnv(envVarPrefix + "VERBOSE") - - var experimental = - hasEnv(envVarPrefix + "EXPERIMENTAL") - - var deprecated = - hasEnv(envVarPrefix + "DEPRECATED") - - var skip = System.getenv(envVarPrefix + "SKIP") - - lazy val explicitelyDisabled = - "1".equals(System.getenv(envVarPrefix + "DISABLE")) - - def envVarHelp = - """ - """ + envVarPrefix + """DISABLE=1 Set this environment variable to disable the plugin - """ + envVarPrefix + """SKIP=File1,File2:line2... Do not optimize any of the listed files (or specific lines). - Can contain absolute paths or file names (can omit trailing .scala). - Each file (name) may be suffixed with :line. - """ + envVarPrefix + """VERBOSE=1 Print details about each successful code transformation to the standard output. - """ + envVarPrefix + """VERY_VERBOSE=1 Verbose + give details on why optimizations were not performed, and on what possible side-effects were detected. - """ + envVarPrefix + """TRACE=1 Display stack trace of failed optimizations (for debugging purpose). - """ + envVarPrefix + """EXPERIMENTAL=1 Perform experimental rewrites (often slower and buggier, use only when debugging the plugin). - """ + envVarPrefix + """DEPRECATED=1 Perform rewrite that were deprecated (deemed or proved to be slower than the original) - """ - type FileAndLineOptimizationFilter = (String, Int) => Boolean - - lazy val fileAndLineOptimizationFilter: FileAndLineOptimizationFilter = { - var skipVar = skip - if (skipVar == null) - skipVar = "" - else - skipVar = skip.trim - //println("[scalacl] SCALACL_SKIP = " + skipVar) - if (skipVar == "") - (path: String, line: Int) => true - else { - skipVar.split(',').map(item => { - val s = item.split(':') - val f = s(0) - val pathFilter: String => Boolean = { - val file = new File(f) - if (file.exists) { - val absFile = file.getAbsolutePath - (path: String) => new File(path).getAbsolutePath != absFile - } else { - val n = file.getName - if (!n.toLowerCase.endsWith(".scala")) { - val ns = n + ".scala" - (path: String) => { - val fn = new File(path).getName - fn != n && fn != ns - } - } else { - (path: String) => { - val fn = new File(path).getName - fn != n - } - } - } - } - if (s.length == 2 && (s(1) ne null)) { - val skippedLine = s(1).toInt - (path: String, line: Int) => { - val v = path == null || !(line == skippedLine && !pathFilter(path)) - //println(path + ":" + line + " = " + v) - v - } - } else { - (path: String, line: Int) => { - val v = path == null || pathFilter(path) - //println(path + ":" + line + " = " + v) - v - } - } - }).reduceLeft[FileAndLineOptimizationFilter] { - case (f1: FileAndLineOptimizationFilter, f2: FileAndLineOptimizationFilter) => - (path: String, line: Int) => { - f1(path, line) && f2(path, line) - } - } - } - } - - private def ifEnv[V <: AnyRef](name: String)(v: => V): V = - if (hasEnv(name)) - v - else - null.asInstanceOf[V] - -} - -trait WithOptions -{ - val global: Global - import global._ - - val options: PluginOptions - - def shouldOptimize(tree: Tree) = { - val pos = tree.pos - try { - !pos.isDefined || options.fileAndLineOptimizationFilter(pos.source.path, pos.line) - } catch { - case ex => - //ex.printStackTrace - true - } - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginRunner.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginRunner.scala deleted file mode 100644 index 6e0ce362f..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/PluginRunner.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package pluginBase - -import java.io.File -import scala.collection.immutable.Stack -import scala.reflect.generic.Names -import scala.reflect.generic.Trees - -import scala.tools.nsc.plugins.PluginComponent -import scala.tools.nsc.Settings -import scala.tools.nsc.Global -import scala.tools.nsc.plugins.Plugin -import scala.util.parsing.input.Position - -import scala.collection.JavaConversions._ -import java.io.BufferedReader -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.PrintWriter -import scala.concurrent.ops -import scala.io.Source -import scala.tools.nsc.CompilerCommand -import scala.tools.nsc.Global -import scala.tools.nsc.Settings -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.reporters.Reporter - -class PluginRunner(pluginDefOpt: Option[PluginDef], options: PluginOptions, settings: Settings, reporter: Reporter) extends Global(settings, reporter) { - override protected def computeInternalPhases() { - super.computeInternalPhases - for (pluginDef <- pluginDefOpt; phase <- pluginDef.createComponents(this, options); if phase != null) - phasesSet += phase - } -} diff --git a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/SharedCompiler.scala b/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/SharedCompiler.scala deleted file mode 100644 index 24a38d5f5..000000000 --- a/libraries/Scalaxy/src/main/scala/scalaxy/pluginBase/SharedCompiler.scala +++ /dev/null @@ -1,81 +0,0 @@ -package com.nativelibs4java.scalaxy ; package pluginBase - -import scala.tools.nsc.CompilerCommand -import scala.tools.nsc.Settings -import scala.tools.nsc.reporters.ConsoleReporter -import scala.tools.nsc.reporters.Reporter - - -class SharedCompiler(enablePlugins: Boolean, pluginDef: PluginDef) { - case class Compiler( - extraArgs: Array[String], - settings: Settings, - pluginOptions: PluginOptions, - runner: PluginRunner - ) - def createCompiler: Compiler = { - val settings = new Settings - val pluginOptions = pluginDef.createOptions(settings) - pluginOptions.test = true - - val runner = new PluginRunner(if (enablePlugins) Some(pluginDef) else None, pluginOptions, settings, new ConsoleReporter(settings)) - Compiler(CompilerMain.extraArgs, settings, pluginOptions, runner) - } - - import scala.concurrent.ops._ - implicit val runner = new scala.concurrent.ThreadRunner - - /// A compiler and a compiler future - var instances: (Compiler, () => Compiler) = null - def newInstances = { - //implicit val runner = new scala.concurrent.ThreadRunner - val fut = future { createCompiler } - if (instances == null) { - instances = (createCompiler, fut) - } else { - // Take last future as new compiler - instances = (instances._2(), fut) - } - } - def compiler = { - if (instances == null) - newInstances - instances._1 - } - - lazy val isAtLeastScala29 = { - try { - Class.forName("scala.sys.process.Process") - true - } catch { case _ => false } - } - - def canReuseCompilers = { - !isAtLeastScala29 && - System.getenv("SCALAXY_DONT_REUSE_COMPILERS") == null - } - def compile(args: Array[String]): PluginOptions = { - //val (extraArgs, settings, runner) = createRunner - - def run = { - val Compiler(extraArgs, settings, pluginOptions, runner) = if (canReuseCompilers) compiler else createCompiler - val command = new CompilerCommand((args ++ extraArgs).toList, settings) { - override val cmdName = "scalacl" - } - if (command.ok) { - val run = new runner.Run - run.compile(command.files) - } - pluginOptions - } - try { - run - } catch { - case _ => - //println("Compilation failed, retrying with a new compiler instance") - newInstances - run - } - } -} - diff --git a/libraries/Scalaxy/src/main/velocity/scalac-plugin.xml b/libraries/Scalaxy/src/main/velocity/scalac-plugin.xml deleted file mode 100644 index ee41fae64..000000000 --- a/libraries/Scalaxy/src/main/velocity/scalac-plugin.xml +++ /dev/null @@ -1,4 +0,0 @@ - - ${project_name}-${project_version} - com.nativelibs4java.scalaxy.plugin.ScalaxyPlugin - diff --git a/libraries/Scalaxy/src/test/resources/scalaxy.PerformanceTest.perf.properties b/libraries/Scalaxy/src/test/resources/scalaxy.PerformanceTest.perf.properties deleted file mode 100644 index 52b6c0391..000000000 --- a/libraries/Scalaxy/src/test/resources/scalaxy.PerformanceTest.perf.properties +++ /dev/null @@ -1,130 +0,0 @@ -simpleListFilter\:100000=1.0 -simpleListFilter\:1000=1.2 -simpleListFilter\:10=1.1 -simpleListFilterNot\:100000=1.0 -simpleListFilterNot\:1000=1.1 -simpleListFilterNot\:10=1.2 -simpleListCount\:100000=0.8 -simpleListCount\:1000=0.9 -simpleListCount\:10=0.9 -simpleListExists\:100000=1.0 -simpleListExists\:1000=0.9 -simpleListExists\:10=0.9 -simpleListForall\:100000=1.0 -simpleListForall\:1000=1.0 -simpleListForall\:10=1.0 -simpleListTakeWhile\:100000=1.1 -simpleListTakeWhile\:1000=0.9 -simpleListTakeWhile\:10=0.9 -simpleListForeach\:100000=0.9 -simpleListForeach\:1000=1.0 -simpleListForeach\:10=1.0 -simpleListMap\:100000=1.0 -simpleListMap\:1000=1.0 -simpleListMap\:10=1.1 -simpleListSum\:100000=1.6 -simpleListSum\:1000=1.3 -simpleListSum\:10=1.1 -simpleListMin\:100000=1.1 -simpleListMin\:1000=1.0 -simpleListMin\:10=0.9 -simpleListMax\:100000=1.1 -simpleListMax\:1000=1.0 -simpleListMax\:10=0.99 -simpleListScanLeft\:100000=0.9 -simpleListScanLeft\:1000=1.1 -simpleListScanLeft\:10=1.3 -simpleListFoldLeft\:100000=1.4 -simpleListFoldLeft\:1000=1.0 -simpleListFoldLeft\:10=1.0 -simpleListReduceLeft\:100000=1.4 -simpleListReduceLeft\:1000=1.15 -simpleListReduceLeft\:10=1.1 -simpleRangeFilter\:100000=2.9 -simpleRangeFilter\:1000=1.5 -simpleRangeFilter\:10=1.3 -simpleRangeFilterNot\:100000=4.4 -simpleRangeFilterNot\:1000=1.6 -simpleRangeFilterNot\:10=1.4 -simpleRangeCount\:100000=6.6 -simpleRangeCount\:1000=1.5 -simpleRangeCount\:10=1.2 -simpleRangeExists\:100000=13.1 -simpleRangeExists\:1000=1.6 -simpleRangeExists\:10=1.2 -simpleRangeForall\:100000=12.8 -simpleRangeForall\:1000=1.4 -simpleRangeForall\:10=1.1 -simpleRangeForeach\:100000=5.0 -simpleRangeForeach\:1000=1.2 -simpleRangeForeach\:10=1.1 -simpleRangeMap\:100000=1.8 -simpleRangeMap\:1000=1.4 -simpleRangeMap\:10=1.3 -simpleRangeSum\:100000=17.7 -simpleRangeSum\:1000=1.7 -simpleRangeSum\:10=1.2 -simpleRangeScanLeft\:100000=1.4 -simpleRangeScanLeft\:1000=1.4 -simpleRangeScanLeft\:10=1.5 -simpleRangeFoldLeft\:100000=15.0 -simpleRangeFoldLeft\:1000=1.7 -simpleRangeFoldLeft\:10=1.1 -simpleArrayTabulate\:100000=8.8 -simpleArrayTabulate\:1000=1.5 -simpleArrayTabulate\:10=1.0 -simpleArrayFilter\:100000=6.3 -simpleArrayFilter\:1000=1.5 -simpleArrayFilter\:10=1.2 -simpleArrayFilterNot\:100000=6.5 -simpleArrayFilterNot\:1000=1.6 -simpleArrayFilterNot\:10=1.3 -simpleArrayCount\:100000=8.6 -simpleArrayCount\:1000=1.7 -simpleArrayCount\:10=1.2 -simpleArrayExists\:100000=5.9 -simpleArrayExists\:1000=1.2 -simpleArrayExists\:10=1.1 -simpleArrayForall\:100000=8.5 -simpleArrayForall\:1000=1.3 -simpleArrayForall\:10=1.1 -simpleArrayTakeWhile\:100000=5.1 -simpleArrayTakeWhile\:1000=1.6 -simpleArrayTakeWhile\:10=1.4 -simpleArrayDropWhile\:100000=4.5 -simpleArrayDropWhile\:1000=1.4 -simpleArrayDropWhile\:10=1.4 -simpleArrayForeach\:100000=11.6 -simpleArrayForeach\:1000=1.4 -simpleArrayForeach\:10=1.0 -simpleArrayMap\:100000=15.9 -simpleArrayMap\:1000=2.2 -simpleArrayMap\:10=1.6 -simpleArraySum\:100000=10.3 -simpleArraySum\:1000=1.4 -simpleArraySum\:10=1.1 -simpleArrayMin\:100000=13.0 -simpleArrayMin\:1000=1.7 -simpleArrayMin\:10=1.2 -simpleArrayMax\:100000=12.6 -simpleArrayMax\:1000=1.5 -simpleArrayMax\:10=1.1 -simpleArrayScanLeft\:100000=14.0 -simpleArrayScanLeft\:1000=2.2 -simpleArrayScanLeft\:10=1.7 -simpleArrayScanRight\:100000=18.3 -simpleArrayScanRight\:1000=2.4 -simpleArrayScanRight\:10=1.6 -simpleArrayFoldLeft\:100000=14.3 -simpleArrayFoldLeft\:1000=1.5 -simpleArrayFoldLeft\:10=1.1 -simpleArrayFoldRight\:100000=6.8 -simpleArrayFoldRight\:1000=1.2 -simpleArrayFoldRight\:10=1.1 -simpleArrayReduceLeft\:100000=12.9 -simpleArrayReduceLeft\:1000=1.7 -simpleArrayReduceLeft\:10=1.1 -simpleArrayReduceRight\:100000=6.5 -simpleArrayReduceRight\:1000=1.3 -simpleArrayReduceRight\:10=1.0 -simpleMatrixTest\:100=1.4 diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/AllOrSome2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/AllOrSome2WhileTest.scala deleted file mode 100644 index a2f2ea7ba..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/AllOrSome2WhileTest.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class AllOrSome2WhileTest extends ScalaxyTestUtils { - - - @Test - def simpleForall { - ensurePluginCompilesSnippetsToSameByteCode( - """ val a = new Array[Double](10) - val s = a.forall(_ != 3) - """, - """ val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = 0 - var t = 0.0 - var hasTrue = true - while (i < n && hasTrue) { - val item = aa(i) - hasTrue = item != 3 - i += 1 - } - hasTrue - } - """ - ) - } - - - @Test - def simpleExists { - ensurePluginCompilesSnippetsToSameByteCode( - """ val a = new Array[Double](10) - val s = a.exists(_ != 3) - """, - """ val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = 0 - var t = 0.0 - var hasTrue = false - while (i < n && !hasTrue) { - val item = aa(i) - hasTrue = item != 3 - i += 1 - } - hasTrue - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayForeach2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayForeach2WhileTest.scala deleted file mode 100644 index 9b2919a55..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayForeach2WhileTest.scala +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ -import Function.{tupled, untupled} - -class ArrayForeach2WhileTest extends ScalaxyTestUtils with TypeUtils { - - @Test - def simpleRefArrayForeach = - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map simpleArrayForeach) - - @Test - def simplePrimitiveArrayForeach = - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map simpleArrayForeach) - - def simpleArrayForeach(typeStr: String) = { - ( - """ - val a = new Array[""" + typeStr + """](10) - a.foreach(println(_)) - """, - """ - val a = new Array[""" + typeStr + """](10) - val aa = a - val n = aa.length - var i = 0 - while (i < n) - { - val item = aa(i) - println(item) - i += 1 - } - """ - ) - } - - @Test - def inlineRefArrayByLengthForeach = - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map inlineArrayByLengthForeach) - - @Test - def inlinePrimitiveArrayByLengthForeach = - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map inlineArrayByLengthForeach) - - def inlineArrayByLengthForeach(typeStr: String) = { - ( - """ - new Array[""" + typeStr + """](10).foreach(println(_)) - """, - """ - val aa = new Array[""" + typeStr + """](10) - val n = aa.length - var i = 0 - while (i < n) - { - val item = aa(i) - println(item) - i += 1 - } - """ - ) - } - - @Test - def inlineRefArrayWithElementsForeach = - ensurePluginCompilesSnippetsToSameByteCode(refValuesList map tupled { inlineArrayWithElementsForeach }) - - @Test - def inlinePrimitiveArrayWithElementsForeach = - ensurePluginCompilesSnippetsToSameByteCode(primValuesList map tupled { inlineArrayWithElementsForeach }) - - def inlineArrayWithElementsForeach(typeStr: String, itemsStr: String) = { - ( - """ - Array(""" + itemsStr + """).foreach(println(_)) - """, - """ - val aa = Array(""" + itemsStr + """) - val n = aa.length - var i = 0 - while (i < n) - { - val item = aa(i) - println(item) - i += 1 - } - """ - ) - } -} \ No newline at end of file diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayMap2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayMap2WhileTest.scala deleted file mode 100644 index 9f3916a35..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/ArrayMap2WhileTest.scala +++ /dev/null @@ -1,183 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ -import Function.{tupled, untupled} - -class ArrayMap2WhileTest extends ScalaxyTestUtils with TypeUtils { - - @Test - def simplePrimitiveArrayTabulate = - ensurePluginCompilesSnippetsToSameByteCode(primValues map tupled { simpleArrayTabulate }) - - @Test - def simpleRefArrayTabulate = - ensurePluginCompilesSnippetsToSameByteCode(refValues map tupled { simpleArrayTabulate }) - - def simpleArrayTabulate(typeStr: String, valStr: String) = { - ( - """ - val length = 10 - val a = Array.tabulate(length)(i => """ + valStr + """) - println(a) - """, - """ - val length = 10 - val a = { - val n = length - val m = Array.ofDim[""" + typeStr + """](n) - var i = 0 - while (i < n) - { - m(i) = """ + valStr + """ - i += 1 - } - m - } - println(a) - """ - ) - } - - @Test - def nestedRefArrayTabulate = - ensurePluginCompilesSnippetsToSameByteCode(refValues map tupled { nestedArrayTabulate }) - - @Test - def nestedPrimitiveArrayTabulate = - ensurePluginCompilesSnippetsToSameByteCode(primValues map tupled { nestedArrayTabulate }) - - def nestedArrayTabulate(typeStr: String, valStr: String) = { - ( - """ - val length = 10 - val a = Array.tabulate(length, length * 2)((i, j) => """ + valStr + """) - println(a) - """, - """ - val length = 10 - val a = { - val n1 = length - val n2 = length * 2 - val multiArray = Array.ofDim[""" + typeStr + """](n1, n2) - var i1 = 0 - while (i1 < n1) - { - val iVal1 = i1 - val subArray1 = multiArray(iVal1); - { - var i2 = 0 - while (i2 < n2) - { - val iVal2 = i2 - subArray1(i2) = """ + valStr + """ - i2 += 1 - } - } - i1 += 1 - } - multiArray - } - println(a) - """ - ) - } - - @Test - def simplePrimitiveArrayMap = - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map simpleArrayMap) - - @Test - def simpleRefArrayMap = - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map simpleArrayMap) - - def simpleArrayMap(typeStr: String) = { - ( - """ - val a = new Array[""" + typeStr + """](10) - val m = a.map(_ + "...") - """, - """ - val a = new Array[""" + typeStr + """](10) - val m = { - val aa = a - val n = aa.length - var i = 0 - val mm = new Array[String](n) - while (i < n) - { - val item = aa(i) - val mapped = item + "..." - mm(i) = mapped - i += 1 - } - mm - } - """ - ) - } - - @Test - def inlinePrimitiveArrayMap = - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map inlineArrayMap) - - @Test - def inlineRefArrayMap = - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map inlineArrayMap) - - def inlineArrayMap(typeStr: String) = { - ( - """ - val m = new Array[""" + typeStr + """](10).map(_ + "...") - """, - """ - val m = { - val aa = new Array[""" + typeStr + """](10) - val n = aa.length - var i = 0 - val mm = new Array[String](n) - while (i < n) - { - val item = aa(i) - val mapped = item + "..." - mm(i) = mapped - i += 1 - } - mm - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/BaseTestUtils.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/BaseTestUtils.scala deleted file mode 100644 index 654c067ed..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/BaseTestUtils.scala +++ /dev/null @@ -1,475 +0,0 @@ -package com.nativelibs4java.scalaxy ; package test -//import plugin._ -import pluginBase._ - -import java.io.BufferedReader -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.io.PrintWriter -import scala.collection.mutable.HashMap -import scala.concurrent.ops -import scala.io.Source - -import java.net.URI -import java.net.URLClassLoader -import javax.tools.DiagnosticCollector -import javax.tools.FileObject -import javax.tools.ForwardingJavaFileManager -import javax.tools.JavaCompiler -import javax.tools.JavaFileManager -import javax.tools.JavaFileObject -import javax.tools.ToolProvider -import org.junit.Assert._ -import scala.tools.nsc.Settings -import scala.actors.Futures._ -import Function.{tupled, untupled} - -object Results { - import java.io._ - import java.util.Properties - def getPropertiesFileName(n: String) = n + ".perf.properties" - val logs = new scala.collection.mutable.HashMap[String, (String, PrintStream, Properties)] - def getLog(key: String) = { - logs.getOrElseUpdate(key, { - val logName = getPropertiesFileName(key) - //println("Opening performance log file : " + logName) - - val logRes = getClass.getClassLoader.getResourceAsStream(logName) - val properties = new java.util.Properties - if (logRes != null) { - println("Reading " + logName) - properties.load(logRes) - } - (logName, new PrintStream(logName), properties) - }) - } - Runtime.getRuntime.addShutdownHook(new Thread { override def run { - for ((_, (logName, out, _)) <- logs) { - println("Wrote " + logName) - out.close - } - }}) -} -object BaseTestUtils { - private var _nextId = 1 - def nextId = BaseTestUtils synchronized { - val id = _nextId - _nextId += 1 - id - } -} -trait BaseTestUtils { - import BaseTestUtils._ - - implicit val baseOutDir = new File("target/testSnippetsClasses") - baseOutDir.mkdirs - - def pluginDef: PluginDef - - object SharedCompilerWithPlugins extends SharedCompiler(true, pluginDef) - object SharedCompilerWithoutPlugins extends SharedCompiler(false, pluginDef) - - lazy val options: PluginOptions = { - val o = pluginDef.createOptions(null) - o.test = true - o - } - /*def compile(src: String, outDir: String) = { - outDir.mkdirs - - val srcFile = File.createTempFile("temp", ".scala") - val out = new PrintWriter(srcFile) - out.println(src) - out.close - //srcFile.delete - - }*/ - def getSnippetBytecode(className: String, source: String, subDir: String, compiler: SharedCompiler) = { - val src = "class " + className + " { def invoke(): Unit = {\n" + source + "\n}}" - val outDir = new File(baseOutDir, subDir) - outDir.mkdirs - val srcFile = new File(outDir, className + ".scala") - val out = new PrintWriter(srcFile) - out.println(src) - out.close - new File(outDir, className + ".class").delete - - compiler.compile( - Array( - "-d", - outDir.getAbsolutePath, - srcFile.getAbsolutePath - ) ++ - getAdditionalClassPath.map( - cp => Seq("-cp", cp.mkString(File.pathSeparator)) - ).getOrElse(Seq()) - ) - - val f = new File(outDir, className + ".class") - if (!f.exists()) - throw new RuntimeException("Class file " + f + " not found !") - - - val byteCodeSource = getClassByteCode(className, outDir.getAbsolutePath) - val byteCode = byteCodeSource.mkString//("\n") - /* - println("COMPILED :") - println("\t" + source.replaceAll("\n", "\n\t")) - println("BYTECODE :") - println("\t" + byteCode.replaceAll("\n", "\n\t")) - */ - - byteCode. - replaceAll("scala/reflect/ClassManifest", "scala/reflect/Manifest"). - replaceAll("#\\d+", "") - } - - def ensurePluginCompilesSnippet(source: String) = { - val (_, testMethodName) = testClassInfo - assertNotNull(getSnippetBytecode(testMethodName, source, "temp", SharedCompilerWithPlugins)) - } - def ensurePluginCompilesSnippetsToSameByteCode(sourcesAndReferences: Traversable[(String, String)]): Unit = { - def flatten(s: Traversable[String]) = s.map("{\n" + _ + "\n};").mkString("\n") - ensurePluginCompilesSnippetsToSameByteCode(flatten(sourcesAndReferences.map(_._1)), flatten(sourcesAndReferences.map(_._2))) - } - def ensurePluginCompilesSnippetsToSameByteCode(source: String, reference: String, allowSameResult: Boolean = false) = { - val (_, testMethodName) = testClassInfo - - import scala.concurrent.ops._ - implicit val runner = new scala.concurrent.ThreadRunner - - /* - val expectedFut = future { getSnippetBytecode(className, reference, "expected", SharedCompilerWithoutPlugins1) } - val withoutPluginFut = future { getSnippetBytecode(className, source, "withoutPlugin", SharedCompilerWithoutPlugins2) } - val withPluginFut = future { getSnippetBytecode(className, source, "withPlugin", SharedCompilerWithPlugins) }//ScalaxyTestUtils.compilerWithPlugin) } - val (expected, withoutPlugin, withPlugin) = (expectedFut(), withoutPluginFut(), withPluginFut()) - */ - val enableFuture = true - - def futEx[V](b: => V): () => V = if (!enableFuture) () => b else { - val f = future { try { Right(b) } catch { case ex => Left(ex) } } - () => f() match { - case Left(ex) => - ex.printStackTrace - assertTrue(ex.toString, false) - error("") - case Right(v) => - v - } - } - - val withPluginFut = futEx { getSnippetBytecode(testMethodName, source, "withPlugin", SharedCompilerWithPlugins) } - val expected = getSnippetBytecode(testMethodName, reference, "expected", SharedCompilerWithoutPlugins) - val withoutPlugin = if (allowSameResult) null else getSnippetBytecode(testMethodName, source, "withoutPlugin", SharedCompilerWithoutPlugins) - val withPlugin = withPluginFut() - - if (!allowSameResult) - assertTrue("Expected result already found without any plugin !!! (was the Scala compiler improved ?)", expected != withoutPlugin) - - if (expected != withPlugin) { - def trans(tit: String, s: String) = - println(tit + " :\n\t" + s.replaceAll("\n", "\n\t")) - - trans("EXPECTED", expected) - trans("FOUND", withPlugin) - - assertEquals(expected, withPlugin) - } - } - def getClassByteCode(className: String, classpath: String) = { - val args = Array("-c", "-classpath", classpath, className) - val p = Runtime.getRuntime.exec("javap " + args.mkString(" "))//"javap", args) - - var err = new StringBuffer - ops.spawn { - import scala.util.control.Exception._ - val inputStream = new BufferedReader(new InputStreamReader(p.getErrorStream)) - var str: String = null - //ignoring(classOf[IOException]) { - while ({ str = inputStream.readLine; str != null }) { - //err.synchronized { - println(str) - err.append(str).append("\n") - //} - //} - } - } - - val out = Source.fromInputStream(p.getInputStream).toList - if (p.waitFor != 0) { - Thread.sleep(100) - error("javap (args = " + args.mkString(" ") + ") failed with :\n" + err.synchronized { err.toString } + "\nAnd :\n" + out) - } - out - } - - import java.io.File - /*val outputDirectory = { - val f = new File(".")//target/classes") - if (!f.exists) - f.mkdirs - f - }*/ - - import java.io._ - - val packageName = "tests" - - case class Res(withPlugin: Boolean, output: AnyRef, time: Double) - type TesterGen = Int => (Boolean => Res) - - def fail(msg: String) = { - println(msg) - println() - assertTrue(msg, false) - } - - trait RunnableMethod { - def apply(args: Any*): Any - } - abstract class RunnableCode(val pluginOptions: PluginOptions) { - def newInstance(constructorArgs: Any*): RunnableMethod - } - - protected def compileCodeWithPlugin(decls: String, code: String) = - compileCode(withPlugin = true, code, "", decls, "") - - def getAdditionalClassPath: Option[Seq[String]] = - None - - protected def compileCode(withPlugin: Boolean, code: String, constructorArgsDecls: String = "", decls: String = "", methodArgsDecls: String = ""): RunnableCode = { - val (testClassName, testMethodName) = testClassInfo - - val suffixPlugin = (if (withPlugin) "Optimized" else "Normal") - val className = "Test_" + testMethodName + "_" + suffixPlugin + "_" + nextId - val src = "package " + packageName + "\nclass " + className + "(" + constructorArgsDecls + """) { - """ + (if (decls == null) "" else decls) + """ - def """ + testMethodName + "(" + methodArgsDecls + ")" + """ = { - """ + code + """ - } - }""" - - val outputDirectory = new File("tmpTestClasses" + suffixPlugin) - def del(dir: File): Unit = { - val fs = dir.listFiles - if (fs != null) - fs foreach del - - dir.delete - } - - del(outputDirectory) - outputDirectory.mkdirs - - var tmpFile = new File(outputDirectory, testMethodName + ".scala") - val pout = new PrintStream(tmpFile) - pout.println(src) - //println("Source = \n\t" + src.replaceAll("\n", "\n\t")) - pout.close - //println(src) - val compileArgs = Array( - "-d", - outputDirectory.getAbsolutePath, - tmpFile.getAbsolutePath - ) ++ getAdditionalClassPath.map( - cp => Seq("-cp", cp.mkString(File.pathSeparator)) - ).getOrElse(Seq()) - - //println("Compiling '" + tmpFile.getAbsolutePath + "' with args '" + compileArgs.mkString(" ") +"'") - val pluginOptions = ( - if (withPlugin) - SharedCompilerWithPlugins - else - SharedCompilerWithoutPlugins - ).compile(compileArgs) - - //println("CLASS LOADER WITH PATH = '" + outputDirectory + "'") - val loader = new URLClassLoader(Array( - outputDirectory.toURI.toURL, - new File(CompilerMain.bootClassPath).toURI.toURL - )) - - val parent = - if (packageName == "") - outputDirectory - else - new File(outputDirectory, packageName.replace('.', File.separatorChar)) - - val f = new File(parent, className + ".class") - if (!f.exists()) - throw new RuntimeException("Class file " + f + " not found !") - - //compileFile(tmpFile, withPlugin, outputDirectory) - - val testClass = loader.loadClass(packageName + "." + className) - val testMethod = testClass.getMethod(testMethodName)//, classOf[Int]) - val testConstructor = testClass.getConstructors.first - - new RunnableCode(pluginOptions) { - override def newInstance(constructorArgs: Any*) = new RunnableMethod { - val inst = - testConstructor.newInstance(constructorArgs.map(_.asInstanceOf[AnyRef]):_*).asInstanceOf[AnyRef] - - assert(inst != null) - - override def apply(args: Any*): Any = { - try { - testMethod.invoke(inst, args.map(_.asInstanceOf[AnyRef]):_*) - } catch { case ex => - ex.printStackTrace - throw ex - } - } - } - } - } - - - private def getTesterGen(withPlugin: Boolean, decls: String, code: String) = { - val runnableCode = compileCode(withPlugin, code, "n: Int", decls, "") - - (n: Int) => { - val i = runnableCode.newInstance(n) - (isWarmup: Boolean) => { - if (isWarmup) { - i() - null - } else { - System.gc - Thread.sleep(50) - val start = System.nanoTime - val o = i().asInstanceOf[AnyRef] - val time: Double = System.nanoTime - start - Res(withPlugin, o, time) - } - } - } - } - def testClassInfo = { - val testTrace = new RuntimeException().getStackTrace.filter(se => se.getClassName.endsWith("Test")).last - val testClassName = testTrace.getClassName - val methodName = testTrace.getMethodName - (testClassName, methodName) - } - - val defaultExpectedFasterFactor = Option(System.getenv(pluginDef.envVarPrefix + "MIN_PERF")).map(_.toDouble).getOrElse(0.95) - val perfRuns = Option(System.getenv(pluginDef.envVarPrefix + "PERF_RUNS")).map(_.toInt).getOrElse(4) - - def ensureCodeWithSameResult(code: String): Unit = { - val (testClassName, testMethodName) = testClassInfo - - val gens @ Array(genWith, genWithout) = Array(getTesterGen(true, "", code), getTesterGen(false, "", code)) - - val testers @ Array(testerWith, testerWithout) = gens.map(_(-1)) - - val firstRun = testers.map(_(false)) - val Array(optimizedOutput, normalOutput) = firstRun.map(_.output) - - val pref = "[" + testClassName + "." + testMethodName + "] " - if (normalOutput != optimizedOutput) { - fail(pref + "ERROR: Output is not the same !\n" + pref + "\t Normal output = " + normalOutput + "\n" + pref + "\tOptimized output = " + optimizedOutput) - } - } - def ensureFasterCodeWithSameResult(decls: String, code: String, params: Seq[Int] = Array(2, 10, 1000, 100000)/*10000, 100, 20, 2)*/, minFaster: Double = 1.0, nRuns: Int = perfRuns): Unit = { - - //println("Ensuring faster code with same result :\n\t" + (decls + "\n#\n" + code).replaceAll("\n", "\n\t")) - val (testClassName, methodName) = testClassInfo - - val gens @ Array(genWith, genWithout) = Array(getTesterGen(true, decls, code), getTesterGen(false, decls, code)) - - def run = params.toList.sorted.map(param => { - //println("Running with param " + param) - val testers @ Array(testerWith, testerWithout) = gens.map(_(param)) - - val firstRun = testers.map(_(false)) - val Array(optimizedOutput, normalOutput) = firstRun.map(_.output) - - val pref = "[" + testClassName + "." + methodName + ", n = " + param + "] " - if (normalOutput != optimizedOutput) { - fail(pref + "ERROR: Output is not the same !\n" + pref + "\t Normal output = " + normalOutput + "\n" + pref + "\tOptimized output = " + optimizedOutput) - } - - val runs: List[Res] = firstRun.toList ++ (1 until nRuns).toList.flatMap(_ => testers.map(_(false))) - def calcTime(list: List[Res]) = { - val times = list.map(_.time) - times.sum / times.size.toDouble - } - val (runsWithPlugin, runsWithoutPlugin) = runs.partition(_.withPlugin) - val (timeWithPlugin, timeWithoutPlugin) = (calcTime(runsWithPlugin), calcTime(runsWithoutPlugin)) - - (param, timeWithoutPlugin / timeWithPlugin) - }).toMap - - val (logName, log, properties) = Results.getLog(testClassName) - - //println("Cold run...") - val coldRun = run - - //println("Warming up..."); - // Warm up the code being benchmarked : - { - val testers = gens.map(_(5)) - (0 until 2500).foreach(_ => testers.foreach(_(true))) - }; - - //println("Warm run...") - val warmRun = run - - - val errors = coldRun.flatMap { case (param, coldFactor) => - val warmFactor = warmRun(param) - //println("coldFactor = " + coldFactor + ", warmFactor = " + warmFactor) - - def f2s(f: Double) = ((f * 10).toInt / 10.0) + "" - def printFacts(warmFactor: Double, coldFactor: Double) = { - val txt = methodName + "\\:" + param + "=" + Array(warmFactor, coldFactor).map(f2s).mkString(";") - //println(txt) - log.println(txt) - } - //def printFact(factor: Double) = log.println(methodName + "\\:" + param + "=" + f2s(factor)) - val (expectedWarmFactor, expectedColdFactor) = { - //val expectedColdFactor = { - val p = Option(properties.getProperty(methodName + ":" + param)).map(_.split(";")).orNull - if (p != null && p.length == 2) { - //val Array(c) = p.map(_.toDouble) - //val c = p.toDouble; printFact(c); c - //log.print("# Test result (" + (if (actualFasterFactor >= f) "succeeded" else "failed") + "): ") - val Array(w, c) = p.map(_.toDouble) - printFacts(w, c) - (w, c) - } else { - //printFact(coldFactor - 0.1); 1.0 - printFacts(warmFactor - 0.1, coldFactor - 0.1) - (defaultExpectedFasterFactor, defaultExpectedFasterFactor) - } - } - - def check(warm: Boolean, factor: Double, expectedFactor: Double) = { - val pref = "[" + testClassName + "." + methodName + ", n = " + param + ", " + (if (warm) "warm" else "cold") + "] " - - if (factor >= expectedFactor) { - println(pref + " OK (" + factor + "x faster, expected > " + expectedFactor + "x)") - Nil - } else { - val msg = "ERROR: only " + factor + "x faster (expected >= " + expectedFactor + "x)" - println(pref + msg) - List(msg) - } - } - - check(false, coldFactor, expectedColdFactor) ++ - check(true, warmFactor, expectedWarmFactor) - } - try { - if (!errors.isEmpty) - assertTrue(errors.mkString("\n"), false) - } finally { - println() - } - } - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/CollectionPerformanceTests.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/CollectionPerformanceTests.scala deleted file mode 100644 index 53bd718d1..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/CollectionPerformanceTests.scala +++ /dev/null @@ -1,92 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import org.junit._ -import Assert._ - -trait ChainedPerformanceTests { - this: CollectionPerformanceTests => - def chain(du: (String, String)) = { - val (definition, use) = du - (definition, use + ".filter(v => (v % 2) == 0).map(_ * 2)") - } -} - -trait NoRightTests { //extends CollectionPerformanceTests { - this: CollectionPerformanceTests => - override def simpleScanRight = {} - override def simpleFoldRight = {} - override def simpleReduceRight = {} -} -trait NoScalarReductionTests {//extends CollectionPerformanceTests { - this: CollectionPerformanceTests => - override def simpleSum = {} - override def simpleProduct = {} - override def simpleMin = {} - override def simpleMax = {} -} -class ListPerformanceTest extends CollectionPerformanceTests with NoRightTests { - override def col = ("val col: List[Int] = (0 to n).toList", "col")//.filter(v => (v % 2) == 0).map(_ * 2)") -} -class ListChainedPerformanceTest extends ListPerformanceTest with ChainedPerformanceTests { - override def col = chain(super.col) -} -class ArrayPerformanceTest extends CollectionPerformanceTests { - override def col = ("val col = Array.tabulate(n)(i => i)", "col") - @Test def simpleArrayTabulate = if (!skip) ensureFasterCodeWithSameResult(null, "Array.tabulate(n)(i => i).toSeq") -} -class ArrayChainedPerformanceTest extends ArrayPerformanceTest with ChainedPerformanceTests { - override def col = chain(super.col) -} -class RangePerformanceTest extends CollectionPerformanceTests with NoRightTests with NoScalarReductionTests { - override def col = (null: String, "(0 until n)") - override def simpleToArray = {} - override def simpleToList = {} - override def simpleTakeWhile = {} - override def simpleDropWhile = {} - override def simpleSum = {} - override def simpleProduct = {} - override def simpleMin = {} - override def simpleMax = {} -} -class RangeChainedPerformanceTest extends CollectionPerformanceTests with ChainedPerformanceTests with NoRightTests with NoScalarReductionTests { - override def col = chain((null, "(0 until n)")) -} - -trait CollectionPerformanceTests extends PerformanceTests { - val skip = PerformanceTests.skip - def col: (String, String) - - /************************** - * Collection conversions * - **************************/ - @Test def simpleToArray = if (!skip) testToArray(col) - @Test def simpleToList = if (!skip) testToList(col) - //@Test def simpleToVector = if (!skip) testToVector(col) - - @Test def simpleFilter = testFilter(col) - @Test def simpleFilterNot = testFilterNot(col) - @Test def simpleCount = testCount(col) - @Test def simpleExists = testExists(col) - @Test def simpleForall = testForall(col) - @Test def simpleTakeWhile = testTakeWhile(col) - @Test def simpleDropWhile = testDropWhile(col) - @Test def simpleForeach = testForeach(col) - @Test def simpleMap = testMap(col) - @Test def simpleSum = testSum(col) - @Test def simpleProduct = testProduct(col) - @Test def simpleMin = testMin(col) - @Test def simpleMax = testMax(col) - @Test def simpleScanLeft = testScanLeft(col) - @Test def simpleScanRight = testScanRight(col) - @Test def simpleFoldLeft = testFoldLeft(col) - @Test def simpleFoldRight = testFoldRight(col) - @Test def simpleReduceLeft = testReduceLeft(col) - @Test def simpleReduceRight = testReduceRight(col) - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/CompilerUtils.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/CompilerUtils.scala deleted file mode 100644 index 0e9ceb89b..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/CompilerUtils.scala +++ /dev/null @@ -1,137 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -object CompilerUtils { - import javax.tools._ - import JavaFileManager._ - import scala.collection.mutable.HashMap - import java.io._ - import java.net._ - - class MemoryFileManager(compiler: JavaCompiler, diagnostics: DiagnosticCollector[JavaFileObject]) extends ForwardingJavaFileManager[JavaFileManager](compiler.getStandardFileManager(diagnostics, null, null)) { - val inputs = new HashMap[String, MemoryJavaFile]() - val outputs = new HashMap[String, MemoryFileObject] - def addSourceInput(path: String, source: String) = { - val pathURI = if (!path.startsWith("file:///")) - "file:///" + path - else - path - - val f = new MemoryJavaFile(pathURI, source, JavaFileObject.Kind.SOURCE); - inputs(pathURI) = f - f - } - - override def getJavaFileForInput(location: JavaFileManager.Location, className: String, kind: JavaFileObject.Kind) = { - if (kind == JavaFileObject.Kind.SOURCE) - inputs(className) - else - super.getJavaFileForInput(location, className, kind); - } - - - def getFullPathForClass(className: String, extension: String) = - "file:///" + getSimplePathForClass(className, extension); - - def getSimplePathForClass(className: String, extension: String) = - className.replace('.', '/') + "." + extension; - - override def getJavaFileForOutput(location: JavaFileManager.Location, className: String, kind: JavaFileObject.Kind, sibling: FileObject) = { - var jo: MemoryJavaFile = null; - if (kind == JavaFileObject.Kind.CLASS) - outputs(getFullPathForClass(className, "class")) = { jo = new MemoryJavaFile(getFullPathForClass(className, "class"), null, kind); jo } - else if (kind == JavaFileObject.Kind.SOURCE) - inputs(getFullPathForClass(className, "java")) = { jo = new MemoryJavaFile(getFullPathForClass(className, "java"), null, kind); jo } - - if (jo == null) - super.getJavaFileForInput(location, className, kind) - else - jo - } - override def getFileForOutput(location: JavaFileManager.Location, packageName: String, relativeName: String, sibling: FileObject) = { - val actualRelativeName = - if (relativeName.startsWith("file:///")) - relativeName.substring("file:///".length()) - else - relativeName - - val out = outputs.getOrElseUpdate(relativeName, new MemoryFileObject(relativeName, null.asInstanceOf[String])) - out - } - } - class MemoryFileObject(var path: String, var content: Array[Byte]) extends FileObject { - def this(path: String, content: String) = this(path, content.getBytes) - - override def delete = { - content = null - true - } - override def getCharContent(ignoreEncodingErrors: Boolean) = - new String(content) - - val lastModified = System.currentTimeMillis - override def getLastModified = - lastModified - - override def getName = path - - override def openInputStream = { - if (content == null) - null - else - new ByteArrayInputStream(content) - } - override def openOutputStream = - new ByteArrayOutputStream() { - override def close = { - super.close - content = toByteArray - } - } - - override def openReader(ignoreEncodingErrors: Boolean) = { - val in = openInputStream - if (in == null) - null - else - new InputStreamReader(in) - } - override def openWriter = { - val out = openOutputStream - if (out == null) - null - else - new OutputStreamWriter(out) - } - override def toUri = - try { - new URI(path); - } catch { - case ex => - ex.printStackTrace(); - null; - } - - override def toString = path + ":\n" + getCharContent(true) - } - - class MemoryJavaFile(path: String, content: String, kind: JavaFileObject.Kind) extends MemoryFileObject(path, content) with JavaFileObject { - import javax.lang.model.element.Modifier - override def getAccessLevel = - Modifier.PUBLIC - - override def getKind = - kind - - override def getNestingKind = - null - - override def isNameCompatible(simpleName: String, kind: JavaFileObject.Kind) = - true // TODO - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/Filter2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/Filter2WhileTest.scala deleted file mode 100644 index 66503fa09..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/Filter2WhileTest.scala +++ /dev/null @@ -1,177 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ -import Function.{tupled, untupled} - -class Filter2WhileTest extends ScalaxyTestUtils with TypeUtils { - - @Test - def simplePrimitiveArrayFilter { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = Array(1, 2, 3, 4) - val m = a.filter(_ != 0) - """, - """ - val a = Array(1, 2, 3, 4) - val m = { - val array1 = a - val n1 = array1.length - var i1 = 0 - val builder1 = new scala.collection.mutable.ArrayBuilder.ofInt - while (i1 < n1) - { - val item1 = array1(i1) - if (item1 != 0) { - builder1 += item1 - } - i1 += 1 - } - builder1.result - } - """ - ) - } - - @Test - def simpleRefArrayFilter { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = Array("1", "2", "3", "4") - val m = a.filter(_ != "") - """, - """ - val a = Array("1", "2", "3", "4") - val m = { - val array1 = a - val n1 = array1.length - var i1 = 0 - val builder1 = new scala.collection.mutable.ArrayBuilder.ofRef[String] - while (i1 < n1) - { - val item1 = array1(i1) - if (item1 != "") { - builder1 += item1 - } - i1 += 1 - } - builder1.result - } - """ - ) - } - - @Test - def tupleArrayFilter { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = Array((1, 2), (10, 20), (100, 200)) - val m = a.filter(_._1 < 30) - """, - """ - val a = Array((1, 2), (10, 20), (100, 200)) - val m = { - val array1 = a - val n1 = array1.length - var i1 = 0 - val builder1 = new scala.collection.mutable.ArrayBuilder.ofRef[(Int, Int)] - while (i1 < n1) - { - val item1 = array1(i1) - if (item1._1 < 30) { - builder1 += item1 - } - i1 += 1 - } - builder1.result - } - """ - ) - } - - - def simpleArrayFilter(typeStr: String, valueStr: String) = { - ( - """ - val a = Array(""" + valueStr + """) - val m = a.filter(_ != """ + valueStr + """) - """, - """ - val m = { - val array1 = a - val n1 = array1.length - var i1 = 0 - val builder1 = new scala.collection.mutable.ArrayBuilder.of""" + (if (primTypeNames.contains(typeStr)) typeStr else "Ref[" + typeStr + "]") + """ - while (i1 < n1) - { - val item1 = array1(i1) - if (item1 != """ + valueStr + """) { - builder1 += item1 - } - i1 += 1 - } - builder1.result - } - """ - ) - } - - @Test - def simpleListFilter { if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = List(1, 2, 3, 4) - val m = a.filter(_ != 0) - """, - """ - val a = List(1, 2, 3, 4) - val m = { - var list1 = a - val builder1 = new scala.collection.mutable.ListBuffer[Int] - //while (!list1.isEmpty) { - while (list1.isInstanceOf[::[Int]]) { - val item1 = list1.head - if (item1 != 0) { - builder1 += item1 - } - list1 = list1.tail - } - builder1.result - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/Fold2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/Fold2WhileTest.scala deleted file mode 100644 index 98b4ff029..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/Fold2WhileTest.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class Fold2WhileTest extends ScalaxyTestUtils { - - @Test - def simpleFoldLeft { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = new Array[Double](10) - val s = a.foldLeft(0.0)(_ + _ * 0.01) - """, - """ - val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = 0 - var t = 0.0 - while (i < n) { - val item = aa(i) - t = t + item * 0.01 - i += 1 - } - t - } - """ - ) - } - - @Test - def simpleFoldRight { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = new Array[Double](10) - val s = a.foldRight(0.0)(_ * 0.01 + _) - """, - """ - val a = new Array[Double](10) - val s = { - val aa = a - var t = 0.0 - val n = aa.length - var i = n - while (i > 0) { - i -= 1 - val item = aa(i) - t = item * 0.01 + t - } - t - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/IntRangeForeach2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/IntRangeForeach2WhileTest.scala deleted file mode 100644 index a30e8b2f7..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/IntRangeForeach2WhileTest.scala +++ /dev/null @@ -1,279 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ -import Function.{tupled, untupled} - -class IntRangeForeach2WhileTest extends ScalaxyTestUtils with TypeUtils { - - @Test - def simpleUntilFilterLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (i <- 0 until 100; if i < 10) - t += 2 * i - """, - """ - val from = 0 - val to = 100 - var t = from - val n = to - var i = 0 - while (i < n) - { - val iVal = i - if (iVal < 10) { - t += 2 * iVal - } - i += 1 - } - """ - ) - } - - @Test - def simpleRange2PrimitiveMap = - ensurePluginCompilesSnippetsToSameByteCode(primValues map tupled { simpleRangeMap }) - - @Test - def simpleRange2RefMap = - ensurePluginCompilesSnippetsToSameByteCode(trivialRefValues map tupled { simpleRangeMap }) - - def simpleRangeMap(typeStr: String, valueStr: String) = { - ( - """ - val m = - for (i <- 0 until 100) - yield """ + valueStr + """ - """, - """ - val m = { - val from = 0 - val to = 100 - val n = to - var i = from - var builder1 = new scala.collection.immutable.VectorBuilder[""" + typeStr + """] - while (i < n) - { - builder1 +=(""" + valueStr + """) - i += 1 - } - builder1.result - } - """ - ) - } - - @Test - def simpleRangeFilter: Unit = { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val r: IndexedSeq[Int] = - (0 until 100).filter(_ != 50) - """, - """ - val r: IndexedSeq[Int] = { - val from = 0 - val to = 100 - var item = from - val builder1 = new scala.collection.immutable.VectorBuilder[Int] - while (item < to) - { - val itemVal = item - if (itemVal != 50) - builder1 += itemVal - item += 1 - } - builder1.result - } - """ - ) - } - - @Test - def simpleToLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ - var t = 0 - for (i <- 0 to 100) - t += 2 * i - """, - """ - var t = 0 - val n = 100 - var i = 0 - while (i <= n) - { - t += 2 * i - i += 1 - } - """ - ) - } - - - @Test - def simpleUntilLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (i <- 0 until 100) - t += 2 * i - """, - """ var t = 0 - val n = 100 - var i = 0 - while (i < n) - { - t += 2 * i - i += 1 - } - """ - ) - } - - - @Test - def simpleToByLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (j <- 50 to 200 by 3) - t += j / 2 - """, - """ var t = 0 - val m = 200 - var j = 50 - while (j <= m) - { - t += j / 2 - j += 3 - } - """ - ) - } - - @Test - def reverseToByLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (j <- 200 to 50 by -3) - t += j / 2 - """, - """ var t = 0 - val m = 50 - var j = 200 - while (j >= m) - { - t += j / 2 - j += -3 - } - """ - ) - } - - @Test - def simpleUntilByLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (j <- 50 until 200 by 3) - t += j / 2 - """, - """ var t = 0 - val m = 200 - var j = 50 - while (j < m) - { - t += j / 2 - j += 3 - } - """ - ) - } - @Test - def testNestedLoop { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - for (i <- 0 to 100 by 5; j <- 0 until 1000) - t += 2 * (i + j) - """, - """ var t = 0 - val n = 100 - var i = 0 - while (i <= n) - { - val m = 1000 - var j = 0 - while (j < m) - { - t += 2 * (i + j) - j += 1 - } - i += 5 - } - """ - ) - } - - @Test - def testNestedLoopWithExtRefs { - ensurePluginCompilesSnippetsToSameByteCode( - """ var t = 0 - def f(x: Int) = x + 1 - def g(x: Int) = x - 1 - for (i <- 0 to 100 by 5; j <- 0 until 1000) - t += 2 * (f(i) + g(j)) - """, - """ var t = 0 - def f(x: Int) = x + 1 - val n = 100 - var i = 0 - while (i <= n) - { - val iVal = i - def g(x: Int) = x - 1 - val m = 1000 - var j = 0 - while (j < m) - { - val jVal = j - t += 2 * (f(iVal) + g(jVal)) - j += 1 - } - i += 5 - } - """ - ) - } - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/ListLoopsRewriteTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/ListLoopsRewriteTest.scala deleted file mode 100644 index 69237b976..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/ListLoopsRewriteTest.scala +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class ListLoopsRewriteTest extends ScalaxyTestUtils with TypeUtils { - - @Test - def simpleRefListForeach = if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map simpleListForeach) - - @Test - def simplePrimitiveListForeach = if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map simpleListForeach) - - def simpleListForeach(typeStr: String) = { - ( - """ - val a = List[""" + typeStr + """]() - a.foreach(println(_)) - """, - """ - val a = List[""" + typeStr + """](); - { - var list = a - while (list.isInstanceOf[::[Int]]) { - //while (!list.isEmpty) { - val item = list.head - println(item) - list = list.tail - } - } - """ - ) - } - - @Test - def simpleRefListMap = if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode(refTypeNames map simpleListMap) - - @Test - def simplePrimitiveListMap = if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode(primTypeNames map simpleListMap) - - def simpleListMap(typeStr: String) = { - ( - """ - val a = List[""" + typeStr + """]() - val m = a.map(_ + "...") - """, - """ - val a = List[""" + typeStr + """](); - val m = { - var list = a - val builder = new scala.collection.mutable.ListBuffer[String] - while (list.isInstanceOf[::[Int]]) { - //while (!list.isEmpty) { - val item = list.head - val mapped = item + "..." - builder += mapped - list = list.tail - } - builder.result - } - """ - ) - } - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/MatrixPerformanceTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/MatrixPerformanceTest.scala deleted file mode 100644 index 9569c8b5d..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/MatrixPerformanceTest.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import org.junit._ -import Assert._ - -class MatrixPerformanceTest extends ScalaxyTestUtils { - import PerformanceTests.skip - - @Test def simpleMatrixTest = if (!skip) ensureFasterCodeWithSameResult( - """ - val a = Array.tabulate[Double](n, n)(_ + _) - val b = Array.tabulate[Double](n, n)(_ + _) - """, - if (!options.stream) - """ - var bigTot = 0.0 - val o = Array.tabulate(n, n)((i, j) => { - var tot = 0.0 - for (k <- 0 until n) - tot += a(i)(k) * b(k)(j) - - bigTot += tot - tot - }) - bigTot + o.size - """ - else - """ - val out = Array.tabulate[Double](n, n)((i, j) => { - (0 until n).map(k => a(i)(k) * b(k)(j)).sum - }) - - out.map(_.toSeq).toSeq // to make it equals-comparable - """, - Seq(100), - minFaster = 20.0 - ) - -} - diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/NoChangeTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/NoChangeTest.scala deleted file mode 100644 index 3c99d6b2e..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/NoChangeTest.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ -import Function.{tupled, untupled} - -class NoChangeTest extends ScalaxyTestUtils with TypeUtils { - - def ensureUnchanged(source: String) = - ensurePluginCompilesSnippetsToSameByteCode(source, source, allowSameResult = true) - - def unchangedCol(col: String) = - ensureUnchanged( - """ - val a = """ + col + """ - val filter = a.filter(_ != 0) - val map = a.map(_ + 1) - val takeWhile = a.takeWhile(_ < 2) - val reduce = a.reduceLeft(_ + _) - val fold = a.foldLeft(0)(_ + _) - val scan = a.scanLeft(0)(_ + _) - a.foreach(println(_)) - """ - ) - - @Test def simpleUnchangedSeq = unchangedCol("Seq(1, 2, 3, 4)") - @Test def simpleUnchangedIndexedSeq = unchangedCol("IndexedSeq(1, 2, 3, 4)") - @Test def simpleUnchangedSet = unchangedCol("Set(1, 2, 3, 4)") - @Test def simpleUnchangedTraversable = unchangedCol("Traversable(1, 2, 3, 4)") - @Test def simpleUnchangedIterable = unchangedCol("Iterable(1, 2, 3, 4)") - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/PastBugsTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/PastBugsTest.scala deleted file mode 100644 index 2734b510b..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/PastBugsTest.scala +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class PastBugsTest extends ScalaxyTestUtils { - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=34 - @Test - def issue34_optimInTrait { - ensurePluginCompilesSnippet(""" - trait Bug { - for (i <- 0 to 10) { - val crash = i - } - } - """) - } - - @Test - def yieldTuplesFromTuplesList { - ensurePluginCompilesSnippet(""" - val l1 = (1 to 5).toList.zipWithIndex - for ((a, b) <- l1) - yield (a, b) - """) - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=40 - @Test - def issue40_tuplesArrayFilteredForeach { - ensureCodeWithSameResult(""" - (for ((i, j) <- Array(1 -> 1, 2 -> 2)) yield (i, j)).toSeq - """) - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=41 - @Test - def issue41_arrayListToArray { - ensureCodeWithSameResult(""" - List(Array(1,2), Array(3,4)).toArray.map(_.toSeq).toSeq - """) - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=42 - @Test - def issue42_anyListToArray { - ensureCodeWithSameResult(""" - def f(a: List[Any]) = a.toArray - f(List(1, 2, 3)).toSeq - """) - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=43 - @Test - def issue43_mapWithBreakOut { - ensureCodeWithSameResult(""" - ( - Array(1).map(_ + 1)(collection.breakOut): Set[Int], - List(1).map(_ + 1)(collection.breakOut): Set[Int], - (0 until 10).map(_ + 1)(collection.breakOut): Set[Int] - ) - """) - } - - /// http://code.google.com/p/nativelibs4java/issues/detail?id=44 - @Test - def issue44_capturingAVarInClosuresThatEvaluateLater { - ensureCodeWithSameResult(""" - (1 to 10).map {i => j: Int => i + j}.map(_(10)) - """) - } - - - - val a: Set[Int] = List(1).map(_ + 1)(collection.breakOut) - - @Test - def yieldTuplesInMap { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = Array(1, 2) - val r: Array[(Int, Int)] = - for (v <- a) yield (v, v) - """, - """ - val a = Array(1, 2); - val r: Array[(Int, Int)] = { - val array = a - val n = array.length - var i = 0 - val m = new Array[(Int, Int)](n) - while (i < n) { - val item = array(i) - val mapped = (item, item) - m(i) = mapped - i += 1 - } - m - } - """ - ) - } - - @Test - def yieldCaseClassFromTuples { - ensurePluginCompilesSnippet( - """ - case class T(a: Int, b: Int) - for ((a, b) <- Array((1, 2), (2, 3))) yield T(a, b) - """ - ) - } - - @Test - def lambdaLiftNestedMap { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = Array(1, 2) - val r: Array[Array[Int]] = - a.map(xx => a.map(x => { def f = x ; f })) - """, - """ - val a = Array(1, 2); - val r: Array[Array[Int]] = { - val array1 = a - val n1 = array1.length - var i1 = 0 - val out2 = new Array[Array[Int]](n1) - while (i1 < n1) { - val item1 = array1(i1) - val mapped2: Array[Int] = { - val array2 = a - val n2 = array2.length - var i2 = 0 - val out1 = new Array[Int](n2) - while (i2 < n2) { - val item2 = array2(i2) - val mapped1 = { - def f = item2 - f - } - out1(i2) = mapped1 - i2 += 1 - } - out1 - } - out2(i1) = mapped2 - i1 += 1 - } - out2 - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/PerformanceTests.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/PerformanceTests.scala deleted file mode 100644 index 9942a190b..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/PerformanceTests.scala +++ /dev/null @@ -1,90 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import org.junit._ -import Assert._ - -object PerformanceTests { - lazy val skip = { - val test = "1" == System.getenv("SCALAXY_TEST_PERF") - if (!test) - println("You can run " + getClass.getName + " by setting the environment variable SCALACL_TEST_PERF=1") - !test - } -} -trait PerformanceTests extends ScalaxyTestUtils { - val skip: Boolean - - val oddPred = "x => (x % 2) != 0" - val firstHalfPred = "x => x < n / 2" - val midPred = "x => x == n / 2" - - def testToList(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".toList") - - def testToArray(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".toArray.toSeq") - - def testFilter(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".filter(" + oddPred + ").toSeq") - - def testFilterNot(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".filterNot(" + oddPred + ").toSeq") - - def testCount(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".count(" + oddPred + ")") - - def testForeach(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, "var tot = 0L; for (v <- " + cc._2 + ") { tot += v }; tot") - - def testMap(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".map(_ + 1).toSeq") - - def testTakeWhile(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".takeWhile(" + firstHalfPred + ").toSeq") - - def testDropWhile(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".dropWhile(" + firstHalfPred + ").toSeq") - - def testExists(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".exists(" + midPred + ")") - - def testForall(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".forall(" + firstHalfPred + ")") - - def testSum(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".sum") - - def testProduct(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".product") - - def testMin(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".min") - - def testMax(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".max") - - def testReduceLeft(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".reduceLeft(_ + _)") - - def testReduceRight(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".reduceRight(_ + _)") - - def testFoldLeft(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".foldLeft(0)(_ + _)") - - def testFoldRight(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".foldRight(0)(_ + _)") - - def testScanLeft(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".scanLeft(0)(_ + _).toSeq") - - def testScanRight(cc: (String, String)) = if (!skip) - ensureFasterCodeWithSameResult(cc._1, cc._2 + ".scanRight(0)(_ + _).toSeq") - -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/Reduce2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/Reduce2WhileTest.scala deleted file mode 100644 index bc3cf3166..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/Reduce2WhileTest.scala +++ /dev/null @@ -1,236 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class Reduce2WhileTest extends ScalaxyTestUtils { - - @Test - def simpleReduceLeft { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = new Array[Double](10) - val s = a.reduceLeft(_ + _ * 0.01) - """, - """ - val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = 0 - var t = 0.0 - var isDefined = false - while (i < n) { - val item = aa(i) - if (!isDefined) { - isDefined = true - t = item - } else - t = t + item * 0.01 - i += 1 - } - if (!isDefined) - throw new ArrayIndexOutOfBoundsException(0) - t - } - """ - ) - } - - @Test - def simpleReduceRight { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = new Array[Double](10) - val s = a.reduceRight(_ * 0.01 + _) - """, - """ - val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = n// - 1 - var t = 0.0//aa(n - 1) - var isDefined = false - while (i > 0) { - i -= 1 - val item = aa(i) - if (!isDefined) { - isDefined = true - t = item - } else - t = item * 0.01 + t - } - if (!isDefined) - throw new ArrayIndexOutOfBoundsException(0) - t - } - """ - ) - } - @Test - def simpleSum { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val s1 = Array(1, 2, 3).sum - val s2 = Array(1.0, 2.0, 3.0).sum - """, - """ - val s1 = { - val a = Array(1, 2, 3) - val n = a.length - var i = 0 - var tot = 0.0 - while (i < n) { - val item = a(i) - tot += item - i += 1 - } - tot - }; - val s2 = { - val a = Array(1.0, 2.0, 3.0) - val n = a.length - var i = 0 - var tot = 0.0 - while (i < n) { - val item = a(i) - tot += item - i += 1 - } - tot - } - """ - ) - } - @Test - def simpleProduct { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val s1 = Array(1, 2, 3).product - val s2 = Array(1.0, 2.0, 3.0).product - """, - """ - val s1 = { - val a = Array(1, 2, 3) - val n = a.length - var i = 0 - var tot = 1.0 - while (i < n) { - val item = a(i) - tot *= item - i += 1 - } - tot - }; - val s2 = { - val a = Array(1.0, 2.0, 3.0) - val n = a.length - var i = 0 - var tot = 1.0 - while (i < n) { - val item = a(i) - tot *= item - i += 1 - } - tot - } - """ - ) - } - - @Test - def simpleMin { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val s1 = Array(1, 2, 3).min - """, - """ - val s1 = { - val a = Array(1, 2, 3) - val n = a.length - var i = 0//1 - var tot = 0//a(0) - var isDefined = false - while (i < n) { - val item = a(i) - if (!isDefined) { - isDefined = true - tot = item - } else { - if (item < tot) - tot = item - } - i += 1 - } - if (!isDefined) - throw new ArrayIndexOutOfBoundsException(0) - tot - }; - """ - ) - } - @Test - def simpleMax { - ensurePluginCompilesSnippetsToSameByteCode( - """ - val s2 = Array(1.0, 2.0, 3.0).max - """, - """ - val s2 = { - val a = Array(1.0, 2.0, 3.0) - val n = a.length - var i = 0//1 - var tot = 0.0//a(0) - var isDefined = false - while (i < n) { - val item = a(i) - if (!isDefined) { - isDefined = true - tot = item - } else { - if (item > tot) - tot = item - } - i += 1 - } - if (!isDefined) - throw new ArrayIndexOutOfBoundsException(0) - tot - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/ScalaceTestUtils.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/ScalaceTestUtils.scala deleted file mode 100644 index db048a050..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/ScalaceTestUtils.scala +++ /dev/null @@ -1,35 +0,0 @@ -package com.nativelibs4java.scalaxy ; package test -import pluginBase._ -import plugin._ - -import java.io.BufferedReader -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.File -import java.io.IOException -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.io.PrintWriter -import scala.collection.mutable.HashMap -import scala.concurrent.ops -import scala.io.Source - -import java.net.URI -import java.net.URLClassLoader -import javax.tools.DiagnosticCollector -import javax.tools.FileObject -import javax.tools.ForwardingJavaFileManager -import javax.tools.JavaCompiler -import javax.tools.JavaFileManager -import javax.tools.JavaFileObject -import javax.tools.ToolProvider -import org.junit.Assert._ -import scala.tools.nsc.Settings -import scala.actors.Futures._ -import Function.{tupled, untupled} - -trait ScalaxyTestUtils extends BaseTestUtils { - def pluginDef: PluginDef = - ScalaxyPluginDef -} - diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/Scan2WhileTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/Scan2WhileTest.scala deleted file mode 100644 index 09681b262..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/Scan2WhileTest.scala +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -import java.io.File -import org.junit._ -import Assert._ - -class Scan2WhileTest extends ScalaxyTestUtils { - - import options.experimental - - @Test - def simpleArrayScanLeft { - ensurePluginCompilesSnippetsToSameByteCode( - """ val a = new Array[Double](10) - val s = a.scanLeft(0.0)(_ + _ * 0.01) - """, - """ val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = 0 - var t = 0.0 - val m = new Array[Double](n + 1) - m(0) = t - while (i < n) { - val item = aa(i) - t = t + item * 0.01 - m(i + 1) = t - i += 1 - } - m - } - """ - ) - } - - - @Test - def simpleListScanLeft { if (options.deprecated) - ensurePluginCompilesSnippetsToSameByteCode( - """ - val a = List(1.0, 2.0) - val s = a.scanLeft(0.0)(_ + _ * 0.01) - """, - """ - val a = List(1.0, 2.0) - val m = { - var list = a - var t = 0.0 - val builder = new scala.collection.mutable.ListBuffer[Double] - builder += t - while (list.isInstanceOf[::[Int]]) { - //while (!list.isEmpty) { - val item = list.head - t = t + item * 0.01 - builder += t - list = list.tail - } - builder.result - } - """ - ) - } - - - @Test - def simpleArrayScanRight = if (experimental) { - ensurePluginCompilesSnippetsToSameByteCode( - """ val a = new Array[Double](10) - val s = a.scanRight(0.0)(_ * 0.01 + _) - """, - """ val a = new Array[Double](10) - val s = { - val aa = a - val n = aa.length - var i = n - var t = 0.0 - val m = new Array[Double](n + 1) - m(0) = t - while (i > 0) { - i -= 1 - val iVal = i - val item = aa(iVal) - t = item * 0.01 + t - m(n - iVal) = t - } - m - } - """ - ) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/SideEffectsTest.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/SideEffectsTest.scala deleted file mode 100644 index 528c47339..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/SideEffectsTest.scala +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ScalaCL - putting Scala on the GPU with JavaCL / OpenCL - * http://scalacl.googlecode.com/ - * - * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * 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. - * * Neither the name of Olivier Chafik nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``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 THE REGENTS AND 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. - */ -package com.nativelibs4java.scalaxy ; package test -//import plugin._ -import common._ - -import java.io.File -import org.junit._ -import Assert._ - -class SideEffectsTest extends ScalaxyTestUtils { - - def assertSideEffectFull(decls: String, code: String) = - assertSideEffect(false, decls, code) - - def assertSideEffectFree(decls: String, code: String) = - assertSideEffect(true, decls, code) - - def assertSideEffect(free: Boolean, decls: String, code: String) = { - val rc = - compileCode(withPlugin = true, decls = decls, code = code) - - //println("rc.pluginOptions.testOutputs = " + rc.pluginOptions.testOutputs) - val sef = rc.pluginOptions.testOutputs.get(HasSideEffects).orNull.asInstanceOf[collection.mutable.ArrayBuffer[_]] - //getOrElse(null) - - assertEquals("Failed to analyze side-effects ! Side effects = \n\t" + Option(sef).map(_.mkString(",\n\t")).getOrElse("testOutputs = " + rc.pluginOptions.testOutputs), free, sef == null || sef.isEmpty) - } - - @Test - def simpleSideEffectAssignment { - assertSideEffectFull(""" - var v = 0 - """, """ - v = 10 - """) - } - - @Test - def simpleSideEffectFreeAssignment { - assertSideEffectFree(""" - //no external declaration - """, """ - var v = 0 - v = 10 - """) - } - - @Test - def simpleMethodCall { - assertSideEffectFull(""" - var v = 0 - def some = v = 10 - """, """ - some - """) - } - - @Test - def mediumSideEffects { - assertSideEffectFree("", """ - import scala.math._ - val x = 10 - val p @ (a, b) = - if ((sin(x / 2) / 10).toInt % 3 < 100) - (1: Float, 2.0) - else - (1.toFloat, 2: Double) - """) - } -} diff --git a/libraries/Scalaxy/src/test/scala/scalaxy/test/TypeUtils.scala b/libraries/Scalaxy/src/test/scala/scalaxy/test/TypeUtils.scala deleted file mode 100644 index d8350dbf8..000000000 --- a/libraries/Scalaxy/src/test/scala/scalaxy/test/TypeUtils.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.scalaxy ; package test -import plugin._ - -trait TypeUtils { - - lazy val primValues = Array( - "Double" -> "1.0", - "Float" -> "1f", - "Int" -> "1", - "Short" -> "(1: Short)", - "Long" -> "1L", - "Byte" -> "(1: Byte)", - "Char" -> "'a'", - "Boolean" -> "true") - - lazy val primValuesList = - primTypeNames.map(p => (p, if (p == "Boolean") "true, true, false" else Array(1, 2, 3).map("(" + _ + ": " + p + ")").mkString(", "))) - - lazy val refValuesList = Array( - "String" -> "\"a\", \"b\", \"c\"", - "List[Int]" -> "List(1), List(2), List(3)", - "(Int, Int)" -> "(1, 1), (2, 2), (3, 3)" - ) - - lazy val trivialRefValues = Array( - "String" -> "\"hello\"" - ) - lazy val refValues = trivialRefValues ++ Array( - "List[Int]" -> "List(1)", - "(Int, Int)" -> "(1, 1)" - ) - lazy val refTypeNames = refValues.map(_._1) - lazy val primTypeNames = primValues.map(_._1) - - lazy val typeValues = primValues ++ refValues - lazy val typeNames = primTypeNames ++ refTypeNames - -} diff --git a/libraries/Utils/pom.xml b/libraries/Utils/pom.xml index 037feb7d2..47a633d2f 100644 --- a/libraries/Utils/pom.xml +++ b/libraries/Utils/pom.xml @@ -6,13 +6,13 @@ http://code.google.com/p/nativelibs4java/ com.nativelibs4java nativelibs4java-utils - 1.5-SNAPSHOT + 1.6 jar com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT + 1.9 .. diff --git a/libraries/Velocity/.gitignore b/libraries/Velocity/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/Velocity/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/Velocity/README.md b/libraries/Velocity/README.md new file mode 100644 index 000000000..0fc749257 --- /dev/null +++ b/libraries/Velocity/README.md @@ -0,0 +1,4 @@ +`maven-velocity-plugin` has migrated to its own repository: [ochafik/maven-velocity-plugin](http://github.com/ochafik/maven-velocity-plugin). + +Please [file issues there](http://github.com/ochafik/maven-velocity-plugin/issues). + diff --git a/libraries/Velocity/pom.xml b/libraries/Velocity/pom.xml deleted file mode 100644 index 5bb1c6112..000000000 --- a/libraries/Velocity/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - 4.0.0 - - com.nativelibs4java - maven-velocity-plugin - 0.8-SNAPSHOT - maven-plugin - http://maven.apache.org - Maven Velocity Code Generator - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - - velocity - velocity - 1.5 - - - - org.apache.maven - maven-plugin-api - 3.0.3 - - - - org.apache.maven - maven-project - 3.0-alpha-2 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - aggregator - t - - - description - t - - - execute - t - - - goal - t - - - phase - t - - - requiresDirectInvocation - t - - - requiresDependencyResolution - t - - - requiresProject - t - - - requiresReports - t - - - requiresOnline - t - - - parameter - t - - - component - t - - - required - t - - - readonly - t - - - - - - - - diff --git a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Execution.java b/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Execution.java deleted file mode 100644 index c28380145..000000000 --- a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Execution.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.nativelibs4java.velocity; - -import java.util.Map; - - -public class Execution { - private Map parameters; - public Map getParameters() { - return parameters; - } -} \ No newline at end of file diff --git a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/MavenLogChute.java b/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/MavenLogChute.java deleted file mode 100644 index 644fa8b3b..000000000 --- a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/MavenLogChute.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.nativelibs4java.velocity; - -import org.apache.velocity.runtime.RuntimeServices; -import org.apache.velocity.runtime.log.LogChute; -import org.apache.maven.plugin.logging.Log; - -/** - * Yet another logging translator, this time going - * from: org.apache.velocity.runtime.log.LogChute - * to: org.apache.maven.plugin.logging.Log - */ -public class MavenLogChute implements LogChute { - private final Log log; - public MavenLogChute(Log logger) { - this.log = logger; - } - - public void init(RuntimeServices arg0) throws Exception {} - - public boolean isLevelEnabled(int lvl) { - return - (lvl == DEBUG_ID && log.isDebugEnabled()) || - (lvl == INFO_ID && log.isInfoEnabled()) || - (lvl == WARN_ID && log.isWarnEnabled()) || - (lvl == ERROR_ID && log.isErrorEnabled()); - } - - public void log(int lvl, String msg) { - if (isLevelEnabled(lvl)) { - switch (lvl) { - case DEBUG_ID : - log.debug(msg); - break; - case INFO_ID : - log.info(msg); - break; - case WARN_ID : - log.warn(msg); - break; - case ERROR_ID : - log.error(msg); - break; - default: - } - } - } - - public void log(int lvl, String msg, Throwable t) { - if (isLevelEnabled(lvl)) { - switch (lvl) { - case DEBUG_ID : - log.debug(msg, t); - break; - case INFO_ID : - log.info(msg, t); - break; - case WARN_ID : - log.warn(msg, t); - break; - case ERROR_ID : - log.error(msg, t); - break; - default: - } - } - } -} diff --git a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Primitive.java b/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Primitive.java deleted file mode 100644 index f97d4a7e8..000000000 --- a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/Primitive.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.nativelibs4java.velocity; - -import java.nio.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * - * @author Olivier - */ -public abstract class Primitive { - private final Class type, wrapper, bufferType; - private final String size; - private final String name, capName, wrapperName, bufferName; - //private final String v1, v2, v3; - - public String getCapName() { - return capName; - } - - public Class getBufferType() { - return bufferType; - } - - public boolean isSignedIntegral() { - return - type == int.class || - type == short.class || - type == long.class || - type == byte.class; - } - - public String getName() { - return name; - } - public String getTypeRef() { - return getWrapperName(); - } -/* - public String getV1() { - return v1; - } - - public String getV2() { - return v2; - } - - public String getV3() { - return v3; - } -*/ - public String getSize() { - return size; - } - - public Class getType() { - return type; - } - - public Class getWrapper() { - return wrapper; - } - - public String getWrapperName() { - return wrapperName; - } - - public String getBufferName() { - return bufferName; - } - - public String value(String intValue) { - return intValue; - } - - public String rawValue(String intValue) { - return value(intValue); - } - - public Primitive(String integralClassName) { - this.type = null; - wrapper = null; - bufferType = null; - size = integralClassName + ".SIZE"; - //v1 = "new " + integralClassName + "(1)"; - //v2 = "new " + integralClassName + "(2)"; - //v3 = "new " + integralClassName + "(3)"; - - name = integralClassName; - capName = integralClassName; - wrapperName = integralClassName; - bufferName = null; - } - - public Primitive(Class type) { - this.type = type; - if (type == Integer.TYPE) { - wrapper = Integer.class; - bufferType = IntBuffer.class; - size = "4"; - //v1 = "1"; - //v2 = "2"; - //v3 = "3"; - } else if (type == Long.TYPE) { - wrapper = Long.class; - bufferType = LongBuffer.class; - size = "8"; - //v1 = "1L"; - //v2 = "2L"; - //v3 = "3L"; - } else if (type == Short.TYPE) { - wrapper = Short.class; - bufferType = ShortBuffer.class; - size = "2"; - //v1 = "(short)1"; - //v2 = "(short)2"; - //v3 = "(short)3"; - } else if (type == Byte.TYPE) { - wrapper = Byte.class; - bufferType = ByteBuffer.class; - size = "1"; - //v1 = "(byte)1"; - //v2 = "(byte)2"; - //v3 = "(byte)3"; - } else if (type == Character.TYPE) { - wrapper = Character.class; - bufferType = CharBuffer.class; - size = "2"; - //v1 = "'a'"; - //v2 = "'b'"; - //v3 = "'c'"; - } else if (type == Float.TYPE) { - wrapper = Float.class; - bufferType = FloatBuffer.class; - size = "4"; - //v1 = "1f"; - //v2 = "2f"; - //v3 = "3f"; - } else if (type == Double.TYPE) { - wrapper = Double.class; - bufferType = DoubleBuffer.class; - size = "8"; - //v1 = "1.0"; - //v2 = "2.0"; - //v3 = "3.0"; - } else if (type == Boolean.TYPE) { - wrapper = Boolean.class; - bufferType = ByteBuffer.class; - size = "1"; - //v1 = "true"; - //v2 = "false"; - //v3 = "true"; - } else - throw new IllegalArgumentException(); - - name = type.getName(); - capName = Character.toUpperCase(name.charAt(0)) + name.substring(1); - wrapperName = wrapper.getSimpleName(); - bufferName = bufferType.getSimpleName(); - } - - static List bridJPrimitives; - public static synchronized List getBridJPrimitives() { - if (bridJPrimitives == null) { - bridJPrimitives = new ArrayList(); - bridJPrimitives.addAll(getPrimitives()); - bridJPrimitives.add(new Primitive("CLong") { - public String value(String intValue) { return "new CLong(" + intValue + ")"; } - public String rawValue(String intValue) { return "(long)" + intValue; } - }); - bridJPrimitives.add(new Primitive("SizeT") { - public String value(String intValue) { return "new SizeT(" + intValue + ")"; } - public String rawValue(String intValue) { return "(long)" + intValue; } - }); - bridJPrimitives.add(new Primitive("Pointer") { - public String value(String intValue) { return "(Pointer)Pointer.pointerToAddress(" + intValue + ")"; } - public String getTypeRef() { return "Pointer"; } - }); - bridJPrimitives = Collections.unmodifiableList(bridJPrimitives); - } - return bridJPrimitives; - } - - static List primitives; - public static synchronized List getPrimitives() { - if (primitives == null) { - primitives = new ArrayList(); - primitives.addAll(getPrimitivesNoBool()); - primitives.add(new Primitive(Boolean.TYPE) { - public String value(String intValue) { return "(((" + intValue + ") % 2) == 1)"; } - }); - primitives = Collections.unmodifiableList(primitives); - } - return primitives; - } - - static List primitivesNoBool; - public static synchronized List getPrimitivesNoBool() { - if (primitivesNoBool == null) { - primitivesNoBool = new ArrayList(); - primitivesNoBool.add(new Primitive(Integer.TYPE) { - public String value(String intValue) { return intValue; } - }); - primitivesNoBool.add(new Primitive(Long.TYPE) { - public String value(String intValue) { return "(long)" + intValue; } - }); - primitivesNoBool.add(new Primitive(Short.TYPE) { - public String value(String intValue) { return "(short)" + intValue; } - }); - primitivesNoBool.add(new Primitive(Byte.TYPE) { - public String value(String intValue) { return "(byte)" + intValue; } - }); - primitivesNoBool.add(new Primitive(Character.TYPE) { - public String value(String intValue) { return "(char)" + intValue; } - }); - primitivesNoBool.add(new Primitive(Float.TYPE) { - public String value(String intValue) { return "(float)" + intValue; } - }); - primitivesNoBool.add(new Primitive(Double.TYPE) { - public String value(String intValue) { return "(double)" + intValue; } - }); - primitivesNoBool = Collections.unmodifiableList(primitivesNoBool); - } - return primitivesNoBool; - } -} diff --git a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/VelocityMojo.java b/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/VelocityMojo.java deleted file mode 100644 index 2f1ab1f0d..000000000 --- a/libraries/Velocity/src/main/java/com/nativelibs4java/velocity/VelocityMojo.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.nativelibs4java.velocity; - -/* - * Copyright 2001-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.model.Resource; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.List; -import org.apache.velocity.*; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.app.Velocity; - -/** - * Generates source code with velocity templates - * @goal generate - * @phase generate-sources - * @description Generates source code with velocity templates - */ -public class VelocityMojo - extends AbstractMojo -{ - /** - * Extra properties - * @parameter - * @optional - */ - private Map properties; - - /** - * Source folder for velocity templates - * @parameter expression="${basedir}/src/" - * @required - */ - private File sourcePathRoot; - - /** - * Source folder for velocity templates - * @parameter expression="${basedir}/src/main/velocity/" - * @required - */ - private File velocitySources; - - /** - * Source folder for velocity test templates - * @parameter expression="${basedir}/src/test/velocity/" - * @required - */ - private File velocityTestSources; - - /** - * Output directory for generated sources. - * @parameter expression="${project.build.directory}/generated-sources/main" - * @optional - */ - private File sourcesOutputDirectory; - - /** - * Output directory for generated test sources. - * @parameter expression="${project.build.directory}/generated-sources/test" - * @optional - */ - private File testSourcesOutputDirectory; - - /** - * Output directory for resources. - * @parameter expression="${project.build.directory}/generated-resources/" - * @optional - */ - private File resourcesOutputDirectory; - - /** - * Output directory test resources. - * @parameter expression="${project.build.directory}/generated-test-resources/" - * @optional - */ - private File testResourcesOutputDirectory; - - /** - * @parameter expression="${project}" - * @required - * @readonly - * @since 1.0 - */ - private MavenProject project; - - static void listVeloFiles(File f, Collection out) throws IOException { - if (f.isHidden()) - return; - - String n = f.getName().toLowerCase(); - if (f.isDirectory()) { - if (n.equals(".svn") || n.equals("CVS")) - return; - - for (File ff : f.listFiles()) - listVeloFiles(ff.getAbsoluteFile(), out); - } else if (f.isFile()) { - //if (n.endsWith(".velo") || n.endsWith(".vm") || n.endsWith(".velocity")) - if (!n.startsWith("."))//endsWith(".velo") || n.endsWith(".vm") || n.endsWith(".velocity")) - out.add(f); - } - } - - public File getOutputFile(File vmFile, File velocitySources, File outputDirectory) throws IOException { - //String canoRoot = sourcePathRoot.getCanonicalPath(); - String canoRoot = velocitySources.getCanonicalPath(); - //String canoSrc = velocitySources.getCanonicalPath(); - String abs = vmFile.getCanonicalPath(); - String rel = abs.substring(canoRoot.length()); - String relLow = rel.toLowerCase(); - for (String suf : new String[] { ".vm", ".velo", ".velocity" }) { - if (relLow.endsWith(suf)) { - rel = rel.substring(0, rel.length() - suf.length()); - break; - } - } - int i = rel.lastIndexOf('.'); - File out = outputDirectory; - //if (i >= 0) { - // String ext = rel.substring(i + 1); - // out = new File(out, ext); - //} - - return new File(out.getCanonicalPath() + rel); - } - public void execute() - throws MojoExecutionException - { - if (executeAll(velocitySources, false)) { - //File jf = new File(outputDirectory, "java"); - //if (jf.exists()) - // outputDirectory = jf; - project.addCompileSourceRoot(sourcesOutputDirectory.toString()); - Resource res = new Resource(); - res.setDirectory(resourcesOutputDirectory.getAbsolutePath()); - project.addResource(res); - } - - if (executeAll(velocityTestSources, true)) { - //File jf = new File(testOutputDirectory, "java"); - //if (jf.exists()) - // testOutputDirectory = jf; - project.addTestCompileSourceRoot(testSourcesOutputDirectory.toString()); - Resource res = new Resource(); - res.setDirectory(testResourcesOutputDirectory.getAbsolutePath()); - project.addTestResource(res); - } - - /*if (templates == null) - getLog().error("Did not find !"); - else { - getLog().info("Found " + templates.size() + " templates"); - for (Template conf : templates) - conf.execute(this); - }*/ - } - - private boolean executeAll(File velocitySources, boolean isTest) throws MojoExecutionException { - VelocityEngine ve = new VelocityEngine(); - - List files = new ArrayList(); - String canoPath; - try { - velocitySources = velocitySources.getCanonicalFile(); - listVeloFiles(velocitySources, files); - - canoPath = sourcePathRoot.getCanonicalPath(); - getLog().info("Velocity root path = " + canoPath); - ve.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new MavenLogChute(getLog())); - ve.setProperty("file.resource.loader.path", canoPath);//file.getParent()); - - ve.init(); - - - } catch (Exception ex) { - throw new MojoExecutionException("Failed to list files from '" + velocitySources + "'", ex); - } - - - getLog().info("Found " + files.size() + " files in '" + velocitySources + "'..."); - getLog().info("Got Maven properties : " + project.getProperties()); - getLog().info("Got properties : " + properties); - - if (files.isEmpty()) - return false; - - for (File file : files) { - try { - file = file.getCanonicalFile(); - - String name = file.getName(); - if (name.endsWith("~") || name.endsWith(".bak")) { - getLog().info("Skipping: '" + name + "'"); - continue; - } - String lowName = name.toLowerCase(); - - File outputDirectory; - boolean isSource = name.endsWith(".java") || name.endsWith(".scala"); - if (isSource) { - outputDirectory = isTest ? testSourcesOutputDirectory : sourcesOutputDirectory; - } else { - outputDirectory = isTest ? testResourcesOutputDirectory : resourcesOutputDirectory; - } - - File outFile = getOutputFile(file, velocitySources, outputDirectory); - if (outFile.exists() && outFile.lastModified() > file.lastModified()) { - getLog().info("Up-to-date: '" + name + "'"); - continue; - } - getLog().info("Executing template '" + name + "'..."); - - //context = new VelocityContext(); - String cano = file.getCanonicalPath(); - cano = cano.substring(canoPath.length()); - if (cano.startsWith(File.separator)) - cano = cano.substring(File.separator.length()); - - org.apache.velocity.Template template = ve.getTemplate(cano);//file.getName()); - - VelocityContext context = new VelocityContext();//execution.getParameters()); - context.put("primitives", Primitive.getPrimitives()); - context.put("primitivesNoBool", Primitive.getPrimitivesNoBool()); - context.put("bridJPrimitives", Primitive.getBridJPrimitives()); - context.put("pom", project); - - for (Map.Entry e : project.getProperties().entrySet()) { - String propName = ((String)e.getKey()).replace('.', '_'), propValue = (String)e.getValue(); - getLog().debug("Got property : " + propName + " = " + propValue); - - context.put(propName, propValue); - } - - if (properties != null) { - for (Map.Entry e : properties.entrySet()) { - String propName = e.getKey(), propValue = e.getValue(); - getLog().debug("Got property : " + propName + " = " + propValue); - - context.put(propName, propValue); - } - } - - StringWriter out = new StringWriter(); - template.merge(context, out); - out.close(); - - outFile.getParentFile().mkdirs(); - - - FileWriter f = new FileWriter(outFile); - f.write(out.toString()); - f.close(); - //getLog().info("\tGenerated '" + outFile.getName() + "'"); - - } catch (Exception ex) { - //throw - new MojoExecutionException("Failed to execute template '" + file + "'", ex).printStackTrace(); - } - } - - return true; - } -} diff --git a/libraries/jnaerator/.classpath b/libraries/jnaerator/.classpath deleted file mode 100644 index 7515929cf..000000000 --- a/libraries/jnaerator/.classpath +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/.gitignore b/libraries/jnaerator/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/.project b/libraries/jnaerator/.project deleted file mode 100644 index 79988b3b7..000000000 --- a/libraries/jnaerator/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - jnaerator-root - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 555885f29..000000000 --- a/libraries/jnaerator/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -#Tue Jun 15 20:56:50 CEST 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/jnaerator/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/CHANGELOG b/libraries/jnaerator/CHANGELOG deleted file mode 100644 index c97bb25a8..000000000 --- a/libraries/jnaerator/CHANGELOG +++ /dev/null @@ -1,209 +0,0 @@ -Current development version (0.11-SNAPSHOT) - -- Fixed infinite loops in simple typedefs (issue #288) -- Fixed some -beautifyNames cases (issue #315) -- Fixed parsing of some C++ templates (including template constructors) -- Added parsing of 'using' C++ statements - -Version 0.10 (20120415, commit 6bc061dfce06b941086a29f696195e82fbaffbdc) - -- Release artifacts are available in Maven Central -- Fixed generation of large long values -- Fixed conditional parsing of __in modifier (and COM modifiers in general) -- Fixed generation of globals and variables included more than once -- Fixed parsing of unary '-' operator -- Fixed parsing of C++ constructors and class inheritance -- Fixed parsing of default values for type name template arguments -- Fixed parsing of const type mutator (fixes `void f(struct x * const);`) (issue #205) -- Fixed parsing of null char escape '\0' (issue #214) -- Fixed conversion of `int a; f(&a);` -- Fixed handling of "long int" and "short int" (issue #267) -- Fixed parsing of __declspec, __attribute__ and some modifiers-related regressions -- Fixed conversion of __inline functions when -convertBodies is on -- Fixed NPE in JNAeratorUtils.findBestPlainStorageName (issue #258) -- Fixed parsing of empty strings (spotted by @ENargit in issue #255) -- Fixed generation of typedefs (issue #273) -0 Fixed generation of casted constants (issue #96) -- Fixed generation of unnamed structs and unions (issue #94) -- Fixed multidimensional array sizes for JNA target (issue #165) -- Fixed handling of hexadecimal constants (issue #296) -- Fixed conversion of comments for BridJ target runtime -- Fixed generation of BridJ calling conventions (issue #282) -- Fixed handling of __stdcall function pointers and functions (issue #282) -- Fixed mapping of bool for JNA(erator) target runtime (issue #289) -- Fixed parsing of malloc, free and many potential modifiers (issue #278 and issue #280) -- Fixed handling of unicode library paths (issue #276) -- Fixed parsing of friend members in C++ classes, and of assignment operators (operator+=, ...) -- Fixed generation of very simple edge cases "long f();", "short f();", "f();" (issue #270) -- Changed naming of anonymous function pointer types : `void f(void (*arg)());` now yields callback `f_arg_callback` -- Enhanced handling of parsing failures : faster failover to "sliced" parsing, reduced verbosity of errors -- Added Maven output modes and -mode switch to choose between Jar, StandaloneJar, Directory, Maven, AutoGeneratedMaven (deprecated -noJar and -noComp) -- Added support for MSVC asm soups + added -removeInlineAsm hack switch that tries to regex-remove __asm soups that still cannot be parsed out -- Added support for BridJ's bundled libraries mechanism and paths (+ enforce them using an enum param) -- Added parsing of expression initializer blocks `v = { 1, 2, 3};` -- Added preservation of original textual representation of constants -- Added tr1 to default C++ includes -- Generate symbols of all files in directories where any file was explicitly listed -- Added support for command-line definition of macros with arguments : -Df(x)=whatever -- Added conversion of `malloc(x * y * sizeof(whatever))` -- Removed C++ name mangling feature for JNA target runtime (was simplistic anyway) - -Version 0.9.9 (20111107, 1cad7b05da2e89ce53246f30b181159ef8fce0c3) - -- Default runtime target is now BridJ: use -runtime JNAerator to retain old behaviour -- Added option -emptyStructsAsForwardDecls to force generation of opaque pointers for empty structs (even if they inherit from other empty structs) -- Fixed Maven plugin : - - add generated files to compilation sources - - now use "generate" goal (issue #152) -- Fixed handling of the empty package -- Fixed verbose mode (logs used to self-overwrite between different parsed files) -- Fixed rare package/className clash in pretty-printer (issue #182) -- Fixed C++ / Object.class method name clashes -- Fixed regression on fake pointers with JNA-based runtimes -- Fixed parsing of large unsigned longs -- Fixed generation of multiple anonymous enums (issue #96) -- Fixed BridJ enum items that refer to other items -- Fixed generation of string constant expressions cast as Pointers (only for JNAerator and BridJ runtimes) -- Fixed -runtime JNA target bug that used JNAerator target for generated library loading code (issue #95 @ jnaerator) -- Fixed varargs & param name generation for BridJ (thanks to Eric Emonet for the fix : https://github.com/ochafik/nativelibs4java/commit/74b59d5152333bf2d7f9d9613662f5fc3c1ecaf2) -- Enhanced BridJ runtime : only use CRuntime when there's no C++ contents -- Updated to ANTLR 3.4 -- Updated runtime to JNA 3.3.0 - -Version 0.9.8 (r2128, 20110621) - -- Better COM JNAeration for BridJ (now supports and converts __declspec(uuid("xxx")) attributes !) -- Accept some ill-formed constructs (mismatched extern "C" { ... }) for better cross-files parsing -- Fixed JNAeration of nested dependent constants defines -- Fixed automatic macro definitions : don't override already defined macros -- Fixed parsing of singleton extern "C" definitions (without curly braces) -- Fixed issue 86 (http://code.google.com/p/jnaerator/issues/detail?id=86) : generate proper array creation code for empty structs with the JNA runtime. -- Fixed issue 85 (http://code.google.com/p/jnaerator/issues/detail?id=85) : generate proper constant pointer casting code for BridJ : `#define PTR ((void*)-1)` generates `Pointer PTR = Pointer.pointerToAddress(-1);` -- Fixed generation of enums -- Fixed typing of (constant) boolean expressions - -Version 0.9.7 (r1817, 20110329) - -- Fixed generation of typed pointers (+ introduced undefined types for BridJ runtime) -- Added generation of globals for BridJ -- Added -parseInOneChunk option to control parsing more finely (forces regular, non isolated-mode parsing, which is more correct but also more fragile) -- Fixed enum renaming (issue 82: http://code.google.com/p/jnaerator/issues/detail?id=82) -- Fixed unescaped quotes in string defines (issue 79: http://code.google.com/p/jnaerator/issues/detail?id=79) -- Fixed some exotic function pointer syntax (issue 84: http://code.google.com/p/jnaerator/issues/detail?id=84) -- Fixed binding of Windows' BOOL type for BridJ: it's int, not boolean !!! - -Version 0.9.6 (r1638, 20110204) - -- Added explicit call to setFieldOrder in JNAerated JNA structures (no need for BridJ, which has its @Field annotations to guarantee proper order) -- Enhanced parsing and AST generation of C/C++ expressions -- Fixed BridJ inherited struct fields indexes computation - -Version 0.9.5 (r1330, 20101011): - -- Moved to JNA 3.2.7 -- Support anonymous bit fields : struct S { int :7; int b; } -- Better beautification of underscored typedefs : typedef struct _Toto___ { ... } Toto; now handled properly -- Extended -I command line syntax to include files directly (which does the same as an #include statement) : files are parsed but their content is not targetted for code generation -- Added -beautifyNames switch to transform some_func() into someFunc() -(http://code.google.com/p/jnaerator/issues/detail?id=59) -- Fixed names with dollars (and Scala struct field setters in particular !) -- Added -scalaStructSetters option -- Fixed callbacks fields -- Fixed studio JVM hanging issue (http://code.google.com/p/jnaerator/issues/detail?id=66) -- JNAerator Studio now launched when there's no command line args (JAR is double-clickable, at last !) -- Fixed struct** fields (PointerByReference instead of faulty Struct.ByReference[] !) -- Changed name of callbacks's single method from "invoke" to "apply" (to make them Scala-friendly) -- Fixed parsing of large files (reverted EASILY_DEBUGGABLE_BUT_FRAGILE_PARSING_MODE to false) -- Added __restrict keyword -- Added -synchronized switch to mark generated methods as synchronized (only in direct-mode JNA and BridJ outputs) -- Fixed generation of BridJ enums, constants and arrays -- Parse(skip) GCC inline assembler (__asm__) -- Parse some ObjectiveC 2 constructs : @package, @required and @optional member modifiers + new @property syntax -- Fixed parser regressions (0x7f, +10) -- Added experimental reification feature for BridJ output (-reification switch) : transforms functions that have a first "this-like" pointer argument into methods of the -corresponding pointer type. - Instead of getting : - {{{ - public native static TestLibrary.GXEntity gxCreateEntity(int someParam); - public native static void gxEntitySetValue(TestLibrary.GXEntity entity, int key, - int value); - public native static int gxEntityGetValue(TestLibrary.GXEntity entity, int key); - /// Pointer to unknown (opaque) type - public static class GXEntity extends TypedPointer { - public GXEntity(long address) { - super(address); - } - public GXEntity(Pointer address) { - super(address); - } - }; - }}} - You'd get the assembly-optimizable BridJ binding : - {{{ - native static @Ptr long gxCreateEntity(int someParam); - native static void gxEntitySetValue(@Ptr long entity, int key, int value); - native static int gxEntityGetValue(@Ptr long entity, int key); - public static class GXEntity extends TypedPointer { - public GXEntity(long address) { - super(address); - } - public GXEntity(Pointer address) { - super(address); - } - public static GXEntity create(int someParam) { - long ret = gxCreateEntity(someParam); - return ret == null ? null : new GXEntity(ret); - } - public void setValue(int key, int value) { - gxEntitySetValue(this.peer, key, value); - } - public int getValue(int key) { - return gxEntityGetValue(this.peer, key); - } - } - }}} - -Version 0.9.4 (r1067@nl4j, 20100717) - -- better C/C++ parsing (cast operators, templates, anonymous structs...) -- fixed JNAerator issues #63 ("JNA runtime does not -support bit fields"), #64 ("on Windows, use -%ProgramFiles%" to infer Visual Studio install directory.") -- enhanced BridJ runtime generation support -- enhanced debug output in verbose mode -- Added -beanStructs command line option to generate getters and setters for JNA (issue 62 @ jnaerator) - -Version 0.9.3 (r760@nl4j, 20100121) - -- Fixed parsing of some common C expressions (better tolerates inline functions) -- Fixed parsing of OpenCL source codes (used by JavaCL Generator project on NativeLibs4Java/JavaCL project) -- Introduced experimental lightweight structures support (use new "-runtime JNAeratorNL4JStructs" switch) -- Added automatic import statements generation to make source code smaller and easier to read (use new -noAutoImports switch to disable). - -Version 0.9.2 (r886, 20081030): - -- Fixed issue #31 : parse unnamed "char *const *" function arguments -- Fixed issue #35 : byref, byval, in, out and bycopy can now be used in most contexts (general case of issue #22 is still not fixed, though) -- Fixed regression on structs with callbacks -- Added "oneway" Objective C modifier -- Allow java-only modifiers, declspec and gcc attributes as identifiers (native, transient, dllimport...) -- Fixed issue #38 : Function pointer pointers were completely broken -- Fixed regression since maven move : missed objectivec static forwards exclusion list -- Deprecated Structure.toArray(), renamed to Structure.castToArray(). -- Added static Structure.newArray(Class, int length) -- JNAerating a typed static newArray(int length) for each structure -- Added "C type" comment to struct fields with non-primitive types -- Deprecated StringPointer -- Added basic output customization capabilities with -choicesOut & -choice switches : syntax is one line of the C function declaration, then n lines of corresponding Java declarations, each function block being separated by an empty line. -- Fixed issue #39 : Failure to parse define with expression containing a cast -- Fixed long constants being generated as NativeLong (now long) -- Fixed regression with function pre-comments -- Fixed generation of references to constants defined in other libraries -- size_t is now mapped to NativeSize. Classes NativeSizeByReference & GlobalNativeSize have also been added, along with a backwards compatibility switch -sizeAsLong (and a switch -gccLong to treat 'long' as 'size_t') -- Fixed primitive type promotion of constants (NativeLong -> long) -- Added -ifRegexMatch switch -- Define __STDC__ in auto configuration -- Fixed issue #44: Hypens in header names translate to hyphens in class names -- Byref & globals mapping of NSInteger now uses NativeSizeByReference and GlobalNativeSize, instead of NativeLong derivates - - diff --git a/libraries/jnaerator/LICENSE.LGPL-3.0.txt b/libraries/jnaerator/LICENSE.LGPL-3.0.txt deleted file mode 100644 index fc8a5de7e..000000000 --- a/libraries/jnaerator/LICENSE.LGPL-3.0.txt +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/libraries/jnaerator/LICENSE.LGPL.header b/libraries/jnaerator/LICENSE.LGPL.header deleted file mode 100644 index a29a0bee4..000000000 --- a/libraries/jnaerator/LICENSE.LGPL.header +++ /dev/null @@ -1,18 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ diff --git a/libraries/jnaerator/README.md b/libraries/jnaerator/README.md new file mode 100644 index 000000000..21e7e18d3 --- /dev/null +++ b/libraries/jnaerator/README.md @@ -0,0 +1,3 @@ +[JNAerator](http://jnaerator.googlecode.com) has migrated to its own repository: [ochafik/JNAerator](http://github.com/ochafik/JNAerator). + +Please [file issues there](http://github.com/ochafik/JNAerator/issues). diff --git a/libraries/jnaerator/anarres/.gitignore b/libraries/jnaerator/anarres/.gitignore deleted file mode 100644 index 66e8a1cb9..000000000 --- a/libraries/jnaerator/anarres/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target -project/boot -project/target -*~ -build/* diff --git a/libraries/jnaerator/anarres/LICENSE b/libraries/jnaerator/anarres/LICENSE deleted file mode 100644 index 11069edd7..000000000 --- a/libraries/jnaerator/anarres/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/libraries/jnaerator/anarres/build.xml b/libraries/jnaerator/anarres/build.xml deleted file mode 100644 index 728c55e8e..000000000 --- a/libraries/jnaerator/anarres/build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/deploy-anarres b/libraries/jnaerator/anarres/deploy-anarres deleted file mode 100755 index 1f4946004..000000000 --- a/libraries/jnaerator/anarres/deploy-anarres +++ /dev/null @@ -1,17 +0,0 @@ -mvn "-Dstorepass=$KEYSTORE_PASS" deploy:deploy-file \ - -Dfile=build/tar/lib/anarres-cpp.jar \ - -Durl=sftp://frs.sourceforge.net:/home/groups/n/na/nativelibs4java/htdocs/maven \ - -DrepositoryId=nativelibs4java-repo \ - -DgroupId=org.anarres.cpp \ - -DartifactId=anarres-cpp-jnaerator \ - -Dpackaging=jar \ - -DgeneratePom.description="JNAerator's version of Anarres JCPP" \ - -DuniqueVersion=true \ - "-Dversion=1.2.6-JNAerator.2" \ - -f pom.xml - -# -f scripts/deploy.pom \ -# -Durl=scp://shell.sourceforge.net/home/groups/j/jn/jnaerator/htdocs/maven \ -# -DgeneratePom=true \ -# -Dfile=../../../jnaerator/trunk/libraries/anarres/build/tar/lib/anarres-cpp.jar \ - diff --git a/libraries/jnaerator/anarres/etc/MANIFEST b/libraries/jnaerator/anarres/etc/MANIFEST deleted file mode 100644 index 7401ff438..000000000 --- a/libraries/jnaerator/anarres/etc/MANIFEST +++ /dev/null @@ -1,2 +0,0 @@ -Class-Path: gnu.getopt.jar -Main-Class: org.anarres.cpp.Main diff --git a/libraries/jnaerator/anarres/etc/build.properties b/libraries/jnaerator/anarres/etc/build.properties deleted file mode 100644 index 3f6814f22..000000000 --- a/libraries/jnaerator/anarres/etc/build.properties +++ /dev/null @@ -1,65 +0,0 @@ -global.version = 1.2.5 -global.name = anarres-cpp - -global.dir.arch = ${global.dir.root}/arch -global.dir.etc = ${global.dir.root}/etc -global.dir.lib = ${global.dir.root}/lib -global.dir.tmp = ${global.dir.root}/build/tmp - -global.dir.licenses = ${global.dir.etc}/licenses - -global.dir.src = ${global.dir.root}/src -global.dir.src.docs = ${global.dir.root}/src/docs -global.dir.src.java = ${global.dir.root}/src/main/java -global.dir.src.velocity = ${global.dir.root}/src/main/velocity -global.dir.src.resources = ${global.dir.root}/src/main/resources -global.dir.src.scripts = ${global.dir.root}/src/scripts -global.dir.src.sql = ${global.dir.root}/src/sql -global.dir.src.tests = ${global.dir.root}/src/test/java -global.dir.src.tools = ${global.dir.root}/src/tools - -# XXX Add hacks. - -global.dir.build = ${global.dir.root}/build -global.dir.build.classes = ${global.dir.root}/build/classes -global.dir.build.cobertura = ${global.dir.root}/build/cobertura -global.dir.build.depcache = ${global.dir.root}/build/depcache -global.dir.build.dist = ${global.dir.root}/build/dist -global.dir.build.docs = ${global.dir.root}/build/docs -global.dir.build.hbm = ${global.dir.root}/build/hbm -global.dir.build.jar = ${global.dir.root}/build/jar -global.dir.build.java = ${global.dir.root}/build/java -global.dir.build.javadoc = ${global.dir.root}/build/javadoc -global.dir.build.lib = ${global.dir.root}/build/lib -global.dir.build.reports = ${global.dir.root}/build/reports -global.dir.build.sql = ${global.dir.root}/build/sql -global.dir.build.tar = ${global.dir.root}/build/tar -global.dir.build.test-xml = ${global.dir.root}/build/test-xml -global.dir.build.tests = ${global.dir.root}/build/tests -global.dir.build.tools = ${global.dir.root}/build/tools -global.dir.build.wsdd = ${global.dir.root}/build/wsdd -global.dir.build.wsdl = ${global.dir.root}/build/wsdl -global.dir.build.xml = ${global.dir.root}/build/xml - -global.file.jar.name = ${global.name}.jar -global.file.jar = ${global.dir.build.tar}/lib/${global.file.jar.name} -global.file.bintar.name = ${global.name}-bin-${global.version}.tar.gz -global.file.bintar = ${global.dir.build.dist}/${global.file.bintar.name} -global.file.srctar.name = ${global.name}-src-${global.version}.tar.gz -global.file.srctar = ${global.dir.build.dist}/${global.file.srctar.name} - -build.compiler = modern -system.javac.optimize = true -system.javac.debug = true -system.javac.source = 1.5 -system.javac.target = ${system.javac.source} -system.javac.deprecation = true - -# system.javadoc.access = package -system.javadoc.access = protected -system.javadoc.source = ${system.javac.source} -system.javadoc.offline = false - -system.jar.compress = true - -wsdl.server.http.url = http://localhost:8080/axis diff --git a/libraries/jnaerator/anarres/etc/checkstyle/config.xml b/libraries/jnaerator/anarres/etc/checkstyle/config.xml deleted file mode 100644 index 22f8d525d..000000000 --- a/libraries/jnaerator/anarres/etc/checkstyle/config.xml +++ /dev/null @@ -1,178 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/global.xml b/libraries/jnaerator/anarres/etc/global.xml deleted file mode 100644 index d465f0753..000000000 --- a/libraries/jnaerator/anarres/etc/global.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/junit/xsl/junit-frames.xsl b/libraries/jnaerator/anarres/etc/junit/xsl/junit-frames.xsl deleted file mode 100644 index a9d37a576..000000000 --- a/libraries/jnaerator/anarres/etc/junit/xsl/junit-frames.xsl +++ /dev/null @@ -1,716 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Unit Test Results. - - - - - - - - - <h2>Frame Alert</h2> - <p> - This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. - </p> - - - - - - - -body { - font:normal 68% verdana,arial,helvetica; - color:#000000; -} -table tr td, table tr th { - font-size: 68%; -} -table.details tr th{ - font-weight: bold; - text-align:left; - background:#a6caf0; -} -table.details tr td{ - background:#eeeee0; -} - -p { - line-height:1.5em; - margin-top:0.5em; margin-bottom:1.0em; -} -h1 { - margin: 0px 0px 5px; font: 165% verdana,arial,helvetica -} -h2 { - margin-top: 1em; margin-bottom: 0.5em; font: bold 125% verdana,arial,helvetica -} -h3 { - margin-bottom: 0.5em; font: bold 115% verdana,arial,helvetica -} -h4 { - margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica -} -h5 { - margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica -} -h6 { - margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica -} -.Error { - font-weight:bold; color:red; -} -.Failure { - font-weight:bold; color:purple; -} -.Properties { - text-align:right; -} - - - - - - - . - - - Unit Test Results: <xsl:value-of select="$class.name"/> - - - - - - - - -

      Class

      - - - - - -
      - -

      Tests

      - - - - - - - - - -
      - - - - - - - - - -
      - - - - cur = TestCases['.'] = new Array(); - - - cur[''] = ''; - - - - - - - - - - - Unit Test Classes: <xsl:value-of select="$name"/> - - - - - - - - - -
      -

      - - <none> -

      -
      - -

      Classes

      - - - - - - - -
      - -
      - - -
      - - - - - - - All Unit Test Classes - - - - - -

      Classes

      - - - - -
      - - -
      - - - - - - - - - / - .html - - - - - - - - - - - - - All Unit Test Packages - - - - - -

      Home

      -

      Packages

      - - - - -
      - - -
      - - - - - - - <none> - - - - - - - - - - Unit Test Results: Summary - - - - - - open('allclasses-frame.html','classListFrame') - -

      Summary

      - - - - - - - - - - - - - - - - - Error - Failure - Pass - - - - - - - - - -
      TestsFailuresErrorsSuccess rateTime
      - - - - - - - -
      - - - - -
      - Note: failures are anticipated and checked for with assertions while errors are unanticipated. -
      - -

      Packages

      - - - - - - - - - - - Error - Failure - Pass - - - - - - - - - -
      - - <none> - - - - -
      - - -
      - - - - - - - - - - - - open('package-frame.html','classListFrame') - -

      Package

      - - - - - -

      Classes

      -

      - - - - - -
      -

      -
      - - -
      - - - - - - - ../ - - - - - - ../ - - - - - - - - stylesheet.css - - - - - -

      Unit Test Results

      - - - - - -
      Designed for use with JUnit and Ant.
      -
      -
      - - - - - Name - Tests - Errors - Failures - Time(s) - - - - - - - Name - Status - Type - Time(s) - - - - - - - - - - Error - Failure - Pass - - - - - - - - - - - - - - - - - - Error - Failure - TableRowColor - - - - - - Failure - - - - Error - - - - Success - - - - - - - - - - - - - - - - - - - - - - - - - N/A - - - - - -

      - - - - - - - -
      - - - - - - - - - - - - -
      - -
      - - - - - - - - - - -
      - diff --git a/libraries/jnaerator/anarres/etc/junit/xsl/junit-noframes.xsl b/libraries/jnaerator/anarres/etc/junit/xsl/junit-noframes.xsl deleted file mode 100644 index 25487f8fd..000000000 --- a/libraries/jnaerator/anarres/etc/junit/xsl/junit-noframes.xsl +++ /dev/null @@ -1,461 +0,0 @@ - - - - - - - - - - Unit Test Results - - - - - - - - - - -
      - - - -
      - - - -
      - - - - - - -
      - - - - - - - - -

      Packages

      - Note: package statistics are not computed recursively, they only sum up all of its testsuites numbers. - - - - - - - - - - - - - - - - - Failure - Error - - - - - - - - - -
      - - - -
      -
      - - - - - - - - - - - - -

      Package

      - - - - - - -
      - Back to top -

      -

      - - - - - - - - -

      TestCase

      - - - - - - - - - - -
      - -

      - - Back to top - - - - -

      Summary

      - - - - - - - - - - - - - - - - - Failure - Error - - - - - - - - - -
      TestsFailuresErrorsSuccess rateTime
      - - - - - - - -
      - - - - -
      - Note: failures are anticipated and checked for with assertions while errors are unanticipated. -
      -
      - - - - cur = TestCases['.'] = new Array(); - - - cur[''] = ''; - - - - - -

      Unit Test Results

      - - - - - -
      Designed for use with JUnit and Ant.
      -
      -
      - - - - Name - Tests - Errors - Failures - Time(s) - - - - - - - Name - Tests - Errors - Failures - Time(s) - - - - - - - Name - Status - Type - Time(s) - - - - - - - - - - - Failure - Error - - - - - - - - - - - - - - - - - - - - - Error - - - - - - Failure - - - - Error - - - - Success - - - - - - - - - - - - - - - - - - - - - - - - N/A - - - - - - -

      - - - -
      - - -
      - - - - - - - - - - - - -
      - -
      - - - - - - - - - - - -
      - diff --git a/libraries/jnaerator/anarres/etc/targets/global-checkstyle.xml b/libraries/jnaerator/anarres/etc/targets/global-checkstyle.xml deleted file mode 100644 index 5c15352d0..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-checkstyle.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-clean.xml b/libraries/jnaerator/anarres/etc/targets/global-clean.xml deleted file mode 100644 index 246a2d09d..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-clean.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-cobertura.xml b/libraries/jnaerator/anarres/etc/targets/global-cobertura.xml deleted file mode 100644 index 425a9fd09..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-cobertura.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-compile.xml b/libraries/jnaerator/anarres/etc/targets/global-compile.xml deleted file mode 100644 index b22604152..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-compile.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-findbugs.xml b/libraries/jnaerator/anarres/etc/targets/global-findbugs.xml deleted file mode 100644 index 9a06996cf..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-findbugs.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-inject.xml b/libraries/jnaerator/anarres/etc/targets/global-inject.xml deleted file mode 100644 index e707b04a3..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-inject.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-jar.xml b/libraries/jnaerator/anarres/etc/targets/global-jar.xml deleted file mode 100644 index 045e85ab8..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-jar.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-javadoc.xml b/libraries/jnaerator/anarres/etc/targets/global-javadoc.xml deleted file mode 100644 index 92c8eaf8b..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-javadoc.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - Shevek, Anarres. All Rights Reserved.]]> - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-junit.xml b/libraries/jnaerator/anarres/etc/targets/global-junit.xml deleted file mode 100644 index e53c5a7d6..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-junit.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-tar.xml b/libraries/jnaerator/anarres/etc/targets/global-tar.xml deleted file mode 100644 index 778cf2f56..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-tar.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-taskdefs.xml b/libraries/jnaerator/anarres/etc/targets/global-taskdefs.xml deleted file mode 100644 index 8218c91f5..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-taskdefs.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-verify.xml b/libraries/jnaerator/anarres/etc/targets/global-verify.xml deleted file mode 100644 index 11c867411..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-verify.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/etc/targets/global-vpp.xml b/libraries/jnaerator/anarres/etc/targets/global-vpp.xml deleted file mode 100644 index 9ffd0b52e..000000000 --- a/libraries/jnaerator/anarres/etc/targets/global-vpp.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/anarres/lib/ant/ant-contrib.jar b/libraries/jnaerator/anarres/lib/ant/ant-contrib.jar deleted file mode 100644 index 6e04e8422..000000000 Binary files a/libraries/jnaerator/anarres/lib/ant/ant-contrib.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/checkstyle/checkstyle-all-4.1.jar b/libraries/jnaerator/anarres/lib/checkstyle/checkstyle-all-4.1.jar deleted file mode 100644 index ea018b65e..000000000 Binary files a/libraries/jnaerator/anarres/lib/checkstyle/checkstyle-all-4.1.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/checkstyle/commons-beanutils-core.jar b/libraries/jnaerator/anarres/lib/checkstyle/commons-beanutils-core.jar deleted file mode 100644 index ce79cbeef..000000000 Binary files a/libraries/jnaerator/anarres/lib/checkstyle/commons-beanutils-core.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/checkstyle/commons-cli.jar b/libraries/jnaerator/anarres/lib/checkstyle/commons-cli.jar deleted file mode 100644 index 22a004e14..000000000 Binary files a/libraries/jnaerator/anarres/lib/checkstyle/commons-cli.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/checkstyle/commons-collections.jar b/libraries/jnaerator/anarres/lib/checkstyle/commons-collections.jar deleted file mode 100644 index f66c6d277..000000000 Binary files a/libraries/jnaerator/anarres/lib/checkstyle/commons-collections.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/checkstyle/commons-logging.jar b/libraries/jnaerator/anarres/lib/checkstyle/commons-logging.jar deleted file mode 100644 index b99c9375a..000000000 Binary files a/libraries/jnaerator/anarres/lib/checkstyle/commons-logging.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/cobertura/asm-2.2.1.jar b/libraries/jnaerator/anarres/lib/cobertura/asm-2.2.1.jar deleted file mode 100644 index 297690f26..000000000 Binary files a/libraries/jnaerator/anarres/lib/cobertura/asm-2.2.1.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/cobertura/cobertura.jar b/libraries/jnaerator/anarres/lib/cobertura/cobertura.jar deleted file mode 100644 index 03baf65e9..000000000 Binary files a/libraries/jnaerator/anarres/lib/cobertura/cobertura.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/cobertura/jakarta-oro-2.0.8.jar b/libraries/jnaerator/anarres/lib/cobertura/jakarta-oro-2.0.8.jar deleted file mode 100644 index 23488d260..000000000 Binary files a/libraries/jnaerator/anarres/lib/cobertura/jakarta-oro-2.0.8.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/annotations.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/annotations.jar deleted file mode 100644 index e16db1f45..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/annotations.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-3.0.jar deleted file mode 100644 index 7a5c727bb..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-analysis-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-analysis-3.0.jar deleted file mode 100644 index c5f795faf..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-analysis-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-commons-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-commons-3.0.jar deleted file mode 100644 index 297153095..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-commons-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-tree-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-tree-3.0.jar deleted file mode 100644 index c6347fe2f..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-tree-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-util-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-util-3.0.jar deleted file mode 100644 index 95159868e..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-util-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-xml-3.0.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/asm-xml-3.0.jar deleted file mode 100644 index b3d1a6457..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/asm-xml-3.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/bcel.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/bcel.jar deleted file mode 100644 index be093c852..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/bcel.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/buggy.icns b/libraries/jnaerator/anarres/lib/findbugs/lib/buggy.icns deleted file mode 100644 index b1f4660e1..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/buggy.icns and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/dom4j-full.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/dom4j-full.jar deleted file mode 100644 index 1efbf7ea4..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/dom4j-full.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs-ant.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs-ant.jar deleted file mode 100644 index 3a2740ec4..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs-ant.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs.jar deleted file mode 100644 index 10c8f7884..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugs.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugsGUI.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/findbugsGUI.jar deleted file mode 100644 index 8cf6984ce..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/findbugsGUI.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/lib/jsr305.jar b/libraries/jnaerator/anarres/lib/findbugs/lib/jsr305.jar deleted file mode 100644 index 90119cb09..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/lib/jsr305.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/plugin/coreplugin.jar b/libraries/jnaerator/anarres/lib/findbugs/plugin/coreplugin.jar deleted file mode 100644 index 0f9c31723..000000000 Binary files a/libraries/jnaerator/anarres/lib/findbugs/plugin/coreplugin.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/findbugs/xsl/default.xsl b/libraries/jnaerator/anarres/lib/findbugs/xsl/default.xsl deleted file mode 100644 index e8f30d46f..000000000 --- a/libraries/jnaerator/anarres/lib/findbugs/xsl/default.xsl +++ /dev/null @@ -1,376 +0,0 @@ - - - - - - - - - - -&nbsp; - - - - - - Code - Warning - - - - - - - FindBugs Report - - - - - - - - - -

      FindBugs Report

      - -

      Project Information

      - - -

      Metrics

      - - -

      Contents

      - - -

      Summary

      - - - - - - - - - - - - tablerow0 - tablerow1 - - - - - - - - - - - tablerow0 - tablerow1 - - - - - - -
      Warning TypeNumber
      Warnings
      Total
      - -

      Warnings

      - -

      Click on a warning row to see full context information.

      - - - - - - - - - Warnings - Warnings_ - - - -

      Details

      - - - - - - - - -
      - - -

      Project: - - - - -

      -

      FindBugs version:

      - -

      Code analyzed:

      -
        - -
      • -
        -
      -



      -
      - - - - - - - - priority- - - - - - - - - - - - - - - - - - - - - -

      :

      - -
      - - - - - - -

      - - - - - - -
      -
      - - - - - -

      lines of code analyzed, - in classes, - in packages.

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      MetricTotalDensity*
      High Priority Warnings - - - - - - - - -
      Medium Priority Warnings - - - - - - - - -
      Low Priority Warnings - - - - - - - - -
      Total Warnings
      -

      (* Defects per Thousand lines of non-commenting source statements)

      -



      - -
      - -
      - - diff --git a/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy-hist.xsl b/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy-hist.xsl deleted file mode 100644 index 808660077..000000000 --- a/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy-hist.xsl +++ /dev/null @@ -1,1127 +0,0 @@ - - - - - - - - - - - - - - - - - - FindBugs (<xsl:value-of select="/BugCollection/@version" />) - Analysis for - <xsl:choose> - <xsl:when test='string-length(/BugCollection/Project/@projectName)>0'><xsl:value-of select="/BugCollection/Project/@projectName" /></xsl:when> - <xsl:otherwise><xsl:value-of select="/BugCollection/Project/@filename" /></xsl:otherwise> - </xsl:choose> - - - - - - -

      - FindBugs () - Analysis for - - - - -

      - - - -
      - -
      -
      - Computing data... -
      - -
      -
      -

      Package Summary

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      PackageCode SizeBugsBugs p1Bugs p2Bugs p3Bugs Exp.
      - Overall - ( packages), - ( classes) -
      -
      - -
      -
      -

      Analyzed Files:

      -
        - -
      • -
        -
      -
      -
      -

      Used Libraries:

      -
        - -
      • -
        - -
      • None
      • -
        -
      -
      -
      -

      Analysis Errors:

      -
        - - -
      • None
      • -
        - -
      • Missing ref classes for analysis: -
          - -
        • -
          -
        -
      • -
        -
      -
      -
      -
      Loading...
      -
      Loading...
      -
      Loading...
      -
      - - - - -
      - - -
      - diff --git a/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy.xsl b/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy.xsl deleted file mode 100644 index 5d152dd7a..000000000 --- a/libraries/jnaerator/anarres/lib/findbugs/xsl/fancy.xsl +++ /dev/null @@ -1,846 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - FindBugs (<xsl:value-of select="/BugCollection/@version" />) - Analysis for - <xsl:choose> - <xsl:when test='string-length(/BugCollection/Project/@projectName)>0'><xsl:value-of select="/BugCollection/Project/@projectName" /></xsl:when> - <xsl:otherwise><xsl:value-of select="/BugCollection/Project/@filename" /></xsl:otherwise> - </xsl:choose> - - - - - - -
      -

      - FindBugs () - Analysis for - - - - -

      - - - - - - - - - - -
      - tip- - tip - /
      - -
      -
      - - - -
      - b-uid-- - - - - - - -
      -
      -
      -
      -
      - -
      -
      -
      -
      -
      -
      -
      - - -
      - - - - -
      -

      FindBugs Analysis generated at:

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      PackageCode SizeBugsBugs p1Bugs p2Bugs p3Bugs Exp.Ratio
      - Overall - ( packages), - ( classes) -
      -
      -
      - - - - - - - - - - - - b-1 -    - P1 - - b-2 -    - P2 - - b-3 -    - P3 - - b-4 -    - Exp. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      - -
      - category--and-code--and-bug- - category--and-code--and-bug- - b-uid-- - - - - - - - -
      -
      -
      - - - - - - - - - - - 0 - - - - - - 0 - - - - - - 0 - - - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - - - - - - 0 - - - - - - 0 - - - - - - 0 - - - - - -
      - -
      - package--and-class- - - - - -
      -
      -
      - - - - - - - - - - - - - - - - - - - - - -
      - -
      - package--and-class--and-type- - package--and-class--and-type- - b-uid-- - - - - - - - -
      -
      -
      - -
      diff --git a/libraries/jnaerator/anarres/lib/findbugs/xsl/plain.xsl b/libraries/jnaerator/anarres/lib/findbugs/xsl/plain.xsl deleted file mode 100644 index 80fff8d7b..000000000 --- a/libraries/jnaerator/anarres/lib/findbugs/xsl/plain.xsl +++ /dev/null @@ -1,306 +0,0 @@ - - - - - - - - - Warning - Priority - Details - - - - - - - FindBugs Report - - - - - - - -

      FindBugs Report

      -

      Produced using FindBugs .

      -

      Project: - - - - -

      -

      Metrics

      - - -

      Summary

      - - - - - - - - - - - - tablerow0 - tablerow1 - - - - - - - - - - - tablerow0 - tablerow1 - - - - - - -
      Warning TypeNumber
      Warnings
      Total
      -



      - -

      Warnings

      - -

      Click on each warning link to see a full description of the issue, and - details of how to resolve it.

      - - - - - - - - - Warnings - Warnings_ - - - -



      -

      Warning Types

      - - - - - - - - -
      - - - - - - - - - - - High - Medium - Low - Unknown - - - -



      - - - -
      In file , - - - line - - - lines - to - - -
      - - -
      -
      -

      - - -
      - - -

      - -



      -
      - - - - - - -

      - - - - - - - - - - - - - - -

      None

      -



      -
      - - - - - -

      lines of code analyzed, - in classes, - in packages.

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      MetricTotalDensity*
      High Priority Warnings - - - - - - - - -
      Medium Priority Warnings - - - - - - - - -
      Low Priority Warnings - - - - - - - - -
      Total Warnings - - - - - - - - - - -
      -

      (* Defects per Thousand lines of non-commenting source statements)

      -



      - -
      - -
      diff --git a/libraries/jnaerator/anarres/lib/findbugs/xsl/summary.xsl b/libraries/jnaerator/anarres/lib/findbugs/xsl/summary.xsl deleted file mode 100644 index 1a93330e4..000000000 --- a/libraries/jnaerator/anarres/lib/findbugs/xsl/summary.xsl +++ /dev/null @@ -1,252 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <xsl:value-of select="$PAGE.TITLE" /> - -

      -

      Analysis for - - - - - -

      -

      -

      - -
      -

      - -
      () -

      - - - - - - -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      - - - - - - -
      -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      - - - - - - - - - - - - - - - - - - - - - - - - -
      - - - - - - - - -
             
      -
      -
      -
      - -
      diff --git a/libraries/jnaerator/anarres/lib/jrat/bcel-326809.jar b/libraries/jnaerator/anarres/lib/jrat/bcel-326809.jar deleted file mode 100644 index 9c8de928f..000000000 Binary files a/libraries/jnaerator/anarres/lib/jrat/bcel-326809.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/jrat/jmxri.jar b/libraries/jnaerator/anarres/lib/jrat/jmxri.jar deleted file mode 100644 index 5e519fd22..000000000 Binary files a/libraries/jnaerator/anarres/lib/jrat/jmxri.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/jrat/shiftone-arbor.jar b/libraries/jnaerator/anarres/lib/jrat/shiftone-arbor.jar deleted file mode 100644 index f16528e47..000000000 Binary files a/libraries/jnaerator/anarres/lib/jrat/shiftone-arbor.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/jrat/shiftone-jrat.jar b/libraries/jnaerator/anarres/lib/jrat/shiftone-jrat.jar deleted file mode 100644 index 3c1c5bfd0..000000000 Binary files a/libraries/jnaerator/anarres/lib/jrat/shiftone-jrat.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/junit/junit.jar b/libraries/jnaerator/anarres/lib/junit/junit.jar deleted file mode 100644 index 717cd08ba..000000000 Binary files a/libraries/jnaerator/anarres/lib/junit/junit.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/log4j/log4j-1.2.13.jar b/libraries/jnaerator/anarres/lib/log4j/log4j-1.2.13.jar deleted file mode 100644 index dde997210..000000000 Binary files a/libraries/jnaerator/anarres/lib/log4j/log4j-1.2.13.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/runtime/getopt/gnu.getopt.jar b/libraries/jnaerator/anarres/lib/runtime/getopt/gnu.getopt.jar deleted file mode 100644 index 1aea24b11..000000000 Binary files a/libraries/jnaerator/anarres/lib/runtime/getopt/gnu.getopt.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/svn/commons-lang-2.0.jar b/libraries/jnaerator/anarres/lib/svn/commons-lang-2.0.jar deleted file mode 100644 index c8a287011..000000000 Binary files a/libraries/jnaerator/anarres/lib/svn/commons-lang-2.0.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/svn/jakarta-regexp-1.3.jar b/libraries/jnaerator/anarres/lib/svn/jakarta-regexp-1.3.jar deleted file mode 100644 index d653a388c..000000000 Binary files a/libraries/jnaerator/anarres/lib/svn/jakarta-regexp-1.3.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/svn/svnClientAdapter.jar b/libraries/jnaerator/anarres/lib/svn/svnClientAdapter.jar deleted file mode 100644 index 502a53f85..000000000 Binary files a/libraries/jnaerator/anarres/lib/svn/svnClientAdapter.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/svn/svnant.jar b/libraries/jnaerator/anarres/lib/svn/svnant.jar deleted file mode 100644 index fc5e2b94b..000000000 Binary files a/libraries/jnaerator/anarres/lib/svn/svnant.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/svn/svnjavahl.jar b/libraries/jnaerator/anarres/lib/svn/svnjavahl.jar deleted file mode 100644 index 4208165c4..000000000 Binary files a/libraries/jnaerator/anarres/lib/svn/svnjavahl.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/vpp/commons-collections-3.1.jar b/libraries/jnaerator/anarres/lib/vpp/commons-collections-3.1.jar deleted file mode 100644 index 41e230fee..000000000 Binary files a/libraries/jnaerator/anarres/lib/vpp/commons-collections-3.1.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/vpp/foundrylogic-vpp-2.2.1-nodeps.jar b/libraries/jnaerator/anarres/lib/vpp/foundrylogic-vpp-2.2.1-nodeps.jar deleted file mode 100644 index 3956a4324..000000000 Binary files a/libraries/jnaerator/anarres/lib/vpp/foundrylogic-vpp-2.2.1-nodeps.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/lib/vpp/velocity-1.4.jar b/libraries/jnaerator/anarres/lib/vpp/velocity-1.4.jar deleted file mode 100644 index 04ec9d2f8..000000000 Binary files a/libraries/jnaerator/anarres/lib/vpp/velocity-1.4.jar and /dev/null differ diff --git a/libraries/jnaerator/anarres/pom.xml b/libraries/jnaerator/anarres/pom.xml deleted file mode 100644 index e889d2fe9..000000000 --- a/libraries/jnaerator/anarres/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - anarres-jnaerator - Anarres JCPP (with JNAerator modifications) - http://www.anarres.org/projects/jcpp/ - 1.2.8-SNAPSHOT - jar - - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - ../.. - - - - org.anarres.cpp.Main - - - - - anarres.author - Anarres Author - contact@anarres.org - - - - - - Apache 2.0 - http://www.apache.org/licenses/LICENSE-2.0.html - repo - Anarres JCPP was patched with some modifications for use in JNAerator.. - Diffs are trivial to make with Original Anarres SVN repository : https://svn.anarres.org/svn/repos/code/java/cpp/trunk/ - - - - - - - gnu.getopt - java-getopt - 1.0.13 - - - org.apache.ant - ant - 1.8.2 - provided - - - commons-collections - commons-collections - 3.2.1 - - - - - - - com.nativelibs4java - maven-velocity-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.11 - - true - - - - - - - diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Argument.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Argument.java deleted file mode 100644 index a868db57e..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Argument.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.IOException; - -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; - -import static org.anarres.cpp.Token.*; - -/** - * A macro argument. - * - * This encapsulates a raw and preprocessed token stream. - */ -/* pp */ class Argument extends ArrayList { - public static final int NO_ARGS = -1; - - private List expansion; - - public Argument() { - this.expansion = null; - } - - public void addToken(Token tok) { - add(tok); - } - - /* pp */ void expand(Preprocessor p) - throws IOException, - LexerException { - /* Cache expansion. */ - if (expansion == null) { - this.expansion = p.expand(this); - // System.out.println("Expanded arg " + this); - } - } - - public Iterator expansion() { - return expansion.iterator(); - } - - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("Argument("); - // buf.append(super.toString()); - buf.append("raw=[ "); - for (int i = 0; i < size(); i++) - buf.append(get(i).getText()); - buf.append(" ];expansion=[ "); - if (expansion == null) - buf.append("null"); - else - for (int i = 0; i < expansion.size(); i++) - buf.append(expansion.get(i).getText()); - buf.append(" ])"); - return buf.toString(); - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/ChrootFileSystem.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/ChrootFileSystem.java deleted file mode 100644 index bce2cfe17..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/ChrootFileSystem.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; - -/** - * A virtual filesystem implementation using java.io in a virtual - * chroot. - */ -public class ChrootFileSystem implements VirtualFileSystem { - private File root; - - public ChrootFileSystem(File root) { - this.root = root; - } - - public VirtualFile getFile(String path) { - return new ChrootFile(path); - } - - public VirtualFile getFile(String dir, String name) { - return new ChrootFile(dir, name); - } - - private class ChrootFile extends File implements VirtualFile { - private File rfile; - - public ChrootFile(String path) { - super(path); - } - - public ChrootFile(String dir, String name) { - super(dir, name); - } - - /* private */ - public ChrootFile(File dir, String name) { - super(dir, name); - } - - @Override - public ChrootFile getParentFile() { - return new ChrootFile(getParent()); - } - - public ChrootFile getChildFile(String name) { - return new ChrootFile(this, name); - } - - @Override - public boolean isFile() { - File real = new File(root, getPath()); - return real.isFile(); - } - - public Source getSource() throws IOException { - return new FileLexerSource(new File(root, getPath()), - getPath()); - } - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppReader.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppReader.java deleted file mode 100644 index fbe3545a2..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppReader.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; -import java.io.Reader; - -import static org.anarres.cpp.Token.*; - -/** - * A Reader wrapper around the Preprocessor. - * - * This is a utility class to provide a transparent {@link Reader} - * which preprocesses the input text. - * - * @see Preprocessor - * @see Reader - */ -public class CppReader extends Reader { - - private Preprocessor cpp; - private String token; - private int idx; - - public CppReader(final Reader r) { - cpp = new Preprocessor(new LexerSource(r, true) { - @Override - public String getName() { - return ""; - } - }); - token = ""; - idx = 0; - } - - public CppReader(Preprocessor p) { - cpp = p; - token = ""; - idx = 0; - } - - /** - * Returns the Preprocessor used by this CppReader. - */ - public Preprocessor getPreprocessor() { - return cpp; - } - - /** - * Defines the given name as a macro. - * - * This is a convnience method. - */ - public void addMacro(String name) - throws LexerException { - cpp.addMacro(name); - } - - /** - * Defines the given name as a macro. - * - * This is a convnience method. - */ - public void addMacro(String name, String value) - throws LexerException { - cpp.addMacro(name, value); - } - - private boolean refill() - throws IOException { - try { - assert cpp != null : "cpp is null : was it closed?"; - if (token == null) - return false; - while (idx >= token.length()) { - Token tok = cpp.token(); - switch (tok.getType()) { - case EOF: - token = null; - return false; - case CCOMMENT: - case CPPCOMMENT: - if (!cpp.getFeature(Feature.KEEPCOMMENTS)) { - token = " "; - break; - } - default: - token = tok.getText(); - break; - } - idx = 0; - } - return true; - } - catch (LexerException e) { - /* Never happens. - if (e.getCause() instanceof IOException) - throw (IOException)e.getCause(); - */ - IOException ie = new IOException(String.valueOf(e)); - ie.initCause(e); - throw ie; - } - } - - public int read() - throws IOException { - if (!refill()) - return -1; - return token.charAt(idx++); - } - - /* XXX Very slow and inefficient. */ - public int read(char cbuf[], int off, int len) - throws IOException { - if (token == null) - return -1; - for (int i = 0; i < len; i++) { - int ch = read(); - if (ch == -1) - return i; - cbuf[off + i] = (char)ch; - } - return len; - } - - public void close() - throws IOException { - if (cpp != null) { - cpp.close(); - cpp = null; - } - token = null; - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppTask.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppTask.java deleted file mode 100644 index f86c2d180..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/CppTask.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; - -import org.anarres.cpp.LexerException; -import org.anarres.cpp.Preprocessor; -import org.anarres.cpp.Token; - -/** - * An ant task for jcpp. - */ -public class CppTask extends Task { - - private static class Macro { - private String name; - private String value; - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setValue(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - } - - private File input; - private File output; - private Preprocessor cpp; - - public CppTask() { - super(); - cpp = new Preprocessor(); - } - - public void setInput(File input) { - this.input = input; - } - - public void setOutput(File output) { - this.output = output; - } - - public void addMacro(Macro macro) { - try { - cpp.addMacro(macro.getName(), macro.getValue()); - } - catch (LexerException e) { - throw new BuildException(e); - } - } - - public void execute() { - FileWriter writer = null; - try { - if (input == null) - throw new BuildException("Input not specified"); - if (output == null) - throw new BuildException("Output not specified"); - cpp.addInput(this.input); - writer = new FileWriter(this.output); - for (;;) { - Token tok = cpp.token(); - if (tok != null && tok.getType() == Token.EOF) - break; - writer.write(tok.getText()); - } - } - catch (Exception e) { - throw new BuildException(e); - } - finally { - if (writer != null) { - try { - writer.close(); - } - catch (IOException e) { - } - } - } - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/DeferredFileReader.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/DeferredFileReader.java deleted file mode 100644 index 0fb90ec22..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/DeferredFileReader.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package org.anarres.cpp; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.nio.CharBuffer; - -public class DeferredFileReader extends Reader { - Reader in; - File file; - - //static java.util.HashSet files = new java.util.HashSet(); - public DeferredFileReader(File file) throws FileNotFoundException { - this.file = file; - if (!file.exists()) - throw new FileNotFoundException(file.toString()); - - //if (!files.add(file)) - // in = new StringReader(""); - //new Exception("Creating " + file).printStackTrace(); - } - - protected void open() throws FileNotFoundException { - if (in == null) { - in = new FileReader(file); - //new Exception("Opening " + file).printStackTrace(); - //System.out.println("< " + file); - } - } - - public File getFile() { - return file; - } - - @Override - public void mark(int readAheadLimit) throws IOException { - open(); - in.mark(readAheadLimit); - } - @Override - public boolean markSupported() { - try { - open(); - return in.markSupported(); - } catch (FileNotFoundException e) { - return false; - } - } - - @Override - public boolean ready() throws IOException { - open(); - return in.ready(); - } - - @Override - public void reset() throws IOException { - open(); - in.reset(); - } - - @Override - public long skip(long n) throws IOException { - open(); - return in.skip(n); - } - - @Override - public String toString() { - return getClass().getName() + "[file=" + getFile() +"]"; - } - - @Override - public int hashCode() { - return getFile().hashCode(); - } - - @Override - public void close() throws IOException { - if (in != null) { - in.close(); - //System.out.println("> " + file); - } - } - - @Override - public int read(CharBuffer target) throws IOException { - open(); - return in.read(target); - } - - @Override - public int read(char[] cbuf) throws IOException { - open(); - return in.read(cbuf); - } - - @Override - public int read() throws IOException { - open(); - return in.read(); - } - - @Override - public int read(char[] cbuf, int off, int len) throws IOException { - open(); - return in.read(cbuf, off, len); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Feature.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Feature.java deleted file mode 100644 index 04a68b710..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Feature.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * Features of the Preprocessor, which may be enabled or disabled. - */ -public enum Feature { - /** Supports ANSI digraphs. */ - DIGRAPHS, - /** Supports ANSI trigraphs. */ - TRIGRAPHS, - /** Outputs linemarker tokens. */ - LINEMARKERS, - /** Reports tokens of type INVALID as errors. */ - CSYNTAX, - /** Preserves comments in the lexed output. */ - KEEPCOMMENTS, - /** Preserves comments in the lexed output, even when inactive. */ - KEEPALLCOMMENTS, - VERBOSE, - DEBUG, - - /** Supports lexing of objective-C. */ - OBJCSYNTAX, - INCLUDENEXT -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FileLexerSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FileLexerSource.java deleted file mode 100644 index 63bbb6078..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FileLexerSource.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -import java.util.List; -import java.util.Iterator; - -import static org.anarres.cpp.Token.*; - -/** - * A {@link Source} which lexes a file. - * - * The input is buffered. - * - * @see Source - */ -public class FileLexerSource extends LexerSource { - // private File file; - private String path; - - /** - * Creates a new Source for lexing the given File. - * - * Preprocessor directives are honoured within the file. - */ - public FileLexerSource(File file, String path) - throws IOException { - super( - new BufferedReader( - new DeferredFileReader( - file - ) - ), - true - ); - - // this.file = file; - this.path = path; - } - - public FileLexerSource(File file) - throws IOException { - this(file, file.getPath()); - } - - public FileLexerSource(String path) - throws IOException { - this(new File(path)); - } - - @Override - /* pp */ - public String getPath() { - return path; - } - - @Override - /* pp */ String getName() { - return getPath(); - } - - public String toString() { - return "file " + path; - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FixedTokenSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FixedTokenSource.java deleted file mode 100644 index eb19685be..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/FixedTokenSource.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; -import java.io.StringReader; - -import java.util.Arrays; -import java.util.List; -import java.util.Iterator; - -/* pp */ class FixedTokenSource extends Source { - private static final Token EOF = - new Token(Token.EOF, ""); - - private List tokens; - private int idx; - - /* pp */ FixedTokenSource(Token... tokens) { - this.tokens = Arrays.asList(tokens); - this.idx = 0; - } - - /* pp */ FixedTokenSource(List tokens) { - this.tokens = tokens; - this.idx = 0; - } - - public Token token() - throws IOException, - LexerException { - if (idx >= tokens.size()) - return EOF; - return tokens.get(idx++); - } - - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("constant token stream " + tokens); - Source parent = getParent(); - if (parent != null) - buf.append(" in ").append(String.valueOf(parent)); - return buf.toString(); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InputLexerSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InputLexerSource.java deleted file mode 100644 index b2a78a96b..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InputLexerSource.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.IOException; - -import java.util.List; -import java.util.Iterator; - -import static org.anarres.cpp.Token.*; - -/** - * A {@link Source} which lexes a file. - * - * The input is buffered. - * - * @see Source - */ -public class InputLexerSource extends LexerSource { - /** - * Creates a new Source for lexing the given Reader. - * - * Preprocessor directives are honoured within the file. - */ - public InputLexerSource(InputStream input) - throws IOException { - super( - new BufferedReader( - new InputStreamReader( - input - ) - ), - true - ); - } - - @Override - /* pp */ - public String getPath() { - return ""; - } - - @Override - /* pp */ String getName() { - return "standard input"; - } - - public String toString() { - return getPath(); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InternalException.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InternalException.java deleted file mode 100644 index ac53017e8..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/InternalException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * An internal exception. - * - * This exception is thrown when an internal state violation is - * encountered. This should never happen. If it ever happens, please - * report it as a bug. - */ -public class InternalException extends RuntimeException { - public InternalException(String msg) { - super(msg); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JavaFileSystem.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JavaFileSystem.java deleted file mode 100644 index 83a5caa35..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JavaFileSystem.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; - -/** - * A virtual filesystem implementation using java.io. - */ -public class JavaFileSystem implements VirtualFileSystem { - public VirtualFile getFile(String path) { - return new JavaFile(path); - } - - public VirtualFile getFile(String dir, String name) { - return new JavaFile(dir, name); - } - - private class JavaFile extends File implements VirtualFile { - public JavaFile(String path) { - super(path); - } - - public JavaFile(String dir, String name) { - super(dir, name); - } - - /* private */ - public JavaFile(File dir, String name) { - super(dir, name); - } - -/* - @Override - public String getPath() { - return getCanonicalPath(); - } -*/ - - @Override - public JavaFile getParentFile() { - String parent = getParent(); - if (parent != null) - return new JavaFile(parent); - File absolute = getAbsoluteFile(); - parent = absolute.getParent(); - /* - if (parent == null) - return null; - */ - return new JavaFile(parent); - } - - public JavaFile getChildFile(String name) { - return new JavaFile(this, name); - } - - public Source getSource() throws IOException { - return new FileLexerSource(this); - } - - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JoinReader.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JoinReader.java deleted file mode 100644 index 91908a7d3..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/JoinReader.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.Reader; -import java.io.PushbackReader; -import java.io.IOException; - -/* pp */ class JoinReader /* extends Reader */ { - private Reader in; - - private PreprocessorListener listener; - private LexerSource source; - private boolean trigraphs; - private boolean warnings; - - private int newlines; - private boolean flushnl; - private int[] unget; - private int uptr; - - public JoinReader(Reader in, boolean trigraphs) { - this.in = in; - this.trigraphs = trigraphs; - this.newlines = 0; - this.flushnl = false; - this.unget = new int[2]; - this.uptr = 0; - } - - public JoinReader(Reader in) { - this(in, false); - } - - public void setTrigraphs(boolean enable, boolean warnings) { - this.trigraphs = enable; - this.warnings = warnings; - } - - /* pp */ void init(Preprocessor pp, LexerSource s) { - this.listener = pp.getListener(); - this.source = s; - setTrigraphs(pp.getFeature(Feature.TRIGRAPHS), - pp.getWarning(Warning.TRIGRAPHS)); - } - - private int __read() throws IOException { - if (uptr > 0) - return unget[--uptr]; - return in.read(); - } - - private void _unread(int c) { - if (c != -1) - unget[uptr++] = c; - assert uptr <= unget.length : - "JoinReader ungets too many characters"; - } - - protected void warning(String msg) - throws LexerException { - if (source != null) - source.warning(msg); - else - throw new LexerException(msg); - } - - private char trigraph(char raw, char repl) - throws IOException, LexerException { - if (trigraphs) { - if (warnings) - warning("trigraph ??" + raw + " converted to " + repl); - return repl; - } - else { - if (warnings) - warning("trigraph ??" + raw + " ignored"); - _unread(raw); - _unread('?'); - return '?'; - } - } - - private int _read() - throws IOException, LexerException { - int c = __read(); - if (c == '?' && (trigraphs || warnings)) { - int d = __read(); - if (d == '?') { - int e = __read(); - switch (e) { - case '(': return trigraph('(', '['); - case ')': return trigraph(')', ']'); - case '<': return trigraph('<', '{'); - case '>': return trigraph('>', '}'); - case '=': return trigraph('=', '#'); - case '/': return trigraph('/', '\\'); - case '\'': return trigraph('\'', '^'); - case '!': return trigraph('!', '|'); - case '-': return trigraph('-', '~'); - } - _unread(e); - } - _unread(d); - } - return c; - } - - public int read() - throws IOException, LexerException { - if (flushnl) { - if (newlines > 0) { - newlines--; - return '\n'; - } - flushnl = false; - } - - for (;;) { - int c = _read(); - switch (c) { - case '\\': - int d = _read(); - switch (d) { - case '\n': - newlines++; - continue; - case '\r': - newlines++; - int e = _read(); - if (e != '\n') - _unread(e); - continue; - default: - _unread(d); - return c; - } - case '\r': - case '\n': - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - flushnl = true; - return c; - case -1: - if (newlines > 0) { - newlines--; - return '\n'; - } - default: - return c; - } - } - } - - public int read(char cbuf[], int off, int len) - throws IOException, LexerException { - for (int i = 0; i < len; i++) { - int ch = read(); - if (ch == -1) - return i; - cbuf[off + i] = (char)ch; - } - return len; - } - - public void close() - throws IOException { - in.close(); - } - - public String toString() { - return "JoinReader(nl=" + newlines + ")"; - } - -/* - public static void main(String[] args) throws IOException { - FileReader f = new FileReader(new File(args[0])); - BufferedReader b = new BufferedReader(f); - JoinReader r = new JoinReader(b); - BufferedWriter w = new BufferedWriter( - new java.io.OutputStreamWriter(System.out) - ); - int c; - while ((c = r.read()) != -1) { - w.write((char)c); - } - w.close(); - } -*/ - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerException.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerException.java deleted file mode 100644 index 41c62756a..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * A preprocessor exception. - * - * Note to users: I don't really like the name of this class. S. - */ -public class LexerException extends Exception { - public LexerException(String msg) { - super(msg); - } - - public LexerException(Throwable cause) { - super(cause); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerSource.java deleted file mode 100644 index c2a38195c..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/LexerSource.java +++ /dev/null @@ -1,822 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; - -import java.util.Set; - -import static org.anarres.cpp.Token.*; - -/** Does not handle digraphs. */ -public class LexerSource extends Source { - private static final boolean DEBUG = false; - - private JoinReader reader; - private boolean ppvalid; - private boolean bol; - private boolean include; - - private boolean digraphs; - - /* Unread. */ - private int u0, u1; - private int ucount; - - private int line; - private int column; - private int lastcolumn; - private boolean cr; - - /* ppvalid is: - * false in StringLexerSource, - * true in FileLexerSource */ - public LexerSource(Reader r, boolean ppvalid) { - this.reader = new JoinReader(r); - this.ppvalid = ppvalid; - this.bol = true; - this.include = false; - - this.digraphs = true; - - this.ucount = 0; - - this.line = 1; - this.column = 0; - this.lastcolumn = -1; - this.cr = false; - } - - @Override - /* pp */ void init(Preprocessor pp) { - super.init(pp); - this.digraphs = pp.getFeature(Feature.DIGRAPHS); - this.reader.init(pp, this); - } - - @Override - public int getLine() { - return line; - } - - @Override - public int getColumn() { - return column; - } - - @Override - /* pp */ boolean isNumbered() { - return true; - } - -/* Error handling. */ - - private final void _error(String msg, boolean error) - throws LexerException { - int _l = line; - int _c = column; - if (_c == 0) { - _c = lastcolumn; - _l--; - } - else { - _c--; - } - if (error) - super.error(_l, _c, msg); - else - super.warning(_l, _c, msg); - } - - /* Allow JoinReader to call this. */ - /* pp */ final void error(String msg) - throws LexerException { - _error(msg, true); - } - - /* Allow JoinReader to call this. */ - /* pp */ final void warning(String msg) - throws LexerException { - _error(msg, false); - } - -/* A flag for string handling. */ - - /* pp */ void setInclude(boolean b) { - this.include = b; - } - -/* - private boolean _isLineSeparator(int c) { - return Character.getType(c) == Character.LINE_SEPARATOR - || c == -1; - } -*/ - - /* XXX Move to JoinReader and canonicalise newlines. */ - private static final boolean isLineSeparator(int c) { - switch ((char)c) { - case '\r': - case '\n': - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - return true; - default: - return (c == -1); - } - } - - - private int read() - throws IOException, - LexerException { - assert ucount <= 2 : "Illegal ucount: " + ucount; - switch (ucount) { - case 2: - ucount = 1; - return u1; - case 1: - ucount = 0; - return u0; - } - - if (reader == null) - return -1; - - int c = reader.read(); - switch (c) { - case '\r': - cr = true; - line++; - lastcolumn = column; - column = 0; - break; - case '\n': - if (cr) { - cr = false; - break; - } - /* fallthrough */ - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - cr = false; - line++; - lastcolumn = column; - column = 0; - break; - default: - cr = false; - column++; - break; - } - -/* - if (isLineSeparator(c)) { - line++; - lastcolumn = column; - column = 0; - } - else { - column++; - } -*/ - - return c; - } - - /* You can unget AT MOST one newline. */ - private void unread(int c) - throws IOException { - /* XXX Must unread newlines. */ - if (c != -1) { - if (isLineSeparator(c)) { - line--; - column = lastcolumn; - cr = false; - } - else { - column--; - } - switch (ucount) { - case 0: - u0 = c; - ucount = 1; - break; - case 1: - u1 = c; - ucount = 2; - break; - default: - throw new IllegalStateException( - "Cannot unget another character!" - ); - } - // reader.unread(c); - } - } - - /* Consumes the rest of the current line into an invalid. */ - private Token invalid(StringBuilder text, String reason) - throws IOException, - LexerException { - int d = read(); - while (!isLineSeparator(d)) { - text.append((char)d); - d = read(); - } - unread(d); - return new Token(INVALID, text.toString(), reason); - } - - private Token ccomment() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("/*"); - int d; - do { - do { - d = read(); - text.append((char)d); - } while (d != '*'); - do { - d = read(); - text.append((char)d); - } while (d == '*'); - } while (d != '/'); - return new Token(CCOMMENT, text.toString()); - } - - private Token cppcomment() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("//"); - int d = read(); - while (!isLineSeparator(d)) { - text.append((char)d); - d = read(); - } - unread(d); - return new Token(CPPCOMMENT, text.toString()); - } - - private int escape(StringBuilder text) - throws IOException, - LexerException { - int d = read(); - switch (d) { - case 'a': text.append('a'); return 0x07; - case 'b': text.append('b'); return '\b'; - case 'f': text.append('f'); return '\f'; - case 'n': text.append('n'); return '\n'; - case 'r': text.append('r'); return '\r'; - case 't': text.append('t'); return '\t'; - case 'v': text.append('v'); return 0x0b; - case '\\': text.append('\\'); return '\\'; - - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - int len = 0; - int val = 0; - do { - val = (val << 3) + Character.digit(d, 8); - text.append((char)d); - d = read(); - } while (++len < 3 && Character.digit(d, 8) != -1); - unread(d); - return val; - - case 'x': - len = 0; - val = 0; - do { - val = (val << 4) + Character.digit(d, 16); - text.append((char)d); - d = read(); - } while (++len < 2 && Character.digit(d, 16) != -1); - unread(d); - return val; - - /* Exclude two cases from the warning. */ - case '"': text.append('"'); return '"'; - case '\'': text.append('\''); return '\''; - - default: - warning("Unnecessary escape character " + (char)d); - case 'p': - text.append((char)d); - return d; - } - } - - private Token character() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("'"); - int d = read(); - if (d == '\\') { - text.append('\\'); - d = escape(text); - } - else if (isLineSeparator(d)) { - unread(d); - return new Token(INVALID, text.toString(), - "Unterminated character literal"); - } - else if (d == '\'') { - text.append('\''); - return new Token(INVALID, text.toString(), - "Empty character literal"); - } - else if (!Character.isDefined(d)) { - text.append('?'); - return invalid(text, "Illegal unicode character literal"); - } - else { - text.append((char)d); - } - - int e = read(); - if (e != '\'') { - // error("Illegal character constant"); - /* We consume up to the next ' or the rest of the line. */ - for (;;) { - if (isLineSeparator(e)) { - unread(e); - break; - } - text.append((char)e); - if (e == '\'') - break; - e = read(); - } - return new Token(INVALID, text.toString(), - "Illegal character constant " + text); - } - text.append('\''); - /* XXX It this a bad cast? */ - return new Token(CHARACTER, - text.toString(), Character.valueOf((char)d)); - } - - private Token string(char open, char close) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - text.append(open); - - StringBuilder buf = new StringBuilder(); - - for (;;) { - int c = read(); - if (c == close) { - break; - } - else if (c == '\\') { - text.append('\\'); - if (!include) { - char d = (char)escape(text); - buf.append(d); - } - } - else if (c == -1) { - unread(c); - // error("End of file in string literal after " + buf); - return new Token(INVALID, text.toString(), - "End of file in string literal after " + buf); - } - else if (isLineSeparator(c)) { - unread(c); - // error("Unterminated string literal after " + buf); - return new Token(INVALID, text.toString(), - "Unterminated string literal after " + buf); - } - else { - text.append((char)c); - buf.append((char)c); - } - } - text.append(close); - return new Token(close == '>' ? HEADER : STRING, - text.toString(), buf.toString()); - } - - private Token _number(StringBuilder text, long val, int d) - throws IOException, - LexerException { - int bits = 0; - for (;;) { - /* XXX Error check duplicate bits. */ - if (d == 'U' || d == 'u') { - bits |= 1; - text.append((char)d); - d = read(); - } - else if (d == 'L' || d == 'l') { - if ((bits & 4) != 0) - /* XXX warn */ ; - bits |= 2; - text.append((char)d); - d = read(); - } - else if (d == 'I' || d == 'i') { - if ((bits & 2) != 0) - /* XXX warn */ ; - bits |= 4; - text.append((char)d); - d = read(); - } - else if (Character.isLetter(d)) { - unread(d); - return new Token(INVALID, text.toString(), - "Invalid suffix \"" + (char)d + - "\" on numeric constant"); - } - else { - unread(d); - return new Token(INTEGER, - text.toString(), Long.valueOf(val)); - } - } - } - - /* We already chewed a zero, so empty is fine. */ - private Token number_octal() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("0"); - int d = read(); - long val = 0; - while (Character.digit(d, 8) != -1) { - val = (val << 3) + Character.digit(d, 8); - text.append((char)d); - d = read(); - } - return _number(text, val, d); - } - - /* We do not know whether know the first digit is valid. */ - private Token number_hex(char x) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("0"); - text.append(x); - int d = read(); - if (Character.digit(d, 16) == -1) { - unread(d); - // error("Illegal hexadecimal constant " + (char)d); - return new Token(INVALID, text.toString(), - "Illegal hexadecimal digit " + (char)d + - " after "+ text); - } - long val = 0; - do { - val = (val << 4) + Character.digit(d, 16); - text.append((char)d); - d = read(); - } while (Character.digit(d, 16) != -1); - return _number(text, val, d); - } - - /* We know we have at least one valid digit, but empty is not - * fine. */ - /* XXX This needs a complete rewrite. */ - private Token number_decimal(int c) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder((char)c); - int d = c; - long val = 0; - do { - val = val * 10 + Character.digit(d, 10); - text.append((char)d); - d = read(); - } while (Character.digit(d, 10) != -1); - return _number(text, val, d); - } - - private Token identifier(int c) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - int d; - text.append((char)c); - for (;;) { - d = read(); - if (Character.isIdentifierIgnorable(d)) - ; - else if (Character.isJavaIdentifierPart(d)) - text.append((char)d); - else - break; - } - unread(d); - return new Token(IDENTIFIER, text.toString()); - } - - private Token whitespace(int c) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - int d; - text.append((char)c); - for (;;) { - d = read(); - if (ppvalid && isLineSeparator(d)) /* XXX Ugly. */ - break; - if (Character.isWhitespace(d)) - text.append((char)d); - else - break; - } - unread(d); - return new Token(WHITESPACE, text.toString()); - } - - /* No token processed by cond() contains a newline. */ - private Token cond(char c, int yes, int no) - throws IOException, - LexerException { - int d = read(); - if (c == d) - return new Token(yes); - unread(d); - return new Token(no); - } - - public Token token() - throws IOException, - LexerException { - Token tok = null; - - int _l = line; - int _c = column; - - int c = read(); - int d; - - switch (c) { - case '\n': - if (ppvalid) { - bol = true; - if (include) { - tok = new Token(NL, _l, _c, "\n"); - } - else { - int nls = 0; - do { - nls++; - d = read(); - } while (d == '\n'); - unread(d); - char[] text = new char[nls]; - for (int i = 0; i < text.length; i++) - text[i] = '\n'; - // Skip the bol = false below. - tok = new Token(NL, _l, _c, new String(text)); - } - if (DEBUG) - System.out.println("lx: Returning NL: " + tok); - return tok; - } - /* Let it be handled as whitespace. */ - break; - - case '!': - tok = cond('=', NE, '!'); - break; - - case '#': - if (bol) - tok = new Token(HASH); - else - tok = cond('#', PASTE, '#'); - break; - - case '+': - d = read(); - if (d == '+') - tok = new Token(INC); - else if (d == '=') - tok = new Token(PLUS_EQ); - else - unread(d); - break; - case '-': - d = read(); - if (d == '-') - tok = new Token(DEC); - else if (d == '=') - tok = new Token(SUB_EQ); - else if (d == '>') - tok = new Token(ARROW); - else - unread(d); - break; - - case '*': - tok = cond('=', MULT_EQ, '*'); - break; - case '/': - d = read(); - if (d == '*') - tok = ccomment(); - else if (d == '/') - tok = cppcomment(); - else if (d == '=') - tok = new Token(DIV_EQ); - else - unread(d); - break; - - case '%': - d = read(); - if (d == '=') - tok = new Token(MOD_EQ); - else if (digraphs && d == '>') - tok = new Token('}'); // digraph - else if (digraphs && d == ':') PASTE: { - d = read(); - if (d != '%') { - unread(d); - tok = new Token('#'); // digraph - break PASTE; - } - d = read(); - if (d != ':') { - unread(d); // Unread 2 chars here. - unread('%'); - tok = new Token('#'); // digraph - break PASTE; - } - tok = new Token(PASTE); // digraph - } - else - unread(d); - break; - - case ':': - /* :: */ - d = read(); - if (digraphs && d == '>') - tok = new Token(']'); // digraph - else - unread(d); - break; - - case '<': - if (include) { - tok = string('<', '>'); - } - else { - d = read(); - if (d == '=') - tok = new Token(LE); - else if (d == '<') - tok = cond('=', LSH_EQ, LSH); - else if (digraphs && d == ':') - tok = new Token('['); // digraph - else if (digraphs && d == '%') - tok = new Token('{'); // digraph - else - unread(d); - } - break; - - case '=': - tok = cond('=', EQ, '='); - break; - - case '>': - d = read(); - if (d == '=') - tok = new Token(GE); - else if (d == '>') - tok = cond('=', RSH_EQ, RSH); - else - unread(d); - break; - - case '^': - tok = cond('=', XOR_EQ, '^'); - break; - - case '|': - d = read(); - if (d == '=') - tok = new Token(OR_EQ); - else if (d == '|') - tok = cond('=', LOR_EQ, LOR); - else - unread(d); - break; - case '&': - d = read(); - if (d == '&') - tok = cond('=', LAND_EQ, LAND); - else if (d == '=') - tok = new Token(AND_EQ); - else - unread(d); - break; - - case '.': - d = read(); - if (d == '.') - tok = cond('.', ELLIPSIS, RANGE); - else - unread(d); - /* XXX decimal fraction */ - break; - - case '0': - /* octal or hex */ - d = read(); - if (d == 'x' || d == 'X') - tok = number_hex((char)d); - else { - unread(d); - tok = number_octal(); - } - break; - - case '\'': - tok = character(); - break; - - case '"': - tok = string('"', '"'); - break; - - case -1: - close(); - tok = new Token(EOF, _l, _c, ""); - break; - } - - if (tok == null) { - if (Character.isWhitespace(c)) { - tok = whitespace(c); - } - else if (Character.isDigit(c)) { - tok = number_decimal(c); - } - else if (Character.isJavaIdentifierStart(c)) { - tok = identifier(c); - } - else { - tok = new Token(c); - } - } - - if (bol) { - switch (tok.getType()) { - case WHITESPACE: - case CCOMMENT: - break; - default: - bol = false; - break; - } - } - - tok.setLocation(_l, _c); - if (DEBUG) - System.out.println("lx: Returning " + tok); - // (new Exception("here")).printStackTrace(System.out); - return tok; - } - - public void close() - throws IOException { - if (reader != null) { - reader.close(); - reader = null; - } - super.close(); - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Macro.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Macro.java deleted file mode 100644 index ca024bc42..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Macro.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * A macro object. - * - * This encapsulates a name, an argument count, and a token stream - * for replacement. The replacement token stream may contain the - * extra tokens {@link Token#M_ARG} and {@link Token#M_STRING}. - */ -public class Macro { - private Source source; - private String name; - /* It's an explicit decision to keep these around here. We don't - * need to; the argument token type is M_ARG and the value - * is the index. The strings themselves are only used in - * stringification of the macro, for debugging. */ - private List args; - private boolean variadic; - private List tokens; - - public Macro(Source source, String name) { - this.source = source; - this.name = name; - this.args = null; - this.variadic = false; - this.tokens = new ArrayList(); - } - - public Macro(String name) { - this(null, name); - } - - /** - * Sets the Source from which this macro was parsed. - */ - public void setSource(Source s) { - this.source = s; - } - - /** - * Returns the Source from which this macro was parsed. - * - * This method may return null if the macro was not parsed - * from a regular file. - */ - public Source getSource() { - return source; - } - - /** - * Returns the name of this macro. - */ - public String getName() { - return name; - } - - /** - * Sets the arguments to this macro. - */ - public void setArgs(List args) { - this.args = args; - } - - /** - * Returns true if this is a function-like macro. - */ - public boolean isFunctionLike() { - return args != null; - } - - /** - * Returns the number of arguments to this macro. - */ - public int getArgs() { - return args.size(); - } - - /** - * Sets the variadic flag on this Macro. - */ - public void setVariadic(boolean b) { - this.variadic = b; - } - - /** - * Returns true if this is a variadic function-like macro. - */ - public boolean isVariadic() { - return variadic; - } - - /** - * Adds a token to the expansion of this macro. - */ - public void addToken(Token tok) { - this.tokens.add(tok); - } - - /** - * Adds a "paste" operator to the expansion of this macro. - * - * A paste operator causes the next token added to be pasted - * to the previous token when the macro is expanded. - * It is an error for a macro to end with a paste token. - */ - public void addPaste(Token tok) { - /* - * Given: tok0 ## tok1 - * We generate: M_PASTE, tok0, tok1 - * This extends as per a stack language: - * tok0 ## tok1 ## tok2 -> - * M_PASTE, tok0, M_PASTE, tok1, tok2 - */ - this.tokens.add(tokens.size() - 1, tok); - } - - /* pp */ List getTokens() { - return tokens; - } - - /* Paste tokens are inserted before the first of the two pasted - * tokens, so it's a kind of bytecode notation. This method - * swaps them around again. We know that there will never be two - * sequential paste tokens, so a boolean is sufficient. */ - public String getText() { - StringBuilder buf = new StringBuilder(); - boolean paste = false; - for (int i = 0; i < tokens.size(); i++) { - Token tok = tokens.get(i); - if (tok.getType() == Token.M_PASTE) { - assert paste == false : "Two sequential pastes."; - paste = true; - continue; - } - else { - buf.append(tok.getText()); - } - if (paste) { - buf.append(" #" + "# "); - paste = false; - } - // buf.append(tokens.get(i)); - } - return buf.toString(); - } - - public String toString() { - StringBuilder buf = new StringBuilder(name); - if (args != null) { - buf.append('('); - Iterator it = args.iterator(); - while (it.hasNext()) { - buf.append(it.next()); - if (it.hasNext()) - buf.append(", "); - else if (isVariadic()) - buf.append("..."); - } - buf.append(')'); - } - if (!tokens.isEmpty()) { - buf.append(" => ").append(getText()); - } - return buf.toString(); - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/MacroTokenSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/MacroTokenSource.java deleted file mode 100644 index 075987558..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/MacroTokenSource.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; -import java.io.StringReader; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import static org.anarres.cpp.Token.*; - -/* This source should always be active, since we don't expand macros - * in any inactive context. */ -/* pp */ class MacroTokenSource extends Source { - private Macro macro; - private Iterator tokens; /* Pointer into the macro. */ - private List args; /* { unexpanded, expanded } */ - private Iterator arg; /* "current expansion" */ - - /* pp */ MacroTokenSource(Macro m, List args) { - this.macro = m; - this.tokens = m.getTokens().iterator(); - this.args = args; - this.arg = null; - } - - @Override - /* pp */ boolean isExpanding(Macro m) { - /* When we are expanding an arg, 'this' macro is not - * being expanded, and thus we may re-expand it. */ - if (/* XXX this.arg == null && */ this.macro == m) - return true; - return super.isExpanding(m); - } - - /* XXX Called from Preprocessor [ugly]. */ - /* pp */ static void escape(StringBuilder buf, CharSequence cs) { - for (int i = 0; i < cs.length(); i++) { - char c = cs.charAt(i); - switch (c) { - case '\\': - buf.append("\\\\"); - break; - case '"': - buf.append("\\\""); - break; - case '\n': - buf.append("\\n"); - break; - case '\r': - buf.append("\\r"); - break; - default: - buf.append(c); - } - } - } - - private void concat(StringBuilder buf, Argument arg) { - Iterator it = arg.iterator(); - while (it.hasNext()) { - Token tok = it.next(); - buf.append(tok.getText()); - } - } - - private Token stringify(Token pos, Argument arg) { - StringBuilder buf = new StringBuilder(); - concat(buf, arg); - // System.out.println("Concat: " + arg + " -> " + buf); - StringBuilder str = new StringBuilder("\""); - escape(str, buf); - str.append("\""); - // System.out.println("Escape: " + buf + " -> " + str); - return new Token(STRING, - pos.getLine(), pos.getColumn(), - str.toString(), buf.toString()); - } - - - /* At this point, we have consumed the first M_PASTE. - * @see Macro#addPaste(Token) */ - private void paste(Token ptok) - throws IOException, - LexerException { - StringBuilder buf = new StringBuilder(); - Token err = null; - /* We know here that arg is null or expired, - * since we cannot paste an expanded arg. */ - - int count = 2; - for (int i = 0; i < count; i++) { - if (!tokens.hasNext()) { - /* XXX This one really should throw. */ - error(ptok.getLine(), ptok.getColumn(), - "Paste at end of expansion"); - buf.append(' ').append(ptok.getText()); - break; - } - Token tok = tokens.next(); - // System.out.println("Paste " + tok); - switch (tok.getType()) { - case M_PASTE: - /* One extra to paste, plus one because the - * paste token didn't count. */ - count += 2; - ptok = tok; - break; - case M_ARG: - int idx = ((Integer)tok.getValue()).intValue(); - concat(buf, args.get(idx)); - break; - /* XXX Test this. */ - case CCOMMENT: - case CPPCOMMENT: - break; - default: - buf.append(tok.getText()); - break; - } - } - - /* Push and re-lex. */ - /* - StringBuilder src = new StringBuilder(); - escape(src, buf); - StringLexerSource sl = new StringLexerSource(src.toString()); - */ - StringLexerSource sl = new StringLexerSource(buf.toString()); - - /* XXX Check that concatenation produces a valid token. */ - - arg = new SourceIterator(sl); - } - - public Token token() - throws IOException, - LexerException { - for (;;) { - /* Deal with lexed tokens first. */ - - if (arg != null) { - if (arg.hasNext()) { - Token tok = arg.next(); - /* XXX PASTE -> INVALID. */ - assert tok.getType() != M_PASTE : - "Unexpected paste token"; - return tok; - } - arg = null; - } - - if (!tokens.hasNext()) - return new Token(EOF, -1, -1, ""); /* End of macro. */ - Token tok = tokens.next(); - int idx; - switch (tok.getType()) { - case M_STRING: - /* Use the nonexpanded arg. */ - idx = ((Integer)tok.getValue()).intValue(); - return stringify(tok, args.get(idx)); - case M_ARG: - /* Expand the arg. */ - idx = ((Integer)tok.getValue()).intValue(); - // System.out.println("Pushing arg " + args.get(idx)); - arg = args.get(idx).expansion(); - break; - case M_PASTE: - paste(tok); - break; - default: - return tok; - } - } /* for */ - } - - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("expansion of ").append(macro.getName()); - Source parent = getParent(); - if (parent != null) - buf.append(" in ").append(String.valueOf(parent)); - return buf.toString(); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/PreprocessorListener.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/PreprocessorListener.java deleted file mode 100644 index d149a7061..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/PreprocessorListener.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; - -/** - * A handler for preprocessor events, primarily errors and warnings. - * - * If no PreprocessorListener is installed in a Preprocessor, all - * error and warning events will throw an exception. Installing a - * listener allows more intelligent handling of these events. - */ -public class PreprocessorListener { - - private int errors; - private int warnings; - - public PreprocessorListener() { - clear(); - } - - public void clear() { - errors = 0; - warnings = 0; - } - - public int getErrors() { - return errors; - } - - public int getWarnings() { - return warnings; - } - - protected void print(String msg) { - System.err.println(msg); - } - - /** - * Handles a warning. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - public void handleWarning(Source source, int line, int column, - String msg) - throws LexerException { - warnings++; - print(source.getName() + ":" + line + ":" + column + - ": warning: " + msg); - } - - /** - * Handles an error. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - public void handleError(Source source, int line, int column, - String msg) - throws LexerException { - errors++; - print(source.getName() + ":" + line + ":" + column + - ": error: " + msg); - } - - public void handleSourceChange(Source source, String event) { - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Source.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Source.java deleted file mode 100644 index a185765a8..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Source.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; -import java.io.StringReader; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import static org.anarres.cpp.Token.*; - -/** - * An input to the Preprocessor. - * - * Inputs may come from Files, Strings or other sources. The - * preprocessor maintains a stack of Sources. Operations such as - * file inclusion or token pasting will push a new source onto - * the Preprocessor stack. Sources pop from the stack when they - * are exhausted; this may be transparent or explicit. - * - * BUG: Error messages are not handled properly. - */ -public abstract class Source implements Iterable, Closeable { - private Source parent; - private boolean autopop; - private PreprocessorListener listener; - private boolean active; - private boolean werror; - - /* LineNumberReader */ - -/* - // We can't do this, since we would lose the LexerException - private class Itr implements Iterator { - private Token next = null; - private void advance() { - try { - if (next != null) - next = token(); - } - catch (IOException e) { - throw new UnsupportedOperationException( - "Failed to advance token iterator: " + - e.getMessage() - ); - } - } - public boolean hasNext() { - return next.getType() != EOF; - } - public Token next() { - advance(); - Token t = next; - next = null; - return t; - } - public void remove() { - throw new UnsupportedOperationException( - "Cannot remove tokens from a Source." - ); - } - } -*/ - - public Source() { - this.parent = null; - this.autopop = false; - this.listener = null; - this.active = true; - this.werror = false; - } - - /** - * Sets the parent source of this source. - * - * Sources form a singly linked list. - */ - /* pp */ void setParent(Source parent, boolean autopop) { - this.parent = parent; - this.autopop = autopop; - } - - /** - * Returns the parent source of this source. - * - * Sources form a singly linked list. - */ - /* pp */ final Source getParent() { - return parent; - } - - // @OverrideMustInvoke - /* pp */ void init(Preprocessor pp) { - setListener(pp.getListener()); - this.werror = pp.getWarnings().contains(Warning.ERROR); - } - - /** - * Sets the listener for this Source. - * - * Normally this is set by the Preprocessor when a Source is - * used, but if you are using a Source as a standalone object, - * you may wish to call this. - */ - public void setListener(PreprocessorListener pl) { - this.listener = pl; - } - - /** - * Returns the File currently being lexed. - * - * If this Source is not a {@link FileLexerSource}, then - * it will ask the parent Source, and so forth recursively. - * If no Source on the stack is a FileLexerSource, returns null. - */ - public String getPath() { - Source parent = getParent(); - if (parent != null) - return parent.getPath(); - return null; - } - - /** - * Returns the human-readable name of the current Source. - */ - /* pp */ String getName() { - Source parent = getParent(); - if (parent != null) - return parent.getName(); - return null; - } - - /** - * Returns the current line number within this Source. - */ - public int getLine() { - Source parent = getParent(); - if (parent == null) - return 0; - return parent.getLine(); - } - - /** - * Returns the current column number within this Source. - */ - public int getColumn() { - Source parent = getParent(); - if (parent == null) - return 0; - return parent.getColumn(); - } - - /** - * Returns true if this Source is expanding the given macro. - * - * This is used to prevent macro recursion. - */ - /* pp */ boolean isExpanding(Macro m) { - Source parent = getParent(); - if (parent != null) - return parent.isExpanding(m); - return false; - } - - /** - * Returns true if this Source should be transparently popped - * from the input stack. - * - * Examples of such sources are macro expansions. - */ - /* pp */ boolean isAutopop() { - return autopop; - } - - /** - * Returns true if this source has line numbers. - */ - /* pp */ boolean isNumbered() { - return false; - } - - /* This is an incredibly lazy way of disabling warnings when - * the source is not active. */ - /* pp */ void setActive(boolean b) { - this.active = b; - } - - /* pp */ boolean isActive() { - return active; - } - - /** - * Returns the next Token parsed from this input stream. - * - * @see Token - */ - public abstract Token token() - throws IOException, - LexerException; - - /** - * Returns a token iterator for this Source. - */ - public Iterator iterator() { - return new SourceIterator(this); - } - - /** - * Skips tokens until the end of line. - * - * @param white true if only whitespace is permitted on the - * remainder of the line. - * @return the NL token. - */ - public Token skipline(boolean white) - throws IOException, - LexerException { - for (;;) { - Token tok = token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok.getLine(), tok.getColumn(), - "No newline before end of file"); - return new Token(NL, - tok.getLine(), tok.getColumn(), - "\n"); - // return tok; - case NL: - /* This may contain one or more newlines. */ - return tok; - case CCOMMENT: - case CPPCOMMENT: - case WHITESPACE: - break; - default: - /* XXX Check white, if required. */ - if (white) - warning(tok.getLine(), tok.getColumn(), - "Unexpected nonwhite token"); - break; - } - } - } - - protected void error(int line, int column, String msg) - throws LexerException { - if (listener != null) - listener.handleError(this, line, column, msg); - else - throw new LexerException("Error at " + line + ":" + column + ": " + msg); - } - - protected void warning(int line, int column, String msg) - throws LexerException { - if (werror) - error(line, column, msg); - else if (listener != null) - listener.handleWarning(this, line, column, msg); - else - throw new LexerException("Warning at " + line + ":" + column + ": " + msg); - } - - public void close() - throws IOException { - } - -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/SourceIterator.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/SourceIterator.java deleted file mode 100644 index d5c63c7c2..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/SourceIterator.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.IOException; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import static org.anarres.cpp.Token.*; - -/** - * An Iterator for {@link Source Sources}, - * returning {@link Token Tokens}. - */ -public class SourceIterator implements Iterator { - private Source source; - private Token tok; - - public SourceIterator(Source s) { - this.source = s; - this.tok = null; - } - - /** - * Rethrows IOException inside IllegalStateException. - */ - private void advance() { - try { - if (tok == null) - tok = source.token(); - } - catch (LexerException e) { - throw new IllegalStateException(e); - } - catch (IOException e) { - throw new IllegalStateException(e); - } - } - - /** - * Returns true if the enclosed Source has more tokens. - * - * The EOF token is never returned by the iterator. - * @throws IllegalStateException if the Source - * throws a LexerException or IOException - */ - public boolean hasNext() { - advance(); - return tok.getType() != EOF; - } - - /** - * Returns the next token from the enclosed Source. - * - * The EOF token is never returned by the iterator. - * @throws IllegalStateException if the Source - * throws a LexerException or IOException - */ - public Token next() { - if (!hasNext()) - throw new NoSuchElementException(); - Token t = this.tok; - this.tok = null; - return t; - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException. - */ - public void remove() { - throw new UnsupportedOperationException(); - } -} - diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/State.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/State.java deleted file mode 100644 index ed5c7369c..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/State.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/* pp */ class State { - boolean parent; - boolean active; - boolean sawElse; - - /* pp */ State() { - this.parent = true; - this.active = true; - this.sawElse = false; - } - - /* pp */ State(State parent) { - this.parent = parent.isParentActive() && parent.isActive(); - this.active = true; - this.sawElse = false; - } - - /* Required for #elif */ - /* pp */ void setParentActive(boolean b) { - this.parent = b; - } - - /* pp */ boolean isParentActive() { - return parent; - } - - /* pp */ void setActive(boolean b) { - this.active = b; - } - - /* pp */ boolean isActive() { - return active; - } - - /* pp */ void setSawElse() { - sawElse = true; - } - - /* pp */ boolean sawElse() { - return sawElse; - } - - public String toString() { - return "parent=" + parent + - ", active=" + active + - ", sawelse=" + sawElse; - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/StringLexerSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/StringLexerSource.java deleted file mode 100644 index 2bf35f8b3..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/StringLexerSource.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - -import java.util.List; -import java.util.Iterator; - -import static org.anarres.cpp.Token.*; - -/** - * A Source for lexing a String. - * - * This class is used by token pasting, but can be used by user - * code. - */ -public class StringLexerSource extends LexerSource { - - /** - * Creates a new Source for lexing the given String. - * - * @param ppvalid true if preprocessor directives are to be - * honoured within the string. - */ - public StringLexerSource(String string, boolean ppvalid) - throws IOException { - super(new StringReader(string), ppvalid); - } - - /** - * Creates a new Source for lexing the given String. - * - * By default, preprocessor directives are not honoured within - * the string. - */ - public StringLexerSource(String string) - throws IOException { - this(string, false); - } - - public String toString() { - return "string literal"; - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/TokenSnifferSource.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/TokenSnifferSource.java deleted file mode 100644 index 1512b2e47..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/TokenSnifferSource.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; -import java.io.StringReader; - -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; - -import static org.anarres.cpp.Token.*; - -@Deprecated -/* pp */ class TokenSnifferSource extends Source { - private List target; - - /* pp */ TokenSnifferSource(List target) { - this.target = target; - } - - public Token token() - throws IOException, - LexerException { - Token tok = getParent().token(); - if (tok.getType() != EOF) - target.add(tok); - return tok; - } - - public String toString() { - return getParent().toString(); - } -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFile.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFile.java deleted file mode 100644 index 405891a77..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFile.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.IOException; - -/** - * An extremely lightweight virtual file interface. - */ -public interface VirtualFile { - // public String getParent(); - public boolean isFile(); - public String getPath(); - public String getName(); - public VirtualFile getParentFile(); - public VirtualFile getChildFile(String name); - public Source getSource() throws IOException; -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFileSystem.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFileSystem.java deleted file mode 100644 index eb5c4a1e8..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/VirtualFileSystem.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * An extremely lightweight virtual file system interface. - */ -public interface VirtualFileSystem { - public VirtualFile getFile(String path); - public VirtualFile getFile(String dir, String name); -} diff --git a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Warning.java b/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Warning.java deleted file mode 100644 index abe38d091..000000000 --- a/libraries/jnaerator/anarres/src/main/java/org/anarres/cpp/Warning.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * Warning classes which may optionally be emitted by the Preprocessor. - */ -public enum Warning { - TRIGRAPHS, - // TRADITIONAL, - IMPORT, - UNDEF, - UNUSED_MACROS, - ENDIF_LABELS, - ERROR, - // SYSTEM_HEADERS -} diff --git a/libraries/jnaerator/anarres/src/main/resources/log4j.properties b/libraries/jnaerator/anarres/src/main/resources/log4j.properties deleted file mode 100644 index 901854cb3..000000000 --- a/libraries/jnaerator/anarres/src/main/resources/log4j.properties +++ /dev/null @@ -1,22 +0,0 @@ -# Set root logger level to DEBUG and its only appender to stdout. -log4j.rootLogger=INFO, stdout - -# stdout is set to be a ConsoleAppender. -log4j.appender.stdout=org.apache.log4j.ConsoleAppender - -# stdout uses PatternLayout. -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -# log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -# log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %p %c{1} - %m%n -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t %x] %p %c - %m%n -# Make log4j honour other programs changing System.out -log4j.appender.stdout.follow=true - -# Turn on Axis exception logging -log4j.logger.org.apache.axis.EXCEPTIONS=DEBUG - -# log4j.logger.org.apache.axis=WARN -# log4j.logger.org.mortbay=WARN -# log4j.logger.com.mchange=WARN - -# log4j.logger.org.anarres.iengine=DEBUG diff --git a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Main.java b/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Main.java deleted file mode 100644 index 00f47f090..000000000 --- a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Main.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import gnu.getopt.Getopt; -import gnu.getopt.LongOpt; - -import static org.anarres.cpp.Token.*; - -/** - * (Currently a simple test class). - */ -public class Main { - - private static class Option extends LongOpt { - private String eg; - private String help; - public Option(String word, int arg, int ch, - String eg, String help) { - super(word, arg, null, ch); - this.eg = eg; - this.help = help; - } - } - - private static final Option[] OPTS = new Option[] { - new Option("help", LongOpt.NO_ARGUMENT, 'h', null, - "Displays help and usage information."), - new Option("define", LongOpt.REQUIRED_ARGUMENT, 'D', "name=definition", - "Defines the given macro."), - new Option("undefine", LongOpt.REQUIRED_ARGUMENT, 'U', "name", - "Undefines the given macro, previously either builtin or defined using -D."), - new Option("include", LongOpt.REQUIRED_ARGUMENT, 1, "file", - "Process file as if \"#" + "include \"file\"\" appeared as the first line of the primary source file."), - new Option("incdir", LongOpt.REQUIRED_ARGUMENT, 'I', "dir", - "Adds the directory dir to the list of directories to be searched for header files."), - new Option("iquote", LongOpt.REQUIRED_ARGUMENT, 0, "dir", - "Adds the directory dir to the list of directories to be searched for header files included using \"\"."), - new Option("warning", LongOpt.REQUIRED_ARGUMENT, 'W', "type", - "Enables the named warning class (" + getWarnings() + ")."), - new Option("no-warnings", LongOpt.NO_ARGUMENT, 'w', null, - "Disables ALL warnings."), - new Option("verbose", LongOpt.NO_ARGUMENT, 'v', null, - "Operates incredibly verbosely."), - new Option("debug", LongOpt.NO_ARGUMENT, 3, null, - "Operates incredibly verbosely."), - new Option("version", LongOpt.NO_ARGUMENT, 2, null, - "Prints jcpp's version number (" + Version.getVersion() + ")"), - }; - - private static CharSequence getWarnings() { - StringBuilder buf = new StringBuilder(); - for (Warning w : Warning.values()) { - if (buf.length() > 0) - buf.append(", "); - String name = w.name().toLowerCase(); - buf.append(name.replace('_', '-')); - } - return buf; - } - - public static void main(String[] args) throws Exception { - (new Main()).run(args); - } - - public void run(String[] args) throws Exception { - Option[]opts = OPTS; - String sopts = getShortOpts(opts); - Getopt g = new Getopt("jcpp", args, sopts, opts); - int c; - String arg; - int idx; - - Preprocessor pp = new Preprocessor(); - pp.addFeature(Feature.DIGRAPHS); - pp.addFeature(Feature.TRIGRAPHS); - pp.addFeature(Feature.LINEMARKERS); - pp.addWarning(Warning.IMPORT); - pp.setListener(new PreprocessorListener()); - pp.addMacro("__JCPP__"); - pp.getSystemIncludePath().add("/usr/local/include"); - pp.getSystemIncludePath().add("/usr/include"); - pp.getFrameworksPath().add("/System/Library/Frameworks"); - pp.getFrameworksPath().add("/Library/Frameworks"); - pp.getFrameworksPath().add("/Local/Library/Frameworks"); - - GETOPT: while ((c = g.getopt()) != -1) { - switch (c) { - case 'D': - arg = g.getOptarg(); - idx = arg.indexOf('='); - if (idx == -1) - pp.addMacro(arg); - else - pp.addMacro(arg.substring(0, idx), - arg.substring(idx + 1)); - break; - case 'U': - pp.getMacros().remove(g.getOptarg()); - break; - case 'I': - pp.getSystemIncludePath().add(g.getOptarg()); - break; - case 0: // --iquote= - pp.getQuoteIncludePath().add(g.getOptarg()); - break; - case 'W': - arg = g.getOptarg().toUpperCase(); - arg = arg.replace('-', '_'); - if (arg.equals("ALL")) - pp.addWarnings(EnumSet.allOf(Warning.class)); - else - pp.addWarning(Enum.valueOf(Warning.class, arg)); - break; - case 'w': - pp.getWarnings().clear(); - break; - case 1: // --include= - // pp.addInput(new File(g.getOptarg())); - // Comply exactly with spec. - pp.addInput(new StringLexerSource( - "#" + "include \"" + g.getOptarg() + "\"\n" - )); - break; - case 2: // --version - version(System.out); - return; - case 'v': - pp.addFeature(Feature.VERBOSE); - break; - case 3: - pp.addFeature(Feature.DEBUG); - break; - case 'h': - usage(getClass().getName(), opts); - return; - default: - throw new Exception("Illegal option " + (char)c); - case '?': - continue; /* Make failure-proof. */ - } - } - - for (int i = g.getOptind(); i < args.length; i++) - pp.addInput(new FileLexerSource(new File(args[i]))); - if (g.getOptind() == args.length) - pp.addInput(new InputLexerSource(System.in)); - - if (pp.getFeature(Feature.VERBOSE)) { - System.err.println("#"+"include \"...\" search starts here:"); - for (String dir : pp.getQuoteIncludePath()) - System.err.println(" " + dir); - System.err.println("#"+"include <...> search starts here:"); - for (String dir : pp.getSystemIncludePath()) - System.err.println(" " + dir); - System.err.println("End of search list."); - } - - try { - for (;;) { - Token tok = pp.token(); - if (tok == null) - break; - if (tok.getType() == Token.EOF) - break; - System.out.print(tok.getText()); - } - } - catch (Exception e) { - e.printStackTrace(System.err); - Source s = pp.getSource(); - while (s != null) { - System.err.println(" -> " + s); - s = s.getParent(); - } - } - - } - - private void version(PrintStream out) { - out.println("Anarres Java C Preprocessor version " + Version.getVersion()); - out.println("Copyright (C) 2008 Shevek (http://www.anarres.org/)."); - out.println("This is free software; see the source for copying conditions. There is NO"); - out.println("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."); - } - - - private static String getShortOpts(Option[] opts) - throws Exception { - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < opts.length; i++) { - char c = (char)opts[i].getVal(); - if (!Character.isLetterOrDigit(c)) - continue; - for (int j = 0; j < buf.length(); j++) - if (buf.charAt(j) == c) - throw new Exception( - "Duplicate short option " + c - ); - buf.append(c); - switch (opts[i].getHasArg()) { - case LongOpt.NO_ARGUMENT: - break; - case LongOpt.OPTIONAL_ARGUMENT: - buf.append("::"); - break; - case LongOpt.REQUIRED_ARGUMENT: - buf.append(":"); - break; - } - } - return buf.toString(); - } - - /* This is incomplete but nearly there. */ - /** - * Wraps a string. - * - * The output form is: - *
      -     * prefix     in[0]
      -     * <--indent-> in[1]
      -     * <--indent-> in[2]
      -     * <-----width---->
      -     * 
      - */ - /* XXX There's some of this in commons. */ - private static String wrap(String in, String prefix, - int indent, int width) { - StringBuilder buf = new StringBuilder(prefix); - - while (buf.length() < indent) - buf.append(' '); - - int start = 0; - - while (start < in.length()) { - while (start < in.length() && - Character.isWhitespace(in.charAt(start))) - start++; - - int end = start + width - indent; - - if (end > in.length()) { - buf.append(in.substring(start)); - break; - } - - int idx = end; - while (!Character.isWhitespace(in.charAt(idx))) - idx--; - - if (idx == start) { - idx = end - 1; - buf.append(in.substring(start, idx)); - buf.append('-'); - } - else { - buf.append(in.substring(start, idx)); - start = idx; - } - - start = idx; - } - - return buf.toString(); - } - - private static void usage(String command, Option[] options) { - StringBuilder text = new StringBuilder("Usage: "); - text.append(command).append('\n'); - for (int i = 0; i < options.length; i++) { - StringBuilder line = new StringBuilder(); - Option opt = options[i]; - line.append(" --").append(opt.getName()); - switch (opt.getHasArg()) { - case LongOpt.NO_ARGUMENT: - break; - case LongOpt.OPTIONAL_ARGUMENT: - line.append("[=").append(opt.eg).append(']'); - break; - case LongOpt.REQUIRED_ARGUMENT: - line.append('=').append(opt.eg); - break; - } - if (Character.isLetterOrDigit(opt.getVal())) - line.append(" (-").append((char)opt.getVal()).append(")"); - if (line.length() < 30) { - while (line.length() < 30) - line.append(' '); - } - else { - line.append('\n'); - for (int j = 0; j < 30; j++) - line.append(' '); - } - /* This should use wrap. */ - line.append(opt.help); - line.append('\n'); - text.append(line); - } - - System.out.println(text); - } - - - -#if (false) - public static void oldmain(String[] args) throws Exception { - List path = new ArrayList(); - path.add("/usr/include"); - path.add("/usr/local/include"); - path.add("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include"); - - Source source = new FileLexerSource(new File(args[0])); - Preprocessor pp = new Preprocessor(source); - pp.setSystemIncludePath(path); - - for (int i = 1; i < args.length; i++) { - pp.push_source(new FileLexerSource(new File(args[i])),true); - } - - Macro m = new Macro("__WORDSIZE"); - m.addToken(new Token(INTEGER, -1, -1, "32", Integer.valueOf(32))); - pp.addMacro(m); - - m = new Macro("__STDC__"); - m.addToken(new Token(INTEGER, -1, -1, "1", Integer.valueOf(1))); - pp.addMacro(m); - - try { - for (;;) { - Token tok = pp.token(); - if (tok != null && tok.getType() == Token.EOF) - break; - switch (2) { - case 0: - System.out.print(tok); - break; - case 1: - System.out.print("[" + tok.getText() + "]"); - break; - case 2: - System.out.print(tok.getText()); - break; - } - } - } - catch (Exception e) { - e.printStackTrace(); - Source s = pp.getSource(); - while (s != null) { - System.out.println(" -> " + s); - s = s.getParent(); - } - - /* - Iterator it = pp.states.iterator(); - while (it.hasNext()) { - System.out.println(" -? " + it.next()); - } - */ - - } - - Map macros = pp.getMacros(); - List keys = new ArrayList( - macros.keySet() - ); - Collections.sort(keys); - Iterator mt = keys.iterator(); - while (mt.hasNext()) { - String key = mt.next(); - Macro macro = macros.get(key); - System.out.println("#" + "macro " + macro); - } - - } -#end - -} diff --git a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Preprocessor.java b/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Preprocessor.java deleted file mode 100644 index 3a80d83f8..000000000 --- a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Preprocessor.java +++ /dev/null @@ -1,2051 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import static org.anarres.cpp.Token.*; - -/** - * A C Preprocessor. - * The Preprocessor outputs a token stream which does not need - * re-lexing for C or C++. Alternatively, the output text may be - * reconstructed by concatenating the {@link Token#getText() text} - * values of the returned {@link Token Tokens}. (See - * {@link CppReader}, which does this.) - */ - - -/* -Source file name and line number information is conveyed by lines of the form - - # linenum filename flags - -These are called linemarkers. They are inserted as needed into -the output (but never within a string or character constant). They -mean that the following line originated in file filename at line -linenum. filename will never contain any non-printing characters; -they are replaced with octal escape sequences. - -After the file name comes zero or more flags, which are `1', `2', -`3', or `4'. If there are multiple flags, spaces separate them. Here -is what the flags mean: - -`1' - This indicates the start of a new file. -`2' - This indicates returning to a file (after having included another - file). -`3' - This indicates that the following text comes from a system header - file, so certain warnings should be suppressed. -`4' - This indicates that the following text should be treated as being - wrapped in an implicit extern "C" block. -*/ - -public class Preprocessor implements Closeable { - private static final Source INTERNAL = new Source() { - @Override - public Token token() - throws IOException, - LexerException { - throw new LexerException("Cannot read from " + getName()); - } - @Override - public String getPath() { - return ""; - } - @Override - public String getName() { - return "internal data"; - } - }; - private static final Macro __LINE__ = new Macro(INTERNAL, "__LINE__"); - private static final Macro __FILE__ = new Macro(INTERNAL, "__FILE__"); - private static final Macro __COUNTER__ = new Macro(INTERNAL, "__COUNTER__"); - - private List inputs; - - /* The fundamental engine. */ - private Map macros; - private Stack states; - private Source source; - - /* Miscellaneous support. */ - private int counter; - - /* Support junk to make it work like cpp */ - private List quoteincludepath; /* -iquote */ - private List sysincludepath; /* -I */ - - //ochafik - /* -F @see http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-3.3/gcc/Directory-Options.html */ - private List frameworkspath; - private Set features; - private Set warnings; - private VirtualFileSystem filesystem; - private PreprocessorListener listener; - //ochafik - private boolean properStringTokensInLinePragmas = false; - private boolean inIncludeNext = false; // whether current include should ignore current file's directory in include paths - - protected Map createMacro() { - return new LinkedHashMap(); - } - - public Preprocessor() { - this.inputs = new ArrayList(); - - this.macros = createMacro(); - macros.put(__LINE__.getName(), __LINE__); - macros.put(__FILE__.getName(), __FILE__); - macros.put(__COUNTER__.getName(), __COUNTER__); - this.states = new Stack(); - states.push(new State()); - this.source = null; - - this.counter = 0; - - this.quoteincludepath = new ArrayList(); - this.sysincludepath = new ArrayList(); - this.frameworkspath = new ArrayList(); - this.features = EnumSet.noneOf(Feature.class); - this.warnings = EnumSet.noneOf(Warning.class); - this.filesystem = new JavaFileSystem(); - this.listener = null; - } - - public Preprocessor(Source initial) { - this(); - addInput(initial); - } - - /** Equivalent to - * 'new Preprocessor(new {@link FileLexerSource}(file))' - */ - public Preprocessor(File file) - throws IOException { - this(new FileLexerSource(file)); - } - - /** - * Sets the VirtualFileSystem used by this Preprocessor. - */ - public void setFileSystem(VirtualFileSystem filesystem) { - this.filesystem = filesystem; - } - - public void setProperStringTokensInLinePragmas(boolean properStringTokensInLinePragmas) { - this.properStringTokensInLinePragmas = properStringTokensInLinePragmas; - } - - /** - * Returns the VirtualFileSystem used by this Preprocessor. - */ - public VirtualFileSystem getFileSystem() { - return filesystem; - } - - /** - * Sets the PreprocessorListener which handles events for - * this Preprocessor. - * - * The listener is notified of warnings, errors and source - * changes, amongst other things. - */ - public void setListener(PreprocessorListener listener) { - this.listener = listener; - Source s = source; - while (s != null) { - // s.setListener(listener); - s.init(this); - s = s.getParent(); - } - } - - /** - * Returns the PreprocessorListener which handles events for - * this Preprocessor. - */ - public PreprocessorListener getListener() { - return listener; - } - - /** - * Returns the feature-set for this Preprocessor. - * - * This set may be freely modified by user code. - */ - public Set getFeatures() { - return features; - } - - /** - * Adds a feature to the feature-set of this Preprocessor. - */ - public void addFeature(Feature f) { - features.add(f); - } - - /** - * Adds features to the feature-set of this Preprocessor. - */ - public void addFeatures(Collection f) { - features.addAll(f); - } - - /** - * Returns true if the given feature is in - * the feature-set of this Preprocessor. - */ - public boolean getFeature(Feature f) { - return features.contains(f); - } - - /** - * Returns the warning-set for this Preprocessor. - * - * This set may be freely modified by user code. - */ - public Set getWarnings() { - return warnings; - } - - /** - * Adds a warning to the warning-set of this Preprocessor. - */ - public void addWarning(Warning w) { - warnings.add(w); - } - - /** - * Adds warnings to the warning-set of this Preprocessor. - */ - public void addWarnings(Collection w) { - warnings.addAll(w); - } - - /** - * Returns true if the given warning is in - * the warning-set of this Preprocessor. - */ - public boolean getWarning(Warning w) { - return warnings.contains(w); - } - - /** - * Adds input for the Preprocessor. - * - * Inputs are processed in the order in which they are added. - */ - public void addInput(Source source) { - source.init(this); - inputs.add(source); - } - - /** - * Adds input for the Preprocessor. - * - * @see #addInput(Source) - */ - public void addInput(File file) - throws IOException { - addInput(new FileLexerSource(file)); - } - - - /** - * Handles an error. - * - * If a PreprocessorListener is installed, it receives the - * error. Otherwise, an exception is thrown. - */ - protected void error(int line, int column, String msg) - throws LexerException { - if (listener != null) - listener.handleError(source, line, column, msg); - else - throw new LexerException("Error at " + line + ":" + column + ": " + msg); - } - - /** - * Handles an error. - * - * If a PreprocessorListener is installed, it receives the - * error. Otherwise, an exception is thrown. - * - * @see #error(int, int, String) - */ - protected void error(Token tok, String msg) - throws LexerException { - error(tok.getLine(), tok.getColumn(), msg); - } - - /** - * Handles a warning. - * - * If a PreprocessorListener is installed, it receives the - * warning. Otherwise, an exception is thrown. - */ - protected void warning(int line, int column, String msg) - throws LexerException { - if (warnings.contains(Warning.ERROR)) - error(line, column, msg); - else if (listener != null) - listener.handleWarning(source, line, column, msg); - else - throw new LexerException("Warning at " + line + ":" + column + ": " + msg); - } - - /** - * Handles a warning. - * - * If a PreprocessorListener is installed, it receives the - * warning. Otherwise, an exception is thrown. - * - * @see #warning(int, int, String) - */ - protected void warning(Token tok, String msg) - throws LexerException { - warning(tok.getLine(), tok.getColumn(), msg); - } - - /** - * Adds a Macro to this Preprocessor. - * - * The given {@link Macro} object encapsulates both the name - * and the expansion. - */ - public void addMacro(Macro m) throws LexerException { - // System.out.println("Macro " + m); - String name = m.getName(); - /* Already handled as a source error in macro(). */ - if ("defined".equals(name)) - throw new LexerException("Cannot redefine name 'defined'"); - macros.put(m.getName(), m); - } - - /** - * Defines the given name as a macro. - * - * The String value is lexed into a token stream, which is - * used as the macro expansion. - */ - public void addMacro(String name, String value) - throws LexerException { - try { - Macro m = new Macro(name); - StringLexerSource s = new StringLexerSource(value); - for (;;) { - Token tok = s.token(); - if (tok.getType() == EOF) - break; - m.addToken(tok); - } - addMacro(m); - } - catch (IOException e) { - throw new LexerException(e); - } - } - - /** - * Defines the given name as a macro, with the value 1. - * - * This is a convnience method, and is equivalent to - * addMacro(name, "1"). - */ - public void addMacro(String name) - throws LexerException { - addMacro(name, "1"); - } - - /** - * Sets the user include path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setQuoteIncludePath(List path) { - this.quoteincludepath = path; - } - - /** - * Returns the user include-path of this Preprocessor. - * - * This list may be freely modified by user code. - */ - public List getQuoteIncludePath() { - return quoteincludepath; - } - - /** - * Sets the system include path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setSystemIncludePath(List path) { - this.sysincludepath = path; - } - - /** - * Returns the system include-path of this Preprocessor. - * - * This list may be freely modified by user code. - */ - public List getSystemIncludePath() { - return sysincludepath; - } - - /** - * Sets the Objective-C frameworks path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setFrameworksPath(List path) { - this.frameworkspath = path; - } - - /** - * Returns the Objective-C frameworks path used by this - * Preprocessor. - * - * This list may be freely modified by user code. - */ - public List getFrameworksPath() { - return frameworkspath; - } - - /** - * Returns the Map of Macros parsed during the run of this - * Preprocessor. - */ - public Map getMacros() { - return macros; - } - - /** - * Returns the named macro. - * - * While you can modify the returned object, unexpected things - * might happen if you do. - */ - public Macro getMacro(String name) { - return macros.get(name); - } - -/* States */ - - private void push_state() { - State top = states.peek(); - states.push(new State(top)); - } - - private void pop_state() - throws LexerException { - State s = states.pop(); - if (states.isEmpty()) { - error(0, 0, "#" + "endif without #" + "if"); - states.push(s); - } - } - - private boolean isActive() { - State state = states.peek(); - return state.isParentActive() && state.isActive(); - } - - -/* Sources */ - - /** - * Returns the top Source on the input stack. - * - * @see Source - * @see #push_source(Source,boolean) - * @see #pop_source() - */ - protected Source getSource() { - return source; - } - - /** - * Pushes a Source onto the input stack. - * - * @see #getSource() - * @see #pop_source() - */ - protected void push_source(Source source, boolean autopop) { - source.init(this); - source.setParent(this.source, autopop); - // source.setListener(listener); - if (listener != null) - listener.handleSourceChange(this.source, "suspend"); - this.source = source; - if (listener != null) - listener.handleSourceChange(this.source, "push"); - } - - /** - * Pops a Source from the input stack. - * - * @see #getSource() - * @see #push_source(Source,boolean) - */ - protected void pop_source() - throws IOException { - if (listener != null) - listener.handleSourceChange(this.source, "pop"); - Source s = this.source; - this.source = s.getParent(); - /* Always a noop unless called externally. */ - s.close(); - if (listener != null && this.source != null) - listener.handleSourceChange(this.source, "resume"); - } - - -/* Source tokens */ - - private Token source_token; - - /* XXX Make this include the NL, and make all cpp directives eat - * their own NL. */ - private Token line_token(int line, String name, String extra) { - /*StringBuilder buf = new StringBuilder(); - buf.append("#line ").append(line) - .append(" \""); - /* XXX This call to escape(name) is correct but ugly. * / - MacroTokenSource.escape(buf, name); - buf.append("\"").append(extra).append("\n"); - return new Token(P_LINE, line, 0, buf.toString(), null); - */ - //* - return new Token(P_LINE, line, 0, - name == null ? "" : - "\n#line " + line + " \"" + (properStringTokensInLinePragmas ? String.valueOf(name).replace("\\", "\\\\") : name) + "\"" + extra + "\n", - null - ); - //*/ - } - - private Token source_token() - throws IOException, - LexerException { - if (source_token != null) { - Token tok = source_token; - source_token = null; - if (getFeature(Feature.DEBUG)) - System.err.println("Returning unget token " + tok); - return tok; - } - - for (;;) { - Source s = getSource(); - if (s == null) { - if (inputs.isEmpty()) - return new Token(EOF); - Source t = inputs.remove(0); - push_source(t, true); - if (getFeature(Feature.LINEMARKERS)) - return line_token(t.getLine(), t.getName(), " 1"); - continue; - } - Token tok = s.token(); - /* XXX Refactor with skipline() */ - if (tok.getType() == EOF && s.isAutopop()) { - // System.out.println("Autopop " + s); - pop_source(); - Source t = getSource(); - if (getFeature(Feature.LINEMARKERS) - && s.isNumbered() - && t != null) { - /* We actually want 'did the nested source - * contain a newline token', which isNumbered() - * approximates. This is not perfect, but works. */ - return line_token(t.getLine() + 1, t.getName(), " 2"); - } - continue; - } - if (getFeature(Feature.DEBUG)) - System.err.println("Returning fresh token " + tok); - return tok; - } - } - - private void source_untoken(Token tok) { - if (this.source_token != null) - throw new IllegalStateException("Cannot return two tokens"); - this.source_token = tok; - } - - private boolean isWhite(Token tok) { - int type = tok.getType(); - return (type == WHITESPACE) - || (type == CCOMMENT) - || (type == CPPCOMMENT); - } - - private Token source_token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = source_token(); - } while (isWhite(tok)); - return tok; - } - - /** - * Returns an NL or an EOF token. - * - * The metadata on the token will be correct, which is better - * than generating a new one. - * - * This method can, as of recent patches, return a P_LINE token. - */ - private Token source_skipline(boolean white) - throws IOException, - LexerException { - // (new Exception("skipping line")).printStackTrace(System.out); - Source s = getSource(); - Token tok = s.skipline(white); - /* XXX Refactor with source_token() */ - if (tok.getType() == EOF && s.isAutopop()) { - // System.out.println("Autopop " + s); - pop_source(); - Source t = getSource(); - if (getFeature(Feature.LINEMARKERS) - && s.isNumbered() - && t != null) { - /* We actually want 'did the nested source - * contain a newline token', which isNumbered() - * approximates. This is not perfect, but works. */ - return line_token(t.getLine() + 1, t.getName(), " 2"); - } - } - return tok; - } - - /* processes and expands a macro. */ - private boolean macro(Macro m, Token orig) - throws IOException, - LexerException { - Token tok; - List args; - - // System.out.println("pp: expanding " + m); - - if (m.isFunctionLike()) { - OPEN: for (;;) { - tok = source_token(); - // System.out.println("pp: open: token is " + tok); - switch (tok.getType()) { - case WHITESPACE: /* XXX Really? */ - case CCOMMENT: - case CPPCOMMENT: - case NL: - break; /* continue */ - case '(': - break OPEN; - default: - source_untoken(tok); - return false; - } - } - - // tok = expanded_token_nonwhite(); - tok = source_token_nonwhite(); - - /* We either have, or we should have args. - * This deals elegantly with the case that we have - * one empty arg. */ - if (tok.getType() != ')' || m.getArgs() > 0) { - args = new ArrayList(); - - Argument arg = new Argument(); - int depth = 0; - boolean space = false; - - ARGS: for (;;) { - // System.out.println("pp: arg: token is " + tok); - switch (tok.getType()) { - case EOF: - error(tok, "EOF in macro args"); - return false; - - case ',': - if (depth == 0) { - if (m.isVariadic() && - /* We are building the last arg. */ - args.size() == m.getArgs() - 1) { - /* Just add the comma. */ - arg.addToken(tok); - } - else { - args.add(arg); - arg = new Argument(); - } - } - else { - arg.addToken(tok); - } - space = false; - break; - case ')': - if (depth == 0) { - args.add(arg); - break ARGS; - } - else { - depth--; - arg.addToken(tok); - } - space = false; - break; - case '(': - depth++; - arg.addToken(tok); - space = false; - break; - - case WHITESPACE: - case CCOMMENT: - case CPPCOMMENT: - /* Avoid duplicating spaces. */ - space = true; - break; - - default: - /* Do not put space on the beginning of - * an argument token. */ - if (space && ! arg.isEmpty()) - arg.addToken(Token.space); - arg.addToken(tok); - space = false; - break; - - } - // tok = expanded_token(); - tok = source_token(); - } - /* space may still be true here, thus trailing space - * is stripped from arguments. */ - - if (args.size() != m.getArgs()) { - error(tok, - "macro " + m.getName() + - " has " + m.getArgs() + " parameters " + - "but given " + args.size() + " args"); - /* We could replay the arg tokens, but I - * note that GNU cpp does exactly what we do, - * i.e. output the macro name and chew the args. - */ - return false; - } - - /* - for (Argument a : args) - a.expand(this); - */ - - for (int i = 0; i < args.size(); i++) { - args.get(i).expand(this); - } - - // System.out.println("Macro " + m + " args " + args); - } - else { - /* nargs == 0 and we (correctly) got () */ - args = null; - } - - } - else { - /* Macro without args. */ - args = null; - } - - if (m == __LINE__) { - push_source(new FixedTokenSource( - new Token[] { new Token(INTEGER, - orig.getLine(), orig.getColumn(), - String.valueOf(orig.getLine()), - Integer.valueOf(orig.getLine())) } - ), true); - } - else if (m == __FILE__) { - StringBuilder buf = new StringBuilder("\""); - String name = getSource().getName(); - if (name == null) - name = ""; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - switch (c) { - case '\\': - buf.append("\\\\"); - break; - case '"': - buf.append("\\\""); - break; - default: - buf.append(c); - break; - } - } - buf.append("\""); - String text = buf.toString(); - push_source(new FixedTokenSource( - new Token[] { new Token(STRING, - orig.getLine(), orig.getColumn(), - text, text) } - ), true); - } - else if (m == __COUNTER__) { - /* This could equivalently have been done by adding - * a special Macro subclass which overrides getTokens(). */ - int value = this.counter++; - push_source(new FixedTokenSource( - new Token[] { new Token(INTEGER, - orig.getLine(), orig.getColumn(), - String.valueOf(value), - Integer.valueOf(value)) } - ), true); - } - else { - push_source(new MacroTokenSource(m, args), true); - } - - return true; - } - - /** - * Expands an argument. - */ - /* I'd rather this were done lazily, but doing so breaks spec. */ - /* pp */ List expand(List arg) - throws IOException, - LexerException { - List expansion = new ArrayList(); - boolean space = false; - - push_source(new FixedTokenSource(arg), false); - - EXPANSION: for (;;) { - Token tok = expanded_token(); - switch (tok.getType()) { - case EOF: - break EXPANSION; - - case WHITESPACE: - case CCOMMENT: - case CPPCOMMENT: - space = true; - break; - - default: - if (space && ! expansion.isEmpty()) - expansion.add(Token.space); - expansion.add(tok); - space = false; - break; - } - } - - pop_source(); - - return expansion; - } - - /* processes a #define directive */ - private Token define() - throws IOException, - LexerException { - Token tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, "Expected identifier"); - return source_skipline(false); - } - /* if predefined */ - - String name = tok.getText(); - if ("defined".equals(name)) { - error(tok, "Cannot redefine name 'defined'"); - return source_skipline(false); - } - - Macro m = new Macro(getSource(), name); - List args; - - tok = source_token(); - if (tok.getType() == '(') { - tok = source_token_nonwhite(); - if (tok.getType() != ')') { - args = new ArrayList(); - ARGS: for (;;) { - switch (tok.getType()) { - case IDENTIFIER: - args.add(tok.getText()); - break; - case NL: - case EOF: - error(tok, - "Unterminated macro parameter list"); - return tok; - case ELLIPSIS: - // Unnamed Variadic Macros - args.add("__VA_ARGS__"); - source_untoken(tok); - break; - default: - error(tok, - "error in macro parameters: " + - tok.getText()); - return source_skipline(false); - } - tok = source_token_nonwhite(); - switch (tok.getType()) { - case ',': - break; - case ELLIPSIS: - tok = source_token_nonwhite(); - if (tok.getType() != ')') - error(tok, - "ellipsis must be on last argument"); - m.setVariadic(true); - break ARGS; - case ')': - break ARGS; - - case NL: - case EOF: - /* Do not skip line. */ - error(tok, - "Unterminated macro parameters"); - return tok; - default: - error(tok, - "Bad token in macro parameters: " + - tok.getText()); - return source_skipline(false); - } - tok = source_token_nonwhite(); - } - } - else { - assert tok.getType() == ')' : "Expected ')'"; - args = Collections.emptyList(); - } - - m.setArgs(args); - } - else { - /* For searching. */ - args = Collections.emptyList(); - source_untoken(tok); - } - - /* Get an expansion for the macro, using indexOf. */ - boolean space = false; - boolean paste = false; - int idx; - - /* Ensure no space at start. */ - tok = source_token_nonwhite(); - EXPANSION: for (;;) { - switch (tok.getType()) { - case EOF: - break EXPANSION; - case NL: - break EXPANSION; - - case CCOMMENT: - case CPPCOMMENT: - /* XXX This is where we implement GNU's cpp -CC. */ - // break; - case WHITESPACE: - if (!paste) - space = true; - break; - - /* Paste. */ - case PASTE: - space = false; - paste = true; - m.addPaste(new Token(M_PASTE, - tok.getLine(), tok.getColumn(), - "#" + "#", null)); - break; - - /* Stringify. */ - case '#': - if (space) - m.addToken(Token.space); - space = false; - Token la = source_token_nonwhite(); - if (la.getType() == IDENTIFIER && - ((idx = args.indexOf(la.getText())) != -1)) { - m.addToken(new Token(M_STRING, - la.getLine(), la.getColumn(), - "#" + la.getText(), - Integer.valueOf(idx))); - } - else { - m.addToken(tok); - /* Allow for special processing. */ - source_untoken(la); - } - break; - - case IDENTIFIER: - if (space) - m.addToken(Token.space); - space = false; - paste = false; - idx = args.indexOf(tok.getText()); - if (idx == -1) - m.addToken(tok); - else - m.addToken(new Token(M_ARG, - tok.getLine(), tok.getColumn(), - tok.getText(), - Integer.valueOf(idx))); - break; - - default: - if (space) - m.addToken(Token.space); - space = false; - paste = false; - m.addToken(tok); - break; - } - tok = source_token(); - } - - if (getFeature(Feature.DEBUG)) - System.err.println("Defined macro " + m); - addMacro(m); - - return tok; /* NL or EOF. */ - } - - private Token undef() - throws IOException, - LexerException { - Token tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " + tok.getText()); - if (tok.getType() == NL || tok.getType() == EOF) - return tok; - } - else { - Macro m = macros.get(tok.getText()); - if (m != null) { - /* XXX error if predefined */ - macros.remove(m.getName()); - } - } - return source_skipline(true); - } - - /** - * Attempts to include the given file. - * - * User code may override this method to implement a virtual - * file system. - */ - protected boolean include(VirtualFile file) - throws IOException, - LexerException { - // System.out.println("Try to include " + file); - if (!file.isFile()) - return false; - if (getFeature(Feature.DEBUG)) - System.err.println("pp: including " + file); - push_source(file.getSource(), true); - return true; - } - - /** - * Includes a file from an include path, by name. - */ - protected boolean include(Iterable path, String name) - throws IOException, - LexerException { - for (String dir : path) { - VirtualFile file = filesystem.getFile(dir, name); - if (include(file)) - return true; - } - // Accept absolute paths in includes - VirtualFile file = filesystem.getFile(name); - if (include(file)) - return true; - - return false; - } - - /** - * Handles an include directive. - */ - private void include(String parent, int line, - String name, boolean quoted) - throws IOException, - LexerException { - VirtualFile pdir = null; - if (quoted) { - if (!inIncludeNext && parent != null) { - VirtualFile pfile = parent == null ? null : filesystem.getFile(parent); - pdir = pfile == null ? null : pfile.getParentFile(); - VirtualFile ifile = pdir.getChildFile(name); - if (include(ifile)) - return; - } - if (include(quoteincludepath, name)) - return; - } else { - // Try to recognize an include from a framework (for both \#include and \#import directives in Objective-C files) - String frameworkName = null; - int i = name.indexOf("/"); - String subName = null; - if (i > 0) { - frameworkName = name.substring(0, i); - subName = name.substring(i + 1); - } - if (subName != null) { - String frameworkDirName = frameworkName + ".framework"; - for (String path : frameworkspath) { - File frameworkDir = new File(path, frameworkDirName); - if (frameworkDir.exists() && frameworkDir.isDirectory()) { - if (getFeature(Feature.DEBUG)) - System.err.println("Found framework: " + frameworkDir); - - File headers = new File(frameworkDir, "Headers"); - if (!headers.exists()) - headers = new File(frameworkDir, "PrivateHeaders"); - - if (headers.exists()) { - pdir = filesystem.getFile(headers.toString()); - VirtualFile ifile = pdir.getChildFile(subName); - if (include(ifile)) - return; - break; - } - } - } - } - } - - if (include(sysincludepath, name)) - return; - - StringBuilder buf = new StringBuilder(); - buf.append("File not found: ").append(name); - buf.append(" in"); - if (quoted) { - buf.append(" .").append('(').append(pdir).append(')'); - for (String dir : quoteincludepath) - buf.append(" ").append(dir); - } - for (String dir : sysincludepath) - buf.append(" ").append(dir); - error(line, 0, buf.toString()); - } - - private Token include(boolean next) - throws IOException, - LexerException { - LexerSource lexer = (LexerSource)source; - try { - lexer.setInclude(true); - Token tok = token_nonwhite(); - - String name; - boolean quoted; - - if (tok.getType() == STRING) { - /* XXX Use the original text, not the value. - * Backslashes must not be treated as escapes here. */ - StringBuilder buf = new StringBuilder((String)tok.getValue()); - HEADER: for (;;) { - tok = token_nonwhite(); - switch (tok.getType()) { - case STRING: - buf.append((String)tok.getValue()); - break; - case NL: - case EOF: - break HEADER; - default: - warning(tok, - "Unexpected token on #"+"include line"); - return source_skipline(false); - } - } - name = buf.toString(); - quoted = true; - } - else if (tok.getType() == HEADER) { - name = (String)tok.getValue(); - quoted = false; - tok = source_skipline(true); - } - else { - error(tok, - "Expected string or header, not " + tok.getText()); - switch (tok.getType()) { - case NL: - case EOF: - return tok; - default: - /* Only if not a NL or EOF already. */ - return source_skipline(false); - } - } - - /* Do the inclusion. */ - include(source == null ? null : source.getPath(), tok == null ? -1 : tok.getLine(), name, quoted); - - /* 'tok' is the 'nl' after the include. We use it after the - * #line directive. */ - if (getFeature(Feature.LINEMARKERS)) - return line_token(1, source.getName(), " 1"); - return tok; - } - finally { - lexer.setInclude(false); - } - } - - protected void pragma(Token name, List value) - throws IOException, - LexerException { - warning(name, "Unknown #" + "pragma: " + name.getText()); - } - - private Token pragma() - throws IOException, - LexerException { - Token name; - - NAME: for (;;) { - Token tok = token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok, - "End of file in #" + "pragma"); - return tok; - case NL: - /* This may contain one or more newlines. */ - warning(tok, - "Empty #" + "pragma"); - return tok; - case CCOMMENT: - case CPPCOMMENT: - case WHITESPACE: - continue NAME; - case IDENTIFIER: - name = tok; - break NAME; - default: - return source_skipline(false); - } - } - - Token tok; - List value = new ArrayList(); - VALUE: for (;;) { - tok = token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok, - "End of file in #" + "pragma"); - break VALUE; - case NL: - /* This may contain one or more newlines. */ - break VALUE; - case CCOMMENT: - case CPPCOMMENT: - break; - case WHITESPACE: - value.add(tok); - break; - default: - value.add(tok); - break; - } - } - - pragma(name, value); - - return tok; /* The NL. */ - } - - /* For #error and #warning. */ - private void error(Token pptok, boolean is_error) - throws IOException, - LexerException { - StringBuilder buf = new StringBuilder(); - buf.append('#').append(pptok.getText()).append(' '); - /* Peculiar construction to ditch first whitespace. */ - Token tok = source_token_nonwhite(); - ERROR: for (;;) { - switch (tok.getType()) { - case NL: - case EOF: - break ERROR; - default: - buf.append(tok.getText()); - break; - } - tok = source_token(); - } - if (is_error) - error(pptok, buf.toString()); - else - warning(pptok, buf.toString()); - } - - - - - /* This bypasses token() for #elif expressions. - * If we don't do this, then isActive() == false - * causes token() to simply chew the entire input line. */ - private Token expanded_token() - throws IOException, - LexerException { - for (;;) { - Token tok = source_token(); - // System.out.println("Source token is " + tok); - if (tok.getType() == IDENTIFIER) { - Macro m = macros.get(tok.getText()); - if (m == null) - return tok; - if (source.isExpanding(m)) - return tok; - if (macro(m, tok)) - continue; - } - return tok; - } - } - - private Token expanded_token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = expanded_token(); - // System.out.println("expanded token is " + tok); - } while (isWhite(tok)); - return tok; - } - - - private Token expr_token = null; - - private Token expr_token() - throws IOException, - LexerException { - Token tok = expr_token; - - if (tok != null) { - // System.out.println("ungetting"); - expr_token = null; - } - else { - tok = expanded_token_nonwhite(); - // System.out.println("expt is " + tok); - - if (tok.getType() == IDENTIFIER && - tok.getText().equals("defined")) { - Token la = source_token_nonwhite(); - boolean paren = false; - if (la.getType() == '(') { - paren = true; - la = source_token_nonwhite(); - } - - // System.out.println("Core token is " + la); - - if (la.getType() != IDENTIFIER) { - error(la, - "defined() needs identifier, not " + - la.getText()); - tok = new Token(INTEGER, - la.getLine(), la.getColumn(), - "0", Integer.valueOf(0)); - } - else if (macros.containsKey(la.getText())) { - // System.out.println("Found macro"); - tok = new Token(INTEGER, - la.getLine(), la.getColumn(), - "1", Integer.valueOf(1)); - } - else { - // System.out.println("Not found macro"); - tok = new Token(INTEGER, - la.getLine(), la.getColumn(), - "0", Integer.valueOf(0)); - } - - if (paren) { - la = source_token_nonwhite(); - if (la.getType() != ')') { - expr_untoken(la); - error(la, "Missing ) in defined()"); - } - } - } - } - - // System.out.println("expr_token returns " + tok); - - return tok; - } - - private void expr_untoken(Token tok) - throws LexerException { - if (expr_token != null) - throw new InternalException( - "Cannot unget two expression tokens." - ); - expr_token = tok; - } - - private int expr_priority(Token op) { - switch (op.getType()) { - case '/': return 11; - case '%': return 11; - case '*': return 11; - case '+': return 10; - case '-': return 10; - case LSH: return 9; - case RSH: return 9; - case '<': return 8; - case '>': return 8; - case LE: return 8; - case GE: return 8; - case EQ: return 7; - case NE: return 7; - case '&': return 6; - case '^': return 5; - case '|': return 4; - case LAND: return 3; - case LOR: return 2; - case '?': return 1; - default: - // System.out.println("Unrecognised operator " + op); - return 0; - } - } - - private long expr(int priority) - throws IOException, - LexerException { - /* - System.out.flush(); - (new Exception("expr(" + priority + ") called")).printStackTrace(); - System.err.flush(); - */ - - Token tok = expr_token(); - long lhs, rhs; - - // System.out.println("Expr lhs token is " + tok); - - switch (tok.getType()) { - case '(': - lhs = expr(0); - tok = expr_token(); - if (tok.getType() != ')') { - expr_untoken(tok); - error(tok, "missing ) in expression"); - return 0; - } - break; - - case '~': lhs = ~expr(11); break; - case '!': lhs = expr(11) == 0 ? 1 : 0; break; - case '-': lhs = -expr(11); break; - case INTEGER: - lhs = ((Number)tok.getValue()).longValue(); - break; - case CHARACTER: - lhs = (long)((Character)tok.getValue()).charValue(); - break; - case IDENTIFIER: - if (warnings.contains(Warning.UNDEF)) - warning(tok, "Undefined token '" + tok.getText() + - "' encountered in conditional."); - lhs = 0; - break; - - default: - expr_untoken(tok); - error(tok, - "Bad token in expression: " + tok.getText()); - return 0; - } - - EXPR: for (;;) { - // System.out.println("expr: lhs is " + lhs + ", pri = " + priority); - Token op = expr_token(); - int pri = expr_priority(op); /* 0 if not a binop. */ - if (pri == 0 || priority >= pri) { - expr_untoken(op); - break EXPR; - } - rhs = expr(pri); - // System.out.println("rhs token is " + rhs); - switch (op.getType()) { - case '/': - if (rhs == 0) { - error(op, "Division by zero"); - lhs = 0; - } - else { - lhs = lhs / rhs; - } - break; - case '%': - if (rhs == 0) { - error(op, "Modulus by zero"); - lhs = 0; - } - else { - lhs = lhs % rhs; - } - break; - case '*': lhs = lhs * rhs; break; - case '+': lhs = lhs + rhs; break; - case '-': lhs = lhs - rhs; break; - case '<': lhs = lhs < rhs ? 1 : 0; break; - case '>': lhs = lhs > rhs ? 1 : 0; break; - case '&': lhs = lhs & rhs; break; - case '^': lhs = lhs ^ rhs; break; - case '|': lhs = lhs | rhs; break; - - case LSH: lhs = lhs << rhs; break; - case RSH: lhs = lhs >> rhs; break; - case LE: lhs = lhs <= rhs ? 1 : 0; break; - case GE: lhs = lhs >= rhs ? 1 : 0; break; - case EQ: lhs = lhs == rhs ? 1 : 0; break; - case NE: lhs = lhs != rhs ? 1 : 0; break; - case LAND: lhs = (lhs != 0) && (rhs != 0) ? 1 : 0; break; - case LOR: lhs = (lhs != 0) || (rhs != 0) ? 1 : 0; break; - - case '?': - /* XXX Handle this? */ - - default: - error(op, - "Unexpected operator " + op.getText()); - return 0; - - } - } - - /* - System.out.flush(); - (new Exception("expr returning " + lhs)).printStackTrace(); - System.err.flush(); - */ - // System.out.println("expr returning " + lhs); - - return lhs; - } - - private Token toWhitespace(Token tok) { - String text = tok.getText(); - int len = text.length(); - boolean cr = false; - int nls = 0; - - for (int i = 0; i < len; i++) { - char c = text.charAt(i); - - switch (c) { - case '\r': - cr = true; - nls++; - break; - case '\n': - if (cr) { - cr = false; - break; - } - /* fallthrough */ - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - cr = false; - nls++; - break; - } - } - - char[] cbuf = new char[nls]; - Arrays.fill(cbuf, '\n'); - return new Token(WHITESPACE, - tok.getLine(), tok.getColumn(), - new String(cbuf)); - } - - private final Token _token() - throws IOException, - LexerException { - - for (;;) { - Token tok; - if (!isActive()) { - try { - /* XXX Tell lexer to ignore warnings. */ - source.setActive(false); - tok = source_token(); - } - finally { - /* XXX Tell lexer to stop ignoring warnings. */ - source.setActive(true); - } - switch (tok.getType()) { - case HASH: - case NL: - case EOF: - /* The preprocessor has to take action here. */ - break; - case WHITESPACE: - return tok; - case CCOMMENT: - case CPPCOMMENT: - // Patch up to preserve whitespace. - if (getFeature(Feature.KEEPALLCOMMENTS)) - return tok; - if (!isActive()) - return toWhitespace(tok); - if (getFeature(Feature.KEEPCOMMENTS)) - return tok; - return toWhitespace(tok); - default: - // Return NL to preserve whitespace. - /* XXX This might lose a comment. */ - return source_skipline(false); - } - } - else { - tok = source_token(); - } - - LEX: switch (tok.getType()) { - case EOF: - /* Pop the stacks. */ - return tok; - - case WHITESPACE: - case NL: - return tok; - - case CCOMMENT: - case CPPCOMMENT: - return tok; - - case '!': case '%': case '&': - case '(': case ')': case '*': - case '+': case ',': case '-': - case '/': case ':': case ';': - case '<': case '=': case '>': - case '?': case '[': case ']': - case '^': case '{': case '|': - case '}': case '~': case '.': - - /* From Olivier Chafik for Objective C? */ - case '@': - /* The one remaining ASCII, might as well. */ - case '`': - - case '#': - - case AND_EQ: - case ARROW: - case CHARACTER: - case DEC: - case DIV_EQ: - case ELLIPSIS: - case EQ: - case GE: - case HEADER: /* Should only arise from include() */ - case INC: - case LAND: - case LE: - case LOR: - case LSH: - case LSH_EQ: - case SUB_EQ: - case MOD_EQ: - case MULT_EQ: - case NE: - case OR_EQ: - case PLUS_EQ: - case RANGE: - case RSH: - case RSH_EQ: - case STRING: - case XOR_EQ: - return tok; - - case INTEGER: - return tok; - - case IDENTIFIER: - Macro m = macros.get(tok.getText()); - if (m == null) - return tok; - if (source.isExpanding(m)) - return tok; - if (macro(m, tok)) - break; - return tok; - - case P_LINE: - if (getFeature(Feature.LINEMARKERS)) - return tok; - break; - - case INVALID: - if (getFeature(Feature.CSYNTAX)) - error(tok, String.valueOf(tok.getValue())); - return tok; - - default: - throw new InternalException("Bad token " + tok); - // break; - - case HASH: - tok = source_token_nonwhite(); - // (new Exception("here")).printStackTrace(); - switch (tok.getType()) { - case NL: - break LEX; /* Some code has #\n */ - case IDENTIFIER: - break; - default: - error(tok, - "Preprocessor directive not a word " + - tok.getText()); - return source_skipline(false); - } - Integer _ppcmd = ppcmds.get(tok.getText()); - if (_ppcmd == null) { - error(tok, - "Unknown preprocessor directive " + - tok.getText()); - return source_skipline(false); - } - int ppcmd = _ppcmd.intValue(); - - PP: switch (ppcmd) { - - case PP_DEFINE: - if (!isActive()) - return source_skipline(false); - else - return define(); - // break; - - case PP_UNDEF: - if (!isActive()) - return source_skipline(false); - else - return undef(); - // break; - - case PP_INCLUDE: - case PP_IMPORT: - inIncludeNext = false; - if (!isActive()) - return source_skipline(false); - else - return include(false); - // break; - case PP_INCLUDE_NEXT: - inIncludeNext = true; - if (!isActive()) - return source_skipline(false); - if (!getFeature(Feature.INCLUDENEXT)) { - error(tok, - "Directive include_next not enabled" - ); - return source_skipline(false); - } - return include(true); - // break; - - case PP_WARNING: - case PP_ERROR: - if (!isActive()) - return source_skipline(false); - else - error(tok, ppcmd == PP_ERROR); - break; - - case PP_IF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } - expr_token = null; - states.peek().setActive(expr(0) != 0); - tok = expr_token(); /* unget */ - if (tok.getType() == NL) - return tok; - return source_skipline(true); - // break; - - case PP_ELIF: - State state = states.peek(); - if (false) { - /* Check for 'if' */ ; - } - else if (state.sawElse()) { - error(tok, - "#elif after #" + "else"); - return source_skipline(false); - } - else if (!state.isParentActive()) { - /* Nested in skipped 'if' */ - return source_skipline(false); - } - else if (state.isActive()) { - /* The 'if' part got executed. */ - state.setParentActive(false); - /* This is like # else # if but with - * only one # end. */ - state.setActive(false); - return source_skipline(false); - } - else { - expr_token = null; - state.setActive(expr(0) != 0); - tok = expr_token(); /* unget */ - if (tok.getType() == NL) - return tok; - return source_skipline(true); - } - // break; - - case PP_ELSE: - state = states.peek(); - if (false) - /* Check for 'if' */ ; - else if (state.sawElse()) { - error(tok, - "#" + "else after #" + "else"); - return source_skipline(false); - } - else { - state.setSawElse(); - state.setActive(! state.isActive()); - return source_skipline(warnings.contains(Warning.ENDIF_LABELS)); - } - // break; - - case PP_IFDEF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } - else { - tok = source_token_nonwhite(); - // System.out.println("ifdef " + tok); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " + - tok.getText()); - return source_skipline(false); - } - else { - String text = tok.getText(); - boolean exists = - macros.containsKey(text); - states.peek().setActive(exists); - return source_skipline(true); - } - } - // break; - - case PP_IFNDEF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } - else { - tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " + - tok.getText()); - return source_skipline(false); - } - else { - String text = tok.getText(); - boolean exists = - macros.containsKey(text); - states.peek().setActive(!exists); - return source_skipline(true); - } - } - // break; - - case PP_ENDIF: - pop_state(); - return source_skipline(warnings.contains(Warning.ENDIF_LABELS)); - // break; - - case PP_LINE: - return source_skipline(false); - // break; - - case PP_PRAGMA: - if (!isActive()) - return source_skipline(false); - return pragma(); - // break; - - default: - /* Actual unknown directives are - * processed above. If we get here, - * we succeeded the map lookup but - * failed to handle it. Therefore, - * this is (unconditionally?) fatal. */ - // if (isActive()) /* XXX Could be warning. */ - throw new InternalException( - "Internal error: Unknown directive " - + tok); - // return source_skipline(false); - } - - - } - } - } - - private Token token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = _token(); - } while (isWhite(tok)); - return tok; - } - - /** - * Returns the next preprocessor token. - * - * @see Token - * @throws LexerException if a preprocessing error occurs. - * @throws InternalException if an unexpected error condition arises. - */ - public Token token() - throws IOException, - LexerException { - Token tok = _token(); - if (getFeature(Feature.DEBUG)) - System.err.println("pp: Returning " + tok); - return tok; - } - -#set ($i = 1) /* First ppcmd is 1, not 0. */ -#set ($ppcmds = [ "define", "elif", "else", "endif", "error", "if", "ifdef", "ifndef", "include", "line", "pragma", "undef", "warning", "include_next", "import" ]) -#foreach ($ppcmd in $ppcmds) - private static final int PP_$ppcmd.toUpperCase() = $i; -#set ($i = $i + 1) -#end - - private static final Map ppcmds = - new HashMap(); - - static { -#foreach ($ppcmd in $ppcmds) - ppcmds.put("$ppcmd", Integer.valueOf(PP_$ppcmd.toUpperCase())); -#end - } - - - public String toString() { - StringBuilder buf = new StringBuilder(); - - Source s = getSource(); - while (s != null) { - buf.append(" -> ").append(String.valueOf(s)).append("\n"); - s = s.getParent(); - } - - Map macros = getMacros(); - List keys = new ArrayList( - macros.keySet() - ); - Collections.sort(keys); - Iterator mt = keys.iterator(); - while (mt.hasNext()) { - String key = mt.next(); - Macro macro = macros.get(key); - buf.append("#").append("macro ").append(macro).append("\n"); - } - - return buf.toString(); - } - - public void close() - throws IOException { - { - Source s = source; - while (s != null) { - s.close(); - s = s.getParent(); - } - } - for (Source s : inputs) { - s.close(); - } - } - -} diff --git a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Token.java b/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Token.java deleted file mode 100644 index 0dca7ff7e..000000000 --- a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Token.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * A Preprocessor token. - * - * @see Preprocessor - */ -public final class Token { - - // public static final int EOF = -1; - - private int type; - private int line; - private int column; - private Object value; - private String text; - - public Token(int type, int line, int column, - String text, Object value) { - this.type = type; - this.line = line; - this.column = column; - this.text = text; - this.value = value; - } - - public Token(int type, int line, int column, String text) { - this(type, line, column, text, null); - } - - /* pp */ Token(int type, String text, Object value) { - this(type, -1, -1, text, value); - } - - /* pp */ Token(int type, String text) { - this(type, text, null); - } - - /* pp */ Token(int type) { - this(type, type < _TOKENS ? texts[type] : "TOK" + type); - } - - /** - * Returns the semantic type of this token. - */ - public int getType() { - return type; - } - - /* pp */ void setLocation(int line, int column) { - this.line = line; - this.column = column; - } - - /** - * Returns the line at which this token started. - * - * Lines are numbered from zero. - */ - public int getLine() { - return line; - } - - /** - * Returns the column at which this token started. - * - * Columns are numbered from zero. - */ - public int getColumn() { - return column; - } - - /** - * Returns the original or generated text of this token. - * - * This is distinct from the semantic value of the token. - * - * @see #getValue() - */ - public String getText() { - return text; - } - - /** - * Returns the semantic value of this token. - * - * For strings, this is the parsed String. - * For integers, this is an Integer object. - * For other token types, as appropriate. - * - * @see #getText() - */ - public Object getValue() { - return value; - } - - /** - * Returns a description of this token, for debugging purposes. - */ - public String toString() { - StringBuilder buf = new StringBuilder(); - - buf.append('[').append(getTokenName(type)); - if (line != -1) { - buf.append('@').append(line); - if (column != -1) - buf.append(',').append(column); - } - buf.append("]:"); - if (text != null) - buf.append('"').append(text).append('"'); - else if (type > 3 && type < 256) - buf.append( (char)type ); - else - buf.append('<').append(type).append('>'); - if (value != null) - buf.append('=').append(value); - return buf.toString(); - } - - /** - * Returns the descriptive name of the given token type. - * - * This is mostly used for stringification and debugging. - */ - public static final String getTokenName(int type) { - if (type < 0) - return "Invalid" + type; - if (type >= names.length) - return "Invalid" + type; - if (names[type] == null) - return "Unknown" + type; - return names[type]; - } - -#set ($i = 257) -#set ($tokens = [ "AND_EQ", "ARROW", "CHARACTER", "CCOMMENT", "CPPCOMMENT", "DEC", "DIV_EQ", "ELLIPSIS", "EOF", "EQ", "GE", "HASH", "HEADER", "IDENTIFIER", "INC", "INTEGER", "LAND", "LAND_EQ", "LE", "LITERAL", "LOR", "LOR_EQ", "LSH", "LSH_EQ", "MOD_EQ", "MULT_EQ", "NE", "NL", "OR_EQ", "PASTE", "PLUS_EQ", "RANGE", "RSH", "RSH_EQ", "STRING", "SUB_EQ", "WHITESPACE", "XOR_EQ", "M_ARG", "M_PASTE", "M_STRING", "P_LINE", "INVALID" ]) -#foreach ($token in $tokens) - /** The token type $token. */ - public static final int $token = $i; -#set ($i = $i + 1) -#end - /** - * The number of possible semantic token types. - * - * Please note that not all token types below 255 are used. - */ - public static final int _TOKENS = $i; - - /** The position-less space token. */ - /* pp */ static final Token space = new Token(WHITESPACE, -1, -1, " "); - - private static final String[] names = new String[_TOKENS]; - private static final String[] texts = new String[_TOKENS]; - static { - for (int i = 0; i < 255; i++) { - texts[i] = String.valueOf(new char[] { (char)i }); - names[i] = texts[i]; - } - - texts[AND_EQ] = "&="; - texts[ARROW] = "->"; - texts[DEC] = "--"; - texts[DIV_EQ] = "/="; - texts[ELLIPSIS] = "..."; - texts[EQ] = "=="; - texts[GE] = ">="; - texts[HASH] = "#"; - texts[INC] = "++"; - texts[LAND] = "&&"; - texts[LAND_EQ] = "&&="; - texts[LE] = "<="; - texts[LOR] = "||"; - texts[LOR_EQ] = "||="; - texts[LSH] = "<<"; - texts[LSH_EQ] = "<<="; - texts[MOD_EQ] = "%="; - texts[MULT_EQ] = "*="; - texts[NE] = "!="; - texts[NL] = "\n"; - texts[OR_EQ] = "|="; - /* We have to split the two hashes or Velocity eats them. */ - texts[PASTE] = "#" + "#"; - texts[PLUS_EQ] = "+="; - texts[RANGE] = ".."; - texts[RSH] = ">>"; - texts[RSH_EQ] = ">>="; - texts[SUB_EQ] = "-="; - texts[XOR_EQ] = "^="; - -#foreach ($token in $tokens) - names[$token] = "$token"; -#end - } - -} diff --git a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Version.java b/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Version.java deleted file mode 100644 index 549fd39eb..000000000 --- a/libraries/jnaerator/anarres/src/main/velocity/org/anarres/cpp/Version.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2008, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -package org.anarres.cpp; - -/** - * System version metadata for Anarres Java C Preprocessor ${version}. - * - * This class contains a main() and may be run to print the version. - */ -public class Version { - - /* Don't instantiate me */ - private Version() { - } - - private static final String VERSION = "${version}"; - - private static final int major; - private static final int minor; - private static final int patch; - - static { - String[] tmp = VERSION.split("\\."); - major = Integer.parseInt(tmp[0]); - minor = Integer.parseInt(tmp[1]); - String[] patchAndVariant = tmp[2].split("-"); - patch = Integer.parseInt(patchAndVariant[0]); - } - - public static String getVersion() { - return VERSION; - } - - public static int getMajor() { - return major; - } - - public static int getMinor() { - return minor; - } - - public static int getPatch() { - return patch; - } - - public static void main(String[] args) { - System.out.println("Version " + VERSION); - System.out.println("getVersion() returns " + getVersion()); - System.out.println("getMajor() returns " + getMajor()); - System.out.println("getMinor() returns " + getMinor()); - System.out.println("getPatch() returns " + getPatch()); - } - -} diff --git a/libraries/jnaerator/anarres/src/scripts/jcpp b/libraries/jnaerator/anarres/src/scripts/jcpp deleted file mode 100755 index ed167c554..000000000 --- a/libraries/jnaerator/anarres/src/scripts/jcpp +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -CPP_JAR=anarres-cpp.jar - -if [ -n "$CPP_ROOT" ] ; then - CPP_ROOT="$CPP_ROOT" -elif [ -f lib/$CPP_JAR ] ; then - CPP_ROOT="." -elif [ -f ../lib/$CPP_JAR ] ; then - CPP_ROOT=".." -elif [ -f $(dirname $0)/lib/$CPP_JAR ] ; then - CPP_ROOT=$(dirname $0) -else - echo "Could not find $CPP_JAR. Please set CPP_ROOT." - exit 1 -fi - -if [ -z "$CPP_LIB" ] ; then - CPP_LIB=$CPP_ROOT/lib -fi - -if [ -z "$CPP_CLASSPATH" ] ; then - CPP_CLASSPATH="$(ls $CPP_LIB/*.jar | tr '\n' ':')" -fi - -if [ -z "$CPP_MAINCLASS" ] ; then - CPP_MAINCLASS=org.anarres.cpp.Main -fi - -CPP_JFLAGS="-Xmx128M" - -exec java $CPP_JFLAGS -cp "$CPP_CLASSPATH" $CPP_MAINCLASS "$@" diff --git a/libraries/jnaerator/anarres/src/scripts/release.sh b/libraries/jnaerator/anarres/src/scripts/release.sh deleted file mode 100644 index cd88d9586..000000000 --- a/libraries/jnaerator/anarres/src/scripts/release.sh +++ /dev/null @@ -1,5 +0,0 @@ -rsync -avP build/dist/anarres-cpp-*.tar.gz shevek@pink.anarres.org:public_html/projects/jcpp/ -rsync -avP --exclude=.svn --exclude=autohandler build/javadoc shevek@pink.anarres.org:public_html/projects/jcpp/ -cp build/tar/lib/anarres-cpp.jar /home/shevek/java/iengine/trunk/lib/runtime/jcpp/ -cp build/tar/lib/anarres-cpp.jar /home/shevek/java/karma/trunk/lib/dp/ -cp build/tar/lib/anarres-cpp.jar /home/shevek/java/dp/trunk/lib/runtime/cpp/ diff --git a/libraries/jnaerator/anarres/src/test/java/AutoTestSuite.java b/libraries/jnaerator/anarres/src/test/java/AutoTestSuite.java deleted file mode 100644 index 894a365e3..000000000 --- a/libraries/jnaerator/anarres/src/test/java/AutoTestSuite.java +++ /dev/null @@ -1,121 +0,0 @@ -import java.lang.reflect.Modifier; - -import java.io.File; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Test; - -public class AutoTestSuite extends TestSuite { - private String testPackage; - private Set testCases; - private boolean testAll; - private File root; - - public AutoTestSuite() { - this.testPackage = System.getProperty("test.package"); - String tcase = System.getProperty("test.case"); - if (tcase != null && tcase.length() > 0) { - this.testCases = new HashSet(Arrays.asList( - tcase.split("[,:]") - )); - } - else { - this.testCases = null; - } - this.testAll = System.getProperty("test.all") != null; - this.root = new File(System.getProperty("test.root")); - - Set tests = new HashSet(); - - findClasses("", root, tests); - - Iterator i = tests.iterator(); - - while(i.hasNext()) { - addTestSuite(i.next()); - } - } - - public void addTestSuite(Class clazz) { - if (testPackage != null) { - String name = clazz.getPackage().getName(); - if (!name.startsWith(testPackage)) { - /* - System.out.println("Skipping test in package '" + - name + "' - does not start with '" + - testPackage + "'"); - */ - return; - } - } - if (testCases != null) { - String name = clazz.getName(); - name = name.substring(name.lastIndexOf('.') + 1); - if (!testCases.contains(name)) { - /* - System.out.println("Skipping test in class '" + - name + "' - does not start with '" + - testCases + "'"); - */ - return; - } - } - /* - if ( - testCases == null && - testPackage == null && - !testAll && - Optional.class.isAssignableFrom(clazz) - ) - { - return; - } - */ - System.out.println("Adding test class '" + clazz + "'"); - super.addTestSuite(clazz); - } - - public static Test suite() { - return new AutoTestSuite(); - } - - private final void findClasses(String pkg, File root, Set result) { - File[] children = root.listFiles(); - for(int i = 0; i 0 || - (modifiers & Modifier.INTERFACE) > 0 || - !TestCase.class.isAssignableFrom(test) || - TestSuite.class.isAssignableFrom(test) - ) - continue; - result.add(test); - } catch (ClassNotFoundException cnfe) { - cnfe.printStackTrace(); - } - } - } - } - } -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/BaseTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/BaseTestCase.java deleted file mode 100644 index ad6ae6a12..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/BaseTestCase.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.anarres.cpp; - -import junit.framework.TestCase; - -public abstract class BaseTestCase extends TestCase { -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/CppReaderTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/CppReaderTestCase.java deleted file mode 100644 index 3e54472c1..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/CppReaderTestCase.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.anarres.cpp; - -import java.util.Collections; - -import java.io.StringReader; -import java.io.BufferedReader; - -import junit.framework.Test; - -public class CppReaderTestCase extends BaseTestCase implements Test { - - private void testCppReader(String in, String out) - throws Exception { - System.out.println("Testing " + in + " => " + out); - StringReader r = new StringReader(in); - CppReader p = new CppReader(r); - p.getPreprocessor().setSystemIncludePath( - Collections.singletonList("src/test/resources/input") - ); - p.getPreprocessor().getFeatures().add(Feature.LINEMARKERS); - BufferedReader b = new BufferedReader(p); - - String line; - while ((line = b.readLine()) != null) { - System.out.println(" >> " + line); - } - } - - public void testCppReader() - throws Exception { - testCppReader("#include \n", "ab"); - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/ErrorTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/ErrorTestCase.java deleted file mode 100644 index 24bdf61ee..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/ErrorTestCase.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.anarres.cpp; - -import java.io.*; - -import junit.framework.Test; - -import static org.anarres.cpp.Token.*; - -public class ErrorTestCase extends BaseTestCase { - - private boolean testError(Preprocessor p) - throws LexerException, - IOException { - for (;;) { - Token tok = p.token(); - if (tok.getType() == EOF) - break; - if (tok.getType() == INVALID) - return true; - } - return false; - } - - private void testError(String input) throws Exception { - StringLexerSource sl; - PreprocessorListener pl; - Preprocessor p; - - /* Without a PreprocessorListener, throws an exception. */ - sl = new StringLexerSource(input, true); - p = new Preprocessor(); - p.addFeature(Feature.CSYNTAX); - p.addInput(sl); - try { - assertTrue(testError(p)); - fail("Lexing unexpectedly succeeded without listener."); - } - catch (LexerException e) { - /* required */ - } - - /* With a PreprocessorListener, records the error. */ - sl = new StringLexerSource(input, true); - p = new Preprocessor(); - p.addFeature(Feature.CSYNTAX); - p.addInput(sl); - pl = new PreprocessorListener(); - p.setListener(pl); - assertNotNull("CPP has listener", p.getListener()); - assertTrue(testError(p)); - assertTrue("Listener has errors", pl.getErrors() > 0); - - /* Without CSYNTAX, works happily. */ - sl = new StringLexerSource(input, true); - p = new Preprocessor(); - p.addInput(sl); - assertTrue(testError(p)); - } - - public void testErrors() throws Exception { - testError("\""); - testError("'"); - testError("''"); - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JavaFileSystemTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JavaFileSystemTestCase.java deleted file mode 100644 index 4f68d6894..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JavaFileSystemTestCase.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.anarres.cpp; - -import java.io.*; - -import junit.framework.Test; - -import static org.anarres.cpp.Token.*; - -public class JavaFileSystemTestCase extends BaseTestCase { - - public void testJavaFileSystem() throws Exception { - JavaFileSystem fs = new JavaFileSystem(); - VirtualFile f; - - /* Anyone who has this file on their Unix box is messed up. */ - f = fs.getFile("/foo/bar baz"); - try { - f.getSource(); /* drop on floor */ - assertTrue("Got a source for a non-file", f.isFile()); - } - catch (FileNotFoundException e) { - assertFalse("Got no source for a file", f.isFile()); - } - - /* We hope we have this. */ - f = fs.getFile("/usr/include/stdio.h"); - try { - f.getSource(); /* drop on floor */ - System.out.println("Opened stdio.h"); - assertTrue("Got a source for a non-file", f.isFile()); - } - catch (FileNotFoundException e) { - System.out.println("Failed to open stdio.h"); - assertFalse("Got no source for a file", f.isFile()); - } - - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JoinReaderTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JoinReaderTestCase.java deleted file mode 100644 index 6c1144918..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/JoinReaderTestCase.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.anarres.cpp; - -import java.io.StringReader; - -import junit.framework.Test; - -public class JoinReaderTestCase extends BaseTestCase implements Test { - - private void testJoinReader(String in, String out, boolean tg) - throws Exception { - System.out.println("Testing " + in + " => " + out); - StringReader r = new StringReader(in); - JoinReader j = new JoinReader(r, tg); - - for (int i = 0; i < out.length(); i++) { - int c = j.read(); - System.out.println("At offset " + i + ": " + (char)c); - assertEquals((char)out.charAt(i), c); - } - assertEquals(-1, j.read()); - assertEquals(-1, j.read()); - } - - private void testJoinReader(String in, String out) - throws Exception { - testJoinReader(in, out, true); - testJoinReader(in, out, false); - } - - public void testJoinReader() - throws Exception { - testJoinReader("ab", "ab"); - testJoinReader("a\\b", "a\\b"); - testJoinReader("a\nb", "a\nb"); - testJoinReader("a\\\nb", "ab\n"); - testJoinReader("foo??(bar", "foo[bar", true); - testJoinReader("foo??/\nbar", "foobar\n", true); - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/LexerSourceTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/LexerSourceTestCase.java deleted file mode 100644 index 7fa788c13..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/LexerSourceTestCase.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.anarres.cpp; - -import java.io.StringReader; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import junit.framework.Test; - -import static org.anarres.cpp.Token.*; - -public class LexerSourceTestCase extends BaseTestCase implements Test { - - private void testLexerSource(String in, int... out) - throws Exception { - System.out.println("Testing '" + in + "' => " + - Arrays.toString(out)); - StringLexerSource s = new StringLexerSource(in); - - for (int i = 0; i < out.length; i++) { - Token tok = s.token(); - System.out.println("Token is " + tok); - assertEquals(out[i], tok.getType()); - } - assertEquals(EOF, s.token().getType()); - } - - public void testLexerSource() - throws Exception { - - testLexerSource("int a = 5;", - IDENTIFIER, WHITESPACE, IDENTIFIER, WHITESPACE, - '=', WHITESPACE, INTEGER, ';', EOF - ); - - // \n is WHITESPACE because ppvalid = false - testLexerSource("# # \r\n\n\r \rfoo", - HASH, WHITESPACE, '#', WHITESPACE, IDENTIFIER - ); - - testLexerSource("%:%:", PASTE); - testLexerSource("%:?", '#', '?'); - testLexerSource("%:%=", '#', MOD_EQ); - testLexerSource("0x1234ffdUL 0765I", - INTEGER, WHITESPACE, INTEGER); - - testLexerSource("+= -= *= /= %= <= >= >>= <<= &= |= ^= x", - PLUS_EQ, WHITESPACE, - SUB_EQ, WHITESPACE, - MULT_EQ, WHITESPACE, - DIV_EQ, WHITESPACE, - MOD_EQ, WHITESPACE, - LE, WHITESPACE, - GE, WHITESPACE, - RSH_EQ, WHITESPACE, - LSH_EQ, WHITESPACE, - AND_EQ, WHITESPACE, - OR_EQ, WHITESPACE, - XOR_EQ, WHITESPACE, - IDENTIFIER); - - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/MainTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/MainTestCase.java deleted file mode 100644 index 313a463af..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/MainTestCase.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.anarres.cpp; - -import java.io.*; - -import junit.framework.Test; - -import static org.anarres.cpp.Token.*; - -public class MainTestCase extends BaseTestCase { - - public void testMain() throws Exception { - Main.main(new String[] { "--version" }); - } - -} diff --git a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/PreprocessorTestCase.java b/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/PreprocessorTestCase.java deleted file mode 100644 index 1b7b32398..000000000 --- a/libraries/jnaerator/anarres/src/test/java/org/anarres/cpp/PreprocessorTestCase.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.anarres.cpp; - -import java.io.*; - -import junit.framework.Test; - -import static org.anarres.cpp.Token.*; - -public class PreprocessorTestCase extends BaseTestCase { - private OutputStreamWriter writer; - private Preprocessor p; - - public void setUp() throws Exception { - final PipedOutputStream po = new PipedOutputStream(); - writer = new OutputStreamWriter(po); - - p = new Preprocessor(); - p.addInput( - new LexerSource( - new InputStreamReader( - new PipedInputStream(po) - ), - true - ) - ); - } - - private static class I { - private String t; - public I(String t) { - this.t = t; - } - public String getText() { - return t; - } - public String toString() { - return getText(); - } - } - - private static I I(String t) { - return new I(t); - } - -/* - * When writing tests in this file, remember the preprocessor - * stashes NLs, so you won't see an immediate NL at the end of any - * input line. You will see it right before the next nonblank on - * the following input line. - */ - - public void testPreprocessor() throws Exception { - /* Magic macros */ - testInput("line = __LINE__\n", - I("line"), WHITESPACE, '=', WHITESPACE, INTEGER - /*, NL - all nls deferred so as not to block the reader */ - ); - testInput("file = __FILE__\n", NL, /* from before, etc */ - I("file"), WHITESPACE, '=', WHITESPACE, STRING - ); - - /* Simple definitions */ - testInput("#define A a /* a defined */\n", NL); - testInput("#define B b /* b defined */\n", NL); - testInput("#define C c /* c defined */\n", NL); - - /* Expansion of arguments */ - testInput("#define EXPAND(x) x\n", NL); - testInput("EXPAND(a)\n", NL, I("a")); - testInput("EXPAND(A)\n", NL, I("a")); - - /* Stringification */ - testInput("#define _STRINGIFY(x) #x\n", NL); - testInput("_STRINGIFY(A)\n", NL, "A"); - testInput("#define STRINGIFY(x) _STRINGIFY(x)\n", NL); - testInput("STRINGIFY(b)\n", NL, "b"); - testInput("STRINGIFY(A)\n", NL, "a"); - - /* Concatenation */ - testInput("#define _CONCAT(x, y) x ## y\n", NL); - testInput("_CONCAT(A, B)\n", NL, I("AB")); - testInput("#define A_CONCAT done_a_concat\n", NL); - testInput("_CONCAT(A, _CONCAT(B, C))\n", NL, - I("done_a_concat"), '(', I("b"), ',', WHITESPACE, I("c"), ')' - ); - testInput("#define CONCAT(x, y) _CONCAT(x, y)\n", NL); - testInput("CONCAT(A, CONCAT(B, C))\n", NL, I("abc")); - testInput("#define _CONCAT3(x, y, z) x ## y ## z\n", NL); - testInput("_CONCAT3(a, b, c)\n", NL, I("abc")); - testInput("_CONCAT3(A, B, C)\n", NL, I("ABC")); - -/* Redefinitions, undefinitions. */ -testInput("#define two three\n", NL); -testInput("one /* one */\n", NL, I("one"), WHITESPACE, CCOMMENT); -testInput("#define one two\n", NL); -testInput("one /* three */\n", NL, I("three"), WHITESPACE, CCOMMENT); -testInput("#undef two\n", NL); -testInput("#define two five\n", NL); -testInput("one /* five */\n", NL, I("five"), WHITESPACE, CCOMMENT); -testInput("#undef two\n", NL); -testInput("one /* two */\n", NL, I("two"), WHITESPACE, CCOMMENT); -testInput("#undef one\n", NL); -testInput("#define one four\n", NL); -testInput("one /* four */\n", NL, I("four"), WHITESPACE, CCOMMENT); -testInput("#undef one\n", NL); -testInput("#define one one\n", NL); -testInput("one /* one */\n", NL, I("one"), WHITESPACE, CCOMMENT); - - /* Variadic macros. */ - testInput("#define var(x...) a x b\n", NL); - testInput("#define var(...) a __VA_ARGS__ b\n", NL); - testInput("var(e, f, g)\n", NL, - I("a"), WHITESPACE, - I("e"), ',', WHITESPACE, - I("f"), ',', WHITESPACE, - I("g"), WHITESPACE, - I("b") - ); - - testInput("#define _Widen(x) L ## x\n", NL); - testInput("#define Widen(x) _Widen(x)\n", NL); - testInput("#define LStr(x) _Widen(#x)\n", NL); - testInput("LStr(x);\n", NL, I("L"), "x"); - - writer.close(); - - Token t; - do { - t = p.token(); - System.out.println("Remaining token " + t); - } while(t.getType() != EOF); - } - - private void testInput(String in, Object... out) - throws Exception { - System.out.print("Input: " + in); - writer.write(in); - writer.flush(); - for (int i = 0; i < out.length; i++) { - Token t = p.token(); - System.out.println(t); - Object v = out[i]; - if (v instanceof String) { - if (t.getType() != STRING) - fail("Expected STRING, but got " + t); - assertEquals((String)v, (String)t.getValue()); - } - else if (v instanceof I) { - if (t.getType() != IDENTIFIER) - fail("Expected IDENTIFIER " + v + ", but got " + t); - assertEquals( ((I)v).getText(), (String)t.getText()); - } - else if (v instanceof Character) - assertEquals( (int)((Character)v).charValue(), t.getType()); - else if (v instanceof Integer) - assertEquals( ((Integer)v).intValue(), t.getType()); - else - fail("Bad object " + v.getClass()); - } - } -} diff --git a/libraries/jnaerator/anarres/src/test/resources/input/test0.c b/libraries/jnaerator/anarres/src/test/resources/input/test0.c deleted file mode 100644 index 150b75995..000000000 --- a/libraries/jnaerator/anarres/src/test/resources/input/test0.c +++ /dev/null @@ -1,61 +0,0 @@ -line = __LINE__ -file = __FILE__ - -#define A a /* a defined */ -#define B b /* b defined */ -#define C c /* c defined */ - -#define EXPAND(x) x -EXPAND(a) -> a -EXPAND(A) -> a - -#define _STRINGIFY(x) #x -_STRINGIFY(A) -> "A" - -#define STRINGIFY(x) _STRINGIFY(x) -STRINGIFY(b) -> "b" -STRINGIFY(A) -> "a" - -#define _CONCAT(x, y) x ## y -_CONCAT(A, B) -> AB - -#define A_CONCAT done_a_concat -_CONCAT(A, _CONCAT(B, C)) -> done_a_concat(b, c) - -#define CONCAT(x, y) _CONCAT(x, y) -CONCAT(A, CONCAT(B, C)) -> abc - -#define _CONCAT3(x, y, z) x ## y ## z -_CONCAT3(a, b, c) -> abc -_CONCAT3(A, B, C) -> ABC -_CONCAT3(A, EXPAND(B), C) -> AEXPAND(b)C - -Line is __LINE__ -File is __FILE__ - -#define two three -one /* one */ -#define one two -one /* three */ -#undef two -#define two five -one /* five */ -#undef two -one /* two */ -#undef one -#define one four -one /* four */ -#undef one -#define one one -one /* one */ - -/* warning line 57 column 0 */ -#warning arse - -#define foo(x) foo(x, b) -foo(1) -> _foo(1, b) without the _ -foo(foo(2)) -> _foo(_foo(2, b), b) without the _ -foo(y, z) - -#define var(x...) a x b -var(e, f, g) -> a e, f, g b diff --git a/libraries/jnaerator/anarres/src/test/resources/input/test0.h b/libraries/jnaerator/anarres/src/test/resources/input/test0.h deleted file mode 100644 index b6697c633..000000000 --- a/libraries/jnaerator/anarres/src/test/resources/input/test0.h +++ /dev/null @@ -1,7 +0,0 @@ - -test0start_2 - -#include "test1.h" - -test0end___6 - diff --git a/libraries/jnaerator/anarres/src/test/resources/input/test1.c b/libraries/jnaerator/anarres/src/test/resources/input/test1.c deleted file mode 100644 index 3e6fbda66..000000000 --- a/libraries/jnaerator/anarres/src/test/resources/input/test1.c +++ /dev/null @@ -1,2 +0,0 @@ -#include "./test0.h" -#include diff --git a/libraries/jnaerator/anarres/src/test/resources/input/test1.h b/libraries/jnaerator/anarres/src/test/resources/input/test1.h deleted file mode 100644 index 0b690f745..000000000 --- a/libraries/jnaerator/anarres/src/test/resources/input/test1.h +++ /dev/null @@ -1,7 +0,0 @@ - -test1start_2 - -test1mid___4 - -test1end___6 - diff --git a/libraries/jnaerator/anarres/src/test/resources/input/trigraph.c b/libraries/jnaerator/anarres/src/test/resources/input/trigraph.c deleted file mode 100644 index 89615fe58..000000000 --- a/libraries/jnaerator/anarres/src/test/resources/input/trigraph.c +++ /dev/null @@ -1 +0,0 @@ -??/ diff --git a/libraries/jnaerator/bin/jnaerator.jar b/libraries/jnaerator/bin/jnaerator.jar deleted file mode 100644 index 77cb89c3f..000000000 Binary files a/libraries/jnaerator/bin/jnaerator.jar and /dev/null differ diff --git a/libraries/jnaerator/jna-jnaerator/.classpath b/libraries/jnaerator/jna-jnaerator/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/jna-jnaerator/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/jna-jnaerator/.gitignore b/libraries/jnaerator/jna-jnaerator/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/jna-jnaerator/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/jna-jnaerator/.project b/libraries/jnaerator/jna-jnaerator/.project deleted file mode 100644 index 29cc90e1d..000000000 --- a/libraries/jnaerator/jna-jnaerator/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - jna-jnaerator - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/jna-jnaerator/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/jna-jnaerator/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 44e29c762..000000000 --- a/libraries/jnaerator/jna-jnaerator/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:08 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/jna-jnaerator/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/jna-jnaerator/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/jna-jnaerator/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/jna-jnaerator/pom.xml b/libraries/jnaerator/jna-jnaerator/pom.xml deleted file mode 100644 index 9f0cb045e..000000000 --- a/libraries/jnaerator/jna-jnaerator/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - 4.0.0 - com.nativelibs4java - jna-jnaerator - JNAerator's Patched JNA Library - http://code.google.com/p/jnaerator/ - jar - - - false - - - - - net.java.dev.jna - jna - - - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - diff --git a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/BitFields.java b/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/BitFields.java deleted file mode 100644 index 53da22c4b..000000000 --- a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/BitFields.java +++ /dev/null @@ -1,469 +0,0 @@ -/* - * Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - *

      - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - */ -package com.sun.jna; - -import java.math.BigInteger; -import java.nio.ByteOrder; -import java.util.IdentityHashMap; -import java.util.Map; - -/** - * Support for C bit fields - * @author Olivier Chafik - */ -public class BitFields { - private static abstract class PrimHandler { - abstract long longValue(Object value); - abstract Object objectValue(long value); - abstract void writeLong(Pointer p, long offset, long value); - abstract long readLong(Pointer p, long offset); - abstract int size(); - abstract void writeObject(Pointer pointer, long offset, Object value); - abstract Object readObject(Pointer p, long offset); - boolean supportsBitOffset() { - return true; - } - boolean supportsBitLength() { - return true; - } - } - private static abstract class NonIntHandler extends PrimHandler { - public void writeLong(Pointer p, long offset, long value) { - throw new UnsupportedOperationException(); - } - public long readLong(Pointer p, long offset) { - throw new UnsupportedOperationException(); - } - public Object objectValue(long value) { - throw new UnsupportedOperationException(); - } - public long longValue(Object value) { - throw new UnsupportedOperationException(); - } - public boolean supportsBitLength() { - return false; - } - } - private static final class StringHandler extends NonIntHandler { - final boolean wide; - public StringHandler(boolean wide) { - this.wide = wide; - } - public Object readObject(Pointer p, long offset) { - p = p.getPointer(offset); - return p != null ? wide ? (Object)new WString(p.getString(0, true)) : (Object)p.getString(0) : null; - } - public int size() { - return Native.POINTER_SIZE; - } - - - public void writeObject(Pointer pointer, long offset, Object value) { - pointer.setPointer(offset, (Pointer)value); - } - - } - private static final PrimHandler - INT_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setInt(offset, (int)value); - } - public long readLong(Pointer p, long offset) { - return p.getInt(offset); - } - public Object objectValue(long value) { - return new Integer((int)value); - } - public long longValue(Object value) { - return ((Integer)value).longValue(); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setInt(offset, value == null ? 0 : ((Integer)value).intValue()); - } - public Object readObject(Pointer p, long offset) { - return new Integer(p.getInt(offset)); - } - public int size() { - return 4; - } - }, - LONG_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setLong(offset, value); - } - public long readLong(Pointer p, long offset) { - return p.getLong(offset); - } - public Object objectValue(long value) { - return new Long(value); - } - public long longValue(Object value) { - return ((Long)value).longValue(); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setLong(offset, value == null ? 0 : ((Long)value).longValue()); - } - public Object readObject(Pointer p, long offset) { - return new Long(p.getLong(offset)); - } - public int size() { - return 8; - } - }, - SHORT_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setShort(offset, (short)value); - } - public long readLong(Pointer p, long offset) { - return p.getShort(offset); - } - public Object objectValue(long value) { - return new Short((short)value); - } - public long longValue(Object value) { - return ((Short)value).longValue(); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setShort(offset, value == null ? 0 : ((Short)value).shortValue()); - } - public Object readObject(Pointer p, long offset) { - return new Short(p.getShort(offset)); - } - public int size() { - return 2; - } - }, - BYTE_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setByte(offset, (byte)value); - } - public long readLong(Pointer p, long offset) { - return p.getByte(offset); - } - public Object objectValue(long value) { - return new Byte((byte)value); - } - public long longValue(Object value) { - return ((Byte)value).longValue(); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setByte(offset, value == null ? 0 : ((Byte)value).byteValue()); - } - public Object readObject(Pointer p, long offset) { - return new Byte(p.getByte(offset)); - } - public int size() { - return 1; - } - }, - CHAR_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setChar(offset, (char)value); - } - public long readLong(Pointer p, long offset) { - return p.getChar(offset); - } - public Object objectValue(long value) { - return new Character((char)value); - } - public long longValue(Object value) { - return ((Character)value).charValue(); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setChar(offset, value == null ? (char)0 : ((Character)value).charValue()); - } - public Object readObject(Pointer p, long offset) { - return new Character(p.getChar(offset)); - } - public int size() { - return 2; - } - }, - BOOL_HANDLER = new PrimHandler() { - public void writeLong(Pointer p, long offset, long value) { - p.setByte(offset, (byte)value); - } - public long readLong(Pointer p, long offset) { - return p.getByte(offset); - } - public Object objectValue(long value) { - return ((byte)value) == 0 ? Boolean.FALSE : Boolean.TRUE; - } - public long longValue(Object value) { - return ((Boolean)value).booleanValue() ? -1 : 0; - } - public void writeObject(Pointer p, long offset, Object value) { - p.setByte(offset, value == null ? 0 : (byte)(Boolean.TRUE.equals(value) ? -1 : 0)); - } - public Object readObject(Pointer p, long offset) { - return p.getByte(offset) == 0 ? Boolean.FALSE : Boolean.TRUE; - } - public int size() { - return 1; - } - }, - DOUBLE_HANDLER = new NonIntHandler() { - public long readLong(Pointer p, long offset) { - return p.getLong(offset); - } - public void writeLong(Pointer p, long offset, long value) { - p.setLong(offset, value); - } - public long longValue(Object value) { - return Double.doubleToRawLongBits(((Double)value).doubleValue()); - } - public Object objectValue(long value) { - return new Double(Double.longBitsToDouble((long)value)); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setDouble(offset, value == null ? 0 : ((Double)value).doubleValue()); - } - public Object readObject(Pointer p, long offset) { - return new Double(p.getDouble(offset)); - } - public int size() { - return 8; - } - }, - FLOAT_HANDLER = new NonIntHandler() { - public long readLong(Pointer p, long offset) { - return p.getInt(offset); - } - public void writeLong(Pointer p, long offset, long value) { - p.setInt(offset, (int)value); - } - public long longValue(Object value) { - return Float.floatToRawIntBits(((Float)value).floatValue()); - } - public Object objectValue(long value) { - return new Float(Float.intBitsToFloat((int)value)); - } - public void writeObject(Pointer p, long offset, Object value) { - p.setFloat(offset, value == null ? 0 : ((Float)value).floatValue()); - } - public Object readObject(Pointer p, long offset) { - return new Float(p.getFloat(offset)); - } - public int size() { - return 4; - } - }, -// POINTER_HANDLER = new NonIntHandler() { -// public void writeObject(Pointer p, long offset, Object value) { -// p.setPointer(offset, ((Pointer)value)); -//} -//public Object readObject(Pointer p, long offset) { -// return p.getPointer(offset); -//} -//public int size() { -// return Native.POINTER_SIZE; -//} -//} - STRING_HANDLER = new StringHandler(false), - WSTRING_HANDLER = new StringHandler(true) - ; - - private static final Map, PrimHandler> primHandlers = new IdentityHashMap, PrimHandler>(10); - static { - primHandlers.put(Integer.TYPE, INT_HANDLER); - primHandlers.put(Integer.class, INT_HANDLER); - - primHandlers.put(Long.TYPE, LONG_HANDLER); - primHandlers.put(Long.class, LONG_HANDLER); - - primHandlers.put(Short.TYPE, SHORT_HANDLER); - primHandlers.put(Short.class, SHORT_HANDLER); - - primHandlers.put(Byte.TYPE, BYTE_HANDLER); - primHandlers.put(Byte.class, BYTE_HANDLER); - - primHandlers.put(Character.TYPE, CHAR_HANDLER); - primHandlers.put(Character.class, CHAR_HANDLER); - - primHandlers.put(Boolean.TYPE, BOOL_HANDLER); - primHandlers.put(Boolean.class, BOOL_HANDLER); - - primHandlers.put(Float.TYPE, FLOAT_HANDLER); - primHandlers.put(Float.class, FLOAT_HANDLER); - - primHandlers.put(Double.TYPE, DOUBLE_HANDLER); - primHandlers.put(Double.class, DOUBLE_HANDLER); - -// primHandlers.put(Pointer.class, POINTER_HANDLER); - primHandlers.put(String.class, STRING_HANDLER); - primHandlers.put(WString.class, WSTRING_HANDLER); - } - private static PrimHandler getHandlerWithAtLeastNBytes(final int n) { - switch (n) { - case 1: - return BYTE_HANDLER; - case 2: - return SHORT_HANDLER; - case 3: - case 4: - return INT_HANDLER; - case 5: - case 6: - case 7: - case 8: - return LONG_HANDLER; - default: - return null; - //throw new UnsupportedOperationException("TODO No handler for " + n + " bytes !"); - } - } - - private static PrimHandler getPrimHandler(Class type, int bitOffset, int bits) { - PrimHandler handler = (PrimHandler)primHandlers.get(type); -// if (handler == null && Pointer.class.isAssignableFrom(type)) -// handler = (PrimHandler)primHandlers.get(Pointer.class); - if (handler == null && (bitOffset | bits) != 0 || - handler != null && ( - !handler.supportsBitOffset() && (bitOffset != 0) || - !handler.supportsBitLength() && (bits != 0) - ) - ) - throw new UnsupportedOperationException("Bit fields only support integral fields !!!"); - //if ((bits & ~63) != 0) - // throw new UnsupportedOperationException("Bit fields cannot be larger than 64 bits !!!"); - - return handler; - } - - static void print(BigInteger bi) { - for (int i = 0, len = bi.bitLength(); i < len; i++) - System.out.print(bi.testBit(i) ? '1' : '0'); - System.out.println(); - } - private static BigInteger shiftedMask(int bits, int bitOffset) { - BigInteger mask = BigInteger.valueOf(bits == 0 ? 0 : 1L); - if (bits != 0) - mask = mask.shiftLeft(bits); - mask = mask.subtract(BigInteger.valueOf(1)); - if (bitOffset != 0) { - mask = mask.shiftLeft(bitOffset); - // Fix sign extension : - for (int i = 0; i < bitOffset; i++) - mask.clearBit(i); - } - return mask; - } - - private static byte[] getBigEndianByteArray(Pointer pointer, long offset, int bytesToFetch) { - byte[] bs = pointer.getByteArray(offset, bytesToFetch); - if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) - revert(bs); - return bs; - } - private static void setBigEndianByteArray(Pointer pointer, long offset, byte[] bs) { - if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) - revert(bs); - pointer.write(offset, bs, 0, bs.length); - } - private static void revert(byte[] bs) { - for (int i = 0, len = bs.length, sup = len >>> 1; i < sup; i++) { - int j = len - i - 1; - - byte t = bs[i]; - bs[i] = bs[j]; - bs[j] = t; - } - } - public static final Object UNHANDLED_TYPE = new Object() {}; - - public static boolean setPrimitiveValue(Pointer pointer, long offset, int bitOffset, int bits, Object value, Class type) { - PrimHandler handler = getPrimHandler(type, bitOffset, bits); - if (handler == null) - return false; - - if ((bitOffset | bits) == 0) { - handler.writeObject(pointer, offset, value); - return true; - } - - if (bits <= 0) - bits = handler.size() << 3; - - // Read existing alien bits to OR them, - // and make sure we read/write bits up to bits + bitOffset - // (may need to use larger type than that of the value for read operation) - int bitLen = bits + bitOffset; - int bytesToFetch = (bitLen >> 3) + ((bitLen & 7) == 0 ? 0 : 1); - PrimHandler io = getHandlerWithAtLeastNBytes(bytesToFetch); - if (io != null) { - long longValue = handler.longValue(value); - longValue <<= bitOffset; - - long existing = io.readLong(pointer, offset); - if (bits != 0) { - long mask = ((1L << bits) - 1) << bitOffset; - longValue &= mask; - existing &= ~mask; - } - longValue |= existing; - io.writeLong(pointer, offset, longValue); - } else { - BigInteger bigValue = BigInteger.valueOf(handler.longValue(value)); - bigValue = bigValue.shiftLeft(bitOffset); - - byte[] bs = getBigEndianByteArray(pointer, offset, bytesToFetch); - BigInteger existing = new BigInteger(bs); - BigInteger mask = shiftedMask(bits, bitOffset); - bigValue = bigValue.and(mask); - existing = existing.and(mask.not()); - bigValue = bigValue.or(existing); - - setBigEndianByteArray(pointer, offset, bigValue.toByteArray()); - } - return true; - } - public static Object getPrimitiveValue(Pointer pointer, long offset, int bitOffset, int bits, Class type) { - PrimHandler handler = getPrimHandler(type, bitOffset, bits); - if (handler == null) - return UNHANDLED_TYPE; - - if ((bitOffset | bits) == 0) - return handler.readObject(pointer, offset); - - if (bits <= 0) - bits = handler.size() << 3; - - // Read bits to up to bits + bitOffset - 1 - int bitLen = bits + bitOffset; - int bytesToFetch = (bitLen >> 3) + ((bitLen & 7) == 0 ? 0 : 1); - - long longValue; - PrimHandler io = getHandlerWithAtLeastNBytes(bytesToFetch); - if (io != null) { - longValue = io.readLong(pointer, offset); - longValue >>= bitOffset; - if (bits != 0) { - long mask = (1L << bits) - 1; - longValue &= mask; - } - } else { - BigInteger bigValue = new BigInteger(getBigEndianByteArray(pointer, offset, bytesToFetch)); - bigValue = bigValue.shiftRight(bitOffset); - if (bits != 0) { - BigInteger mask = shiftedMask(bits, 0); - bigValue = bigValue.and(mask); - } - longValue = bigValue.longValue(); - } - return handler.objectValue(longValue); - } - - -} - diff --git a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/CallbackReferenceHack.java b/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/CallbackReferenceHack.java deleted file mode 100644 index 2995eda27..000000000 --- a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/CallbackReferenceHack.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.sun.jna; - -public class CallbackReferenceHack { - public static Callback getCallback(Class type, Pointer p) { - return CallbackReference.getCallback(type, p); - } - public static Pointer getFunctionPointer(Callback cb) { - return CallbackReference.getFunctionPointer(cb); - } -} diff --git a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Pointer.java b/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Pointer.java deleted file mode 100644 index 623a95900..000000000 --- a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Pointer.java +++ /dev/null @@ -1,1290 +0,0 @@ -/* This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - *

      - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - */ -package com.sun.jna; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.List; - -/** - * An abstraction for a native pointer data type. A Pointer instance - * represents, on the Java side, a native pointer. The native pointer could - * be any type of native pointer. Methods such as write, - * read, getXXX, and setXXX, provide - * means to access memory underlying the native pointer.

      - * The constructors are intentionally package-private, since it's not generally - * a good idea to be creating C pointers de novo. - * - * @author Sheng Liang, originator - * @author Todd Fast, suitability modifications - * @author Timothy Wall, robust library loading - * @see Function - */ -public class Pointer { - - /** Size of a native pointer, in bytes. */ - public static final int SIZE; - - static { - // Force load of native library - if ((SIZE = Native.POINTER_SIZE) == 0) { - throw new Error("Native library not initialized"); - } - } - - /** Convenience constant, same as null. */ - public static final Pointer NULL = null; - - /** Convenience constant, equivalent to (void*)CONSTANT. */ - public static final Pointer createConstant(long peer) { - return new Opaque(peer); - } - - /** Convenience constant, equivalent to (void*)CONSTANT. - This version will avoid setting any of the high bits on 64-bit - systems. - */ - public static final Pointer createConstant(int peer) { - return new Opaque((long)peer & 0xFFFFFFFF); - } - - /** Pointer value of the real native pointer. Use long to be 64-bit safe. - */ - protected long peer; - - /** Derived class must assign peer pointer value. */ - Pointer() { } - - /** Create from native pointer. Don't use this unless you know what - * you're doing. - */ - public Pointer(long peer) { - this.peer = peer; - } - - public Pointer share(long offset) { - return share(offset, 0); - } - - /** Provide a view of this pointer with a different peer base. */ - public Pointer share(long offset, long sz) { - if (offset == 0) return this; - return new Pointer(peer + offset); - } - - /** Zero memory for the given number of bytes. */ - public void clear(long size) { - setMemory(0, size, (byte)0); - } - - /** - * Compares this Pointer to the specified object. - * - * @param o - * A Pointer instance - * @return True if the other object is a Pointer, - * and the C pointers being pointed to by these objects are also - * equal. Returns false otherwise. - */ - public boolean equals(Object o) { - if (o == this) return true; - if (o == null) return false; - return o instanceof Pointer && ((Pointer)o).peer == peer; - } - - /** - * Returns a hashcode for the native pointer represented by this - * Pointer object - * - * @return A hash code value for the represented native pointer - */ - public int hashCode() { - return (int)((peer >>> 32) + (peer & 0xFFFFFFFF)); - } - - - ////////////////////////////////////////////////////////////////////////// - // Raw read methods - ////////////////////////////////////////////////////////////////////////// - - /** Returns the offset of the given value in memory from the given offset, - * or -1 if the value is not found. - */ - public long indexOf(long offset, byte value) { - return Native.indexOf(peer + offset, value); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf byte array into which data is copied - * @param index array index from which to start copying - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, byte[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf short array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, short[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf char array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, char[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf int array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, int[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf long array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, long[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf float array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, float[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf double array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, double[] buf, int index, int length) { - Native.read(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying from memory pointed to by - * native pointer, into the specified array. - * - * @param offset byte offset from pointer from which data is copied - * @param buf {@link Pointer} array into which data is copied - * @param index array index to which data is copied - * @param length number of elements from native pointer that must be copied - */ - public void read(long offset, Pointer[] buf, int index, int length) { - for (int i=0;i < length;i++) { - Pointer p = getPointer(offset + i*Pointer.SIZE); - Pointer oldp = buf[i+index]; - // Avoid replacing the original pointer if it hasn't changed - if (oldp == null || p == null || p.peer != oldp.peer) { - buf[i+index] = p; - } - } - } - - - ////////////////////////////////////////////////////////////////////////// - // Raw write methods - ////////////////////////////////////////////////////////////////////////// - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf byte array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, byte[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf short array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, short[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf char array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, char[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf int array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, int[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf long array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, long[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf float array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, float[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** - * Indirect the native pointer, copying into memory pointed to by - * native pointer, from the specified array. - * - * @param offset byte offset from pointer into which data is copied - * @param buf double array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long offset, double[] buf, int index, int length) { - Native.write(peer + offset, buf, index, length); - } - - /** Write the given array of Pointer to native memory. - * @param bOff byte offset from pointer into which data is copied - * @param buf Pointer array from which to copy - * @param index array index from which to start copying - * @param length number of elements from buf that must be - * copied - */ - public void write(long bOff, Pointer[] buf, int index, int length) { - for (int i=0;i < length;i++) { - setPointer(bOff + i * Pointer.SIZE, buf[index + i]); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Java type read methods - ////////////////////////////////////////////////////////////////////////// - - Object getValue(long offset, Class type, Object currentValue) { - return getValue(offset, 0, 0, type, currentValue); - } - - Object getValue(long offset, int bitOffset, int bits, Class type, Object currentValue) { - - Object result = BitFields.getPrimitiveValue(this, offset, bitOffset, bits, type); - if (result != BitFields.UNHANDLED_TYPE) - return result; - - result = null; - if (Structure.class.isAssignableFrom(type)) { - Structure s = (Structure)currentValue; - if (Structure.ByReference.class.isAssignableFrom(type)) { - s = Structure.updateStructureByReference(type, s, getPointer(offset)); - } - else { - s.useMemory(this, (int)offset); - s.read(); - } - result = s; - } - else if (type == boolean.class || type == Boolean.class) { - result = Function.valueOf(getInt(offset) != 0); - } - else if (type == byte.class || type == Byte.class) { - result = new Byte(getByte(offset)); - } - else if (type == short.class || type == Short.class) { - result = new Short(getShort(offset)); - } - else if (type == char.class || type == Character.class) { - result = new Character(getChar(offset)); - } - else if (type == int.class || type == Integer.class) { - result = new Integer(getInt(offset)); - } - else if (type == long.class || type == Long.class) { - result = new Long(getLong(offset)); - } - else if (type == float.class || type == Float.class) { - result=new Float(getFloat(offset)); - } - else if (type == double.class || type == Double.class) { - result = new Double(getDouble(offset)); - } - else if (Pointer.class.isAssignableFrom(type)) { - Pointer p = getPointer(offset); - if (p != null) { - Pointer oldp = currentValue instanceof Pointer - ? (Pointer)currentValue : null; - if (oldp == null || p.peer != oldp.peer) - result = p; - else - result = oldp; - } - } - else if (type == String.class) { - Pointer p = getPointer(offset); - result = p != null ? p.getString(0) : null; - } - else if (type == WString.class) { - Pointer p = getPointer(offset); - result = p != null ? new WString(p.getString(0, true)) : null; - } - else if (Callback.class.isAssignableFrom(type)) { - // Overwrite the Java memory if the native pointer is a different - // function pointer. - Pointer fp = getPointer(offset); - if (fp == null) { - result = null; - } - else { - Callback cb = (Callback)currentValue; - Pointer oldfp = CallbackReference.getFunctionPointer(cb); - if (!fp.equals(oldfp)) { - cb = CallbackReference.getCallback(type, fp); - } - result = cb; - } - } - else if (Buffer.class.isAssignableFrom(type)) { - Pointer bp = getPointer(offset); - if (bp == null) { - result = null; - } - else { - Pointer oldbp = currentValue == null ? null - : Native.getDirectBufferPointer((Buffer)currentValue); - if (oldbp == null || !oldbp.equals(bp)) { - throw new IllegalStateException("Can't autogenerate a direct buffer on memory read"); - } - result = currentValue; - } - } - else if (NativeMapped.class.isAssignableFrom(type)) { - NativeMapped nm = (NativeMapped)currentValue; - if (nm != null) { - Object value = getValue(offset, nm.nativeType(), null); - result = nm.fromNative(value, new FromNativeContext(type)); - } - else { - NativeMappedConverter tc = NativeMappedConverter.getInstance(type); - Object value = getValue(offset, tc.nativeType(), null); - result = tc.fromNative(value, new FromNativeContext(type)); - } - } - else if (type.isArray()) { - result = currentValue; - if (result == null) { - throw new IllegalStateException("Need an initialized array"); - } - getArrayValue(offset, result, type.getComponentType()); - } - else { - throw new IllegalArgumentException("Reading \"" - + type + "\" from memory is not supported"); - } - return result; - } - - /** Copy memory starting at offset into the array with element type cls. */ - private void getArrayValue(long offset, Object o, Class cls) { - int length = 0; - length = Array.getLength(o); - Object result = o; - - if (cls == byte.class) { - read(offset, (byte[])result, 0, length); - } - else if (cls == short.class) { - read(offset, (short[])result, 0, length); - } - else if (cls == char.class) { - read(offset, (char[])result, 0, length); - } - else if (cls == int.class) { - read(offset, (int[])result, 0, length); - } - else if (cls == long.class) { - read(offset, (long[])result, 0, length); - } - else if (cls == float.class) { - read(offset, (float[])result, 0, length); - } - else if (cls == double.class) { - read(offset, (double[])result, 0, length); - } - else if (Pointer.class.isAssignableFrom(cls)) { - read(offset, (Pointer[])result, 0, length); - } - else if (Structure.class.isAssignableFrom(cls)) { - Structure[] sarray = (Structure[])result; - if (Structure.ByReference.class.isAssignableFrom(cls)) { - Pointer[] parray = getPointerArray(offset, sarray.length); - for (int i=0;i < sarray.length;i++) { - sarray[i] = Structure.updateStructureByReference(cls, sarray[i], parray[i]); - } - } - else { - for (int i=0;i < sarray.length;i++) { - if (sarray[i] == null) { - sarray[i] = Structure.newInstance(cls); - } - sarray[i].useMemory(this, (int)(offset + i * sarray[i].size())); - sarray[i].read(); - } - } - } - else if (NativeMapped.class.isAssignableFrom(cls)) { - NativeMapped[] array = (NativeMapped[])result; - NativeMappedConverter tc = NativeMappedConverter.getInstance(cls); - int size = Native.getNativeSize(result.getClass(), result) / array.length; - for (int i=0;i < array.length;i++) { - Object value = getValue(offset + size*i, tc.nativeType(), array[i]); - array[i] = (NativeMapped)tc.fromNative(value, new FromNativeContext(cls)); - } - } - else { - throw new IllegalArgumentException("Reading array of " - + cls - + " from memory not supported"); - } - } - - /** - * Indirect the native pointer as a pointer to byte. This is - * equivalent to the expression - * *((jbyte *)((char *)Pointer + offset)). - * - * @param offset offset from pointer to perform the indirection - * @return the byte value being pointed to - */ - public byte getByte(long offset) { - return Native.getByte(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to wchar_t. This - * is equivalent to the expression - * *((wchar_t*)((char *)Pointer + offset)). - * - * @param offset offset from pointer to perform the indirection - * @return the wchar_t value being pointed to - */ - public char getChar(long offset) { - return Native.getChar(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to short. This is - * equivalent to the expression - * *((jshort *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the short value being pointed to - */ - public short getShort(long offset) { - return Native.getShort(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to int. This is - * equivalent to the expression - * *((jint *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the int value being pointed to - */ - public int getInt(long offset) { - return Native.getInt(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to long. This is - * equivalent to the expression - * *((jlong *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the long value being pointed to - */ - public long getLong(long offset) { - return Native.getLong(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to long. This is - * equivalent to the expression - * *((long *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the long value being pointed to - */ - public NativeLong getNativeLong(long offset) { - return new NativeLong(NativeLong.SIZE == 8 ? getLong(offset) : getInt(offset)); - } - - /** - * Indirect the native pointer as a pointer to float. This is - * equivalent to the expression - * *((jfloat *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the float value being pointed to - */ - public float getFloat(long offset) { - return Native.getFloat(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to double. This - * is equivalent to the expression - * *((jdouble *)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return the double value being pointed to - */ - public double getDouble(long offset) { - return Native.getDouble(peer + offset); - } - - /** - * Indirect the native pointer as a pointer to pointer. This is equivalent - * to the expression - * *((void **)((char *)Pointer + offset)). - * - * @param offset byte offset from pointer to perform the indirection - * @return a {@link Pointer} equivalent of the pointer value - * being pointed to, or null if the pointer value is - * NULL; - */ - public Pointer getPointer(long offset) { - return Native.getPointer(peer + offset); - } - - /** - * Get a ByteBuffer mapped to the memory pointed to by the pointer, - * ensuring the buffer uses native byte order. - * - * @param offset byte offset from pointer to start the buffer - * @param length Length of ByteBuffer - * @return a direct ByteBuffer that accesses the memory being pointed to, - */ - public ByteBuffer getByteBuffer(long offset, long length) { - return Native.getDirectByteBuffer(peer + offset, length).order(ByteOrder.nativeOrder()); - } - - /** - * Copy native memory to a Java String. If wide is true, - * access the memory as an array of wchar_t, otherwise - * as an array of char, using the default platform encoding. - * - * @param offset byte offset from pointer to obtain the native string -v * @param wide whether to convert from a wide or standard C string - * @return the String value being pointed to - */ - public String getString(long offset, boolean wide) { - return Native.getString(peer + offset, wide); - } - - /** - * Copy native memory to a Java String. If the system property - * jna.encoding is set, uses it as the native charset - * when decoding the value, otherwise falls back to the default platform - * encoding. - * - * @param offset byte offset from pointer to obtain the native string - * @return the String value being pointed to - */ - public String getString(long offset) { - String encoding = System.getProperty("jna.encoding"); - if (encoding != null) { - long len = indexOf(offset, (byte)0); - if (len != -1) { - if (len > Integer.MAX_VALUE) { - throw new OutOfMemoryError("String exceeds maximum length: " + len); - } - byte[] data = getByteArray(offset, (int)len); - try { - return new String(data, encoding); - } - catch(UnsupportedEncodingException e) { - } - } - } - return getString(offset, false); - } - - /** Read a native array of bytes of size arraySize from the - given offset from this {@link Pointer}. - */ - public byte[] getByteArray(long offset, int arraySize) { - byte[] buf = new byte[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of wchar_t of size arraySize from the - given offset from this {@link Pointer}. - */ - public char[] getCharArray(long offset, int arraySize) { - char[] buf = new char[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of int16 of size arraySize from the - given offset from this {@link Pointer}. - */ - public short[] getShortArray(long offset, int arraySize) { - short[] buf = new short[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of int32 of size arraySize from the - given offset from this {@link Pointer}. - */ - public int[] getIntArray(long offset, int arraySize) { - int[] buf = new int[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of int64 of size arraySize from the - given offset from this {@link Pointer}. - */ - public long[] getLongArray(long offset, int arraySize) { - long[] buf = new long[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of float of size arraySize from the - given offset from this {@link Pointer}. - */ - public float[] getFloatArray(long offset, int arraySize) { - float[] buf = new float[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Read a native array of double of size arraySize from the - given offset from this {@link Pointer}. - */ - public double[] getDoubleArray(long offset, int arraySize) { - double[] buf = new double[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Returns an array of {@link Pointer}. The array length is - * determined by a NULL-valued terminating element. - */ - public Pointer[] getPointerArray(long offset) { - List array = new ArrayList(); - int addOffset = 0; - Pointer p = getPointer(offset); - while (p != null) { - array.add(p); - addOffset += Pointer.SIZE; - p = getPointer(offset + addOffset); - } - return (Pointer[])array.toArray(new Pointer[array.size()]); - } - - /** Returns an array of {@link Pointer} of the requested size. */ - public Pointer[] getPointerArray(long offset, int arraySize) { - Pointer[] buf = new Pointer[arraySize]; - read(offset, buf, 0, arraySize); - return buf; - } - - /** Returns an array of String based on a native array - * of char *. The array length is determined by a - * NULL-valued terminating element. - */ - public String[] getStringArray(long offset) { - return getStringArray(offset, -1, false); - } - - /** Returns an array of String based on a native array - * of char *, using the given array length. - */ - public String[] getStringArray(long offset, int length) { - return getStringArray(offset, length, false); - } - - /** Returns an array of String based on a native array - * of char* or wchar_t* based on the - * wide parameter. The array length is determined by a - * NULL-valued terminating element. - */ - public String[] getStringArray(long offset, boolean wide) { - return getStringArray(offset, -1, wide); - } - - /** Returns an array of String based on a native array - * of char* or wchar_t* based on the - * wide parameter, using the given array length. - */ - public String[] getStringArray(long offset, int length, boolean wide) { - - List strings = new ArrayList(); - Pointer p; - int addOffset = 0; - if (length != -1) { - p = getPointer(offset + addOffset); - int count = 0; - while (count++ < length) { - String s = p == null ? null : p.getString(0, wide); - strings.add(s); - if (count < length) { - addOffset += SIZE; - p = getPointer(offset + addOffset); - } - } - } - else { - while ((p = getPointer(offset + addOffset)) != null) { - String s = p == null ? null : p.getString(0, wide); - strings.add(s); - addOffset += SIZE; - } - } - return (String[])strings.toArray(new String[strings.size()]); - } - - ////////////////////////////////////////////////////////////////////////// - // Java type write methods - ////////////////////////////////////////////////////////////////////////// - - void setValue(long offset, Object value, Class type) { - setValue(offset, 0, 0, value, type); - } - - void setValue(long offset, int bitOffset, int bits, Object value, Class type) { - - if (BitFields.setPrimitiveValue(this, offset, bitOffset, bits, value, type)) - return; - - // Set the value at the offset according to its type - if (type == boolean.class || type == Boolean.class) { - setInt(offset, Boolean.TRUE.equals(value) ? -1 : 0); - } - else if (type == byte.class || type == Byte.class) { - setByte(offset, value == null ? 0 : ((Byte)value).byteValue()); - } - else if (type == short.class || type == Short.class) { - setShort(offset, value == null ? 0 : ((Short)value).shortValue()); - } - else if (type == char.class || type == Character.class) { - setChar(offset, value == null ? 0 : ((Character)value).charValue()); - } - else if (type == int.class || type == Integer.class) { - setInt(offset, value == null ? 0 : ((Integer)value).intValue()); - } - else if (type == long.class || type == Long.class) { - setLong(offset, value == null ? 0 : ((Long)value).longValue()); - } - else if (type == float.class || type == Float.class) { - setFloat(offset, value == null ? 0f : ((Float)value).floatValue()); - } - else if (type == double.class || type == Double.class) { - setDouble(offset, value == null ? 0.0 : ((Double)value).doubleValue()); - } - else if (type == Pointer.class) { - setPointer(offset, (Pointer)value); - } - else if (type == String.class) { - setPointer(offset, (Pointer)value); - } - else if (type == WString.class) { - setPointer(offset, (Pointer)value); - } - else if (Structure.class.isAssignableFrom(type)) { - Structure s = (Structure)value; - if (Structure.ByReference.class.isAssignableFrom(type)) { - setPointer(offset, s == null ? null : s.getPointer()); - if (s != null) { - s.autoWrite(); - } - } - else { - s.useMemory(this, (int)offset); - s.write(); - } - } - else if (Callback.class.isAssignableFrom(type)) { - setPointer(offset, CallbackReference.getFunctionPointer((Callback)value)); - } - else if (Buffer.class.isAssignableFrom(type)) { - Pointer p = value == null ? null - : Native.getDirectBufferPointer((Buffer)value); - setPointer(offset, p); - } - else if (NativeMapped.class.isAssignableFrom(type)) { - NativeMappedConverter tc = NativeMappedConverter.getInstance(type); - Class nativeType = tc.nativeType(); - setValue(offset, bitOffset, bits, tc.toNative(value, new ToNativeContext()), nativeType); - } - else if (type.isArray()) { - setArrayValue(offset, value, type.getComponentType()); - } - else { - throw new IllegalArgumentException("Writing " + type + " to memory is not supported"); - } - } - - private void setArrayValue(long offset, Object value, Class cls) { - if (cls == byte.class) { - byte[] buf = (byte[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == short.class) { - short[] buf = (short[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == char.class) { - char[] buf = (char[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == int.class) { - int[] buf = (int[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == long.class) { - long[] buf = (long[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == float.class) { - float[] buf = (float[])value; - write(offset, buf, 0, buf.length); - } - else if (cls == double.class) { - double[] buf = (double[])value; - write(offset, buf, 0, buf.length); - } - else if (Pointer.class.isAssignableFrom(cls)) { - Pointer[] buf = (Pointer[])value; - write(offset, buf, 0, buf.length); - } - else if (Structure.class.isAssignableFrom(cls)) { - Structure[] sbuf = (Structure[])value; - if (Structure.ByReference.class.isAssignableFrom(cls)) { - Pointer[] buf = new Pointer[sbuf.length]; - for (int i=0;i < sbuf.length;i++) { - if (sbuf[i] == null) { - buf[i] = null; - } - else { - buf[i] = sbuf[i].getPointer(); - sbuf[i].write(); - } - } - write(offset, buf, 0, buf.length); - } - else { - for (int i=0;i < sbuf.length;i++) { - if (sbuf[i] == null) { - sbuf[i] = Structure.newInstance(cls); - } - sbuf[i].useMemory(this, (int)(offset + i * sbuf[i].size())); - sbuf[i].write(); - } - } - } - else if (NativeMapped.class.isAssignableFrom(cls)) { - NativeMapped[] buf = (NativeMapped[])value; - NativeMappedConverter tc = NativeMappedConverter.getInstance(cls); - Class nativeType = tc.nativeType(); - int size = Native.getNativeSize(value.getClass(), value) / buf.length; - for (int i=0;i < buf.length;i++) { - Object element = tc.toNative(buf[i], new ToNativeContext()); - setValue(offset + i*size, element, nativeType); - } - } - else { - throw new IllegalArgumentException("Writing array of " - + cls + " to memory not supported"); - } - } - - /** Write value to the requested bank of memory. - * @param offset byte offset from pointer to start - * @param length number of bytes to write - * @param value value to be written - */ - public void setMemory(long offset, long length, byte value) { - Native.setMemory(peer + offset, length, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jbyte *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value byte value to set - */ - public void setByte(long offset, byte value) { - Native.setByte(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jshort *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value short value to set - */ - public void setShort(long offset, short value) { - Native.setShort(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((wchar_t *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value char value to set - */ - public void setChar(long offset, char value) { - Native.setChar(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jint *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value int value to set - */ - public void setInt(long offset, int value) { - Native.setInt(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jlong *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value long value to set - */ - public void setLong(long offset, long value) { - Native.setLong(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((long *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value long value to set - */ - public void setNativeLong(long offset, NativeLong value) { - if (NativeLong.SIZE == 8) { - setLong(offset, value.longValue()); - } else { - setInt(offset, value.intValue()); - } - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jfloat *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value float value to set - */ - public void setFloat(long offset, float value) { - Native.setFloat(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((jdouble *)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value double value to set - */ - public void setDouble(long offset, double value) { - Native.setDouble(peer + offset, value); - } - - /** - * Set value at location being pointed to. This is equivalent - * to the expression - * *((void **)((char *)Pointer + offset)) = value. - * - * @param offset byte offset from pointer at which value - * must be set - * @param value Pointer holding the actual pointer value to - * set, which may be null to indicate a NULL - * pointer. - */ - public void setPointer(long offset, Pointer value) { - Native.setPointer(peer + offset, value != null ? value.peer : 0); - } - - /** - * Copy string value to the location being pointed to. Copy - * each element in value, converted to native encoding, at an - * offsetfrom the location pointed to by this pointer. - * - * @param offset byte offset from pointer at which characters in - * value must be set - * @param value java.lang.String value to set - * @param wide whether to write the native string as an array of - * wchar_t. If false, writes as a NUL-terminated array of - * char using the default platform encoding. - */ - public void setString(long offset, String value, boolean wide) { - Native.setString(peer + offset, value, wide); - } - - /** - * Copy string value to the location being pointed to. Copy - * each element in value, converted to native encoding, at an - * offsetfrom the location pointed to by this pointer. - * Uses the value of the system property jna.encoding, if set, - * to determine the appropriate native charset in which to encode the value. - * If the property is not set, uses the default platform encoding. - * - * @param offset byte offset from pointer at which characters in - * value must be set - * @param value java.lang.String value to set - */ - public void setString(long offset, String value) { - byte[] data = Native.getBytes(value); - write(offset, data, 0, data.length); - setByte(offset + data.length, (byte)0); - } - - public String toString() { - return "native@0x" + Long.toHexString(peer); - } - - /** Read the native peer value. Use with caution. */ - public static long nativeValue(Pointer p) { - return p.peer; - } - - /** Set the native peer value. Use with caution. */ - public static void nativeValue(Pointer p, long value) { - p.peer = value; - } - - /** Pointer which disallows all read/write access. */ - private static class Opaque extends Pointer { - private Opaque(long peer) { super(peer); } - private final String MSG = "This pointer is opaque: " + this; - public long indexOf(long offset, byte value) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, byte[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, char[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, short[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, int[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, long[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, float[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void read(long bOff, double[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, byte[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, char[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, short[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, int[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, long[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, float[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public void write(long bOff, double[] buf, int index, int length) { - throw new UnsupportedOperationException(MSG); - } - public byte getByte(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public char getChar(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public short getShort(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public int getInt(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public long getLong(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public float getFloat(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public double getDouble(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public Pointer getPointer(long bOff) { - throw new UnsupportedOperationException(MSG); - } - public String getString(long bOff, boolean wide) { - throw new UnsupportedOperationException(MSG); - } - public void setByte(long bOff, byte value) { - throw new UnsupportedOperationException(MSG); - } - public void setChar(long bOff, char value) { - throw new UnsupportedOperationException(MSG); - } - public void setShort(long bOff, short value) { - throw new UnsupportedOperationException(MSG); - } - public void setInt(long bOff, int value) { - throw new UnsupportedOperationException(MSG); - } - public void setLong(long bOff, long value) { - throw new UnsupportedOperationException(MSG); - } - public void setFloat(long bOff, float value) { - throw new UnsupportedOperationException(MSG); - } - public void setDouble(long bOff, double value) { - throw new UnsupportedOperationException(MSG); - } - public void setPointer(long offset, Pointer value) { - throw new UnsupportedOperationException(MSG); - } - public void setString(long offset, String value, boolean wide) { - throw new UnsupportedOperationException(MSG); - } - public String toString() { - return "opaque@0x" + Long.toHexString(peer); - } - } -} diff --git a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/PointerUtils.java b/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/PointerUtils.java deleted file mode 100644 index 23d3c5d33..000000000 --- a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/PointerUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.sun.jna; - -public class PointerUtils { - public static long getAddress(Pointer p) { - return p.peer; - } - public static long getAddress(PointerType p) { - return p.getPointer().peer; - } - public static Pointer fromAddress(long peer) { - return new Pointer(peer); - } - -} diff --git a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Structure.java b/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Structure.java deleted file mode 100644 index 23f73d78d..000000000 --- a/libraries/jnaerator/jna-jnaerator/src/main/java/com/sun/jna/Structure.java +++ /dev/null @@ -1,1499 +0,0 @@ -/* This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - *

      - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - */ -package com.sun.jna; - -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.Buffer; -import java.util.AbstractCollection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; - -/** - * Represents a native structure with a Java peer class. When used as a - * function parameter or return value, this class corresponds to - * struct*. When used as a field within another - * Structure, it corresponds to struct. The - * tagging interfaces {@link ByReference} and {@link ByValue} may be used - * to alter the default behavior. - *

      - * See the overview for supported - * type mappings. - *

      - * Structure alignment and type mappings are derived by default from the - * enclosing interface definition (if any) by using - * {@link Native#getStructureAlignment} and {@link Native#getTypeMapper}. - *

      - * Structure fields corresponding to native fields must be public. - * The may additionally have the following modifiers:
      - *

        - *
      • volatile JNA will not write the field unless specifically - * instructed to do so via {@link #writeField(String)}. - *
      • final JNA will overwrite the field via {@link #read()}, - * but otherwise the field is not modifiable from Java. Take care when using - * this option, since the compiler will usually assume all accesses - * to the field (for a given Structure instance) have the same value. - *
      - * NOTE: Strings are used to represent native C strings because usage of - * char * is generally more common than wchar_t *. - *

      - * NOTE: This class assumes that fields are returned in {@link Class#getFields} - * in the same or reverse order as declared. If your VM returns them in - * no particular order, you're out of luck. - * - * @author Todd Fast, todd.fast@sun.com - * @author twall@users.sf.net - */ -@SuppressWarnings({"unchecked", "unused", "serial"}) -public abstract class Structure { - - /** Tagging interface to indicate the value of an instance of the - * Structure type is to be used in function invocations rather - * than its address. The default behavior is to treat - * Structure function parameters and return values as by - * reference, meaning the address of the structure is used. - */ - public interface ByValue { } - /** Tagging interface to indicate the address of an instance of the - * Structure type is to be used within a Structure definition - * rather than nesting the full Structure contents. The default behavior - * is to inline Structure fields. - */ - public interface ByReference { } - - private static class MemberOrder { - private static final String[] FIELDS = { - "first", "second", "middle", "penultimate", "last", - }; - public int first; - public int second; - public int middle; - public int penultimate; - public int last; - } - - private static final boolean REVERSE_FIELDS; - private static final boolean REQUIRES_FIELD_ORDER; - - static final boolean isPPC; - static final boolean isSPARC; - static final boolean isARM; - - static { - // Check for predictable field order; IBM and JRockit store fields in - // reverse order; Excelsior JET requires explicit order - Field[] fields = MemberOrder.class.getFields(); - List names = new ArrayList(); - for(int i=0;i < fields.length;i++) { - names.add(fields[i].getName()); - } - List expected = Arrays.asList(MemberOrder.FIELDS); - List reversed = new ArrayList(expected); - Collections.reverse(reversed); - - REVERSE_FIELDS = names.equals(reversed); - REQUIRES_FIELD_ORDER = !(names.equals(expected) || REVERSE_FIELDS); - String arch = System.getProperty("os.arch").toLowerCase(); - isPPC = "ppc".equals(arch) || "powerpc".equals(arch); - isSPARC = "sparc".equals(arch); - isARM = "arm".equals(arch); - } - - /** Use the platform default alignment. */ - public static final int ALIGN_DEFAULT = 0; - /** No alignment, place all fields on nearest 1-byte boundary */ - public static final int ALIGN_NONE = 1; - /** validated for 32-bit x86 linux/gcc; align field size, max 4 bytes */ - public static final int ALIGN_GNUC = 2; - /** validated for w32/msvc; align on field size */ - public static final int ALIGN_MSVC = 3; - - /** Align to a 2-byte boundary. */ - //public static final int ALIGN_2 = 4; - /** Align to a 4-byte boundary. */ - //public static final int ALIGN_4 = 5; - /** Align to an 8-byte boundary. */ - //public static final int ALIGN_8 = 6; - - static final int MAX_GNUC_ALIGNMENT = - isSPARC || ((isPPC || isARM) && Platform.isLinux()) - ? 8 : Native.LONG_SIZE; - protected static final int CALCULATE_SIZE = -1; - - // This field is accessed by native code - private Pointer memory; - private int size = CALCULATE_SIZE; - private int alignType; - private int structAlignment; - private final Map structFields = new LinkedHashMap(); - // Keep track of java strings which have been converted to C strings - private final Map nativeStrings = new HashMap(); - private TypeMapper typeMapper; - // This field is accessed by native code - private long typeInfo; - private List fieldOrder; - private boolean autoRead = true; - private boolean autoWrite = true; - private Structure[] array; - - protected Structure() { - this((Pointer)null); - } - - protected Structure(TypeMapper mapper) { - this((Pointer)null, ALIGN_DEFAULT, mapper); - } - - /** Create a structure cast onto preallocated memory. */ - protected Structure(Pointer p) { - this(p, ALIGN_DEFAULT); - } - - protected Structure(Pointer p, int alignment) { - this(p, alignment, null); - } - - protected Structure(Pointer p, int alignment, TypeMapper mapper) { - setAlignType(alignment); - setTypeMapper(mapper); - if (p != null) { - useMemory(p); - } - else { - allocateMemory(CALCULATE_SIZE); - } - } - - /** Return all fields in this structure (ordered). */ - Map fields() { - return structFields; - } - - /** Change the type mapping for this structure. May cause the structure - * to be resized and any existing memory to be reallocated. - * If null, the default mapper for the - * defining class will be used. - */ - protected void setTypeMapper(TypeMapper mapper) { - if (mapper == null) { - Class declaring = getClass().getDeclaringClass(); - if (declaring != null) { - mapper = Native.getTypeMapper(declaring); - } - } - this.typeMapper = mapper; - this.size = CALCULATE_SIZE; - if (this.memory instanceof AutoAllocated) { - this.memory = null; - } - } - - /** Change the alignment of this structure. Re-allocates memory if - * necessary. If alignment is {@link #ALIGN_DEFAULT}, the default - * alignment for the defining class will be used. - */ - protected void setAlignType(int alignType) { - if (alignType == ALIGN_DEFAULT) { - Class declaring = getClass().getDeclaringClass(); - if (declaring != null) - alignType = Native.getStructureAlignment(declaring); - if (alignType == ALIGN_DEFAULT) { - if (Platform.isWindows()) - alignType = ALIGN_MSVC; - else - alignType = ALIGN_GNUC; - } - } - this.alignType = alignType; - this.size = CALCULATE_SIZE; - if (this.memory instanceof AutoAllocated) { - this.memory = null; - } - } - - protected Memory autoAllocate(int size) { - return new AutoAllocated(size); - } - - /** Set the memory used by this structure. This method is used to - * indicate the given structure is nested within another or otherwise - * overlaid on some other memory block and thus does not own its own - * memory. - */ - protected void useMemory(Pointer m) { - useMemory(m, 0); - } - - /** Set the memory used by this structure. This method is used to - * indicate the given structure is nested within another or otherwise - * overlaid on some other memory block and thus does not own its own - * memory. - */ - protected void useMemory(Pointer m, int offset) { - // Invoking size() here is important when this method is invoked - // from the ctor, to ensure fields are properly scanned and allocated - try { - // Set the structure's memory field temporarily to avoid - // auto-allocating memory in the call to size() - this.memory = m; - if (size == CALCULATE_SIZE) { - size = calculateSize(false); - } - if (size != CALCULATE_SIZE) { - this.memory = m.share(offset, size); - } - this.array = null; - } - catch(IndexOutOfBoundsException e) { - throw new IllegalArgumentException("Structure exceeds provided memory bounds"); - } - } - - protected void ensureAllocated() { - if (memory == null) { - allocateMemory(); - } - else if (size == CALCULATE_SIZE) { - size = calculateSize(true); - } - } - - /** Attempt to allocate memory if sufficient information is available. - * Returns whether the operation was successful. - */ - protected void allocateMemory() { - allocateMemory(calculateSize(true)); - } - - /** Provided for derived classes to indicate a different - * size than the default. Returns whether the operation was successful. - * Will leave memory untouched if it is non-null and not allocated - * by this class. - */ - protected void allocateMemory(int size) { - if (size == CALCULATE_SIZE) { - // Analyze the struct, but don't worry if we can't yet do it - size = calculateSize(false); - } - else if (size <= 0) { - throw new IllegalArgumentException("Structure size must be greater than zero: " + size); - } - // May need to defer size calculation if derived class not fully - // initialized - if (size != CALCULATE_SIZE) { - if (this.memory == null - || this.memory instanceof AutoAllocated) { - this.memory = autoAllocate(size); - } - this.size = size; - } - } - - public int size() { - ensureAllocated(); - if (size == CALCULATE_SIZE) { - size = calculateSize(true); - } - return size; - } - - public void clear() { - memory.clear(size()); - } - - /** Return a {@link Pointer} object to this structure. Note that if you - * use the structure's pointer as a function argument, you are responsible - * for calling {@link #write()} prior to the call and {@link #read()} - * after the call. These calls are normally handled automatically by the - * {@link Function} object when it encounters a {@link Structure} argument - * or return value. - */ - public Pointer getPointer() { - ensureAllocated(); - return memory; - } - - ////////////////////////////////////////////////////////////////////////// - // Data synchronization methods - ////////////////////////////////////////////////////////////////////////// - - // Keep track of ByReference reads to avoid creating multiple structures - // mapped to the same address - private static final ThreadLocal reads = new ThreadLocal() { - protected synchronized Object initialValue() { - return new HashMap(); - } - }; - - // Keep track of what is currently being read/written to avoid redundant - // reads (avoids problems with circular references). - private static final ThreadLocal busy = new ThreadLocal() { - /** Avoid using a hash-based implementation since the hash code - will change if structure field values change. - */ - class StructureSet extends AbstractCollection implements Set { - private Structure[] elements; - private int count; - private void ensureCapacity(int size) { - if (elements == null) { - elements = new Structure[size*3/2]; - } - else if (elements.length < size) { - Structure[] e = new Structure[size*3/2]; - System.arraycopy(elements, 0, e, 0, elements.length); - elements = e; - } - } - public int size() { return count; } - public boolean contains(Object o) { - return indexOf(o) != -1; - } - public boolean add(Object o) { - if (!contains(o)) { - ensureCapacity(count+1); - elements[count++] = (Structure)o; - } - return true; - } - private int indexOf(Object o) { - Structure s1 = (Structure)o; - for (int i=0;i < count;i++) { - Structure s2 = elements[i]; - if (s1 == s2 - || (s1.getClass() == s2.getClass() - && s1.size() == s2.size() - && s1.getPointer().equals(s2.getPointer()))) { - return i; - } - } - return -1; - } - public boolean remove(Object o) { - int idx = indexOf(o); - if (idx != -1) { - if (--count > 0) { - elements[idx] = elements[count]; - elements[count] = null; - } - return true; - } - return false; - } - /** Simple implementation so that toString() doesn't break. - Provides an iterator over a snapshot of this Set. - */ - public Iterator iterator() { - Structure[] e = new Structure[count]; - System.arraycopy(elements, 0, e, 0, count); - return Arrays.asList(e).iterator(); - } - } - protected synchronized Object initialValue() { - return new StructureSet(); - } - }; - static Set busy() { - return (Set)busy.get(); - } - static Map reading() { - return (Map)reads.get(); - } - - /** - * Reads the fields of the struct from native memory - */ - public void read() { - // convenience: allocate memory and/or calculate size if it hasn't - // been already; this allows structures to do field-based - // initialization of arrays and not have to explicitly call - // allocateMemory in a ctor - ensureAllocated(); - - // Avoid redundant reads - if (busy().contains(this)) { - return; - } - busy().add(this); - if (this instanceof Structure.ByReference) { - reading().put(getPointer(), this); - } - try { - for (Iterator i=structFields.values().iterator();i.hasNext();) { - readField((StructField)i.next()); - } - } - finally { - busy().remove(this); - if (reading().get(getPointer()) == this) { - reading().remove(getPointer()); - } - } - } - - /** Returns the calculated offset of the given field. */ - protected int fieldOffset(String name) { - ensureAllocated(); - StructField f = (StructField)structFields.get(name); - if (f == null) - throw new IllegalArgumentException("No such field: " + name); - return f.offset; - } - - /** Force a read of the given field from native memory. The Java field - * will be updated from the current contents of native memory. - * @return the new field value, after updating - * @throws IllegalArgumentException if no field exists with the given name - */ - public Object readField(String name) { - ensureAllocated(); - StructField f = (StructField)structFields.get(name); - if (f == null) - throw new IllegalArgumentException("No such field: " + name); - return readField(f); - } - - /** Obtain the value currently in the Java field. Does not read from - * memory. - */ - Object getField(StructField structField) { - try { - return structField.field.get(this); - } - catch (Exception e) { - throw new Error("Exception reading field '" - + structField.name + "' in " + getClass() - + ": " + e); - } - } - - void setField(StructField structField, Object value) { - try { - structField.field.set(this, value); - } - catch(IllegalAccessException e) { - throw new Error("Unexpectedly unable to write to field '" - + structField.name + "' within " + getClass() - + ": " + e); - } - } - - /** Only keep the original structure if its native address is unchanged. - * Otherwise replace it with a new object. - * @param type Structure subclass - * @param s Original Structure object - * @param address the native struct * - * @return Updated Structure.ByReference object - */ - static Structure updateStructureByReference(Class type, Structure s, Pointer address) { - if (address == null) { - s = null; - } - else { - if (s == null || !address.equals(s.getPointer())) { - Structure s1 = (Structure)reading().get(address); - if (s1 != null && type.equals(s1.getClass())) { - s = s1; - } - else { - s = newInstance(type); - s.useMemory(address); - } - } - s.autoRead(); - } - return s; - } - - /** Read the given field and return its value. The Java field will be - * updated from the contents of native memory. - */ - // TODO: make overridable method with calculated native type, offset, etc - Object readField(StructField structField) { - - // Get the offset of the field - int offset = structField.offset; - - // Determine the type of the field - Class fieldType = structField.type; - FromNativeConverter readConverter = structField.readConverter; - if (readConverter != null) { - fieldType = readConverter.nativeType(); - } - // Get the current value only for types which might need to be preserved - Object currentValue = (Structure.class.isAssignableFrom(fieldType) - || Callback.class.isAssignableFrom(fieldType) - || Buffer.class.isAssignableFrom(fieldType) - || Pointer.class.isAssignableFrom(fieldType) - || NativeMapped.class.isAssignableFrom(fieldType) - || fieldType.isArray()) - ? getField(structField) : null; - Object result = memory.getValue(offset, structField.bitOffset, structField.bits, fieldType, currentValue); - // TODO: process against current value here - - if (readConverter != null) { - result = readConverter.fromNative(result, structField.context); - } - - // Update the value on the field - setField(structField, result); - return result; - } - - /** - * Writes the fields of the struct to native memory - */ - public void write() { - // convenience: allocate memory if it hasn't been already; this - // allows structures to do field-based initialization of arrays and not - // have to explicitly call allocateMemory in a ctor - ensureAllocated(); - - // Update native FFI type information, if needed - if (this instanceof ByValue) { - getTypeInfo(); - } - - // Avoid redundant writes - if (busy().contains(this)) { - return; - } - busy().add(this); - try { - // Write all fields, except those marked 'volatile' - for (Iterator i=structFields.values().iterator();i.hasNext();) { - StructField sf = (StructField)i.next(); - if (!sf.isVolatile) { - writeField(sf); - } - } - } - finally { - busy().remove(this); - } - } - - /** Write the given field to native memory. The current value in the Java - * field will be translated into native memory. - * @throws IllegalArgumentException if no field exists with the given name - */ - public void writeField(String name) { - ensureAllocated(); - StructField f = (StructField)structFields.get(name); - if (f == null) - throw new IllegalArgumentException("No such field: " + name); - writeField(f); - } - - /** Write the given field value to the field and native memory. The - * given value will be written both to the Java field and the - * corresponding native memory. - * @throws IllegalArgumentException if no field exists with the given name - */ - public void writeField(String name, Object value) { - ensureAllocated(); - StructField f = (StructField)structFields.get(name); - if (f == null) - throw new IllegalArgumentException("No such field: " + name); - setField(f, value); - writeField(f); - } - - void writeField(StructField structField) { - - if (structField.isReadOnly) - return; - - // Get the offset of the field - int offset = structField.offset; - - // Get the value from the field - Object value = getField(structField); - - // Determine the type of the field - Class fieldType = structField.type; - ToNativeConverter converter = structField.writeConverter; - if (converter != null) { - value = converter.toNative(value, new StructureWriteContext(this, structField.field)); - fieldType = converter.nativeType(); - } - - // Java strings get converted to C strings, where a Pointer is used - if (String.class == fieldType - || WString.class == fieldType) { - - // Allocate a new string in memory - boolean wide = fieldType == WString.class; - if (value != null) { - NativeString nativeString = new NativeString(value.toString(), wide); - // Keep track of allocated C strings to avoid - // premature garbage collection of the memory. - nativeStrings.put(structField.name, nativeString); - value = nativeString.getPointer(); - } - else { - value = null; - nativeStrings.remove(structField.name); - } - } - - try { - memory.setValue(offset, structField.bitOffset, structField.bits, value, fieldType); - } - catch(IllegalArgumentException e) { - e.printStackTrace(); - String msg = "Structure field \"" + structField.name - + "\" was declared as " + structField.type - + (structField.type == fieldType - ? "" : " (native type " + fieldType + ")") - + ", which is not supported within a Structure"; - throw new IllegalArgumentException(msg); - } - } - - private boolean hasFieldOrder() { - synchronized(this) { - return fieldOrder != null; - } - } - - protected List getFieldOrder() { - synchronized(this) { - if (fieldOrder == null) { - fieldOrder = new ArrayList(); - } - return fieldOrder; - } - } - - /** Provided for VMs where the field order as returned by {@link - * Class#getFields()} is not predictable. - */ - protected void setFieldOrder(String[] fields) { - getFieldOrder().addAll(Arrays.asList(fields)); - // Force recalculation of size/field layout - this.size = CALCULATE_SIZE; - if (this.memory instanceof AutoAllocated) { - this.memory = null; - } - } - - /** Sort the structure fields according to the given array of names. */ - protected void sortFields(List fields, List names) { - for (int i=0;i < names.size();i++) { - String name = (String)names.get(i); - for (int f=0;f < fields.size();f++) { - Field field = (Field)fields.get(f); - if (name.equals(field.getName())) { - Collections.swap(fields, i, f); - break; - } - } - } - } - - protected List getFields(boolean force) { - // Restrict to valid fields - List flist = new ArrayList(); - for (Class cls = getClass(); - !cls.equals(Structure.class); - cls = cls.getSuperclass()) { - List classFields = new ArrayList(); - Field[] fields = cls.getDeclaredFields(); - for (int i=0;i < fields.length;i++) { - int modifiers = fields[i].getModifiers(); - if (Modifier.isStatic(modifiers) - || !Modifier.isPublic(modifiers)) - continue; - classFields.add(fields[i]); - } - if (REVERSE_FIELDS) { - Collections.reverse(classFields); - } - flist.addAll(0, classFields); - } - if (REQUIRES_FIELD_ORDER || hasFieldOrder()) { - List fieldOrder = getFieldOrder(); - if (fieldOrder.size() < flist.size()) { - if (force) { - throw new Error("This VM does not store fields in a predictable order; you must use Structure.setFieldOrder to explicitly indicate the field order: " + System.getProperty("java.vendor") + ", " + System.getProperty("java.version")); - } - return null; - } - sortFields(flist, fieldOrder); - } - return flist; - } - - /** Calculate the amount of native memory required for this structure. - * May return {@link #CALCULATE_SIZE} if the size can not yet be - * determined (usually due to fields in the derived class not yet - * being initialized). - *

      - * If the force parameter is true will throw - * an {@link IllegalStateException} if the size can not be determined. - * @throws IllegalStateException an array field is not initialized - * @throws IllegalArgumentException when an unsupported field type is - * encountered - */ - int calculateSize(boolean force) { - // TODO: maybe cache this information on a per-class basis - // so that we don't have to re-analyze this static information each - // time a struct is allocated. - - structAlignment = 1; - int calculatedSize = 0; - int cumulativeBitOffset = 0; - List fields = getFields(force); - if (fields == null) { - return CALCULATE_SIZE; - } - - boolean firstField = true; - for (Iterator i=fields.iterator();i.hasNext();firstField=false) { - Field field = (Field)i.next(); - int modifiers = field.getModifiers(); - - Class type = field.getType(); - StructField structField = new StructField(); - structField.isVolatile = Modifier.isVolatile(modifiers); - structField.isReadOnly = Modifier.isFinal(modifiers); - if (Modifier.isFinal(modifiers)) { - field.setAccessible(true); - } - structField.field = field; - structField.name = field.getName(); - structField.type = type; - - // Check for illegal field types - if (Callback.class.isAssignableFrom(type) && !type.isInterface()) { - throw new IllegalArgumentException("Structure Callback field '" - + field.getName() - + "' must be an interface"); - } - if (type.isArray() - && Structure.class.equals(type.getComponentType())) { - String msg = "Nested Structure arrays must use a " - + "derived Structure type so that the size of " - + "the elements can be determined"; - throw new IllegalArgumentException(msg); - } - - int fieldAlignment = 1; - if (!Modifier.isPublic(field.getModifiers())) - continue; - - Object value = getField(structField); - if (value == null) { - if (Structure.class.isAssignableFrom(type) - && !(ByReference.class.isAssignableFrom(type))) { - try { - value = newInstance(type); - setField(structField, value); - } - catch(IllegalArgumentException e) { - String msg = "Can't determine size of nested structure: " - + e.getMessage(); - throw new IllegalArgumentException(msg); - } - } - else if (type.isArray()) { - // can't calculate size yet, defer until later - if (force) { - throw new IllegalStateException("Array fields must be initialized"); - } - return CALCULATE_SIZE; - } - } - Class nativeType = type; - if (NativeMapped.class.isAssignableFrom(type)) { - NativeMappedConverter tc = NativeMappedConverter.getInstance(type); - if (value == null) { - value = tc.defaultValue(); - setField(structField, value); - } - nativeType = tc.nativeType(); - structField.writeConverter = tc; - structField.readConverter = tc; - structField.context = new StructureReadContext(this, field); - } - else if (typeMapper != null) { - ToNativeConverter writeConverter = typeMapper.getToNativeConverter(type); - FromNativeConverter readConverter = typeMapper.getFromNativeConverter(type); - if (writeConverter != null && readConverter != null) { - value = writeConverter.toNative(value, - new StructureWriteContext(this, structField.field)); - nativeType = value != null ? value.getClass() : Pointer.class; - structField.writeConverter = writeConverter; - structField.readConverter = readConverter; - structField.context = new StructureReadContext(this, field); - } - else if (writeConverter != null || readConverter != null) { - String msg = "Structures require bidirectional type conversion for " + type; - throw new IllegalArgumentException(msg); - } - } - try { - structField.size = Native.getNativeSize(nativeType, value); - fieldAlignment = getNativeAlignment(nativeType, value, firstField); - } - catch(IllegalArgumentException e) { - // Might simply not yet have a type mapper set - if (!force && typeMapper == null) { - return CALCULATE_SIZE; - } - String msg = "Invalid Structure field in " + getClass() + ", field name '" + structField.name + "', " + structField.type + ": " + e.getMessage(); - throw new IllegalArgumentException(msg); - } - - Integer bits = getBitsAnnotation(field); - if (bits == null || firstField) { - // Align fields as appropriate - if (cumulativeBitOffset != 0) { - cumulativeBitOffset = 0; - calculatedSize++; - } - structAlignment = Math.max(structAlignment, fieldAlignment); - if ((calculatedSize % fieldAlignment) != 0) { - calculatedSize += fieldAlignment - (calculatedSize % fieldAlignment); - } - } - structField.offset = calculatedSize; - structField.bitOffset = cumulativeBitOffset; - - if (bits != null) { - int nBits = bits.intValue(); - structField.bits = nBits; - structField.size = (nBits >>> 3) + ((nBits & 7) != 0 ? 1 : 0); - cumulativeBitOffset += nBits; - calculatedSize += cumulativeBitOffset >>> 3; - cumulativeBitOffset &= 7; - } else { - calculatedSize += structField.size; - } - - // Save the field in our list - structFields.put(structField.name, structField); - } - - if (cumulativeBitOffset > 0) - calculatedSize = calculateAlignedSize(calculatedSize + 1); - - if (calculatedSize > 0) { - int size = calculateAlignedSize(calculatedSize); - // Update native FFI type information, if needed - if (this instanceof ByValue) { - getTypeInfo(); - } - if (this.memory != null - && !(this.memory instanceof AutoAllocated)) { - // Ensure we've set bounds on the memory used - this.memory = this.memory.share(0, size); - } - return size; - } - - throw new IllegalArgumentException("Structure " + getClass() - + " has unknown size (ensure " - + "all fields are public)"); - } - - /** - * Override this in a subclass to support bit fields (@link http://en.wikipedia.org/wiki/C_syntax#Bit_fields) : - * - * package com.sun.jna; - * import java.lang.annotation.*; - * - * @Retention(RetentionPolicy.RUNTIME) - * @Target( {ElementType.FIELD} ) - * public @interface Bits { - * int value(); - * } - * - * - * @Override - * protected Integer getBitsAnnotation(Field field) { - * Bits bits = field.getAnnotation(Bits.class); - * return bits == null ? null : bits.value(); - * } - * - */ - protected Integer getBitsAnnotation(Field field) { - return null; - } - - int calculateAlignedSize(int calculatedSize) { - // Structure size must be an integral multiple of its alignment, - // add padding if necessary. - if (alignType != ALIGN_NONE) { - if ((calculatedSize % structAlignment) != 0) { - calculatedSize += structAlignment - (calculatedSize % structAlignment); - } - } - return calculatedSize; - } - - protected int getStructAlignment() { - if (size == CALCULATE_SIZE) { - // calculate size, but don't allocate memory - calculateSize(true); - } - return structAlignment; - } - - /** Overridable in subclasses. */ - // TODO: write getNaturalAlignment(stack/alloc) + getEmbeddedAlignment(structs) - // TODO: move this into a native call which detects default alignment - // automatically - protected int getNativeAlignment(Class type, Object value, boolean isFirstElement) { - int alignment = 1; - if (NativeMapped.class.isAssignableFrom(type)) { - NativeMappedConverter tc = NativeMappedConverter.getInstance(type); - type = tc.nativeType(); - value = tc.toNative(value, new ToNativeContext()); - } - int size = Native.getNativeSize(type, value); - if (type.isPrimitive() || Long.class == type || Integer.class == type - || Short.class == type || Character.class == type - || Byte.class == type || Boolean.class == type - || Float.class == type || Double.class == type) { - alignment = size; - } - else if (Pointer.class == type - || Buffer.class.isAssignableFrom(type) - || Callback.class.isAssignableFrom(type) - || WString.class == type - || String.class == type) { - alignment = Pointer.SIZE; - } - else if (Structure.class.isAssignableFrom(type)) { - if (ByReference.class.isAssignableFrom(type)) { - alignment = Pointer.SIZE; - } - else { - if (value == null) - value = newInstance(type); - alignment = ((Structure)value).getStructAlignment(); - } - } - else if (type.isArray()) { - alignment = getNativeAlignment(type.getComponentType(), null, isFirstElement); - } - else { - throw new IllegalArgumentException("Type " + type + " has unknown " - + "native alignment"); - } - if (alignType == ALIGN_NONE) { - alignment = 1; - } - else if (alignType == ALIGN_MSVC) { - alignment = Math.min(8, alignment); - } - else if (alignType == ALIGN_GNUC) { - // NOTE this is published ABI for 32-bit gcc/linux/x86, osx/x86, - // and osx/ppc. osx/ppc special-cases the first element - if (!isFirstElement || !(Platform.isMac() && isPPC)) { - alignment = Math.min(MAX_GNUC_ALIGNMENT, alignment); - } - } - return alignment; - } - - public String toString() { - return toString(Boolean.getBoolean("jna.dump_memory")); - } - - public String toString(boolean debug) { - return toString(0, true, true); - } - - private String format(Class type) { - String s = type.getName(); - int dot = s.lastIndexOf("."); - return s.substring(dot + 1); - } - - private String toString(int indent, boolean showContents, boolean dumpMemory) { - String LS = System.getProperty("line.separator"); - String name = format(getClass()) + "(" + getPointer() + ")"; - if (!(getPointer() instanceof Memory)) { - name += " (" + size() + " bytes)"; - } - String prefix = ""; - for (int idx=0;idx < indent;idx++) { - prefix += " "; - } - String contents = LS; - if (!showContents) { - contents = "...}"; - } - else for (Iterator i=structFields.values().iterator();i.hasNext();) { - StructField sf = (StructField)i.next(); - Object value = getField(sf); - String type = format(sf.type); - String index = ""; - contents += prefix; - if (sf.type.isArray() && value != null) { - type = format(sf.type.getComponentType()); - index = "[" + Array.getLength(value) + "]"; - } - contents += " " + type + " " - + sf.name + index + "@" + Integer.toHexString(sf.offset); - if (value instanceof Structure) { - value = ((Structure)value).toString(indent + 1, !(value instanceof Structure.ByReference), dumpMemory); - } - contents += "="; - if (value instanceof Long) { - contents += Long.toHexString(((Long)value).longValue()); - } - else if (value instanceof Integer) { - contents += Integer.toHexString(((Integer)value).intValue()); - } - else if (value instanceof Short) { - contents += Integer.toHexString(((Short)value).shortValue()); - } - else if (value instanceof Byte) { - contents += Integer.toHexString(((Byte)value).byteValue()); - } - else { - contents += String.valueOf(value).trim(); - } - contents += LS; - if (!i.hasNext()) - contents += prefix + "}"; - } - if (indent == 0 && dumpMemory) { - final int BYTES_PER_ROW = 4; - contents += LS + "memory dump" + LS; - byte[] buf = getPointer().getByteArray(0, size()); - for (int i=0;i < buf.length;i++) { - if ((i % BYTES_PER_ROW) == 0) contents += "["; - if (buf[i] >=0 && buf[i] < 16) - contents += "0"; - contents += Integer.toHexString(buf[i] & 0xFF); - if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1) - contents += "]" + LS; - } - contents += "]"; - } - return name + " {" + contents; - } - - /** Returns a view of this structure's memory as an array of structures. - * Note that this Structure must have a public, no-arg - * constructor. If the structure is currently using auto-allocated - * {@link Memory} backing, the memory will be resized to fit the entire - * array. - */ - public Structure[] toArray(Structure[] array) { - ensureAllocated(); - if (this.memory instanceof AutoAllocated) { - // reallocate if necessary - Memory m = (Memory)this.memory; - int requiredSize = array.length * size(); - if (m.size() < requiredSize) { - useMemory(autoAllocate(requiredSize)); - } - } - array[0] = this; - int size = size(); - for (int i=1;i < array.length;i++) { - array[i] = Structure.newInstance(getClass()); - array[i].useMemory(memory.share(i*size, size)); - array[i].read(); - } - - if (!(this instanceof ByValue)) { - // keep track for later auto-read/writes - this.array = array; - } - - return array; - } - - /** Returns a view of this structure's memory as an array of structures. - * Note that this Structure must have a public, no-arg - * constructor. If the structure is currently using auto-allocated - * {@link Memory} backing, the memory will be resized to fit the entire - * array. - */ - public Structure[] toArray(int size) { - return toArray((Structure[])Array.newInstance(getClass(), size)); - } - - private Class baseClass() { - if ((this instanceof Structure.ByReference - || this instanceof Structure.ByValue) - && Structure.class.isAssignableFrom(getClass().getSuperclass())) { - return getClass().getSuperclass(); - } - return getClass(); - } - - /** This structure is equal to another based on the same data type - * and visible data fields. - */ - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof Structure)) { - return false; - } - if (o.getClass() != getClass() - && ((Structure)o).baseClass() != baseClass()) { - return false; - } - Structure s = (Structure)o; - if (s.size() == size()) { - clear(); write(); - byte[] buf = getPointer().getByteArray(0, size()); - s.clear(); s.write(); - byte[] sbuf = s.getPointer().getByteArray(0, s.size()); - return Arrays.equals(buf, sbuf); - } - return false; - } - - /** Since {@link #equals} depends on the native address, use that - * as the hash code. - */ - public int hashCode() { - clear(); write(); - return Arrays.hashCode(getPointer().getByteArray(0, size())); - } - - protected void cacheTypeInfo(Pointer p) { - typeInfo = p.peer; - } - - /** Override to supply native type information for the given field. */ - protected Pointer getFieldTypeInfo(StructField f) { - return FFIType.get(getField(f), f.type); - } - - /** Obtain native type information for this structure. */ - Pointer getTypeInfo() { - Pointer p = getTypeInfo(this); - cacheTypeInfo(p); - return p; - } - - /** Set whether the structure is automatically synchronized to native memory - before and after a native function call. Convenience method for -

      
      -        boolean auto = ...;
      -        setAutoRead(auto);
      -        setAutoWrite(auto);
      -        
      - */ - public void setAutoSynch(boolean auto) { - setAutoRead(auto); - setAutoWrite(auto); - } - - /** Set whether the structure is read from native memory prior to - a native function call. - */ - public void setAutoRead(boolean auto) { - this.autoRead = auto; - } - - /** Returns whether the structure is read from native memory prior to - a native function call. - */ - public boolean getAutoRead() { - return this.autoRead; - } - - /** Set whether the structure is written to native memory after a native - function call. - */ - public void setAutoWrite(boolean auto) { - this.autoWrite = auto; - } - - /** Returns whether the structure is written to native memory after a native - function call. - */ - public boolean getAutoWrite() { - return this.autoWrite; - } - - /** Exposed for testing purposes only. */ - static Pointer getTypeInfo(Object obj) { - return FFIType.get(obj); - } - - /** Create a new Structure instance of the given type - * @param type - * @return the new instance - * @throws IllegalArgumentException if the instantiation fails - */ - public static Structure newInstance(Class type) throws IllegalArgumentException { - try { - Structure s = (Structure)type.newInstance(); - if (s instanceof ByValue) { - s.allocateMemory(); - } - return s; - } - catch(InstantiationException e) { - String msg = "Can't instantiate " + type + " (" + e + ")"; - throw new IllegalArgumentException(msg); - } - catch(IllegalAccessException e) { - String msg = "Instantiation of " + type - + " not allowed, is it public? (" + e + ")"; - throw new IllegalArgumentException(msg); - } - } - - class StructField extends Object { - public String name; - public Class type; - public Field field; - public int size = -1; - public int offset = -1; - public int bitOffset = 0, bits = 0; - public boolean isVolatile; - public boolean isReadOnly; - public FromNativeConverter readConverter; - public ToNativeConverter writeConverter; - public FromNativeContext context; - } - /** This class auto-generates an ffi_type structure appropriate for a given - * structure for use by libffi. The lifecycle of this structure is easier - * to manage on the Java side than in native code. - */ - static class FFIType extends Structure { - public static class size_t extends IntegerType { - public size_t() { this(0); } - public size_t(long value) { super(Native.POINTER_SIZE, value); } - } - private static Map typeInfoMap = new WeakHashMap(); - // Native.initIDs initializes these fields to their appropriate - // pointer values. These are in a separate class from FFIType so that - // they may be initialized prior to loading the FFIType class - private static class FFITypes { - private static Pointer ffi_type_void; - private static Pointer ffi_type_float; - private static Pointer ffi_type_double; - private static Pointer ffi_type_longdouble; - private static Pointer ffi_type_uint8; - private static Pointer ffi_type_sint8; - private static Pointer ffi_type_uint16; - private static Pointer ffi_type_sint16; - private static Pointer ffi_type_uint32; - private static Pointer ffi_type_sint32; - private static Pointer ffi_type_uint64; - private static Pointer ffi_type_sint64; - private static Pointer ffi_type_pointer; - } - static { - if (Native.POINTER_SIZE == 0) - throw new Error("Native library not initialized"); - if (FFITypes.ffi_type_void == null) - throw new Error("FFI types not initialized"); - typeInfoMap.put(void.class, FFITypes.ffi_type_void); - typeInfoMap.put(Void.class, FFITypes.ffi_type_void); - typeInfoMap.put(float.class, FFITypes.ffi_type_float); - typeInfoMap.put(Float.class, FFITypes.ffi_type_float); - typeInfoMap.put(double.class, FFITypes.ffi_type_double); - typeInfoMap.put(Double.class, FFITypes.ffi_type_double); - typeInfoMap.put(long.class, FFITypes.ffi_type_sint64); - typeInfoMap.put(Long.class, FFITypes.ffi_type_sint64); - typeInfoMap.put(int.class, FFITypes.ffi_type_sint32); - typeInfoMap.put(Integer.class, FFITypes.ffi_type_sint32); - typeInfoMap.put(short.class, FFITypes.ffi_type_sint16); - typeInfoMap.put(Short.class, FFITypes.ffi_type_sint16); - Pointer ctype = Native.WCHAR_SIZE == 2 - ? FFITypes.ffi_type_uint16 : FFITypes.ffi_type_uint32; - typeInfoMap.put(char.class, ctype); - typeInfoMap.put(Character.class, ctype); - typeInfoMap.put(byte.class, FFITypes.ffi_type_sint8); - typeInfoMap.put(Byte.class, FFITypes.ffi_type_sint8); - typeInfoMap.put(boolean.class, FFITypes.ffi_type_uint32); - typeInfoMap.put(Boolean.class, FFITypes.ffi_type_uint32); - typeInfoMap.put(Pointer.class, FFITypes.ffi_type_pointer); - typeInfoMap.put(String.class, FFITypes.ffi_type_pointer); - typeInfoMap.put(WString.class, FFITypes.ffi_type_pointer); - } - // From ffi.h - private static final int FFI_TYPE_STRUCT = 13; - // Structure fields - public size_t size; - public short alignment; - public short type = FFI_TYPE_STRUCT; - public Pointer elements; - - private FFIType(Structure ref) { - Pointer[] els; - if (ref instanceof Union) { - StructField sf = ((Union)ref).biggestField; - els = new Pointer[] { - get(ref.getField(sf), sf.type), null, - }; - } - else { - els = new Pointer[ref.fields().size() + 1]; - int idx = 0; - for (Iterator i=ref.fields().values().iterator();i.hasNext();) { - StructField sf = (StructField)i.next(); - els[idx++] = ref.getFieldTypeInfo(sf); - } - } - init(els); - } - // Represent fixed-size arrays as structures of N identical elements - private FFIType(Object array, Class type) { - int length = Array.getLength(array); - Pointer[] els = new Pointer[length+1]; - Pointer p = get(null, type.getComponentType()); - for (int i=0;i < length;i++) { - els[i] = p; - } - init(els); - } - private void init(Pointer[] els) { - elements = new Memory(Pointer.SIZE * els.length); - elements.write(0, els, 0, els.length); - write(); - } - - static Pointer get(Object obj) { - if (obj == null) - return FFITypes.ffi_type_pointer; - if (obj instanceof Class) - return get(null, (Class)obj); - return get(obj, obj.getClass()); - } - - private static Pointer get(Object obj, Class cls) { - synchronized(typeInfoMap) { - Object o = typeInfoMap.get(cls); - if (o instanceof Pointer) { - return (Pointer)o; - } - if (o instanceof FFIType) { - return ((FFIType)o).getPointer(); - } - if (Buffer.class.isAssignableFrom(cls) - || Callback.class.isAssignableFrom(cls)) { - typeInfoMap.put(cls, FFITypes.ffi_type_pointer); - return FFITypes.ffi_type_pointer; - } - if (Structure.class.isAssignableFrom(cls)) { - if (obj == null) obj = newInstance(cls); - if (ByReference.class.isAssignableFrom(cls)) { - typeInfoMap.put(cls, FFITypes.ffi_type_pointer); - return FFITypes.ffi_type_pointer; - } - FFIType type = new FFIType((Structure)obj); - typeInfoMap.put(cls, type); - return type.getPointer(); - } - if (NativeMapped.class.isAssignableFrom(cls)) { - NativeMappedConverter c = NativeMappedConverter.getInstance(cls); - return get(c.toNative(obj, new ToNativeContext()), c.nativeType()); - } - if (cls.isArray()) { - FFIType type = new FFIType(obj, cls); - // Store it in the map to prevent premature GC of type info - typeInfoMap.put(obj, type); - return type.getPointer(); - } - throw new IllegalArgumentException("Unsupported Structure field type " + cls); - } - } - } - - private class AutoAllocated extends Memory { - public AutoAllocated(int size) { - super(size); - // Always clear new structure memory - super.clear(); - } - } - - private static void structureArrayCheck(Structure[] ss) { - Pointer base = ss[0].getPointer(); - int size = ss[0].size(); - for (int si=1;si < ss.length;si++) { - if (ss[si].getPointer().peer != base.peer + size*si) { - String msg = "Structure array elements must use" - + " contiguous memory (bad backing address at Structure array index " + si + ")"; - throw new IllegalArgumentException(msg); - } - } - } - - public static void autoRead(Structure[] ss) { - structureArrayCheck(ss); - if (ss[0].array == ss) { - ss[0].autoRead(); - } - else { - for (int si=0;si < ss.length;si++) { - ss[si].autoRead(); - } - } - } - - public void autoRead() { - if (getAutoRead()) { - read(); - if (array != null) { - for (int i=1;i < array.length;i++) { - array[i].autoRead(); - } - } - } - } - - public static void autoWrite(Structure[] ss) { - structureArrayCheck(ss); - if (ss[0].array == ss) { - ss[0].autoWrite(); - } - else { - for (int si=0;si < ss.length;si++) { - ss[si].autoWrite(); - } - } - } - - public void autoWrite() { - if (getAutoWrite()) { - write(); - if (array != null) { - for (int i=1;i < array.length;i++) { - array[i].autoWrite(); - } - } - } - } - - protected int getNativeSize(Class nativeType, Object value) { - return Native.getNativeSize(nativeType, value); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/.classpath b/libraries/jnaerator/jnaerator-parser/.classpath deleted file mode 100644 index 63252a00e..000000000 --- a/libraries/jnaerator/jnaerator-parser/.classpath +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-parser/.gitignore b/libraries/jnaerator/jnaerator-parser/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/jnaerator-parser/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/jnaerator-parser/.project b/libraries/jnaerator/jnaerator-parser/.project deleted file mode 100644 index 550216eca..000000000 --- a/libraries/jnaerator/jnaerator-parser/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - jnaerator-parser - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/jnaerator-parser/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/jnaerator-parser/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 3ee3ae270..000000000 --- a/libraries/jnaerator/jnaerator-parser/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:15 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/jnaerator-parser/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/jnaerator-parser/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/jnaerator-parser/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/jnaerator-parser/pom.xml b/libraries/jnaerator/jnaerator-parser/pom.xml deleted file mode 100644 index e4b9e7d15..000000000 --- a/libraries/jnaerator/jnaerator-parser/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - 4.0.0 - com.nativelibs4java - jnaerator-parser - JNAerator Parser - http://code.google.com/p/jnaerator/ - jar - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - com.nativelibs4java - ochafik-util - - - org.antlr - antlr-runtime - - - com.nativelibs4java - anarres-jnaerator - - - - - - - org.antlr - antlr3-maven-plugin - - - - - - diff --git a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCDemangling.g b/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCDemangling.g deleted file mode 100644 index 788263ccf..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCDemangling.g +++ /dev/null @@ -1,302 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public Lticense for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - - -/** - This grammar is by no mean complete. - It is able to parse preprocessed C & Objective-C files and can tolerate some amount of C++. - It lacks serious expression support, which is being worked on. - Complex variable declarations may not be supported, such as complex signatures of functions that return function pointers... -*/ - -grammar ObjCDemangling; -options { - backtrack = false; - //output = AST; - //memoize = true; - //k = 3; -} - -@header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Set; -import java.util.HashMap; -import java.util.HashSet; - - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.parser.TypeRef.*; -import static com.ochafik.lang.jnaerator.parser.Expression.*; -import static com.ochafik.lang.jnaerator.parser.Declaration.*; -import static com.ochafik.lang.jnaerator.parser.Identifier.*; -import static com.ochafik.lang.jnaerator.parser.Statement.*; -import static com.ochafik.lang.jnaerator.parser.Declarator.*; -import static com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; - -} - -@members { - protected String next() { - return input.LT(1).getText(); - } - - static HashMap predefRefs = new HashMap(); - static { - predefRefs.put("c", typeRef("char")); - - predefRefs.put("i", typeRef("int")); - predefRefs.put("s", typeRef("short")); - predefRefs.put("l", typeRef("long")); - predefRefs.put("q", typeRef("long").addModifiers(ModifierType.Long)); - predefRefs.put("C", typeRef("char").addModifiers(ModifierType.Unsigned)); - predefRefs.put("I", typeRef("int").addModifiers(ModifierType.Unsigned)); - predefRefs.put("S", typeRef("short").addModifiers(ModifierType.Unsigned)); - predefRefs.put("L", typeRef("long").addModifiers(ModifierType.Unsigned)); - predefRefs.put("Q", typeRef("long").addModifiers(ModifierType.Unsigned, ModifierType.Long)); - predefRefs.put("f", typeRef("float")); - predefRefs.put("d", typeRef("double")); - predefRefs.put("B", typeRef("BOOL")); - predefRefs.put("v", typeRef("void")); - } - boolean isPredefRef(String s) { - return predefRefs.containsKey(s); - } - public TypeRef getPredefRef(String s) { - return predefRefs.get(s).clone(); - } -} - -@lexer::header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -} - -mangledTypeEOF returns [TypeRef type] : mangledType { $type = $mangledType.type; } EOF; -mangledType returns [TypeRef type] - : structType { $type = $structType.type; } | - unionType { $type = $unionType.type; } | - arrayType { $type = $arrayType.type; } | - primitiveType { $type = $primitiveType.type; } | - '^' ( - //'?' { $type = new TypeRef.Pointer(typeRef("void"), PointerStyle.Pointer); } | - pointed=mangledType { - $type = new TypeRef.Pointer($pointed.type, Declarator.PointerStyle.Pointer); - } - ) - ; - -primitiveType returns [TypeRef type] - : - { isPredefRef(next()) }? IDENTIFIER { - $type = getPredefRef($IDENTIFIER.text); - } | - '*' { $type = new TypeRef.Pointer(typeRef("char"), PointerStyle.Pointer); } | - '@' { $type = typeRef("id"); } | - '#' { $type = typeRef("Class"); } | - ':' { $type = typeRef("SEL"); } | - '?' { $type = typeRef("__opaque_unknown_type"); } - ; - -structType returns [Struct type] - : { - $type = new Struct(); - $type.setType(Struct.Type.CStruct); - $type.setForwardDeclaration(true); - } '{' - ( - tagName=IDENTIFIER '=' { - $type.setTag(ident($tagName.text)); - } - ) - ( - f=structField { - $type.addDeclaration($f.field); - $type.setForwardDeclaration(false); - } - )* - '}' - - ; - -arrayType returns [TypeRef type] - : - '[' - size=DECIMAL_NUMBER? - ct=mangledType { - $type = new TypeRef.ArrayRef($ct.type, $size.text == null ? null : expr(Constant.Type.Int, Integer.parseInt($size.text))); - - } - ']' - ; - -methodType returns [Function method] - : - rt=mangledType { - $method = new Function(Function.Type.ObjCMethod, null, $rt.type); - } - DECIMAL_NUMBER - '@' DECIMAL_NUMBER ':' DECIMAL_NUMBER - ( - at=mangledType DECIMAL_NUMBER { - $method.addArg(new Arg(null, $at.type)); - } - )* - EOF - ; -unionType returns [Struct type] - : { - $type = new Struct(); - $type.setType(Struct.Type.CUnion); - } '(' - ( - tagName=IDENTIFIER '=' { - $type.setTag(ident($tagName.text)); - } - )? - ( - f=structField { $type.addDeclaration($f.field); } - )+ - ')' - - ; - -structField returns [VariablesDeclaration field] -@init { - DirectDeclarator declarator = null; -} - : - { - $field = new VariablesDeclaration(); - $field.addDeclarator(declarator = new DirectDeclarator()); - } - ( - fieldName=STRING { - declarator.setName(String.valueOf(Constant.parseString($fieldName.text).getValue())); - } - )? - ( - fieldType=mangledType { - $field.setValueType($fieldType.type); - } | - 'b' bits=DECIMAL_NUMBER { - declarator.setBits(Integer.parseInt($bits.text)); - $field.setValueType(typeRef("int")); - } - ) - ; - -fragment -Letter - : '$' | - '_' | - 'A'..'Z' | - 'a'..'z' - ; - -IDENTIFIER - : - Letter+ - ; - -DECIMAL_NUMBER - : //('-' | '+')? - ('0' | '1'..'9' '0'..'9'*) - ; - -OCTAL_NUMBER - : '0' - ('0'..'7')+ - ; - -fragment -CharEscape - : '\\' - ( - 'b' | - 't' | - 'n' | - 'f' | - 'r' | - '\"' | - '\'' | - '\\' - ) | - OctalEscape - ; - - -fragment -OctalEscape - : '\\' ( - ('0'..'3') ('0'..'7') ('0'..'7') | - ('0'..'7') ('0'..'7') | - ('0'..'7') - ) - ; - -STRING - : '"' - ( - CharEscape | - ~( - '\\' | - '"' - ) - )* - '"' - ; diff --git a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCpp.g b/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCpp.g deleted file mode 100644 index 0664a548e..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/ObjCpp.g +++ /dev/null @@ -1,2386 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public Lticense for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -/** - This grammar is by no mean complete. - It is able to parse preprocessed C & Objective-C files and can tolerate some amount of C++. -*/ - - -grammar ObjCpp; -options { - backtrack = true; - memoize = true; - k = 2; -} - -scope Symbols { - Set typeIdentifiers; -} -scope CurrentClass { - Identifier name; -} -scope ModifierKinds { - EnumSet allowedKinds; - EnumSet forbiddenKinds; -} -scope IsTypeDef { - boolean isTypeDef; -} -scope ModContext { - boolean isObjCArgDef; - boolean isInExtMod; -} - -@header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Set; -import java.util.HashSet; -import static com.ochafik.lang.jnaerator.parser.TypeRef.*; -import static com.ochafik.lang.jnaerator.parser.Expression.*; -import static com.ochafik.lang.jnaerator.parser.Declaration.*; -import static com.ochafik.lang.jnaerator.parser.Identifier.*; -import static com.ochafik.lang.jnaerator.parser.Statement.*; -import static com.ochafik.lang.jnaerator.parser.Declarator.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -} - -@members { - public enum Language { - C, CPlusPlus, ObjectiveC - } - public EnumSet possibleLanguages = EnumSet.allOf(Language.class); - - String lastComment; - String file; - int sourceLineDelta = 0; // line(token) = token.line - lastLineToken.line + lastLine; sourceLineDelta = lastLine - lastLineToken.line - //String pack; - - public Set topLevelTypeIdentifiers;// = new HashSet();//java.util.Arrays.asList("CHAR")); - public interface ObjCParserHelper { - boolean isObjCppPrimitive(String identifier); - } - public ObjCParserHelper objCParserHelper; - boolean isPrimitiveType(String identifier) { - return objCParserHelper != null && objCParserHelper.isObjCppPrimitive(identifier); - } - public EnumSet newKinds(ModifierKind first, ModifierKind... rest) { - return EnumSet.of(first, rest); - } - public void setupScopes() { - if (hasModifierKinds()) - return; - - Symbols_scope ss = new Symbols_scope(); - ss.typeIdentifiers = new HashSet(); - Symbols_stack.push(ss); - - ModifierKinds_scope mk = new ModifierKinds_scope(); - - //mk.allowedKinds = EnumSet.allOf(ModifierKind.class); - - mk.forbiddenKinds = EnumSet.noneOf(ModifierKind.class); - mk.forbiddenKinds.addAll(Arrays.asList( - ModifierKind.VCParameterAnnotation, - ModifierKind.Attribute, - ModifierKind.Declspec, - ModifierKind.Java, - //ModifierKind.ObjectiveC, // TODO find a way to disable this... - ModifierKind.OpenCL, - ModifierKind.StringAnnotation - )); - //mk.forbiddenKinds.add(ModifierKind.ObjectiveCRemoting); - - ModifierKinds_stack.push(mk); - } - void setCurrentClassName(Identifier name) { - ((CurrentClass_scope)CurrentClass_stack.peek()).name = name; - } - Identifier getCurrentClassName() { - if (CurrentClass_stack.isEmpty()) - return null; - - return ((CurrentClass_scope)CurrentClass_stack.peek()).name; - } - boolean hasModifierKinds() { - if (ModifierKinds_stack.isEmpty()) - return false; - if (ModifierKinds_stack.size() > 1) - return true; - ModifierKinds_scope kinds = (ModifierKinds_scope)ModifierKinds_stack.get(0); - return kinds.allowedKinds != null || kinds.forbiddenKinds != null; - } - ModifierKinds_scope getModifierKinds() { - if (!hasModifierKinds()) - setupScopes(); -// return null; - return (ModifierKinds_scope)ModifierKinds_stack.get(ModifierKinds_stack.size() - 1); - } - public void forbidKinds(ModifierKind... kinds) { - ModifierKinds_scope scope = getModifierKinds(); - if (scope == null) - return; - if (scope.forbiddenKinds == null) - scope.forbiddenKinds = EnumSet.copyOf(Arrays.asList(kinds)); - else - scope.forbiddenKinds.addAll(Arrays.asList(kinds)); - - if (scope.allowedKinds != null) - scope.allowedKinds.removeAll(Arrays.asList(kinds)); - } - public void allowKinds(ModifierKind... kinds) { - ModifierKinds_scope scope = getModifierKinds(); - if (scope == null) - return; - if (scope.allowedKinds == null) - scope.allowedKinds = EnumSet.copyOf(Arrays.asList(kinds)); - else - scope.allowedKinds.addAll(Arrays.asList(kinds)); - - if (scope.forbiddenKinds != null) - scope.forbiddenKinds.removeAll(Arrays.asList(kinds)); - } - public boolean isAllowed(Modifier mod) { - if (!hasModifierKinds()) - setupScopes(); - - int nScopes = ModifierKinds_stack.size(); - for (int i = nScopes; i-- != 0;) { - ModifierKinds_scope scope = (ModifierKinds_scope)ModifierKinds_stack.get(i); - boolean allowed = false; - for (ModifierKind kind : mod.getKinds()) { - if (scope.forbiddenKinds != null && scope.forbiddenKinds.contains(kind)) - return false; - if (scope.allowedKinds != null && scope.allowedKinds.contains(kind)) - allowed = true; - } - if (allowed) - return true; - } - return true; - //if (true) return true; - /*ModifierKinds_scope scope = getModifierKinds(); - if (scope == null) - return true; - return scope.allowedKinds.containsAll(mod.getKinds());*/ - } - public void addTypeIdent(String ident) { - try { - $Symbols::typeIdentifiers.add(ident); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - boolean isObjCArgDef() { - if (ModContext_stack.isEmpty()) - return false; - ModContext_scope scope = (ModContext_scope)ModContext_stack.get(ModContext_stack.size() - 1); - return scope.isObjCArgDef; - } - boolean isInExtMod() { - if (ModContext_stack.isEmpty()) - return false; - ModContext_scope scope = (ModContext_scope)ModContext_stack.get(ModContext_stack.size() - 1); - return scope.isInExtMod; - } - boolean isTypeDef() { - if (IsTypeDef_stack.isEmpty()) - return false; - IsTypeDef_scope scope = (IsTypeDef_scope)IsTypeDef_stack.get(IsTypeDef_stack.size() - 1); - return scope.isTypeDef; - } - void defineTypeIdentifierInParentScope(Identifier i) { - if (i != null && i.isPlain()) - defineTypeIdentifierInParentScope(i.toString()); - } - void defineTypeIdentifierInParentScope(String name) { - if (name == null || Symbols_stack.isEmpty()) - return; - int s = Symbols_stack.size(); - Symbols_scope sp = (Symbols_scope)Symbols_stack.get(s - 2 >= 0 ? s - 2 : s - 1); - sp.typeIdentifiers.add(name); - } - boolean isTypeIdentifier(String identifier) { - if (possibleLanguages.contains(Language.ObjectiveC)) { - if ("SEL".equals(identifier) || - "id".equals(identifier) || - "IMP".equals(identifier) || - "Class".equals(identifier) || - "Protocol".equals(identifier) || - "BOOL".equals(identifier) || - "NSObject".equals(identifier) || - "NSClass".equals(identifier)) - return true; - } - for (Object oscope : Symbols_stack) { - Symbols_scope scope = (Symbols_scope)oscope; - if (scope.typeIdentifiers.contains(identifier)) - return true; - } - if (isPrimitiveType(identifier)) { - //System.err.println("Found primitive : " + identifier); - return true; - } - //System.err.println("Not a primitive : " + identifier); - return topLevelTypeIdentifiers == null ? false : topLevelTypeIdentifiers.contains(identifier); - } - public void setFile(String file) { - this.file = file; - possibleLanguages = guessPossibleLanguages(file); - } - - public EnumSet guessPossibleLanguages(String file) { - int i = file.lastIndexOf("."); - if (i > 0) { - String ext = file.substring(i + 1).toLowerCase(); - - if (ext.equals("h")) - return EnumSet.allOf(Language.class); - else if (ext.equals("c")) - return EnumSet.of(Language.C); - else if (ext.startsWith("c") || ext.startsWith("h")) // cxx, hxx - return EnumSet.of(Language.C, Language.CPlusPlus); - else if (ext.equals("m")) - return EnumSet.of(Language.C, Language.ObjectiveC); - else if (ext.equals("mm")) - return EnumSet.allOf(Language.class); - } - return EnumSet.allOf(Language.class); - } - public String getFile() { - return file; - } - - public int getLine() { - return getLine(getTokenStream().get(getTokenStream().index())); - } - - public int getLine(Token token) { - return token.getLine(); //+ sourceLineDelta; - } - - protected T mark(T element, int tokenLine) { - element.setElementFile(getFile()); - if (tokenLine >= 0) - element.setElementLine(tokenLine + sourceLineDelta); - return element; - } - protected String getCommentBefore() { - return getCommentBefore(getTokenStream().index()); - } - protected String getCommentBefore(int index) { - String comment = null; - boolean toleratedNewLine = false; - while (index > 0) { - Token token = getTokenStream().get(--index); - if (token.getType() == COMMENT || token.getType() == LINE_COMMENT) { - //if (comment != null) - //return comment; - if (comment != null && comment.endsWith("\n") && toleratedNewLine) - return null; - if (comment != null) - return comment; - comment = token.getText(); - if (comment != null && comment.endsWith("\n") && toleratedNewLine) - return null; - } else if (token.getType() == WS) { - if (token.getText().indexOf("\n") >= 0) { - if (comment != null) - return comment; - else if (toleratedNewLine) - return null; - else - toleratedNewLine = true; - } - } else - return null; - } - return comment; - } - protected String getCommentAfterOnSameLine(int index, String forbiddenChars) { - int size = getTokenStream().size(); - while (index < size) { - Token token = getTokenStream().get(index++); - String tt = token.getText(); - if (token.getType() == COMMENT || token.getType() == LINE_COMMENT) - return tt; - else if (tt.indexOf("\n") >= 0 || forbiddenChars != null && tt.matches(".*?[" + forbiddenChars + "].*")) - break; - } - return null; - } - protected Declaration decl(TaggedTypeRef type) { - return mark(new TaggedTypeRefDeclaration(type), type.getElementLine()); - } - - protected String next() { - return next(1); - } - protected String next(int i) { - return input.LT(i).getText(); - } - protected Modifier parseModifier(String s, ModifierKind... anyModKind) { - Modifier mod = ModifierType.parseModifier(next(), anyModKind); - if (mod == null) - return null; - if (mod.isAllOf(ModifierKind.ObjectiveC, ModifierKind.OnlyInArgDef) && !isObjCArgDef()) - return null; - if (mod.isA(ModifierKind.Java)) - return null; - - //if (mod.isAnyOf(ModifierKind.Declspec, ModifierKind.Attribute) && !isInExtMod()) - // return null; - - if (!mod.isAnyOf(anyModKind) && !isAllowed(mod)) - return null; - - return mod; - } - protected boolean next(ModifierKind... anyModKind) { - return parseModifier(next(), anyModKind) != null; - } - protected boolean next(String... ss) { - return next(1, ss); - } - protected boolean next(Identifier id) { - if (id == null) - return false; - return next(id.toString()); - } - - protected boolean next(int i, String... ss) { - String n = next(i); - for (String s : ss) - if (s.equals(n)) - return true; - - return false; - } - - String getSurroundings(Token t, int width) { - if (t == null) - return null; - int x = t.getTokenIndex(); - List strs = new ArrayList(); - int size = getTokenStream().size(); - for (int i = x - width; i < x + width + 1; i++) { - if (i < 0 || i >= size) - continue; - - strs.add(getTokenStream().get(i).getText()); - } - return com.ochafik.util.string.StringUtils.implode(strs, " "); - } - @Override - public String getErrorMessage(RecognitionException e, String[] tokenNames) { - if (e instanceof NoViableAltException) { - NoViableAltException ne = (NoViableAltException)e; - checkInterrupt(); - return "Failed to match any alternative with token " + ne.token + "\n\t" + - " File: " + getFile() + ":" + (ne.line + sourceLineDelta) + "\n\t" + - "Input: " + getSurroundings(ne.token, 5).replace('\n', ' ') + "\n\t" + - " Rule: " + ne.grammarDecisionDescription + "\n\t" + - "Stack: " + getRuleInvocationStack(e, getClass().getName()) + "\n"; - } else - return super.getErrorMessage(e, tokenNames); - } - @Override - public String getTokenErrorDisplay(Token t) { - return t.toString(); - } - protected boolean checkInterrupt() { - if (Thread.interrupted()) - throw new RuntimeException(new InterruptedException()); - - return true; - } -} - -@lexer::header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -import static com.ochafik.lang.jnaerator.parser.Expression.*; -} - -lineDirective - : ln='#line' line=DECIMAL_NUMBER { - try { - sourceLineDelta = Integer.parseInt($line.text) - $ln.getLine() - 1; - } catch (Exception ex) { - System.err.println("ERROR: unparsable line in #line directive : " + $line.text); - sourceLineDelta = 0; - } - } - ( - unescapedString=STRING { - String fileStr = $unescapedString.text.trim(); - if (fileStr.startsWith("\"")) { - fileStr = fileStr.substring(1); - if (fileStr.endsWith("\"")) - fileStr = fileStr.substring(0, fileStr.length() - 1); - } - setFile(fileStr); - } - ) - depth=DECIMAL_NUMBER - ; - -sourceFile returns [SourceFile sourceFile] -scope Symbols; -@init { - $Symbols::typeIdentifiers = new HashSet(); -} - : - { $sourceFile = new SourceFile(); }//mark(new SourceFile(), getLine()); } - ( - declaration { - $sourceFile.addDeclaration($declaration.declaration); - } | - lineDirective { - if ($sourceFile.getElementFile() == null) - $sourceFile.setElementFile(getFile()); - } | - { next("extern") }?=> IDENTIFIER STRING '{' | - '}' - )* - EOF - ; - -externDeclarations returns [ExternDeclarations declaration] - : { next("extern") }?=> IDENTIFIER - STRING { - $declaration = mark(new ExternDeclarations(), getLine($STRING)); - $declaration.setLanguage($STRING.text); - } - ( - '{' - ( - ed=declaration { - $declaration.addDeclaration($ed.declaration); - } | - lineDirective - )* - '}' | - dd=declaration { - $declaration.addDeclaration($dd.declaration); - } - ) - ; - -declaration returns [Declaration declaration, List modifiers, String preComment, int startTokenIndex, Template template] -scope IsTypeDef; -scope ModContext; -@before { - checkInterrupt(); -} -@after { - if ($declaration == null) - try { - int i = $start.getTokenIndex(); - if (i > 0) { - String s1 = getTokenStream().get(i - 1).getText(), s2 = i > 1 ? getTokenStream().get(i - 2).getText() : null; - String s = (s2 == null ? "" : s2) + s1; - if (s.matches(".*\n\\s*\n")) - $declaration = new EmptyDeclaration(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - if ($template != null) { - $template.setDeclaration($declaration); - if ($declaration instanceof TaggedTypeRefDeclaration) { - TaggedTypeRefDeclaration ttrd = (TaggedTypeRefDeclaration)$declaration; - TaggedTypeRef ttr = (TaggedTypeRef)ttrd.getTaggedTypeRef(); - if (ttr != ttr) - defineTypeIdentifierInParentScope(ttr.getTag()); - } - $declaration = $template; - } -} - : - - ( tp=templatePrefix { $template = $tp.template; } )? - { - $modifiers = new ArrayList(); - $startTokenIndex = getTokenStream().index(); - $preComment = getCommentBefore($startTokenIndex); - } - ( - ( - { next("__pragma") }?=> pragmaContent | - functionDeclaration { - $declaration = $functionDeclaration.function; - } | - { next("extern") }?=> externDeclarations { - $declaration = $externDeclarations.declaration; - } | - { next("using") }?=> IDENTIFIER qualifiedIdentifier ';' { - // TODO - } | - varDecl ';' { - $declaration = $varDecl.decl; - } | - objCClassDef { - $declaration = decl($objCClassDef.struct); - } | - typeDef { - $declaration = $typeDef.typeDef; - } | - forwardClassDecl { - $declaration = new Declarations($forwardClassDecl.declarations); - } | - //nonMutableTypeRef ';' | // TODO - namespaceDecl { - $declaration = $namespaceDecl.namespace; - }// | - //';' */// allow isolated semi-colons - ) - { - String commentAfter = getCommentAfterOnSameLine($startTokenIndex, null); - if ($declaration != null) { - $declaration.setCommentBefore($preComment); - $declaration.setCommentAfter(commentAfter); - $declaration.addModifiers($modifiers); - } - } - ) - ; - -namespaceDecl returns [Namespace namespace] - : - 'namespace' ns=IDENTIFIER '{' { - $namespace = new Namespace(); - $namespace.setName(new SimpleIdentifier($ns.text)); - } - ( - subD=declaration { - $namespace.addDeclaration($subD.declaration); - } | - lineDirective - )* - '}' - ; - -forwardClassDecl returns [List declarations] - : { $declarations = new ArrayList(); } - '@class' - n1=IDENTIFIER { - $declarations.add(decl(Struct.forwardDecl(new SimpleIdentifier($n1.text), Struct.Type.ObjCClass))); - defineTypeIdentifierInParentScope($n1.text); - } - (',' - nx=IDENTIFIER { - $declarations.add(decl(Struct.forwardDecl(new SimpleIdentifier($nx.text), Struct.Type.ObjCClass))); - defineTypeIdentifierInParentScope($nx.text); - } - )* - ';' - ; - -functionPointerVarDecl returns [Declaration decl] - : tr=mutableTypeRef { - ($tr.type instanceof FunctionSignature) && - ((FunctionSignature)$tr.type).getFunction().getName() != null - }? { - $decl = new FunctionPointerDeclaration(((FunctionSignature)$tr.type)); - } - ';' - ; - -enumItem returns [Enum.EnumItem item] - : n=IDENTIFIER ('=' v=topLevelExpr)? { - $item = mark(new Enum.EnumItem($n.text, $v.text == null ? null : $v.expr), getLine($n)); - $item.setCommentBefore(getCommentBefore($n.getTokenIndex())); - $item.setCommentAfter(getCommentAfterOnSameLine($n.getTokenIndex() - 1, "}")); - } - ; - -enumBody returns [Enum e] -scope ModContext; - : - { - $e = new Enum(); - $e.setType(Enum.Type.C); - $e.setForwardDeclaration(false); - } - '{' - ( - i1=enumItem { - if ($i1.text != null) - $e.addItem($i1.item); - } - ( - ',' - (ix=enumItem { - if ($ix.text != null) - $e.addItem($ix.item); - })? - )* - )? - '}' - ; -enumCore returns [Enum e] -@init { - List modifiers = new ArrayList(); -} - : - t='enum' - ( - ( m1=modifiers { modifiers.addAll($m1.modifiers); } )? - ( - ab=enumBody { - $e = $ab.e; - $e.setForwardDeclaration(false); - } | - tag=qualifiedIdentifier - ( - ( m2=modifiers { modifiers.addAll($m2.modifiers); } )? - nb=enumBody { - $e = $nb.e; - $e.setForwardDeclaration(false); - } | { - $e = new Enum(); - $e.setType(Enum.Type.C); - $e.setForwardDeclaration(true); - } - ) { - $e.setTag($tag.identifier); - } - ) - ) { - //$e.setCommentBefore(getCommentBefore($t.getTokenIndex())); - $e = mark($e, getLine($t)); - $e.addModifiers(modifiers); - defineTypeIdentifierInParentScope($e.getTag()); - } - ; - - -objCClassDef returns [Struct struct] - : - octype=('@protocol'|'@interface') - className=IDENTIFIER { - defineTypeIdentifierInParentScope($className.text); - $struct = mark(new Struct(), getLine($octype)); - //$struct.setForwardDeclaration(true); - //$struct.setCommentBefore(getCommentBefore($octype.getTokenIndex())); - $struct.setType($octype.text.equals("@interface") ? - Struct.Type.ObjCClass : - Struct.Type.ObjCProtocol - ); - $struct.setTag(new SimpleIdentifier($className.text)); - } - ( - ( - ':' parentClass=IDENTIFIER { - if ($parentClass.text != null) - $struct.addParent(new SimpleIdentifier($parentClass.text)); - } - ) | - ( - '(' categoryName=IDENTIFIER ')' { - $struct.setCategoryName($categoryName.text); - } - ) | - ) - ( - '<' ( - p1=IDENTIFIER { $struct.addProtocol(new SimpleIdentifier($p1.text)); } - ( - ',' - px=IDENTIFIER { $struct.addProtocol(new SimpleIdentifier($px.text)); } - )* - )? '>' - )? - ( - '{' - ( - '@package' | // TODO keep in AST - '@required' | // TODO keep in AST - '@optional' | // TODO keep in AST - '@public' { $struct.setNextMemberVisibility(Struct.MemberVisibility.Public); } | - '@private' { $struct.setNextMemberVisibility(Struct.MemberVisibility.Private); } | - '@protected' { $struct.setNextMemberVisibility(Struct.MemberVisibility.Protected); } | - ( - functionPointerOrSimpleVarDecl ';' { - $struct.addDeclaration($functionPointerOrSimpleVarDecl.decl); - } - ) | - lineDirective - )* - '}' - )? - { $struct.setNextMemberVisibility(Struct.MemberVisibility.Public); } - ( - objCMethodDecl { - $struct.addDeclaration($objCMethodDecl.function); - } | - objCPropertyDecl { - $struct.addDeclaration($objCPropertyDecl.property); - } | - typeDef { - $struct.addDeclaration($typeDef.typeDef); - } | - vd=varDecl ';' { !($vd.decl instanceof VariablesDeclaration) }? { - $struct.addDeclaration($vd.decl); - } | - lineDirective - )* - '@end' - ; - -functionPointerOrSimpleVarDecl returns [Declaration decl] - : - fv=varDecl { - $decl = $fv.decl; - } | - functionPointerVarDecl { - $decl = $functionPointerVarDecl.decl; - } - ; - -objCPropertyDecl returns [Property property] - : - '@property' - ( '(' IDENTIFIER ( ',' IDENTIFIER ) * ) ? // TODO parse modifiers : assign, nonatomic, readonly, copy... - functionPointerOrSimpleVarDecl ';' { - $property = new Property($functionPointerOrSimpleVarDecl.decl); - } - ; - -objCMethodDecl returns [Function function] -scope ModContext; -@init { - $ModContext::isObjCArgDef = true; -} - : { - $function = new Function(); - $function.setType(Function.Type.ObjCMethod); - } - tk=( - tp='+' { - $function.addModifiers(ModifierType.Static); - $function = mark($function, getLine($tp)); - $function.setCommentBefore(getCommentBefore($tp.getTokenIndex())); - } | - tm='-' { - $function = mark($function, getLine($tm)); - $function.setCommentBefore(getCommentBefore($tm.getTokenIndex())); - } - ) - ( - // Optional return type - '(' - returnTypeRef=mutableTypeRef? { - $function.setValueType($returnTypeRef.type); - } - ')' - )? - methodName=(IDENTIFIER | 'class') { - $function.setName(new SimpleIdentifier($methodName.text)); - $function.setCommentAfter(getCommentAfterOnSameLine($methodName.getTokenIndex(), null)); - } - ( - ':' '(' argType1=mutableTypeRef ')' argName1=IDENTIFIER { - Arg arg = new Arg($argName1.text, $argType1.type); - arg.setSelector($methodName.text); - $function.addArg(arg); - } - ( - sel=IDENTIFIER ':' - '(' argType=mutableTypeRef ')' - argName=IDENTIFIER { - Arg arg = new Arg($argName.text, $argType.type); - arg.setSelector($sel.text); - $function.addArg(arg); - } - )* - ( - ',' '...' { - $function.addArg(Arg.createVarArgs()); - } - )? - )? - ';' - ; - -structBody returns [Struct struct] -scope ModContext; -scope Symbols; -@init { - $Symbols::typeIdentifiers = new HashSet(); -} - : - { - $struct = new Struct(); - $struct.setForwardDeclaration(false); - } - '{' - ( - ( - { next("public") }? IDENTIFIER { $struct.setNextMemberVisibility(Struct.MemberVisibility.Public); } | - { next("private") }? IDENTIFIER { $struct.setNextMemberVisibility(Struct.MemberVisibility.Private); } | - { next("protected") }? IDENTIFIER { $struct.setNextMemberVisibility(Struct.MemberVisibility.Protected); } - ) ':' | - { next("friend") }? IDENTIFIER ( - friendDecl=declaration { - $struct.addDeclaration(new FriendDeclaration(friendDecl.declaration)); - } | - friendVar=varDecl ';' { - $struct.addDeclaration(new FriendDeclaration(decl.declaration)); - } - ) | - tp=templatePrefix? - { next(getCurrentClassName()) }? id=IDENTIFIER s=functionDeclarationSuffix { - Function f = new Function(); - f.setName(getCurrentClassName()); - f.setType(Function.Type.CppMethod); - f.setArgs($s.args); - f.addModifiers($s.postModifiers); - f.setInitializers($s.initializers); - f.setBody($s.body); - - if ($tp.template != null) { - $tp.template.setDeclaration(f); - $struct.addDeclaration($tp.template); - } else { - $struct.addDeclaration(f); - } - } | - decl=declaration { - $struct.addDeclaration($decl.declaration); - } | - fv=varDecl ';' { - $struct.addDeclaration($fv.decl); - } | - lineDirective - )* - '}' - ; - -structCore returns [Struct struct] -scope Symbols; -scope ModContext; -scope CurrentClass; -@init { - $Symbols::typeIdentifiers = new HashSet(); - List modifiers = new ArrayList(); - Identifier parentIdentifier = null; -} -@after { - $struct = mark($struct, getLine($typeToken)); - $struct.setType( - $typeToken.text.equals("struct") ? Struct.Type.CStruct : - $typeToken.text.equals("union") ? Struct.Type.CUnion : - Struct.Type.CPPClass - ); - - Function.Type forcedType = null; - if ($struct.getType() == Struct.Type.CPPClass) - forcedType = Function.Type.CppMethod; - - if (forcedType != null) - for (Declaration d : $struct.getDeclarations()) { - if (d instanceof Function) - ((Function)d).setType(forcedType); - } - $struct.addModifiers(modifiers); -} - : - //{ next("struct", "class", "union") }?=> typeToken=IDENTIFIER - //typeToken=('struct' | 'union' | { next("class") }?=> IDENTIFIER) - typeToken=('struct' | 'union' | 'class') - ( - ( m1=modifiers { modifiers.addAll($m1.modifiers); } )? - ( - ab=structBody { - $struct = $ab.struct; - $struct.setForwardDeclaration(false); - } | - tag=qualifiedIdentifier { - defineTypeIdentifierInParentScope($tag.identifier); - setCurrentClassName($tag.identifier); - } - ( - ( - ( m2=modifiers { modifiers.addAll($m2.modifiers); } )? - ( - ':' - ( { next("public", "private", "virtual") }? p=IDENTIFIER )?//m3=modifiers - parent=qualifiedIdentifier { - parentIdentifier = $parent.identifier; - } - )? - nb=structBody { - $struct = $nb.struct; - $struct.setForwardDeclaration(false); - if (parentIdentifier != null) - $struct.addParent(parentIdentifier); - } - ) | { - $struct = new Struct(); - $struct.setForwardDeclaration(true); - } - ) { - $struct.setTag($tag.identifier); - } - ) - ) - ; - -anyOp returns [java.lang.Enum op] - : binaryOp { $op = $binaryOp.op; } | - unaryOp { $op = $unaryOp.op; } | - assignmentOp { $op = $assignmentOp.op; } - ; - -//structInsides returns [List declarations, Struct.MemberVisibility - -functionDeclaration returns [Function function] -scope Symbols; -@init { - $Symbols::typeIdentifiers = new HashSet(); -} - : { - $function = mark(new Function(), -1); - $function.setType(Function.Type.CFunction); - } - ( - // C++ cast operator - { next("operator") }?=> IDENTIFIER { - $function.setName(ident("operator")); - mark($function, getLine($start)); - } - ( castPreMods=modifiers { $function.addModifiers($castPreMods.modifiers); } )? - castTypeRef=mutableTypeRef { - $function.setValueType($castTypeRef.type); - } | - ( preMods1=modifiers { $function.addModifiers($preMods1.modifiers); } )? - returnTypeRef=mutableTypeRef { - $function.setValueType($returnTypeRef.type); - } - ( preMods2=modifiers { $function.addModifiers($preMods2.modifiers); } )? - name=qualifiedCppFunctionName { - $function.setName($name.identifier); - mark($function, getLine($start)); - } - ) - s=functionDeclarationSuffix { - $function.setArgs($s.args); - $function.addModifiers($s.postModifiers); - if (!$s.initializers.isEmpty()) { - $function.setInitializers($s.initializers); - $function.setType(Function.Type.CppMethod); - } - $function.setThrows($s.thrown != null); - $function.setThrown($s.thrown); - $function.setBody($s.body); - } - ; - -functionDeclarationSuffix returns [List args, List postModifiers, List initializers, Block body, List thrown] - : - { - $initializers = new ArrayList(); - } - argList { - $args = $argList.args; - } - ( postMods=modifiers { $postModifiers = $postMods.modifiers; } )? - ( - { next("throw") }? IDENTIFIER { - $thrown = new ArrayList(); - } - '(' - ( - t1=mutableTypeRef { - $thrown.add($t1.type); - } - ( - ',' - tx=mutableTypeRef { - $thrown.add($tx.type); - } - )* - )? - ')' - )? - ( - ':' - i1=constructorInitializer { $initializers.add($i1.init); } - ( - ',' ix=constructorInitializer { $initializers.add($ix.init); } - )* - )? - ( - ( - { next(2, "0") }? '=' DECIMAL_NUMBER // TODO mark in DOM - )? - ';' | - statementsBlock { - $body = $statementsBlock.statement; - } - ) - ; -constructorInitializer returns [FunctionCall init] - : qn=qualifiedCppFunctionName { - $init = new FunctionCall(new TypeRefExpression(new SimpleTypeRef($qn.identifier))); - } - '(' ( - el=topLevelExprList { $init.addArguments($el.exprs); } - )? ')' - ; - -modifiers returns [List modifiers] -@init { $modifiers = new ArrayList(); } - : - m=modifier { - $modifiers.addAll($m.modifiers); - } - ( - x=modifier { - $modifiers.addAll($x.modifiers); - } - )* - ; - -pragmaContent : - //{ next("__pragma") }?=> pragmaContent - // MSVC-specific : parse as token soup for now - IDENTIFIER '(' - (IDENTIFIER | constant | ',' | ':' | '(' (IDENTIFIER | constant | ',' | ':')* ')')* - ')' - ';'? - //) - ; - -modifier returns [List modifiers, String asmName] -@init { $modifiers = new ArrayList(); } - : - - { next("__pragma") }?=> pragmaContent | - { next("extern") }?=> IDENTIFIER ex=STRING { - $modifiers.add(ModifierType.Extern); // TODO - } | - { parseModifier(next()) != null }? m=IDENTIFIER { - $modifiers.add(ModifierType.parseModifier($m.text)); - } | - //{ next("__declspec", "__attribute__") }?=> IDENTIFIER - ( '__declspec' | '__attribute__' ) - '('+ ( - { next(ModifierKind.Extended) }? m=IDENTIFIER - ( - '(' arg=constant ')' { - $modifiers.add(new ValuedModifier(ModifierType.parseModifier($m.text), $arg.constant)); - } | - { - $modifiers.add(ModifierType.parseModifier($m.text)); - } - ) - //extendedModifiers { $modifiers.addAll($extendedModifiers.modifiers); } - - )* ')'+ | - { next("__asm") }?=> IDENTIFIER '(' ( - an=STRING { - String s = String.valueOf(Constant.parseString($an.text).getValue()); - if ($asmName == null) - $asmName = s; - else - $asmName += s; - } - )+ ')' | - { next("__success") }?=> - IDENTIFIER '(' 'return' binaryOp expression ')' | - - // TODO handle it properly @see http://blogs.msdn.com/staticdrivertools/archive/2008/11/06/annotating-for-success.aspx - { next(ModifierKind.VCAnnotation1Arg, ModifierKind.VCAnnotation2Args) }?=> - m=IDENTIFIER '(' x=constant ')' { - $modifiers.add(new ValuedModifier(ModifierType.parseModifier($m.text), $x.constant)); - } - ; - -//http://msdn.microsoft.com/en-us/library/dabb5z75.aspx -extendedModifiers returns [List modifiers] -scope ModContext; -@init { - $ModContext::isInExtMod = true; -} - : { $modifiers = new ArrayList(); } - ( - { next(ModifierKind.Extended) }? m=IDENTIFIER - ( - '(' arg=constant ')' { - $modifiers.add(new ValuedModifier(ModifierType.parseModifier($m.text), $arg.constant)); - } | - { - $modifiers.add(ModifierType.parseModifier($m.text)); - } - ) - )* - ; -argDef returns [Arg arg] - : ( - tr=mutableTypeRef { - if ($tr.type != null) { - $arg = new Arg(); - $arg.setValueType($tr.type); - int i = getTokenStream().index() + 1; - $arg.setCommentBefore(getCommentBefore(i)); - $arg.setCommentAfter(getCommentAfterOnSameLine(i, ")")); - } - } - ) - ( - declarator { - if ($arg != null) { - $arg.setDeclarator($declarator.decl); - } - } - )? - /*modifiers { - $arg.addModifiers($modifiers.modifiers); - }*/ - ( '=' dv=topLevelExpr { - if ($arg != null) - $arg.setDefaultValue($dv.expr); - } )? - | - '...' { - $arg = Arg.createVarArgs(); - } - ; - -typeMutator returns [TypeMutator mutator] - : - { next("const", "__const") }?=> IDENTIFIER { - $mutator = TypeMutator.CONST; - } | - '*' { - $mutator = TypeMutator.STAR; - } | - '&' { - $mutator = TypeMutator.AMPERSTAND; - } | - '^' { - $mutator = TypeMutator.HAT; - } | - '[' ']' { $mutator = TypeMutator.BRACKETS; } - ; - -arrayTypeMutator returns [TypeMutator mutator] - : '[' - expression { - $mutator = TypeMutator.array($expression.expr); - } - ']' - ; - -templatePrefix returns [Template template] -scope IsTypeDef; -@init { - $IsTypeDef::isTypeDef = true; - $template = new Template(); -} - : - { next("template") }? IDENTIFIER - '<' - ( - t1=templateArgDecl { - $template.addArg($t1.arg); - } - ( - ',' tx=templateArgDecl { - $template.addArg($tx.arg); - } - )* - )? - '>' - ; - -templateArgDecl returns [Arg arg] - : t=('class' | 'typename') n=IDENTIFIER { - $arg = new Arg($n.text, new SimpleTypeRef($t.text)); - addTypeIdent($n.text); - } - ( - '=' tr=mutableTypeRef { - $arg.setDefaultValue(expr($tr.type)); - } - )? | - argDef { - $arg = $argDef.arg; - } //mutableTypeRef ('=' constant)? - ( - '=' v=expression { - $arg.setDefaultValue($v.expr); - } - )? - ; - -functionSignatureSuffix returns [FunctionSignature signature] - : tk='(' { - $signature = mark(new FunctionSignature(new Function(Function.Type.CFunction, null, null)), getLine($tk)); - $signature.getFunction().setType(Function.Type.CFunction); - } - ( - m1=modifiers { - $signature.getFunction().addModifiers($m1.modifiers); - } - )? - ( - pt=('*' | '^') { - if ($pt.text != null && $pt.text.equals("^")) - $signature.setType(FunctionSignature.Type.ObjCBlock); - } - ( - m2=modifiers { - $signature.getFunction().addModifiers($m2.modifiers); - } - )? - )? - ( - ii=IDENTIFIER { - if (isTypeDef()) - addTypeIdent($ii.text); - $signature.getFunction().setName(new SimpleIdentifier($IDENTIFIER.text)); - } - )? - ')' - '(' ( - a1=argDef { - if (!$a1.text.equals("void")) - $signature.getFunction().addArg($a1.arg); - } - ( - ',' - ax=argDef { - $signature.getFunction().addArg($ax.arg); - } - )* - )? ')' - ; - -functionSignatureSuffixNoName returns [FunctionSignature signature] - : tk='(' m=modifiers? pt=('*' | '^') ')' { - $signature = mark(new FunctionSignature(new Function(Function.Type.CFunction, null, null)), getLine($tk)); - if ($pt.text.equals("^")) - $signature.setType(FunctionSignature.Type.ObjCBlock); - $signature.getFunction().setType(Function.Type.CFunction); - if ($m.modifiers != null) - $signature.getFunction().addModifiers($m.modifiers); - } - '(' ( - a1=argDef { - if (!$a1.text.equals("void")) - ((FunctionSignature)$signature).getFunction().addArg($a1.arg); - } - ( - ',' - ax=argDef { - ((FunctionSignature)$signature).getFunction().addArg($ax.arg); - } - )* - )? ')' - ; - -mutableTypeRef returns [TypeRef type] -@before { - checkInterrupt(); -} - : - nonMutableTypeRef { - $type = $nonMutableTypeRef.type; - } - ( - ( - m1=typeMutator { - $type = $m1.mutator.mutateType($type); - } - ) | - ( - f1=functionSignatureSuffix { - assert $f1.signature != null && $f1.signature.getFunction() != null; - if ($f1.signature != null && $f1.signature.getFunction() != null) { - $f1.signature.getFunction().setValueType($type); - $type = $f1.signature; - } - } - ) - )* - ; - -declarator returns [Declarator decl] - : - m=modifiers? - ( - ( - ( - ( - directDeclarator { - $decl = $directDeclarator.decl; - } - ) | - ( - pt=('*' | '&' | '^') - inner=declarator { - // TODO EMPTY DECLARATOR... maybe not the brightest idea one can have... - $decl = new PointerDeclarator($inner.decl == null ? new DirectDeclarator(null) : $inner.decl, PointerStyle.parsePointerStyle($pt.text)); - //$decl = new PointerDeclarator(new DirectDeclarator("toto")/*$inner.decl*/, PointerStyle.parsePointerStyle($pt.text)); - //$decl = new DirectDeclarator("toto"); - } - ) - ) - ( - ':' bits=DECIMAL_NUMBER { - if ($decl != null) - $decl.setBits(Integer.parseInt($bits.text)); - } - )? - ) | - ':' bits=DECIMAL_NUMBER { - $decl = mark(new DirectDeclarator(null), getLine($bits)); - $decl.setBits(Integer.parseInt($bits.text)); - } - ) - { - if ($decl != null && $m.modifiers != null) - $decl.setModifiers($m.modifiers); - } - ; - -typeDef returns [TypeDef typeDef] -scope IsTypeDef; -@init { - $IsTypeDef::isTypeDef = true; -} - : 'typedef' - varDecl ';' { - VariablesDeclaration vd = $varDecl.decl; - $typeDef = new TypeDef(vd.getValueType(), vd.getDeclarators()); - } - ; - -varDeclEOF returns [Declaration decl] - : varDecl ';' EOF { $decl = $varDecl.decl; } - ; - -declarationEOF returns [Declaration declaration] - : d=declaration EOF { $declaration = $d.declaration; } - ; - -varDecl returns [VariablesDeclaration decl] - : - tr=nonMutableTypeRef { - $decl = new VariablesDeclaration($tr.type); - } - ( - d1=declaratorsList { - $decl.setDeclarators($d1.declarators); - } - )? - ; - -objCProtocolRefList - : '<' - IDENTIFIER - ( - ',' - IDENTIFIER - )* - '>' - ; - -declaratorWithValue returns [Declarator decl] - : - declarator { - $decl = $declarator.decl; - } - ( - '=' - dv=topLevelExpr { - $decl.setDefaultValue($dv.expr); - } - )? - ; - -declaratorsList returns [List declarators] - : { $declarators = new ArrayList(); } - d=declaratorWithValue { - $declarators.add($d.decl); - } - ( - ',' - x=declaratorWithValue { - $declarators.add($x.decl); - } - )* - ; - -directDeclarator returns [Declarator decl] - : - ( - { parseModifier(next()) == null }?=> IDENTIFIER { - $decl = mark(new DirectDeclarator($IDENTIFIER.text), getLine($IDENTIFIER)); - if (isTypeDef()) { - addTypeIdent($IDENTIFIER.text); - } - } | - '(' inner=declarator ')' { - $decl = $inner.decl; - if ($decl != null) - $decl.setParenthesized(true); - } - ) - ( - '[' - ( - ( - expression { - if ($decl instanceof ArrayDeclarator) - ((ArrayDeclarator)$decl).addDimension($expression.expr); - else - $decl = new ArrayDeclarator($decl, $expression.expr); - } - ) | - ( - { - $decl = new ArrayDeclarator($decl, new Expression.EmptyArraySize()); - } - ) - ) - ']' | - argList { - $decl = new FunctionDeclarator($decl, $argList.args); - } - )* - ; - -argList returns [List args, boolean isObjC] - : { - $isObjC = false; - $args = new ArrayList(); - } - - op='(' - ( - a1=argDef { - if (!$a1.text.equals("void")) - $args.add($a1.arg); - } - ( - ',' - ax=argDef { - $args.add($ax.arg); - } - )* - ( - ',' '...' { - $isObjC = true; - $args.add(Arg.createVarArgs()); - } - )? - )? - cp=')' - ; - -nonMutableTypeRef returns [TypeRef type] -scope ModifierKinds; -@init { - List modifiers = new ArrayList(); - //TypeRef ref = null; - int line = -1; -} -@after { - if ($type == null && !modifiers.isEmpty()) { - $type = new Primitive(null); - } - if ($type != null) { - $type.addModifiers(modifiers); - mark($type, line); - } -} - : - ( preMods=modifiers { - modifiers.addAll($preMods.modifiers); - try { - if (ModifierType.UUID.isContainedBy(modifiers)) - allowKinds(ModifierKind.VCParameterAnnotation); - } catch (Throwable th) { - th.printStackTrace(); - } - - } )? - ( - 'typename' pn=typeName { $type = $pn.type; } | - { - next(2, "<") || - isTypeIdentifier(next()) || - ( - parseModifier(next(1)) == null && - (isTypeDef() || !next(2, "=", ",", ";", ":", "[", "(", ")")) - ) - }?=> an=typeName { $type = $an.type; } | - structCore { $type = $structCore.struct; } | - enumCore { $type = $enumCore.e; } - )? - ( postMods=modifiers { modifiers.addAll($postMods.modifiers); } )? - /* - ( - ( preMods=modifiers { modifiers.addAll($preMods.modifiers); } )? - ( - //{ parseModifier(next()) == null }?=> - tr1=typeRefInsides { - $type = $tr1.type; - } - ( postMods1=modifiers { modifiers.addAll($postMods1.modifiers); } )? - )? - ) | - //{ parseModifier(next()) == null }? - ( - tr2=typeRefInsides { - $type = $tr2.type; - } - ( postMods2=modifiers { modifiers.addAll($postMods2.modifiers); } )? - )*/ - ; - - -typeRefInsides returns [TypeRef type] - : - 'typename' pn=typeName { $type = $pn.type; } | - { - isTypeIdentifier(next()) || - ( - parseModifier(next(1)) == null && - !next(2, "=", ",", ";", ":", "[", "(", ")") - ) - }?=> an=typeName { $type = $an.type; } | - structCore { $type = $structCore.struct; } | - enumCore { $type = $enumCore.e; } - ; - -typeName returns [TypeRef type] - : - i=qualifiedIdentifier { - if ($i.identifier.isPlain() && isPrimitiveType($i.identifier.toString())) - $type = new Primitive($i.identifier.toString()); - else - $type = new SimpleTypeRef($i.identifier); - if ($i.identifier.isPlain()) - addTypeIdent($i.identifier.toString()); - } - ; - -objCMethodCall returns [FunctionCall expr] - : - '[' target=expression methodName=IDENTIFIER { - $expr = new FunctionCall(); - $expr.setFunction(new VariableRef(new SimpleIdentifier($methodName.text))); - $expr.setTarget($target.expr); - $expr.setMemberRefStyle(MemberRefStyle.SquareBrackets); - } - ( - ':' arg1=expression { - $expr.addArgument(null, $arg1.expr); - } - ( - selx=IDENTIFIER ':' argx=expression { - $expr.addArgument($selx.text, $argx.expr); - } - )* - )? - ']' - ; - -binaryOp returns [Expression.BinaryOperator op] - : t=( - '+' | '-' | '*' | '/' | '%' | - '<<' | '>>>' | '>>' | - '^' | '||' | '|' | '&&' | '&' | - '<=' | '>=' | '<' | '>' | '==' | '!=' - ) { - $op = Expression.getBinaryOperator($t.text); - if ($op == null) - throw new RuntimeException("Failed to parse op " + $t.text); - } - ; - -postfixOp returns [Expression.UnaryOperator op] - : - '++' { - $op = UnaryOperator.PostIncr; - } | - '--' { - $op = UnaryOperator.PostDecr; - } - ; - -typeRefOrExpression returns [Expression expr] - : tr=mutableTypeRef { - $expr = new Expression.TypeRefExpression($tr.type); - } | - e=topLevelExpr { - $expr = $e.expr; - } - ; - -simpleIdentifier returns [SimpleIdentifier identifier] - : i=IDENTIFIER { $identifier = new SimpleIdentifier($i.text); } - ( - '<' ( - a1=typeRefOrExpression { $identifier.addTemplateArgument($a1.expr); } - ( - ',' - ax=typeRefOrExpression { $identifier.addTemplateArgument($ax.expr); } - )* - )? '>' - )? - ; - -qualifiedIdentifier returns [Identifier identifier] - : - '::'? - i1=simpleIdentifier { $identifier = $i1.identifier; } - ( - '::' ix=simpleIdentifier { $identifier = $identifier.derive(QualificationSeparator.Colons, $ix.identifier); } - )* - ; - -qualifiedCppFunctionName returns [Identifier identifier] - : i1=simpleCppFunctionName { $identifier = $i1.identifier; } - ( - '::' ix=simpleCppFunctionName { $identifier = $identifier.derive(QualificationSeparator.Colons, $ix.identifier); } - )* - ; - -operator returns [Expression.Operator op] - : - unaryOp { $op = $unaryOp.op; } | - postfixOp { $op = $postfixOp.op; } | - binaryOp { $op = $binaryOp.op; } | - assignmentOp { $op = $assignmentOp.op; } | - '=' { $op = BinaryOperator.Assign; } | - '->' '*' { $op = BinaryOperator.ArrowStar; } | - '[' ']' { $op = BinaryOperator.SquareBrackets; } | - '(' ')' { $op = UnaryOperator.Parenthesis; } | - ',' { $op = BinaryOperator.Comma; } | - '->' { $op = BinaryOperator.Arrow; } - ; - -simpleCppFunctionName returns [SimpleIdentifier identifier] - : - { next("operator") }? IDENTIFIER operator { - $identifier = new SimpleIdentifier("operator" + $operator.op.toString()); - } | - pre='~'? //n=IDENTIFIER anyOp? { - i=simpleIdentifier { - if ($pre.text != null) - $i.identifier.setName($pre.text + $i.identifier.getName()); - $identifier = $i.identifier; - } - ; - -expressionsBlock returns [ExpressionsBlock expr] - : - '{' { - $expr = new ExpressionsBlock(); - } - ( - e1=expression { - $expr.addExpression($e1.expr); - } - ( - ',' - ex=expression { - $expr.addExpression($ex.expr); - } - )* - )? - '}' - ; - - -baseExpression returns [Expression expr] - : - i=simpleIdentifier { $expr = new VariableRef($i.identifier); } | - constant { $expr = $constant.constant; } | - '(' expression ')' { - $expr = $expression.expr; - if ($expr != null) - $expr.setParenthesis(true); - } | - objCMethodCall { $expr = $objCMethodCall.expr; } | - expressionsBlock { $expr = $expressionsBlock.expr; } | - selectorExpr | - protocolExpr | - encodingExpr//| - ; - -selectorExpr returns [Expression expr] - : '@selector' - '(' - selectorName - ')' - ; - -selectorName - : IDENTIFIER (IDENTIFIER ':')* - ; - -protocolExpr - : '@protocol' - '(' - IDENTIFIER - ')' - ; - -encodingExpr - : '@encode' - '(' - IDENTIFIER - ')' - ; - -assignmentExpr returns [Expression expr] - : e=inlineCondExpr { $expr = $e.expr; } - ( - op=assignmentOp f=assignmentExpr { - $expr = new AssignmentOp($expr, getAssignmentOperator($op.text), $f.expr); - } - )? - ; - -assignmentOp returns [Expression.AssignmentOperator op] - : t=('=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' | '~=') { - $op = getAssignmentOperator($t.text); - } - ; - -inlineCondExpr returns [Expression expr] - : e=logOrExpr { $expr = $e.expr; } - ( - '?' - logOrExpr - ':' - logOrExpr - )* - ; - -addExpr returns [Expression expr] - : e=multExpr { $expr = $e.expr; } - ( - op=('+' | '-') - f=multExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -multExpr returns [Expression expr] - : e=castExpr { $expr = $e.expr; } - ( - op=('%' | '*' | '/') - f=castExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -bitOrExpr returns [Expression expr] - : e=xorExpr { $expr = $e.expr; } - ( - op='|' - f=xorExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -bitAndExpr returns [Expression expr] - : e=equalExpr { $expr = $e.expr; } - ( - op='&' - f=equalExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - - -shiftExpr returns [Expression expr] - : e=addExpr { $expr = $e.expr; } - ( - op=('>>' | '<<') - f=addExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -xorExpr returns [Expression expr] - : e=bitAndExpr { $expr = $e.expr; } - ( - op='^' - f=bitAndExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -logOrExpr returns [Expression expr] - : e=logAndExpr { $expr = $e.expr; } - ( - op='||' - f=logAndExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -logAndExpr returns [Expression expr] - : e=bitOrExpr { $expr = $e.expr; } - ( - op='&&' - f=bitOrExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -equalExpr returns [Expression expr] - : e=compareExpr { $expr = $e.expr; } - ( - op=('!=' | '==') - f=compareExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -compareExpr returns [Expression expr] - : e=shiftExpr { $expr = $e.expr; } - ( - op=('<' | '<=' | '>' | '>=') - f=shiftExpr { $expr = new BinaryOp($expr, getBinaryOperator($op.text), $f.expr); } - )* - ; - -castExpr returns [Expression expr] - : '(' tr=mutableTypeRef ')' ( - inner=castExpr { $expr = new Cast($tr.type, $inner.expr); } | - '(' expression ( ',' expression ) + ')' // TODO OpenCL tuple cast - ) | - e=unaryExpr { $expr = $e.expr; } - ; - -unaryExpr returns [Expression expr] - : - { next("sizeof") }? IDENTIFIER ( - '(' tr=mutableTypeRef ')' { - $expr = new FunctionCall(varRef("sizeof"), new TypeRefExpression($tr.type)); - } - //| unaryExpr // TODO check this !!! - ) | - p=postfixExpr { $expr = $p.expr; } | - uo=unaryOp castExpr { $expr = new UnaryOp($castExpr.expr, $uo.op); } - ; - -unaryOp returns [Expression.UnaryOperator op] - : t=('++' | '--' | '&' | '*' | '-' | '~' | '!') { - $op = Expression.getUnaryOperator($t.text); - } - ; - -postfixExpr returns [Expression expr] -@init { - List multiArrayDims = new ArrayList(); -} - : - { next("new") }? IDENTIFIER tr=nonMutableTypeRef - ( - ( - topLevelExprList? { - if ($topLevelExprList.exprs == null) - $expr = new New(tr); - else - $expr = new New(tr, $topLevelExprList.exprs); - } - ) | - ( - ( - '[' dim=expression ']' { - multiArrayDims.add($expression.expr); - } - )+ - { - NewArray na = new NewArray(); - na.setType(tr); - na.setDimensions(multiArrayDims); - $expr = na; - } - ) - ) | - baseExpression { $expr = $baseExpression.expr; } - ( - '[' expression ']' { - $expr = new ArrayAccess($expr, $expression.expr); - } | - '(' topLevelExprList? ')' { - FunctionCall fc = new FunctionCall($expr); - if ($topLevelExprList.exprs != null) - for (Expression x : $topLevelExprList.exprs) - fc.addArgument(x); - $expr = fc; - } | - '::' ao=simpleIdentifier { - $expr = new MemberRef($expr, MemberRefStyle.Colons, $ao.identifier); - } | - '.' di=simpleIdentifier { - $expr = new MemberRef($expr, MemberRefStyle.Dot, $di.identifier); - } | - '->' ai=simpleIdentifier { - $expr = new MemberRef($expr, MemberRefStyle.Arrow, $ai.identifier); - } | - postfixOp { - $expr = new UnaryOp($expr, $postfixOp.op); - } - )* - ; - -topLevelExpr returns [Expression expr] - : e=assignmentExpr { $expr = $e.expr; } - ; -topLevelExprList returns [List exprs] - : - { $exprs = new ArrayList(); } - e=topLevelExpr { $exprs.add($e.expr); } - ( - ',' - f=topLevelExpr { $exprs.add($f.expr); } - )* - ; - -expression returns [Expression expr] -@before { - checkInterrupt(); -} - : l=topLevelExprList { - if ($l.exprs != null) { - if ($l.exprs.size() == 1) - $expr = $l.exprs.get(0); - else - $expr = new ExpressionSequence($l.exprs); - } - } - ; - - -statementsBlock returns [Block statement] -scope Symbols; -@init { - $Symbols::typeIdentifiers = new HashSet(); -} - : { $statement = new Block(); } - '{' - ( - statement { - $statement.addStatement($statement.stat); - } | - lineDirective - )* - '}' - ; - -gccAsmInOut - : - STRING '(' IDENTIFIER ')' - ; -gccAsmInOuts - : - gccAsmInOut ( ',' gccAsmInOut )* - ; - -statement returns [Statement stat] - : - b=statementsBlock { - $stat = $b.statement; - } | - // GCC inline asm (see http://ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html) - { next("__asm__") }?=> IDENTIFIER '(' - STRING* ( ':' gccAsmInOuts )* - ')' ';' ? | - // MSVC inline asm soup - { next("__asm") }?=> IDENTIFIER '{' - ( expression | ',' )* - '}'| - { next("foreach") }?=> IDENTIFIER '(' varDecl { next("in") }? IDENTIFIER expression ')' statement { - // TODO - } | - { next("delete") }?=> IDENTIFIER ( - '[' ']' delArr=expression { - $stat = new Delete($delArr.expr, true); - } | - del=expression { - $stat = new Delete($del.expr, false); - } - ) ';' | - pe=postfixExpr ';' { - // Hack to make sure that f(x); is not parsed as a declaration ! - // Must stay before declaration. - $stat = new ExpressionStatement($pe.expr); - } | - declaration { - $stat = stat($declaration.declaration); - } | - es=expression ';' { - $stat = new ExpressionStatement($es.expr); - } | - rt='return' rex=expression? ';' { - $stat = mark(new Return($rex.expr), getLine($rt)); - } | - IDENTIFIER ':' | // label - 'break' ';' | - 'if' '(' ifTest=topLevelExpr ')' thn=statement ('else' els=statement)? { - $stat = new Statement.If(ifTest.expr, thn, els); - } | - 'while' '(' whileTest=topLevelExpr ')' wh=statement { - $stat = new Statement.While(whileTest.expr, wh); - } | - 'do' doStat=statement 'while' '(' doWhileTest=topLevelExpr ')' ';' { - $stat = new Statement.DoWhile(doWhileTest.expr, doStat); - } | - 'for' '(' - ( - (varDecl | expression) ? ';' expression? ';' expression? | - varDecl ':' expression // Java foreach - ) - ')' forStat=statement { - // TODO - } | - 'switch' '(' expression ')' '{' // TODO - ( - 'case' topLevelExpr ':' | - statement | - lineDirective - )* - '}' | - ';' - ; - -constant returns [Constant constant] - : s=('-' | '+')? ( - DECIMAL_NUMBER { $constant = Constant.parseDecimal(($s.text == null ? "" : $s.text) + $DECIMAL_NUMBER.text); } | - HEXADECIMAL_NUMBER { $constant = Constant.parseHex($HEXADECIMAL_NUMBER.text, "-".equals($s.text)); } | - OCTAL_NUMBER { $constant = Constant.parseOctal($OCTAL_NUMBER.text, "-".equals($s.text)); } - ) | - CHARACTER { $constant = Constant.parseCharOrStringInteger($CHARACTER.text); } | - s2=('-' | '+')? FLOAT_NUMBER { $constant = Constant.parseFloat(($s2.text == null ? "" : $s2.text) + $FLOAT_NUMBER.text); } | - //CHARACTER { $constant = Constant.parseChar($CHARACTER.text); } | - STRING { $constant = Constant.parseString($STRING.text); } - ; - - -fragment -Letter - : '$' | - '_' | - 'A'..'Z' | - 'a'..'z' - ; - -javaTemplateArg returns [Expression expr] - : - t=javaType { - $expr = expr($t.typeRef); - } | - tk='?' { - $expr = expr($tk.text); - } - ; - -javaTypeIdent returns [Identifier ident] - : - f=IDENTIFIER { - $ident = ident($f.text); - } - ( - '.' n=IDENTIFIER { - $ident = $ident.derive(Identifier.QualificationSeparator.Dot, $n.text); - } - )+ - ( - '<' - first=javaTemplateArg { - $ident.resolveLastSimpleIdentifier().addTemplateArgument($first.expr); - } - ( - ',' - other=javaTemplateArg { - $ident.resolveLastSimpleIdentifier().addTemplateArgument($other.expr); - } - )* - '>' - )? - - ; - -javaType returns [TypeRef typeRef] - : - i=javaTypeIdent { - $typeRef = new TypeRef.SimpleTypeRef($i.ident); - } - ( - '[' ']' { - $typeRef = new TypeRef.ArrayRef($typeRef); - } - ) - ; - -javaArg returns [Arg arg] - : - t=javaType n=IDENTIFIER { - $arg = new Arg($n.text, $t.typeRef); - } - ; - -javaMethodDeclaration returns [Function function] - : - ret=javaType - name=IDENTIFIER { - $function = new Function(); - $function.setType(Function.Type.JavaMethod); - $function.setName(ident($name.text)); - $function.setValueType($ret.typeRef); - } - '(' - first=javaArg { - $function.addArg($first.arg); - } - ( - ',' - other=javaArg { - $function.addArg($other.arg); - } - ) - ')' - ';' - ; - -IDENTIFIER - : - ( - //( - Letter - ( - Letter | - '0'..'9' - )* - //) | - /*( - 'operator' - ( - '+' '+'? '='? | - '-' '-'? '='? | - '*' '='? | - '/' '='? | - '%' '='? | - '<' '<'? '='? | - '>' ('>' '>'?)? '='? | - '^' '='? | - '|' '|'? '='? | - '&' '&'? '='? | - '=' '='? | - '!' '='? | - '~' '='? - ) - )*/ - ) - ; - -fragment -FloatingPointExponentSuffix - : ('e' | 'E') - ('+' | '-')? - ('0'..'9')+ - ; - -fragment -FloatingPointConstantSuffix - : 'f' | - 'F' | - 'd' | - 'D' - ; - -fragment -CharEscape - : '\\' - ( - 'b' | - 't' | - 'n' | - 'f' | - 'r' | - '\"' | - '\'' | - '\\' - ) | - OctalEscape - ; - -fragment -OctalEscape - : '\\' ( - ('0'..'3') ('0'..'7') ('0'..'7') | - ('0'..'7') ('0'..'7') | - ('0'..'7') - ) - ; - -fragment -UnicodeEscape - : '\\' - 'u' - HexDigit HexDigit HexDigit HexDigit - ; - - -CHARACTER - : '\'' - ( - CharEscape | - ~( - '\\' | - '\'' - ) - )+ - '\'' - ; - -STRING - : '"' - ( - CharEscape | - ~( - '\\' | - '"' - ) - )* - '"' - ; - - -fragment -HexDigit - : '0'..'9' | - 'a'..'f' | - 'A'..'F' - ; - -fragment -IntegerConstantSuffix - : ('u' | 'U') | - ( - ('l' | 'L') - ('l' | 'L')? - ) - ; - -HEXADECIMAL_NUMBER - : '0' ('x'|'X') - HexDigit+ - IntegerConstantSuffix? - ; - -DECIMAL_NUMBER - : //('-' | '+')? - ('0' | '1'..'9' '0'..'9'*) - IntegerConstantSuffix? - ; - -OCTAL_NUMBER - : '0' - ('0'..'7')+ - IntegerConstantSuffix? - ; - -FLOAT_NUMBER - : //('-' | '+')? - ('0'..'9')+ - ( - '.' - ('0'..'9')* - )? - FloatingPointExponentSuffix? - FloatingPointConstantSuffix? - ; - -WS - : ( - ' ' | - '\r' | - '\t' | - '\u000C' | - '\n' - ) { - $channel=HIDDEN; - } - ; - -COMMENT - : ( - '/*' - ( options {greedy=false;} : . )* - '*/' - ) { - $channel=HIDDEN; - } - ; - -LINE_COMMENT - : ( - '//' - ~('\n'|'\r')* - ('\r'? '\n' | { input.LT(1) == EOF }? ) - ) { - $channel=HIDDEN; - } - ; - diff --git a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/XCodeProject.g b/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/XCodeProject.g deleted file mode 100644 index 6f5be8fea..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/antlr3/com/ochafik/lang/jnaerator/parser/XCodeProject.g +++ /dev/null @@ -1,276 +0,0 @@ -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -/** - This grammar is by no mean complete. - It is able to parse preprocessed C & Objective-C files and can tolerate some amount of C++. - It lacks serious expression support, which is being worked on. - Complex variable declarations may not be supported, such as complex signatures of functions that return function pointers... -*/ - -grammar XCodeProject; -options { - backtrack=true; - output=AST; - k=3; -} - -@header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -} - -@members { - -} - -@lexer::header { -/* - Copyright (c) 2009 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ - -package com.ochafik.lang.jnaerator.parser; -} - -xCodeProject - : map - ; - -map returns [Map map] - : { $map = new HashMap(); } - '{' - ( - IDENTIFIER '=' value ';' { - $map.put($IDENTIFIER.text, $value.value); - } - )* - '}' - ; - -value returns [Object value] - : constant { $value = $constant.constant; } | - map { $value = $map.map; } | - IDENTIFIER { - try { - $value = Integer.parseInt($IDENTIFIER.text); - } catch (Exception ex) { - $value = $IDENTIFIER.text; - } - } | - list { $value = $list.list; } - ; - -list returns [List list] - : { $list = new ArrayList(); } - '(' - ( - head=value { $list.add($head.value); } - ( - ',' - v=value { $list.add($v.value); } - )* - )? - ')' - ; - -constant returns [Object constant] - : //DECIMAL_NUMBER { $constant = Integer.parseInt($DECIMAL_NUMBER.text); } | - //HEXADECIMAL_NUMBER { $constant = Integer.parseInt($HEXADECIMAL_NUMBER.text, 16); } | - //OCTAL_NUMBER { $constant = Integer.parseInt($OCTAL_NUMBER.text, 8); } | - //FLOAT_NUMBER { $constant = Float.parseFloat($FLOAT_NUMBER.text); } | - CHARACTER { $constant = $CHARACTER.text.substring(1, $CHARACTER.text.length() - 2); } | - STRING { $constant = $STRING.text.substring(1, $STRING.text.length() - 2); } - ; - - -fragment -Letter - : '$' | - '_' | - 'A'..'Z' | - 'a'..'z' - ; - -IDENTIFIER - : ( - Letter | - '0'..'9' - )* - ; - -fragment -FloatingPointExponentSuffix - : ('e' | 'E') - ('+' | '-')? - ('0'..'9')+ - ; - -fragment -FloatingPointConstantSuffix - : 'f' | - 'F' | - 'd' | - 'D' - ; - -fragment -CharEscape - : '\\' - ( - 'b' | - 't' | - 'n' | - 'f' | - 'r' | - '\"' | - '\'' | - '\\' - ) | - OctalEscape - ; - -fragment -OctalEscape - : '\\' ( - ('0'..'3') ('0'..'7') ('0'..'7') | - ('0'..'7') ('0'..'7') | - ('0'..'7') - ) - ; - -fragment -UnicodeEscape - : '\\' - 'u' - HexDigit HexDigit HexDigit HexDigit - ; - - -CHARACTER - : '\'' - ( - CharEscape | - ~( - '\\' | - '\'' - ) - )+ - '\'' - ; - -STRING - : '"' - ( - CharEscape | - ~( - '\\' | - '"' - ) - )* - '"' - ; - - -fragment -HexDigit - : '0'..'9' | - 'a'..'f' | - 'A'..'F' - ; - -fragment -IntegerConstantSuffix - : ('u' | 'U') | - ( - ('l' | 'L') - ('l' | 'L')? - ) - ; - -WS - : ( - ' ' | - '\r' | - '\t' | - '\u000C' | - '\n' - ) { - $channel=HIDDEN; - } - ; - -COMMENT - : ( - '/*' - ( options {greedy=false;} : . )* - '*/' - ) { - $channel=HIDDEN; - } - ; - -LINE_COMMENT - : ( - '//' - ~('\n'|'\r')* - '\r'? - '\n' - ) { - $channel=HIDDEN; - } - ; - diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Annotation.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Annotation.java deleted file mode 100644 index 21c07092a..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Annotation.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class Annotation extends Element { - - TypeRef annotationClass; - //Class annotationClass; - final List arguments = new ArrayList(); - String argument; - - public Annotation() { - - } - - public Annotation(Class annotationClass, Expression... arguments) { - this(typeRef(annotationClass), arguments); - } - public Annotation(TypeRef annotationClass, Expression... arguments) { - setAnnotationClass(annotationClass); - setArguments(Arrays.asList(arguments)); - } - public Annotation(TypeRef annotationClass, String argument) { - setAnnotationClass(annotationClass); - setArgument(argument); - } - - public void setArgument(String argument) { - this.argument = argument; - } - public String getArgument() { - return argument; - } - public void setArguments(List arguments) { - changeValue(this, this.arguments, arguments); - } - public List getArguments() { - return unmodifiableList(arguments); - } - - public TypeRef getAnnotationClass() { - return annotationClass; - } - public void setAnnotationClass(TypeRef annotationClass) { - this.annotationClass = changeValue(this, this.annotationClass, annotationClass); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitAnnotation(this); - } - - @Override - public Element getNextChild(Element child) { - return getNextSibling(arguments, child); - } - - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(arguments, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getAnnotationClass()) { - setAnnotationClass((TypeRef)by); - return true; - } - return replaceChild(arguments, Expression.class, this, child, by); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Arg.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Arg.java deleted file mode 100644 index 4405afcbf..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Arg.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Declarator.MutableByDeclarator; - -public class Arg extends Declaration { - String selector; - boolean varArg; - Declarator declarator; - Expression defaultValue; - - public Arg(String name, TypeRef type) { - this(); - setName(name); - setValueType(type); - } - - public Arg() { - } - - @Override -// @Deprecated - public TypeRef getValueType() { - return super.getValueType(); - } - - public TypeRef createMutatedType() { - TypeRef vt = getValueType(); - if (vt == null) - return null; - if (getDeclarator() != null) { - MutableByDeclarator type = getDeclarator().mutateType(vt); - if (type instanceof TypeRef) - return (TypeRef)getDeclarator().mutateType(vt); - else { - assert false; - return null; - } - } - return vt; - } - - public Declarator getDeclarator() { - return declarator; - } - public void setDeclarator(Declarator declarator) { - this.declarator = changeValue(this, this.declarator, declarator); - } - public String getName() { - return declarator == null ? null : declarator.resolveName(); - } - public void setName(String name) { - if (declarator == null) - setDeclarator(new Declarator.DirectDeclarator(name)); - else - declarator.propagateName(name); - } - @Override - public Arg clone() { - return (Arg)super.clone(); - } - - public Expression getDefaultValue() { - return defaultValue; - } - public void setDefaultValue(Expression defaultValue) { - this.defaultValue = changeValue(this, this.defaultValue, defaultValue); - } - - public static Arg createVarArgs() { - Arg a = new Arg(null, null); - a.varArg = true; - return a; - } - - public String getSelector() { - return selector; - } - - public void setSelector(String selector) { - this.selector = selector; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getDefaultValue()) { - setDefaultValue((Expression) by); - return true; - } - if (child == getDeclarator()) { - setDeclarator((Declarator) by); - return true; - } - return super.replaceChild(child, by); - } - - public void accept(Visitor visitor) { - visitor.visitArg(this); - } - - public boolean isVarArg() { - return varArg; - } - public Arg setVarArg(boolean v) { - varArg = v; - return this; - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declaration.java deleted file mode 100644 index 0b3dbf52f..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declaration.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; -import java.util.List; - -public abstract class Declaration extends Statement {//ModifiableElement { - - protected TypeRef valueType; - protected MemberVisibility visibility; - /*protected int bits = -1; - - public void setBits(int bits) { - this.bits = bits; - } - public int getBits() { - return bits; - }*/ - - @Override - public Declaration clone() { - return (Declaration) super.clone(); - } - - public TypeRef getValueType() { - return valueType; - } - public void setValueType(TypeRef valueType) { - if (valueType == null) - valueType = null; - this.valueType = changeValue(this, this.valueType, valueType); - } - - @Override - public List harvestModifiers() { - List mods = super.harvestModifiers(); - if (getValueType() != null) - mods.addAll(getValueType().harvestModifiers()); - return mods; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getValueType()) { - setValueType((TypeRef) by); - return true; - } - return super.replaceChild(child, by); - } - - public void setVisibility(MemberVisibility visibility) { - this.visibility = visibility; - } - public MemberVisibility getVisibility() { - return visibility; - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarations.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarations.java deleted file mode 100644 index d2bc832d4..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarations.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * - * @author ochafik - */ -public class Declarations extends Declaration implements DeclarationsHolder { - final List declarations = new ArrayList(); - - public Declarations() {} - public Declarations(List declarations) { - setDeclarations(declarations); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitDeclarations(this); - } - - public void addDeclaration(Declaration declaration) { - if (declaration != null) { - declaration.setParentElement(this); - declarations.add(declaration); - } - } - - public void addDeclarations(List ds) { - if (ds == null) - return; - for (Declaration d : ds) - d.setParentElement(this); - declarations.addAll(ds); - } - public void setDeclarations(List declarations) { - changeValue(this, this.declarations, declarations); - } - public void setDeclarations(Declaration... declarations) { - setDeclarations(Arrays.asList(declarations)); - } - public List getDeclarations() { - return unmodifiableList(declarations); - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(declarations, child); - if (e != null) - return e; - return super.getNextChild(child); - } - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(declarations, child); - if (e != null) - return e; - return super.getPreviousChild(child); - } - - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(declarations, Declaration.class, this, child, by)) - return true; - return super.replaceChild(child, by); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/DeclarationsHolder.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/DeclarationsHolder.java deleted file mode 100644 index 4516e5f61..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/DeclarationsHolder.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.Collections; -import java.util.List; - -public interface DeclarationsHolder { - void addDeclaration(Declaration d); - List getDeclarations(); - - public static class ListWrapper implements DeclarationsHolder { - public ListWrapper(List list) { - this.list = list; - } - - List list; - - public void addDeclaration(Declaration d) { - list.add(d); - } - - public List getDeclarations() { - return Collections.unmodifiableList(list); - } - - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarator.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarator.java deleted file mode 100644 index f427867d2..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Declarator.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import com.ochafik.lang.jnaerator.parser.Function.Type; - -/** - * @see MSDN Typedef Declarations - * @author ochafik - * - */ -public abstract class Declarator extends ModifiableElement { - protected Expression defaultValue; - boolean parenthesized = false; - int bits = -1; - public int getBits() { - return bits; - } - public void setBits(int bits) { - this.bits = bits; - } - @Override - public Declarator clone() { - return (Declarator)super.clone(); - } - public static interface MutableByDeclarator { - MutableByDeclarator clone(); - } - - public enum PointerStyle - { - Pointer { @Override public String toString() { return "*"; } }, - Reference { @Override public String toString() { return "&"; } }, - HatPointer { @Override public String toString() { return "^"; } }; - - static Map styles = new TreeMap(); - static { - for (PointerStyle style : values()) - styles.put(style.toString(), style); - } - public static PointerStyle parsePointerStyle(String s) { - return styles.get(s); - } - } - - @Override - public Declarator addModifiers(Modifier... mds) { - return (Declarator)super.addModifiers(mds); - } - public abstract MutableByDeclarator mutateType(MutableByDeclarator t); - - public final MutableByDeclarator mutateTypeKeepingParent(MutableByDeclarator type) { - MutableByDeclarator mutated = mutateType(type); - ((Element)mutated).setParentElement(((Element)type).getParentElement()); - return mutated; - } - public static class DirectDeclarator extends Declarator { - public DirectDeclarator(String name, int bits, Expression defaultValue) { - setName(name); - setBits(bits); - setDefaultValue(defaultValue); - } - public DirectDeclarator(String name) { - setName(name); - } - - public DirectDeclarator(String name, Expression defaultValue) { - setName(name); - setDefaultValue(defaultValue); - } - - public DirectDeclarator() {} - - String name; - public void setName(String name) { - this.name = name; - } - public String getName() { - return this.name; - } - public String resolveName() { - return getName(); - } - public MutableByDeclarator mutateType(MutableByDeclarator type) { - if (type == null) - return null; - type = type.clone(); - if (type instanceof Function) { - ((Function)type).setName(new Identifier.SimpleIdentifier(getName())); - } - ((Element)type).importDetails(this, false); - return type; - } - @Override - public void accept(Visitor visitor) { - visitor.visitDirectDeclarator(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - return super.replaceChild(child, by); - } - - @Override - public void propagateName(String name) { - setName(name); - } - } - - public static abstract class TargettedDeclarator extends Declarator { - public TargettedDeclarator() {} - public TargettedDeclarator(Declarator target) { - setTarget(target); - } - - Declarator target; - public Declarator getTarget() { - return target; - } - public void setTarget(Declarator target) { - this.target = changeValue(this, this.target, target); - } - @Override - public String resolveName() { - return getTarget() != null ? getTarget().resolveName() : null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) { - setTarget((Declarator)by); - return true; - } - return super.replaceChild(child, by); - } - - @Override - public void propagateName(String name) { - if (getTarget() != null) - getTarget().propagateName(name); - else - setTarget(new DirectDeclarator(name)); - } - } - - public static class PointerDeclarator extends TargettedDeclarator { - Declarator.PointerStyle pointerStyle; - public PointerDeclarator() {} - public PointerDeclarator(Declarator target, Declarator.PointerStyle pointerStyle) { - super(target); - setPointerStyle(pointerStyle); - } - @Override - public void accept(Visitor visitor) { - visitor.visitPointerDeclarator(this); - } - @Override - public MutableByDeclarator mutateType(MutableByDeclarator type) { - if (type == null) - return null; - - type = type.clone(); - if (type instanceof Function) { - type = (MutableByDeclarator)new TypeRef.FunctionSignature((Function)type).importDetails((Element)type, true); - } else if (type instanceof TypeRef) { - type = (MutableByDeclarator) new TypeRef.Pointer((TypeRef)type, getPointerStyle()).importDetails((Element)type, true); - } else - throw new IllegalArgumentException(type.getClass().getName() + " cannot be mutated by pointer"); - ((Element)type).importDetails(this, false); - return getTarget() == null ? type : getTarget().mutateType(type); - } - public Declarator.PointerStyle getPointerStyle() { - return pointerStyle; - } - public void setPointerStyle(Declarator.PointerStyle pointerStyle) { - this.pointerStyle = pointerStyle; - } - } - public static class FunctionDeclarator extends TargettedDeclarator { - final List args = new ArrayList(); - - public FunctionDeclarator() {} - public FunctionDeclarator(Declarator target, List args) { - setTarget(target); - setArgs(args); - } - - @Override - public MutableByDeclarator mutateType(MutableByDeclarator type) { - /*if (type == null) { - System.out.println("mutating null type : " + this); - return null; - }*/ - type = type == null ? null : type.clone(); - - if (type == null || type instanceof TypeRef) { - Function f = new Function(); - f.importDetails(this, false); - f.setValueType((TypeRef)type); - f.setType(Type.CFunction); - f.setArgs(getArgs()); - - return getTarget().mutateType(f); - } else if (type instanceof Function) { - Function ff = (Function)type; - - Function f = new Function(); - f.importDetails(this, false); - f.setValueType(new TypeRef.FunctionSignature(ff)); - f.setType(Type.CFunction); - f.setArgs(getArgs()); - - return getTarget().mutateType(f); - } else { - throw new IllegalArgumentException("Function declarator can only mutate type references ! (mutating \"" + type + "\" by \"" + this + "\")"); - - } - } - public List getArgs() { - return unmodifiableList(args); - } - public void setArgs(List args) { - changeValue(this, this.args, args); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitFunctionDeclarator(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(args, Arg.class, this, child, by)) - return true; - return super.replaceChild(child, by); - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(args, child); - if (e != null) - return e; - - return super.getNextChild(child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(args, child); - if (e != null) - return e; - - return super.getNextChild(child); - } - - } - public static class ArrayDeclarator extends TargettedDeclarator { - protected final List dimensions = new ArrayList(); - public ArrayDeclarator() {} - public ArrayDeclarator(Declarator target, List dimensions) { - super(target); - setDimensions(dimensions); - } - public ArrayDeclarator(Declarator target, Expression... dimensions) { - this(target, Arrays.asList(dimensions)); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitArrayDeclarator(this); - } - public void setDimensions(List dimensions) { - changeValue(this, this.dimensions, dimensions); - } - public List getDimensions() { - return unmodifiableList(dimensions); - } - public void addDimension(Expression ex) { - if (ex == null) - return; - dimensions.add(ex); - ex.setParentElement(this); - } - - public MutableByDeclarator mutateType(MutableByDeclarator type) { - if (type == null) - return null; - - type = type.clone(); - if (type instanceof TypeRef) - type = new TypeRef.ArrayRef((TypeRef)type, deepClone(getDimensions())); - else if (type instanceof Function) - { - Function f = (Function)type; - f.setValueType(new TypeRef.ArrayRef(f.getValueType(), deepClone(getDimensions()))); - type = f; - } - ((Element)type).importDetails(this, false); - return target.mutateType(type); - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(dimensions, child); - if (e != null) - return null; - return super.getNextChild(child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(dimensions, child); - if (e != null) - return null; - return super.getPreviousChild(child); - } - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (replaceChild(dimensions, Expression.class, this, child, by)) - return true; - return super.replaceChild(child, by); - } - } - - public void setDefaultValue(Expression defaultValue) { - this.defaultValue = changeValue(this, this.defaultValue, defaultValue); - } - public Expression getDefaultValue() { - return defaultValue; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getDefaultValue()) { - setDefaultValue((Expression) by); - return true; - } - - return super.replaceChild(child, by); - } - - public boolean isParenthesized() { - return parenthesized; - } - public void setParenthesized(boolean parenthesized) { - this.parenthesized = parenthesized; - } - - public abstract String resolveName(); - public abstract void propagateName(String name); - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Define.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Define.java deleted file mode 100644 index 6412beda8..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Define.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - - -public class Define extends Declaration { - - Expression value; - String name; - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Define(String name, Expression value) { - this(); - setName(name); - setValue(value); - } - - public Define() { - } - - @Override - public void accept(Visitor visitor) { - visitor.visitDefine(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getValue()) { - setValue((Expression) by); - return true; - } - return super.replaceChild(child, by); - } - - public Expression getValue() { - return value; - } - public void setValue(Expression value) { - this.value = changeValue(this, this.value, value); - } - @Override - public Element getNextSibling() { - return super.getNextSibling(); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Element.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Element.java deleted file mode 100644 index 162674a57..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Element.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.WeakHashMap; - -import com.ochafik.lang.jnaerator.parser.ObjCppParser.Language; -import com.ochafik.lang.reflect.GettersAndSettersHelper; -import com.ochafik.lang.reflect.GettersAndSettersHelper.GetterAndSetterInfo; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import java.util.Collections; - -public abstract class Element { - //List parentElements = new ArrayList(); - Element parentElement; - protected List nameSpace = new ArrayList(); - String elementFile; - int elementLine = -1; - String commentBefore, commentAfter; - static int nextId = 1; - private final int id = nextId++; - protected EnumSet possibleLanguages; - - protected Map attributes; - - public Element() { - if (Thread.interrupted()) - throw new RuntimeException(new InterruptedException()); - } - - - public Map getAttributes() { - return attributes == null ? Collections.EMPTY_MAP : Collections.unmodifiableMap(attributes); - } - - public Object getAttribute(Object key) { - return attributes == null ? null : attributes.get(key); - } - public void setAttribute(Object key, Object value) { - if (attributes == null) - attributes = new HashMap(); - - attributes.put(key, value); - } - public void setAttributes(Map attributes) { - this.attributes = attributes == null ? null : new HashMap(attributes); - } - - - public EnumSet getPossibleLanguages() { - return possibleLanguages; - } - public EnumSet resolvePossibleLanguages() { - if (possibleLanguages != null) - return possibleLanguages; - Element parent = getParentElement(); - if (parent != null) - return parent.resolvePossibleLanguages(); - return null; - } - public void setPossibleLanguages(EnumSet possibleLanguages) { - this.possibleLanguages = possibleLanguages; - } - - public int getId() { - return id; - } - public void stripDetails() { - setCommentBefore(null); - setCommentAfter(null); - setElementFile(null); - setElementLine(-1); - } - public void addNameSpace(String nameSpace) { - this.nameSpace.add(0, nameSpace); - } - public List getNameSpace() { - return unmodifiableList(nameSpace); - } - public void setNameSpace(List nameSpace) { - this.nameSpace.clear(); - this.nameSpace.addAll(nameSpace); - } - - public Element importComments(Element e, String... extraComments) { - if (e != null) { - importDetails(e, false); - moveAllCommentsBefore(); - } - addToCommentBefore(extraComments); - return this; - } - - public Element importDetails(Element from, boolean move) { - if (from == null) - return this; - - if (!from.getNameSpace().isEmpty()) - setNameSpace(from.getNameSpace()); - - if (from.getElementFile() != null) - setElementFile(from.getElementFile()); - if (from.getElementLine() >= 0) - setElementLine(from.getElementLine()); - if (from.getCommentBefore() != null) - addToCommentBefore(from.getCommentBefore()); - if (from.getCommentAfter() != null) - setCommentAfter(from.getCommentAfter()); - - if (move) - from.stripDetails(); - return this; - } - protected List unmodifiableList(List list) { - return new SemiUnmodifiableList(list); - } - - public static String getFileOfAscendency(Element decl) { - Element e = decl; - String file = null; - Set visitedIds = new TreeSet(); - while (e != null && (file = e.getElementFile()) == null && visitedIds.add(e.getId())) { - e = e.getParentElement(); - } - return file; - } - - public static String cleanComment(String s) { - s = s.trim(); - if (s.startsWith("//")) - s = s.replaceAll("^//+", ""); - else if (s.startsWith("/*")) { - s = s.replaceAll("^/\\*++!?", "").replaceAll("\\*/$", ""); - s = s.replaceAll("\n\\s+", "\n").replaceAll("\n\\*\\s?+", "\n"); - } - s = s.replaceAll("\\*/", "* /"); - s = s.replaceAll("
      \n", "\n"); - s = s.replaceAll("
      $", ""); - return s.trim(); - } - - public void addToCommentBefore(List s) { - String b = getCommentBefore(); - List ss = new ArrayList(); - if (b != null && (b = cleanComment(b)).length() > 0) - ss.add(b); - for (String a : s) - if (a != null && (a = cleanComment(a)).length() > 0) - ss.add(a); - //s); - //if (b != null && b.trim().length() > 0) - // ss.add(0, b); - - setCommentBefore(ss.isEmpty() ? null : StringUtils.implode(ss, "\n")); - } - public void moveAllCommentsBefore() { - if (getCommentAfter() != null) { - addToCommentBefore(getCommentAfter()); - setCommentAfter(null); - } - } - public void addToCommentBefore(String... s) { - addToCommentBefore(Arrays.asList(s)); - } -// public String formatComments(CharSequence indent, boolean mergeCommentsAfter, String... otherComments) { -// return formatComments(indent, commentBefore, commentAfter, mergeCommentsAfter, otherComments); -// } - public void setCommentBefore(String text) { - commentBefore = text; - } - public String getCommentBefore() { - return commentBefore; - } - - /*public String formatCommentAfter() { - return commentAfter == null ? "" : commentAfter; - } - public String formatCommentBefore() { - return commentBefore == null ? "" : commentBefore; - }*/ - public void setCommentAfter(String commentAfter) { - this.commentAfter = commentAfter; - } - public String getCommentAfter() { - return commentAfter; - } - public String getElementFile() { - return elementFile; - } - public void setElementFile(String elementFile) { - this.elementFile = elementFile; - } - public void setElementLine(int elementLine) { - this.elementLine = elementLine; - } - public int getElementLine() { - return elementLine; - } - - /// final so that it is easier to implement listeners - public final Element getParentElement() { - return parentElement; - } - /// final so that it is easier to implement listeners - public final void setParentElement(Element parentElement) { - if (parentElement == null) - this.parentElement = null; // break here - else - this.parentElement = parentElement; - } - - private static WeakHashMap, GettersAndSettersHelper> elementClassesGettersAndSetters = new WeakHashMap, GettersAndSettersHelper>(); - private static final GettersAndSettersHelper.FieldGetter fieldGetter = new GettersAndSettersHelper.FieldGetter() { - - public Field getField(Class c, String name) throws SecurityException, NoSuchFieldException { - return c.getField(name); - } - - }; - public GettersAndSettersHelper getGettersAndSetters() { - Class type = getClass(); - GettersAndSettersHelper helper = elementClassesGettersAndSetters.get(type); - if (helper == null) - elementClassesGettersAndSetters.put(type, helper = new GettersAndSettersHelper(type, fieldGetter)); - - return helper; - } - @SuppressWarnings("unchecked") - public static List deepClone(List list) { - List clone = new ArrayList(list.size()); - for (T e : list) - clone.add((T)e.clone()); - - return clone; - } - public Element clone() { - - String fieldName = null; - try { - Element clone = getClass().newInstance(); - Map infos = getGettersAndSetters().gettersAndSetters; - //System.out.println("Infos for " + getClass().getName() + " = " + infos.keySet()); - for (Map.Entry e : infos.entrySet()) { - fieldName = e.getKey(); - if (fieldName.equals("parentElement")) - continue; - if (fieldName.equals("possibleLanguages")) - fieldName = fieldName.toString(); - - GetterAndSetterInfo p = e.getValue(); - if (p.getter == null || p.setter == null) - continue; - - Object value = p.getter.invoke(this); - Object clonedValue; - if (fieldName.equals("attributes")) - clonedValue = value; - else - clonedValue = cloneObject(value); - p.setter.invoke(clone, clonedValue); - } - return clone; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - protected static Object cloneObject(Object value) throws CloneNotSupportedException { - if (value == null) - return null; - - Class type = value.getClass(); - if (Element.class.isAssignableFrom(type)) - return ((Element)value).clone(); - else if (EnumSet.class.isAssignableFrom(type)) - return ((EnumSet)value).clone(); - else if (Collection.class.isAssignableFrom(type)) - return cloneElements((Collection) value); - else if (Map.class.isAssignableFrom(type)) - return cloneElements((Map) value); - else if (Pair.class.isAssignableFrom(type)) { - Pair pair = (Pair)value; - return new Pair(cloneObject(pair.getFirst()), cloneObject(pair.getSecond())); - } - //else if (value instanceof String || type.isPrimitive()) - return value; - - //throw new CloneNotSupportedException(); - } - public static Collection cloneElements(Collection col) throws CloneNotSupportedException { - Collection colClone; - if (col instanceof List) - colClone = new ArrayList(col.size()); - else if (col instanceof LinkedHashSet) - colClone = new LinkedHashSet(col.size()); - else if (col instanceof HashSet) - colClone = new HashSet(col.size()); - else if (col instanceof TreeSet) - colClone = new TreeSet(); - else if (col instanceof Set) - colClone = new LinkedHashSet(col.size()); - else - throw new CloneNotSupportedException(); - - for (Object o : col) { - o = cloneObject(o); - colClone.add(o); - } - return colClone; - } - - public static Map cloneElements(Map col) throws CloneNotSupportedException { - Map colClone; - if (col instanceof LinkedHashMap) - colClone = new LinkedHashMap(col.size()); - else if (col instanceof HashMap) - colClone = new HashMap(col.size()); - else if (col instanceof TreeMap) - colClone = new TreeMap(); - else if (col instanceof Map) - colClone = new LinkedHashMap(); - else - throw new CloneNotSupportedException(); - - for (Map.Entry entry : col.entrySet()) - colClone.put(cloneObject(entry.getKey()), cloneObject(entry.getValue())); - - return colClone; - } - /* - public void addParentElement(Element e) { - parentElements.add(e); - } - public void removeParentElement(Element e) { - parentElements.remove(e); - }*/ - - public abstract boolean replaceChild(Element child, Element by); - public abstract Element getNextChild(Element child); - public abstract Element getPreviousChild(Element child); - - public Element getNextSibling() { - Element pe = getParentElement(); - if (pe != null) - return pe.getNextChild(this); - return null; - } - - public Element getPreviousSibling() { - Element pe = getParentElement(); - if (pe != null) - return pe.getPreviousChild(this); - return null; - } - - @SuppressWarnings("unchecked") - public static boolean replaceChild(List list, Class type, Element parent, Element child, Element by) { - int i = indexOfInstance(child, list); - - if (i >= 0) { - T old; - if (by == null) - old = list.remove(i); - else - old = list.set(i, type == null ? (T)by : type.cast(by)); - - if (old != by) { - if (old != null) - old.setParentElement(null); - - if (by != null) - by.setParentElement(parent); - } - return true; - } - - return false; - } - - static int indexOfInstance(Element e, List list) { - int i = -1; - for (int k = 0, n = list.size(); k < n; k++) - if (list.get(k) == e) { - i = k; - break; - } - return i; - } - public static Element getNextSibling(List list, Element child) { - int i = indexOfInstance(child, list); - if (i >= 0) { - return i < list.size() - 1 ? list.get(i + 1) : null; - } - return null; - } - - public static Element getPreviousSibling(List list, Element child) { - int i = indexOfInstance(child, list); - if (i >= 0) { - return i > 0 ? list.get(i - 1) : null; - } - return null; - } - public static void changeValue(Element parent, List oldValue, List newValue) { - for (T t : oldValue) - t.setParentElement(null); - - oldValue.clear(); - - if (newValue != null) { - for (T t : newValue) { - if (t == null) - continue; - t.setParentElement(parent); - oldValue.add(t); - } - } - } - public static T changeValue(Element parent, T oldValue, T newValue) { - if (oldValue != newValue) { - if (oldValue != null) - oldValue.setParentElement(null); - - if (newValue != null) - newValue.setParentElement(parent); - } - return newValue; - } - - List elementListGettersAndSetters; - - public boolean insertSibling(Element siblingToInsert, boolean before) { - Element parent = getParentElement(); - if (parent == null) - return false; - - return parent.insertChild(this, siblingToInsert, before); - } - @SuppressWarnings("unchecked") - public boolean insertChild(Element existingChild, Element childToInsert, boolean before) { - if (elementListGettersAndSetters == null) { - elementListGettersAndSetters = new ArrayList(); - GettersAndSettersHelper gettersAndSetters = getGettersAndSetters(); - - for (Map.Entry e : gettersAndSetters.gettersAndSetters.entrySet()) { - GetterAndSetterInfo p = e.getValue(); - if (!p.isFull()) - continue; - - Type returnType = p.getter.getGenericReturnType(); - if (returnType instanceof ParameterizedType) { - ParameterizedType paramReturnType = (ParameterizedType) returnType; - Type rawType = paramReturnType.getRawType(); - Type[] typeArguments = paramReturnType.getActualTypeArguments(); - Type typeArgument = typeArguments.length == 1 ? typeArguments[0] : null; - if (typeArgument != null && typeArgument instanceof Class && rawType instanceof Class) { - Class typeClass = (Class) typeArgument; - Class rawClass = (Class) rawType; - if (Element.class.isAssignableFrom(typeClass) && List.class.isAssignableFrom(rawClass)) { - p.elementType = (Class)typeClass; - elementListGettersAndSetters.add(p);//new ListGetterAndSetterInfo(e.getKey(), (Class)typeClass, p.getter, p.setter)); - } - } - } - } - } - Class t = existingChild.getClass(), t2 = childToInsert.getClass(); - for (GetterAndSetterInfo info : elementListGettersAndSetters) { - if (!info.elementType.isAssignableFrom(t) || !info.elementType.isAssignableFrom(t2)) - continue; - - try { - List list = (List)info.getter.invoke(this); - if (list instanceof SemiUnmodifiableList) - list = ((SemiUnmodifiableList)list).getList(); - int i = indexOfInstance(existingChild, list); - if (i < 0) - continue; - - list.add(before ? i : i + 1, childToInsert); - childToInsert.setParentElement(this); - return true; - } catch (Exception e) { - throw new RuntimeException("Implementation bug in " + Element.class + ".insertChild !", e); - } - } - return false; - } - public boolean replaceBy(Element element) { - Element pe = getParentElement(); - if (pe != null) - return pe.replaceChild(this, element); - - return false; - } - - public boolean replaceByAndVisit(Element element, Visitor visitor) { - if (!replaceBy(element)) - return false; - - element.accept(visitor); - return true; - } - - @SuppressWarnings("unchecked") - public T findParentOfType(Class type) { - return (T)findParentOfTypes(type); - } - public Object findParentOfTypes(Class... types) { - Element e = this; - for (;;) { - e = e.getParentElement(); - if (e == null) - return null; - - for (Class type : types) - if (type.isAssignableFrom(e.getClass())) - return type.cast(e); - } - } - -// static int depth; - @Override - public String toString() { - return new Printer(null).append(this).toString(); - } - - public abstract void accept(Visitor visitor); - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ElementsHelper.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ElementsHelper.java deleted file mode 100644 index 7bdb8ffdb..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ElementsHelper.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -import static com.ochafik.lang.jnaerator.parser.Expression.*; - -import java.util.Arrays; - -import static com.ochafik.lang.jnaerator.parser.Identifier.*; -import static com.ochafik.lang.jnaerator.parser.Statement.*; - -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import java.util.ArrayList; -import java.util.List; -public class ElementsHelper { - public static Expression memberRef(Expression x, String name) { - return memberRef(x, MemberRefStyle.Dot, name); - } - public static Expression memberRef(Expression x, MemberRefStyle style, String name) { - return new Expression.MemberRef(x, style, new SimpleIdentifier(name)); - } - public static Expression classLiteral(Class c) { - if (c == null) - return null; - if (c.isPrimitive()) { - if (c == Integer.TYPE) - c = Integer.class; - else if (c == Long.TYPE) - c = Long.class; - else if (c == Short.TYPE) - c = Short.class; - else if (c == Byte.TYPE) - c = Byte.class; - else if (c == Character.TYPE) - c = Character.class; - else if (c == Boolean.TYPE) - c = Boolean.class; - else if (c == Float.TYPE) - c = Float.class; - else if (c == Double.TYPE) - c = Double.class; - - return staticField(c, "TYPE"); - } - return staticField(c, "class"); - } - public static Expression staticField(Class c, String name) { - return memberRef(expr(typeRef(ident(c))), MemberRefStyle.Dot, name); - } - - public static Expression thisField(String name) { - return memberRef(thisRef(), MemberRefStyle.Dot, name); - } - - public static Expression thisRef() { - return varRef("this"); - } - - public static Expression memberRef(Expression x, MemberRefStyle style, Identifier name) { - return new Expression.MemberRef(x, style, name); - } - - public static Expression memberRef(Expression x, Identifier name) { - return memberRef(x, MemberRefStyle.Dot, name); - } - public static Expression varRef(String name) { - return new Expression.VariableRef(new SimpleIdentifier(name)); - } - public static Expression varRef(SimpleIdentifier name) { - return new Expression.VariableRef(name); - } - public static Expression varRef(Identifier name) { - if (name instanceof SimpleIdentifier) - return varRef((SimpleIdentifier)name); - return memberRef(expr(typeRef(name.resolveAllButLastIdentifier())), MemberRefStyle.Dot, name.resolveLastSimpleIdentifier()); - } - public static Expression enumRef(java.lang.Enum e) { - return memberRef(expr(typeRef(e.getDeclaringClass())), e.name()); - } - public static Identifier ident(String... others) { - if (others == null) - return null; - - List list = new ArrayList(); - for (String o : others) - if (o != null && (o = o.trim()).length() > 0) - for (String elt : o.split("\\.")) - list.add(new SimpleIdentifier(elt)); - - if (list.isEmpty()) - return null; - if (list.size() == 1) - return list.get(0); - - QualifiedIdentifier id = new QualifiedIdentifier(QualificationSeparator.Dot); - id.setIdentifiers(list); - return id; - } - public static List getClassSimpleIdentifiers(String className) { - List elts = new ArrayList(); - for (String s : className.split("[.$]")) - if (s.length() > 0) - elts.add(new SimpleIdentifier(s)); - - return elts; - } - public static Identifier ident(Class cl, Expression... args) { - if (cl == null) - return null; - if (cl == Void.TYPE || cl == Void.class) - return ident("void"); - QualifiedIdentifier id = new QualifiedIdentifier(QualificationSeparator.Dot); - id.setIdentifiers(getClassSimpleIdentifiers(cl.getName())); - id.resolveLastSimpleIdentifier().setTemplateArguments(Arrays.asList(args)); - return id; - } - public static Identifier ident(Identifier ident, String name) { - return ident(ident, ident(name)); - } - public static Identifier ident(Identifier ident, Identifier... others) { - if (ident == null) { - if (others.length > 0) - return ident(others[0], Arrays.copyOfRange(others, 1, others.length)); - return null; - } - return ident.derive(Identifier.QualificationSeparator.Dot, others); - } - public static Expression opaqueExpr(String s) { - return new OpaqueExpression(s); - } - public static Expression cast(TypeRef t, Expression s) { - return new Cast(t, s); - } - public static Expression nullExpr() { - return new NullExpression(); - } - public static Expression expr(TypeRef tr) { - return new TypeRefExpression(tr); - } - public static Expression expr(boolean c) { - return expr(Constant.Type.Bool, c); - } - public static Expression expr(double c) { - return expr(Constant.Type.Double, c); - } - public static Expression expr(int c) { - return expr(Constant.Type.Int, c); - } - public static Expression expr(String c) { - return expr(Constant.Type.String, c); - } - public static Expression expr(Constant.Type type, Object value) { - return new Constant(type, value, null); - } - public static Expression expr(UnaryOperator op, Expression b) { - return new UnaryOp(b, op); - } - public static Expression expr(Expression a, BinaryOperator op, Expression b) { - return new BinaryOp(a, op, b); - } - public static Expression expr(Expression a, AssignmentOperator op, Expression b) { - return new AssignmentOp(a, op, b); - } - - @SuppressWarnings("unchecked") - public static List clones(List list) { - List clone = new ArrayList(list.size()); - for (T e : list) - clone.add((T)e.clone()); - return clone; - } - public static FunctionCall methodCall(Expression x, MemberRefStyle style, String name, Expression... exprs) { - return new FunctionCall(memberRef(x, style, name), exprs); - } - // Given Pointer, returns T - public static TypeRef getSingleTypeParameter(TypeRef tr) { - if (!(tr instanceof SimpleTypeRef)) - return null; - - SimpleTypeRef str = (SimpleTypeRef) tr; - Identifier name = str.getName(); - if (name == null) - return null; - - SimpleIdentifier id = name.resolveLastSimpleIdentifier(); - List templateArguments = id.getTemplateArguments(); - if (templateArguments.size() != 1) - return null; - Expression x = templateArguments.get(0); - if (!(x instanceof TypeRefExpression)) - return null; - - return ((TypeRefExpression)x).getType(); - } - public static FunctionCall methodCall(Expression x, String name, Expression... exprs) { - return methodCall(x, MemberRefStyle.Dot, name, exprs); - } - public static FunctionCall methodCall(String name, Expression... exprs) { - return new FunctionCall(memberRef(null, null, name), exprs); - } - public static TypeRef typeRef(Class cl) { - if (cl == null) - return null; - - if (cl.isArray()) - return new TypeRef.ArrayRef(typeRef(cl.getComponentType())); - if (cl.isPrimitive() || cl == Void.class) - return new TypeRef.Primitive(cl.getSimpleName()); - - return typeRef(ident(cl)); - } - - public static SimpleTypeRef typeRef(String name) { - return typeRef(ident(name)); - } - public static SimpleTypeRef typeRef(Identifier name) { - return name == null ? null : new SimpleTypeRef(name); - } - public static TypeRef subType(SimpleTypeRef tr, Identifier name) { - return typeRef(ident(tr.getName(), name)); - } - public static Statement stat(Declaration d) { - return d;//new Statement.DeclarationStatement(d); - } - public static Statement tryRethrow(Statement st) { - String exName = "$ex$"; - return new Try(st, null, new Catch(new VariablesDeclaration(typeRef(Throwable.class), new Declarator.DirectDeclarator(exName)), new Throw(new New(typeRef(RuntimeException.class), varRef(exName))))); - } - public static Statement stat(Expression x) { - return new ExpressionStatement(x); - } - public static Statement stat(TypeRef tr, String varName, Expression ass) { - VariablesDeclaration vd = new VariablesDeclaration(tr, new Declarator.DirectDeclarator(varName, ass)); - return vd;//new Statement.DeclarationStatement(vd); - } - public static Block block(Statement... x) { - return new Block(x); - } - - public static TaggedTypeRefDeclaration decl(TaggedTypeRef tr) { - return tr == null ? null : new TaggedTypeRefDeclaration(tr); - } -/* - - public static TypeRef typeRef(TypeRef parentTypeRef, Style style, Identifier subName) { - if (parentTypeRef == null) - return typeRef(subName); - return new SubTypeRef(parentTypeRef, style, subName); - }*/ -// public static TypeRef typeRef(TypeRef parentTypeRef, String subName) { -// return typeRef(parentTypeRef, Style.Dot, subName); -// } - - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/EmptyDeclaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/EmptyDeclaration.java deleted file mode 100644 index 4565681c0..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/EmptyDeclaration.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -public class EmptyDeclaration extends Declaration { - - public EmptyDeclaration() {} - public EmptyDeclaration(String... comments) { - addToCommentBefore(comments); - } - @Override - public void accept(Visitor visitor) { - visitor.visitEmptyDeclaration(this); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Enum.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Enum.java deleted file mode 100644 index 809b6e052..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Enum.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.List; - -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import java.util.Arrays; -import java.util.Collections; - -public class Enum extends TaggedTypeRef { - Type type = Type.C; - - public static enum Type { - C, Java - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } - - public static class EnumItem extends Element { - String name; - List arguments = new ArrayList(); - Struct body; - Type type; - - public EnumItem() { - super(); - } - - public Type getType() { - if (type == null && (getParentElement() instanceof Enum)) - return ((Enum)getParentElement()).getType(); - return type; - } - - public void setType(Type type) { - this.type = type; - } - - public EnumItem(String name, Expression... arguments) { - setName(name); - setArguments(Arrays.asList(arguments)); - } - - public Struct getBody() { - return body; - } - - public void setBody(Struct body) { - this.body = changeValue(this, this.body, body); - } - - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public List getArguments() { - return Collections.unmodifiableList(arguments); - } - public void setArguments(List arguments) { - changeValue(this, this.arguments, arguments); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitEnumItem(this); - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(arguments, child); - if (e != null) - return e; - return null; - } - - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(arguments, child); - if (e != null) - return e; - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(arguments, Expression.class, this, child, by)) - return true; - - if (child == getBody()) { - setBody((Struct) by); - return true; - } - return false; - } - - } - final List items = new ArrayList(); - final List interfaces = new ArrayList(); - - Struct body; - //private LinkedHashMap values = new LinkedHashMap(); - //Integer lastValue = 0; - - public void addItem(EnumItem item) { - if (item == null) - return; - - item.setParentElement(this); - items.add(item); - } - - public void accept(Visitor visitor) { - visitor.visitEnum(this); - } - - public List getItems() { - return unmodifiableList(items); - } - public void setItems(List items) { - changeValue(this, this.items, items); - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - e = getNextSibling(items, child); - if (e != null) - return e; - e = getNextSibling(interfaces, child); - if (e != null) - return e; - - return super.getNextChild(child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - e = getPreviousSibling(items, child); - if (e != null) - return e; - e = getPreviousSibling(interfaces, child); - if (e != null) - return e; - - return super.getPreviousChild(child); - } - - public Struct getBody() { - return body; - } - - public void setBody(Struct body) { - this.body = changeValue(this, this.body, body); - } - - public List getInterfaces() { - return Collections.unmodifiableList(interfaces); - } - - public void setInterfaces(List interfaces) { - changeValue(this, this.interfaces, interfaces); - } - public void addInterface(Identifier interf) { - if (interf == null) - return; - interf.setParentElement(this); - interfaces.add(interf); - } - - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - - if (replaceChild(items, EnumItem.class, this, child, by)) - return true; - if (replaceChild(interfaces, Identifier.class, this, child, by)) - return true; - - if (child == getBody()) { - setBody((Struct) by); - return true; - } - return super.replaceChild(child, by); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java deleted file mode 100644 index c1f493136..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java +++ /dev/null @@ -1,1510 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.util.listenable.Pair; - -public abstract class Expression extends Element { - private static final long MAX_UINT_VALUE = 2L * Integer.MAX_VALUE; - - public static class ExpressionsBlock extends ExpressionSequence { - - @Override - public void accept(Visitor visitor) { - visitor.visitExpressionsBlock(this); - } - - } - public static class ExpressionSequence extends Expression { - final List expressions = new ArrayList(); - public ExpressionSequence() { - - } - public ExpressionSequence(Expression... expressions) { - this(Arrays.asList(expressions)); - } - public ExpressionSequence(List expressions) { - setExpressions(expressions); - } - public void addExpression(Expression e) { - if (e != null) { - expressions.add(e); - e.setParentElement(this); - } - - } - public List getExpressions() { - return expressions; - } - public void setExpressions(List sequence) { - changeValue(this, this.expressions, sequence); - } - @Override - public void accept(Visitor visitor) { - visitor.visitExpressionSequence(this); - } - @Override - public Element getNextChild(Element child) { - return getNextSibling(getExpressions(), child); - } - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(getExpressions(), child); - } - @Override - public boolean replaceChild(Element child, Element by) { - return replaceChild(getExpressions(), Expression.class, this, child, by); - } - } - public static class OpaqueExpression extends Expression { - String opaqueString; - public void setOpaqueString(String opaqueString) { - this.opaqueString = opaqueString; - } - public String getOpaqueString() { - return opaqueString; - } - public OpaqueExpression() { - } - public OpaqueExpression(String opaqueString) { - setOpaqueString(opaqueString); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitOpaqueExpression(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - return false; - } - - } - boolean parenthesis; - public Expression setParenthesis(boolean parenthesis) { - this.parenthesis = parenthesis; - return this; - } - public Expression setParenthesisIfNeeded() { - setParenthesis(!( - this instanceof VariableRef || - this instanceof FunctionCall || - this instanceof MemberRef || - this instanceof ArrayAccess - )); - return this; - } - public boolean getParenthesis() { - return parenthesis; - } - public boolean isParenthesis() { - return parenthesis; - } - - @Override - public Expression clone() { - return (Expression)super.clone(); - } - - public enum MemberRefStyle { - Dot, SquareBrackets, Arrow, Colons - } - - public static MemberRefStyle parseMemberRefStyle(String s) { - if (s.equals("->")) - return MemberRefStyle.Arrow; - if (s.equals(".")) - return MemberRefStyle.Dot; - if (s.equals("::")) - return MemberRefStyle.Colons; - return null; - } - - public static class TypeRefExpression extends Expression { - TypeRef type; - - public TypeRefExpression(TypeRef type) { - setType(type); - } - public TypeRefExpression() {} - - public TypeRef getType() { - return type; - } - public void setType(TypeRef type) { - this.type = changeValue(this, this.type, type); - } - @Override - public void accept(Visitor visitor) { - visitor.visitTypeRefExpression(this); - } - @Override - public Element getNextChild(Element child) { - return null; - } - @Override - public Element getPreviousChild(Element child) { - return null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getType()) { - setType((TypeRef) by); - return true; - } - return false; - } - } - - public static class EmptyArraySize extends Expression { - - @Override - public void accept(Visitor visitor) { - visitor.visitEmptyArraySize(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - return false; - } - } - - public static class MemberRef extends Expression { - MemberRefStyle memberRefStyle; - Expression target; - - Identifier name; - - public MemberRef(SimpleIdentifier name) { - setName(name); - } - public MemberRef(Expression target, MemberRefStyle memberRefStyle, Identifier name) { - setTarget(target); - setName(name); - setMemberRefStyle(memberRefStyle); - } - - public MemberRef() { - } - - public void setName(Identifier name) { - this.name = changeValue(this, this.name, name); - } - public Identifier getName() { - return name; - } - public void setTarget(Expression target) { - this.target = changeValue(this, this.target, target); - } - public Expression getTarget() { - return target; - } - - public void setMemberRefStyle(MemberRefStyle memberRefStyle) { - this.memberRefStyle = memberRefStyle; - } - public MemberRefStyle getMemberRefStyle() { - return memberRefStyle; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) - setTarget((Expression)by); - if (child == getName()) - setName((Identifier)by); - return false; - } - - - @Override - public void accept(Visitor visitor) { - visitor.visitMemberRef(this); - } - @Override - public Element getNextChild(Element child) { - // TODO Auto-generated method stub - return null; - } - @Override - public Element getPreviousChild(Element child) { - // TODO Auto-generated method stub - return null; - } - - } - public static class NewArray extends Expression { - TypeRef type; - List dimensions = new ArrayList(); - List initialValues = new ArrayList(); - - public NewArray() {} - - public NewArray(TypeRef type, Expression[] dimensions, Expression[] initialValues) { - setType(type); - setDimensions(Arrays.asList(dimensions)); - setInitialValues(Arrays.asList(initialValues)); - } - public List getDimensions() { - return unmodifiableList(dimensions); - } - public void addDimension(Expression dimension) { - if (dimension == null) - return; - - dimension.setParentElement(this); - dimensions.add(dimension); - } - - public void setDimensions(List dimensions) { - changeValue(this, this.dimensions, dimensions); - } - public List getInitialValues() { - return unmodifiableList(initialValues); - } - public void setInitialValues(List initialValues) { - changeValue(this, this.initialValues, initialValues); - } - public TypeRef getType() { - return type; - } - public void setType(TypeRef type) { - this.type = changeValue(this, this.type, type); - } - @Override - public void accept(Visitor visitor) { - visitor.visitNewArray(this); - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(dimensions, child); - if (e == null) - e = getNextSibling(initialValues, child); - return e; - } - - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(dimensions, child); - if (e == null) - e = getPreviousSibling(initialValues, child); - return e; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getType()) { - setType((TypeRef)by); - return true; - } - return - replaceChild(initialValues, Expression.class, this, child, by) || - replaceChild(dimensions, Expression.class, this, child, by); - } - - } - - public static class New extends Expression { - TypeRef type; - FunctionCall construction; - public New(TypeRef type) { - setType(type); - } - public New(TypeRef type, FunctionCall construction) { - setType(type); - setConstruction(construction); - } - public New(TypeRef type, Expression... arguments) { - setType(type); - setConstruction(new FunctionCall(null, arguments)); - } - public New(TypeRef type, List arguments) { - this(type, arguments.toArray(new Expression[arguments.size()])); - } - public New() {} - public void setType(TypeRef type) { - this.type = changeValue(this, this.type, type); - } - public TypeRef getType() { - return type; - } - public void setConstruction(FunctionCall construction) { - this.construction = changeValue(this, this.construction, construction); - } - public FunctionCall getConstruction() { - return construction; - } - @Override - public void accept(Visitor visitor) { - visitor.visitNew(this); - } - @Override - public Element getNextChild(Element child) { - return null; - } - @Override - public Element getPreviousChild(Element child) { - return null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getType()) { - setType((TypeRef) by); - return true; - } - if (child == getConstruction()) { - setConstruction((FunctionCall) by); - return true; - } - return false; - } - } - public static class FunctionCall extends MemberRef { - Expression function; - //String functionName; - List> arguments = new ArrayList>(); - - public List> getArguments() { - return unmodifiableList(arguments); - } - public void setArguments(List> arguments) { - for (Pair p : this.arguments) - p.getSecond().setParentElement(null); - this.arguments.clear(); - for (Pair p : arguments) - addArgument(p.getFirst(), p.getSecond()); - } - - public FunctionCall(Expression function) { - setFunction(function); - } - public FunctionCall(Expression function, Expression... unnamedArgs) { - setFunction(function); - for (Expression x : unnamedArgs) - if (x != null) - addArgument(x); - } - - public FunctionCall(Expression target, Expression function, MemberRefStyle memberRefStyle, Expression... unnamedArgs) { - setTarget(target); - setFunction(function); - setMemberRefStyle(memberRefStyle); - for (Expression x : unnamedArgs) - addArgument(x); - } - public FunctionCall() { - } - - public void addArgument(Expression ex) { - addArgument(null, ex); - } - public void addArguments(List ex) { - for (Expression x : ex) - addArgument(null, x); - } - public void addArgument(String argumentSelector, Expression ex) { - if (ex == null) - return; - - ex.setParentElement(this); - arguments.add(new Pair(argumentSelector, ex)); - } - public Expression getFunction() { - return function; - } - public void setFunction(Expression function) { - this.function = changeValue(this, this.function, function); - } - @Override - public void accept(Visitor visitor) { - visitor.visitFunctionCall(this); - } - - protected int indexOf(Element x, List> list) { - int i = 0; - for (Pair p : list) { - if (p.getValue() == x) - return i; - i++; - } - return -1; - } - - @Override - public Element getNextChild(Element child) { - int i = indexOf(child, arguments); - if (i >= 0) { - return i < arguments.size() - 1 ? arguments.get(i + 1).getValue() : null; - } - return null; - } - - @Override - public Element getPreviousChild(Element child) { - int i = indexOf(child, arguments); - if (i >= 0) { - return i > 0 ? arguments.get(i - 1).getValue() : null; - } - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) { - setTarget((Expression) by); - return true; - } - if (child == getFunction()) { - setFunction((Expression) by); - return true; - } - //return replaceChild(arguments, Expression.class, this, child, by); - int i = indexOf(child, arguments); - if (i >= 0) { - Expression old; - if (by == null) - old = arguments.remove(i).getValue(); - else - old = arguments.get(i).setValue((Expression)by); - - if (old != by) { - if (old != null) - old.setParentElement(null); - - if (by != null) - by.setParentElement(this); - } - return true; - } - - return super.replaceChild(child, by); - } - } - public static class ArrayAccess extends Expression { - Expression target, index; - public ArrayAccess() {} - public ArrayAccess(Expression target, Expression index) { - setTarget(target); - setIndex(index); - } - public Expression getTarget() { - return target; - } - public void setTarget(Expression target) { - this.target = changeValue(this, this.target, target); - } - public void setIndex(Expression index) { - this.index = changeValue(this, this.index, index); - } - public Expression getIndex() { - return index; - } - @Override - public void accept(Visitor visitor) { - visitor.visitArrayAccess(this); - } - @Override - public Element getNextChild(Element child) { - return null; - } - @Override - public Element getPreviousChild(Element child) { - return null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) { - setTarget((Expression)by); - return true; - } - if (child == getIndex()) { - setIndex((Expression)by); - return true; - } - return false; - } - } - - public static class VariableRef extends Expression { - Identifier name; - - - public VariableRef(Identifier name) { - setName(name); - } - - public VariableRef() { - } - - public Identifier getName() { - return name; - } - - public void setName(Identifier name) { - this.name = changeValue(this, this.name, name); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitVariableRef(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getName()) { - setName((Identifier) by); - return true; - } - return false; - } - } - - public enum BinaryOperator implements Operator { - Assign("="), - Arrow("->"), - ArrowStar("->*"), - SquareBrackets("[]"), - Comma(","), - Plus("+"), Minus("-"), Divide("/"), Multiply("*"), Modulo("%"), LeftShift("<<"), RightShift(">>"), SignedRightShift(">>>"), XOR("^"), - LessEqual("<=", true), GreaterEqual(">=", true), Less("<", true), Greater(">", true), IsEqual("==", true), IsDifferent("!=", true), - BitOr("|"), Or("||", true), BitAnd("&"), And("&&", true); - - final String s; - public final boolean givesBool; - BinaryOperator(String s) { - this(s, false); - } - BinaryOperator(String s, boolean givesBool) { - this.s = s; - this.givesBool = givesBool; - } - @Override - public String toString() { - return s; - } - }; - public interface Operator { - - } - public enum AssignmentOperator implements Operator { - Equal("=", null), - MultiplyEqual("*=", BinaryOperator.Multiply), - DivideEqual("/=", BinaryOperator.Divide), - ModuloEqual("%=", BinaryOperator.Modulo), - PlusEqual("+=", BinaryOperator.Plus), - MinusEqual("-=", BinaryOperator.Minus), - LeftShiftEqual("<<=", BinaryOperator.LeftShift), - RightShiftEqual(">>=", BinaryOperator.RightShift), - SignedRightShiftEqual(">>>=", BinaryOperator.SignedRightShift), - BitAndEqual("&=", BinaryOperator.BitAnd), - XOREqual("^=", BinaryOperator.XOR), - //ComplementEqual("~=", BinaryOperator.C), - BitOrEqual("|=", BinaryOperator.BitOr); - - String s; - AssignmentOperator(String s, BinaryOperator correspondingBinaryOp) { - this.s = s; - this.correspondingBinaryOp = correspondingBinaryOp; - } - @Override - public String toString() { - return s; - } - BinaryOperator correspondingBinaryOp; - public BinaryOperator getCorrespondingBinaryOp() { - return correspondingBinaryOp; - } - } - public enum UnaryOperator implements Operator { - Not("!"), - Minus("-"), - Parenthesis("()"), - Complement("~"), - Reference("&"), - Dereference("*"), - PreIncr("++"), - PreDecr("--"), - PostIncr("++"), - PostDecr("--"); - - String s; - UnaryOperator(String s) { - this.s = s; - } - @Override - public String toString() { - return s; - } - }; - - static final Map assignOps = new HashMap(); - static final Map binOps = new HashMap(); - static final Map unOps = new HashMap(); - static final Map assignOpsRev = new HashMap(); - static final Map binOpsRev = new HashMap(); - static final Map unOpsRev = new HashMap(); - //public static final Expression EMPTY_EXPRESSION = new Constant(null, null, ""); - static { - for (AssignmentOperator op : AssignmentOperator.values()) - map(assignOps, assignOpsRev, op.toString(), op); - for (UnaryOperator op : UnaryOperator.values()) - map(unOps, unOpsRev, op.toString(), op); - for (BinaryOperator op : BinaryOperator.values()) - map(binOps, binOpsRev, op.toString(), op); - } - static void map(Map m, Map r, K k, V v) { - m.put(k, v); - r.put(v, k); - } - public static BinaryOperator getBinaryOperator(String s) { - return binOps.get(s); - } - - - public static AssignmentOperator getAssignmentOperator(String s) { - AssignmentOperator op = assignOps.get(s); - if (op == null) - throw new RuntimeException("Failed to parse op " + s); - - return op; - } - - public static UnaryOperator getUnaryOperator(String s) { - UnaryOperator op = unOps.get(s); - if (op == null) - throw new RuntimeException("Failed to parse op " + s); - - return op; - } - public static java.lang.Enum getAnyOperator(String s) { - - java.lang.Enum e = binOps.get(s);//Expression.getBinaryOperator(s); - if (e != null) - return e; - e = unOps.get(s);//Expression.getUnaryOperator(s); - if (e != null) - return e; - return Expression.getAssignmentOperator(s); - } - - public static class NullExpression extends Expression { - - @Override - public void accept(Visitor visitor) { - visitor.visitNullExpression(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - return false; - } - } - public static class ConditionalExpression extends Expression { - Expression test, thenValue, elseValue; - - public Expression getTest() { - return test; - } - - public void setTest(Expression test) { - this.test = changeValue(this, this.test, test); - } - - public Expression getThenValue() { - return thenValue; - } - - public void setThenValue(Expression thenValue) { - this.thenValue = changeValue(this, this.thenValue, thenValue); - } - - public Expression getElseValue() { - return elseValue; - } - - public void setElseValue(Expression elseValue) { - this.elseValue = changeValue(this, this.elseValue, elseValue); - } - - - @Override - public void accept(Visitor visitor) { - visitor.visitConditionalExpression(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTest()) { - setTest((Expression)by); - return true; - } - if (child == getThenValue()) { - setThenValue((Expression)by); - return true; - } - if (child == getElseValue()) { - setElseValue((Expression)by); - return true; - } - return false; - } - - } - public static class Cast extends Expression { - TypeRef type; - Expression target; - - public Cast(TypeRef type, Expression target) { - setTarget(target); - setType(type); - } - - public Cast() { - } - - public void setTarget(Expression target) { - this.target = changeValue(this, this.target, target); - } - public void setType(TypeRef type) { - this.type = changeValue(this, this.type, type); - } - public Expression getTarget() { - return target; - } - public TypeRef getType() { - return type; - } - @Override - public void accept(Visitor visitor) { - visitor.visitCast(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - @Override - public Element getPreviousChild(Element child) { - return null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) { - setTarget((Expression)by); - return true; - } - if (child == getType()) { - setType((TypeRef)by); - return true; - } - return false; - } - } - public static class AssignmentOp extends Expression { - Expression target, value; - AssignmentOperator operator; - - public AssignmentOp() { - } - public AssignmentOp(Expression target, AssignmentOperator operator, Expression value) { - if (operator == null) - throw new NullPointerException(); - - setValue(value); - setTarget(target); - setOperator(operator); - } - - public AssignmentOperator getOperator() { - return operator; - } - public void setOperator(AssignmentOperator operator) { - this.operator = operator; - } - public Expression getValue() { - return value; - } - public Expression getTarget() { - return target; - } - public void setValue(Expression value) { - this.value = changeValue(this, this.value, value); - } - public void setTarget(Expression target) { - this.target = changeValue(this, this.target, target); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitAssignmentOp(this); - } - - @Override - public Element getNextChild(Element child) { - if (child == getTarget()) - return getValue(); - - return null; - } - - @Override - public Element getPreviousChild(Element child) { - if (child == getValue()) - return getTarget(); - - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTarget()) { - setTarget((Expression) by); - return true; - } - if (child == getValue()) { - setValue((Expression) by); - return true; - } - return false; - } - - - } - - public static class BinaryOp extends Expression { - BinaryOperator operator; - Expression firstOperand, secondOperand; - - public BinaryOp(Expression firstOperand, BinaryOperator operator, Expression secondOperand) { - if (operator == null) - throw new NullPointerException(); - - setOperator(operator); - setFirstOperand(firstOperand); - setSecondOperand(secondOperand); - } - - public BinaryOp() { - } - public void setOperator(BinaryOperator operator) { - this.operator = operator; - } - public Expression getSecondOperand() { - return secondOperand; - } - public Expression getFirstOperand() { - return firstOperand; - } - public void setSecondOperand(Expression secondOperand) { - this.secondOperand = changeValue(this, this.secondOperand, secondOperand); - } - public void setFirstOperand(Expression firstOperand) { - this.firstOperand = changeValue(this, this.firstOperand, firstOperand); - } - - public BinaryOperator getOperator() { - return operator; - } - - @Override - public void accept(Visitor visitor) { - visitor.visitBinaryOp(this); - } - - @Override - public Element getNextChild(Element child) { - if (child == getFirstOperand()) - return getSecondOperand(); - - return null; - } - - @Override - public Element getPreviousChild(Element child) { - if (child == getSecondOperand()) - return getFirstOperand(); - - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getFirstOperand()) { - setFirstOperand((Expression) by); - return true; - } - if (child == getSecondOperand()) { - setSecondOperand((Expression) by); - return true; - } - return false; - } - - } - - public static class UnaryOp extends Expression { - UnaryOperator operator; - Expression operand; - - public UnaryOp(Expression operand, UnaryOperator operator) { - setOperand(operand); - setOperator(operator); - } - - public UnaryOp() { - } - - public Expression getOperand() { - return operand; - } - - public void setOperator(UnaryOperator operator) { - this.operator = operator; - } - public void setOperand(Expression operand) { - this.operand = changeValue(this, this.operand, operand); - } - public UnaryOperator getOperator() { - return operator; - } - - @Override - public void accept(Visitor visitor) { - visitor.visitUnaryOp(this); - } - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getOperand()) { - setOperand((Expression) by); - return true; - } - return false; - } - - } - - public static class Constant extends Expression { - public enum Type { - Int, String, Char, IntegerString, Float, Short, Byte, Long, UInt, Double, LongString, ULong, Bool, Null - } - public enum IntForm { - Hex, Octal, String, Decimal - } - Type type; - IntForm intForm; - Object value; - String originalTextualRepresentation; - - - public Constant(Type type, IntForm intForm, Object value, String originalTextualRepresentation) { - if (value == null) - throw new NullPointerException(); - setType(type); - setIntForm(intForm); - setValue(value); - setOriginalTextualRepresentation(originalTextualRepresentation); - - checkType(); - } - - public void setOriginalTextualRepresentation(String originalTextualRepresentation) { - this.originalTextualRepresentation = originalTextualRepresentation; - } - - public String getOriginalTextualRepresentation() { - return originalTextualRepresentation; - } - - void checkType() { - if (type == null) - return; - - Object value = getValue(); - switch (type) { - case Int: - case UInt: - case IntegerString: - value = (Integer)value; - break; - case ULong: - case Long: - case LongString: - value = (Long)value; - break; - case Char: - value = (Character)value; - break; - case Double: - value = (Double)value; - break; - case Float: - value = (Float)value; - break; - case String: - value = (String)value; - break; - case Bool: - value = (Boolean)value; - } - } - public static Constant newNull() { - return new Constant(Constant.Type.Null, null, null); - } - public Constant(Type type, Object value, String originalTextualRepresentation) { - setType(type); - setValue(value); - setOriginalTextualRepresentation(originalTextualRepresentation); - - checkType(); - } - - public void setIntForm(IntForm intForm) { - this.intForm = intForm; - } - public IntForm getIntForm() { - return intForm; - } - public Type getType() { - return type; - } - public void setType(Type type) { - this.type = type; - } - - public Constant() { - } - /* - public Constant fromString(String s) { - String v = s.toUpperCase(); - Type type = null; - if (v.startsWith("\"")) - type = Type.String; - else if (v.startsWith("'")) - type = v.length()Type.String; - else if (v.contains(".")) { - if (v.endsWith("L")) - c = Float.TYPE; - else - c = Double.TYPE; - } else if (v.endsWith("L")) - c = Long.TYPE; - else if (v.endsWith("F")) - c = Float.TYPE; - else if (v.endsWith("D")) - c = Double.TYPE; - else { - //TODO try to parse as long and if it fails as integer, use Long.TYPE - c = Integer.TYPE; - } - }*/ - public Object getValue() { - return value; - } - public void setValue(Object value) { - this.value = value; - } - - static String intStr(int intVal) { - return String.valueOf((char)(0xff & (intVal >> 24))) + - ((char)(0xff & (intVal >> 16)))+ - ((char)(0xff & (intVal >> 8)))+ - ((char)(0xff & (intVal))) - ; - } - - public void accept(Visitor visitor) { - visitor.visitConstant(this); - } - - - @Override - public Element getNextChild(Element child) { - return null; - } - - @Override - public Element getPreviousChild(Element child) { - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - return false; - } - - public Integer asInteger() { - switch (getType()) { - case Int: - case IntegerString: - return (Integer)value; - } - throw new ClassCastException("Constant " + getValue() + " is not an integer, but a " + getType()); - } - - - public static Constant parseCharOrStringInteger(final String orig) { - String string = orig; - int len = string.length(); - if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'') - throw new IllegalArgumentException("Expecting char or integer string, got " + string); - - string = string.substring(1, len - 1); - len -= 2; - if (len == 4) { - boolean isIntegerString = true; - for (int i = len; i-- != 0;) { - if (string.charAt(i) == '\\') { - isIntegerString = false; - break; - } - } - if (isIntegerString) { - long result = 0; - for (int i = 0; i < len; i++) { - result = result << 8 | (int)string.charAt(i); - } - if (len == 4) - return new Constant(Type.IntegerString, IntForm.String, (int)result, orig); - else - return new Constant(Type.LongString, IntForm.String, result, orig); - } - } - return new Constant(Type.Char, parseNakedString(string).charAt(0), orig); - - } - - public static Constant parseChar(final String orig) { - String string = orig; - int len = string.length(); - if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'') - throw new IllegalArgumentException("Expecting char, got " + string); - - string = string.substring(1, len - 1); - return new Constant(Type.Char, parseNakedString(string).charAt(0), orig); - } - - private static String parseNakedString(String string) { - //return StringUtils.javaUnEscape(string) - int len = string.length(); - StringBuffer b = new StringBuffer(len); - for (int i = 0; i < len;) { - char c = string.charAt(i++); - if (c == '\\') { - c = string.charAt(i++); - switch (c) { - case 't': - b.append('\t'); - break; - case 'n': - b.append('\n'); - break; - case 'r': - b.append('\r'); - break; - case 'f': - b.append('\f'); - break; - case 'b': - b.append('\b'); - break; - case '\\': - b.append('\\'); - break; - case '"': - b.append('"'); - break; - case '\'': - b.append('\''); - break; - case 'u': - if (i < (len - 3)) { - b.append((char)Integer.parseInt(string.substring(i, i + 4), 16)); - i += 4; - } - break; - case '0': - b.append('\0'); - break; - default: - if (Character.isDigit(c)) { - int start = i - 1; - int end = i; - while (Character.isDigit(string.charAt(end))) { - end++; - } - b.append((char)Integer.parseInt(string.substring(start, end), 8)); - i = end; - } - } - } else { - b.append(c); - } - } - return b.toString(); - } - - public static Constant parseStringInteger(final String orig) { - String string = orig; - int len = string.length(); - if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'' || ((len -= 2) != 4 && len != 8)) - throw new IllegalArgumentException("Expecting 'xxxx' or 'xxxxxxxx', got " + string); - - string = string.substring(1, len - 1); - long result = 0; - for (int i = len; i-- != 0;) { - result = result << 8 | (int)string.charAt(i); - } - if (len == 4) - return new Constant(Type.Int, IntForm.String, (int)result, orig); - else - return new Constant(Type.Long, IntForm.String, result, orig); - } - - public static Constant parseString(final String orig) { - String string = orig; - int len = string.length(); - if (len < 2 || string.charAt(0) != '"' || string.charAt(len - 1) != '"') - throw new IllegalArgumentException("Expecting string, got " + string); - - string = string.substring(1, len - 1); - return new Constant(Type.String, parseNakedString(string), orig); - } - - public static Constant parseDecimal(String string) { - return parseDecimal(string, 10, IntForm.Decimal, false); - } - - public static Constant parseDecimal(final String string, int radix, IntForm form, boolean negate) { - return parseDecimal(string, radix, form, negate, string); - } - public static Constant parseDecimal(String string, int radix, IntForm form, boolean negate, final String orig) { - string = string.trim().toLowerCase(); - int len = string.length(); - boolean unsigned = false; - if (string.endsWith("ll") || string.endsWith("li")) - return new Constant(Type.Long, Long.parseLong(string.substring(0, len - 2), radix), orig); - else if (string.endsWith("l")) - string = string.substring(0, len - 1); - else if (string.endsWith("s")) - return new Constant(Type.Short, Long.parseLong(string.substring(0, len - 1), radix), orig); - //else if (string.endsWith("b")) - // return new Constant(Type.Byte, Long.parseLong(string.substring(0, len - 1), radix)); - else if (string.endsWith("u")) { - string = string.substring(0, len - 1); - unsigned = true; - } - - long val; - if (string.equals("ffffffffffffffff")) - val = 0xffffffffffffffffL; - else { - if (string.startsWith("+")) - string = string.substring(1); - - /*int len2 = string.length(); - if (len2 > 0 && !Character.isDigit(string.charAt(len2 - 1))) { - string = string.substring(0, len2 - 1); - len2--; - }*/ - try { - if (string.length() == 16) // only for large longs (otherwise would need to prepend "0" to avoid sign issues) - val = new java.math.BigInteger(string, radix).longValue(); - else - val = Long.parseLong(string, radix); - } catch (NumberFormatException ex) { - unsigned = true; - val = Long.parseLong(string.substring(0, string.length() - 1), radix); - val = val * radix + Short.parseShort(string.substring(string.length() - 1)); - } - } - - if (negate) { - val = -val; -// form = IntForm.Decimal; - } - - //TODO handle unsigned properly ! - if ((form == IntForm.Hex && len <= 8) || val > Integer.MIN_VALUE && val < Integer.MAX_VALUE) - return new Constant(form == IntForm.Hex || unsigned ? Type.UInt : Type.Int, form, (int)val, orig); - else if (val >= 0 && val < MAX_UINT_VALUE) - return new Constant(Type.UInt, form, (int)val, orig); - else - return new Constant(unsigned ? Type.ULong : Type.Long, form, val, orig); - - } - - public static Constant parseHex(final String orig, boolean negate) { - String string = orig; - string = string.trim().toLowerCase(); - if (!string.startsWith("0x")) - throw new IllegalArgumentException("Expected hex literal, got " + string); - - try { - return parseDecimal(string.substring(2), 16, IntForm.Hex, negate, orig); - } catch (NumberFormatException ex) { - throw new NumberFormatException("Parsing hex : \"" + string +"\""); - } - } - - public static Constant parseOctal(String string, boolean negate) { - string = string.trim().toLowerCase(); - if (!string.startsWith("0")) - throw new IllegalArgumentException("Expected octal literal, got " + string); - - return parseDecimal(string.substring(1), 8, IntForm.Octal, negate); - } - - public static Constant parseFloat(final String orig) { - String string = orig; - string = string.trim().toLowerCase(); - if (string.length() > 0) { - int lm1 = string.length() - 1; - char c = string.charAt(lm1); - if (Character.isLetter(c)) { - String beg = string.substring(0, lm1); - if (c == 'f') - return new Constant(Type.Float, Float.parseFloat(beg), orig); - - } - } - return new Constant(Type.Double, Double.parseDouble(string), orig); - } - static final String[] trailingTypeInfos = new String[] { "ll", "li", "l", "s", "u" }; - static String trimTrailingTypeInfo(String s) { - if (s == null) - return null; - - String low = s.toLowerCase(); - for (String end : trailingTypeInfos) { - if (low.endsWith(end)) - return s.substring(0, s.length() - end.length()); - } - return s; - } - public Constant asJava() { - Type type = getType(); - String txt = originalTextualRepresentation; - switch (type) { - case Byte: - case Int: - case Long: - case LongString: - case Short: - txt = trimTrailingTypeInfo(txt); - break; - case UInt: - case ULong: - case IntegerString: - txt = null; - break; - } - - switch (type) { - case Long: - case ULong: - if (txt != null) - txt += "L"; - case LongString: - type = Type.Long; - break; - case UInt: - if ((getValue() instanceof Long) && ((Long)getValue()) > Integer.MAX_VALUE) - txt = null; - case IntegerString: - type = Type.Int; - break; - } - - return new Constant(type, getValue(), txt); - } - - - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ExternDeclarations.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ExternDeclarations.java deleted file mode 100644 index 227e96807..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ExternDeclarations.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.List; - -public class ExternDeclarations extends Declarations { - String language; - public String getLanguage() { - return language; - } - public void setLanguage(String language) { - this.language = language; - } - @Override - public void accept(Visitor visitor) { - visitor.visitExternDeclarations(this); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FriendDeclaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FriendDeclaration.java deleted file mode 100644 index 67173bd7a..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FriendDeclaration.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -public class FriendDeclaration extends Declaration { - Declaration friend; - public FriendDeclaration() { - super(); - } - public void setFriend(Declaration friend) { - this.friend = changeValue(this, this.friend, friend); - } - public Declaration getFriend() { - return friend; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getFriend()) { - setFriend((Declaration) by); - return true; - } - return super.replaceChild(child, by); - } - public FriendDeclaration(Declaration friend) { - super(); - setFriend(friend); - } - @Override - public void accept(Visitor visitor) { - visitor.visitFriendDeclaration(this); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Function.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Function.java deleted file mode 100644 index 77c48f318..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Function.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.ident; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import java.util.Collections; - -public class Function extends Declaration implements Declarator.MutableByDeclarator { - //private Struct owner; - - final List args = new ArrayList(); - final List thrown = new ArrayList(); - final List initializers = new ArrayList(); - boolean throws_; - Statement.Block body; - Type type; - - Identifier name; - - public Function setName(Identifier name) { -// if (name != null && name.toString().equals("NSStringFromSelector")) -// name = name; - - this.name = changeValue(this, this.name, name); - return this; - } - public Identifier getName() { - return name; - } - public enum Type { - CFunction, ObjCMethod, CppMethod, JavaMethod, StaticInit - } - - public boolean getThrows() { - return throws_; - } - - public void setThrows(boolean throws_) { - this.throws_ = throws_; - } - - - public void setInitializers(List initializers) { - changeValue(this, this.initializers, initializers); - } - public void addInitializer(FunctionCall i) { - if (i == null) - return; - - i.setParentElement(this); - initializers.add(i); - } - public List getInitializers() { - return unmodifiableList(initializers); - } - String asmName; - public void setAsmName(String asmName) { - this.asmName = asmName; - } - public String getAsmName() { - return asmName; - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - e = getNextSibling(initializers, child); - if (e != null) - return e; - e = getNextSibling(thrown, child); - if (e != null) - return e; - return getNextSibling(args, child); - } - - @Override - public Function clone() { - return (Function) super.clone(); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - e = getPreviousSibling(initializers, child); - if (e != null) - return e; - e = getPreviousSibling(thrown, child); - if (e != null) - return e; - return getPreviousSibling(args, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getBody()) { - setBody((Statement.Block)by); - return true; - } - if (child == getName()) { - setName((Identifier)by); - return true; - } - if (replaceChild(args, Arg.class, this, child, by)) - return true; - - if (replaceChild(thrown, TypeRef.class, this, child, by)) - return true; - - if (replaceChild(initializers, FunctionCall.class, this, child, by)) - return true; - - return super.replaceChild(child, by); - } - - - - public Type getType() { - return type; - } - public void setType(Type type) { - this.type = type; - } - public Arg addArg(Arg a) { - if (a != null) { - args.add(a); - a.setParentElement(this); - } - return a; - } - public List getArgs() { - return unmodifiableList(args); - } - public void setArgs(List args) { - changeValue(this, this.args, args); - } - - public TypeRef addThrown(TypeRef a) { - if (a != null) { - thrown.add(a); - a.setParentElement(this); - } - return a; - } - public List getThrown() { - return unmodifiableList(thrown); - } - public void setThrown(List thrown) { - changeValue(this, this.thrown, thrown); - } - - public Function setBody(Statement.Block body) { - this.body = changeValue(this, this.body, body); - return this; - } - - //public static class CFunction extends Function { - public Function() {} - - public Function(Type type, Identifier name, TypeRef returnType) { - setType(type); - setName(name); - setValueType(returnType); - } - public Function(Type type, Identifier name, TypeRef returnType, Arg... args) { - this(type, name, returnType, Arrays.asList(args)); - } - - public Function(Type type, Identifier name, TypeRef returnType, List args) { - setType(type); - setName(name); - setValueType(returnType); - setArgs(args); - } - - @Override - public Function addAnnotation(Annotation a) { - return (Function)super.addAnnotation(a); - } - - @Override - public Function addModifiers(Modifier... mds) { - return (Function) super.addModifiers(mds); - } - - - public void accept(Visitor visitor) { - visitor.visitFunction(this); - } - public Statement.Block getBody() { - return body; - } - - Scanner eraser = new Scanner() { - - @Override - public void visitSimpleIdentifier(SimpleIdentifier e) { - super.visitSimpleIdentifier(e); - e.setTemplateArguments(Collections.EMPTY_LIST); - } - - }; - public E erase(E e) { - eraser.visit(e); - return e; - } - - public enum SignatureType { - Full(true, true), - ArgsOnly(false, false), - ArgsAndRet(false, true), - JavaStyle(true, false); - - public final boolean hasName, hasReturnType; - private SignatureType(boolean hasName, boolean hasReturnType) { - this.hasName = hasName; - this.hasReturnType = hasReturnType; - } - } - public String computeSignature(SignatureType signatureType) { - StringBuilder b = new StringBuilder(); - - if (type == Type.ObjCMethod) { - b.append(modifiers.contains(ModifierType.Static) ? "+" : "-"); - b.append("("); - TypeRef t = getValueType(); - if (t == null) - b.append("id"); - else { - t = t.clone(); - erase(t); - t.setCommentAfter(null); - t.setCommentBefore(null); - b.append(t); - } - b.append(")"); - b.append(getName()); - boolean firstArg = true; - for (Arg arg : args) { - if (arg.isVarArg()) { - if (!firstArg) - b.append(", "); - b.append("..."); - } else { - if (!firstArg) - b.append(" " + arg.getSelector()); - b.append(":("); - t = arg.createMutatedType(); - if (t != null) { - erase(t); - t.setCommentAfter(null); - t.setCommentBefore(null); - b.append(t); - } - b.append(')'); - //No arg name in signature : b.append(arg.getName()); - } - firstArg = false; - } - } else { - if (signatureType.hasReturnType && getValueType() != null) { - TypeRef t = getValueType().clone(); - erase(t); - t.stripDetails(); - b.append(t); - b.append(' '); - } - if (signatureType.hasName) - b.append(getName()); - boolean first = true; - b.append('('); - for (Arg arg : getArgs()) { - if (first) { - first = false; - } else - b.append(", "); - TypeRef t = arg.createMutatedType(); - if (t != null) { - erase(t); - t.stripDetails(); - } - b.append(t); - } - b.append(')'); - } - return b.toString(); - } - - public static Function fromMethod(Method m) { - Function f = new Function( - Function.Type.JavaMethod, - ident(m.getName()), - m.getReturnType() == null ? typeRef("void") : typeRef(m.getReturnType()) - ); - int i = 0; - for (Class c : m.getParameterTypes()) { - f.addArg(new Arg("arg" + (i++), typeRef(c))); - } - int modifiers = m.getModifiers(); - if (java.lang.reflect.Modifier.isPrivate(modifiers)) - f.addModifiers(ModifierType.Private); - if (java.lang.reflect.Modifier.isProtected(modifiers)) - f.addModifiers(ModifierType.Protected); - if (java.lang.reflect.Modifier.isPublic(modifiers)) - f.addModifiers(ModifierType.Public); - if (java.lang.reflect.Modifier.isStatic(modifiers)) - f.addModifiers(ModifierType.Static); - - if (java.lang.reflect.Modifier.isAbstract(modifiers)) - f.addModifiers(ModifierType.Abstract); - if (java.lang.reflect.Modifier.isFinal(modifiers)) - f.addModifiers(ModifierType.Final); - if (java.lang.reflect.Modifier.isNative(modifiers)) - f.addModifiers(ModifierType.Native); - if (java.lang.reflect.Modifier.isSynchronized(modifiers)) - f.addModifiers(ModifierType.Synchronized); - - /*TODO org.rococoa.ReturnType returnType = m.getAnnotation(ReturnType.class); - if (returnType != null && returnType.value() != null) { - f.addAnnotation(new Annotation(ReturnType.class, classLiteral(returnType.value()))); - }*/ - return f; - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FunctionPointerDeclaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FunctionPointerDeclaration.java deleted file mode 100644 index 0d35b961e..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/FunctionPointerDeclaration.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; - -public class FunctionPointerDeclaration extends Declaration { - Expression defaultValue; - - public FunctionPointerDeclaration(FunctionSignature functionSignature) { - this(); - setValueType(functionSignature); - //setName(functionSignature.getFunction().getName()); - } - - public FunctionPointerDeclaration() { - } - - public Expression getDefaultValue() { - return defaultValue; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getDefaultValue()) { - setDefaultValue((Expression) by); - return true; - } - return super.replaceChild(child, by); - } - - public void setDefaultValue(Expression defaultValue) { - this.defaultValue = changeValue(this, this.defaultValue, defaultValue); - } - @Override - public FunctionSignature getValueType() { - return (FunctionSignature)super.getValueType(); - } - @Override - public void setValueType(TypeRef valueType) { - super.setValueType((FunctionSignature)valueType); - } - public void accept(Visitor visitor) { - visitor.visitFunctionPointerDeclaration(this); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Identifier.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Identifier.java deleted file mode 100644 index 96609c1f4..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Identifier.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.ochafik.lang.SyntaxUtils; - -public abstract class Identifier extends Element implements Comparable { - public enum QualificationSeparator { - Colons("::"), - Dot("."); - - private QualificationSeparator(String s) { - this.s = s; - } - private String s; - @Override - public String toString() { - return s; - } - } - public QualifiedIdentifier derive(QualificationSeparator separator, Identifier... subIdentifiers) { - QualifiedIdentifier qi = new QualifiedIdentifier(separator); - qi.add(this); - for (Identifier i : subIdentifiers) - if (i != null) - qi.add(i); - return qi; - } - public QualifiedIdentifier derive(QualificationSeparator separator, String... subIdentifiers) { - QualifiedIdentifier qi = new QualifiedIdentifier(separator); - qi.add(this); - for (String i : subIdentifiers) - qi.add(new SimpleIdentifier(i)); - return qi; - } - @Override - public Identifier clone() { - return (Identifier)super.clone(); - } - public abstract boolean isPlain(); - public abstract SimpleIdentifier resolveLastSimpleIdentifier(); - public abstract List resolveSimpleIdentifiers(); - - public abstract Identifier eraseTemplateArguments(); - - public static class SimpleIdentifier extends Identifier { - private String name; - protected List templateArguments = new ArrayList(); - - public SimpleIdentifier() {} - public SimpleIdentifier(String name, Expression... args) { - setName(name); - setTemplateArguments(Arrays.asList(args)); - } - public void addTemplateArgument(Expression x) { - if (x == null) - return; - x.setParentElement(this); - templateArguments.add(x); - } - - public Identifier eraseTemplateArguments() { - return new SimpleIdentifier(getName()); - } - public List getTemplateArguments() { - return unmodifiableList(templateArguments); - } - public String getName() { - return name; - } - public void setName(String name) { - if (name != null && (name.contains(".") || name.contains("::"))) - throw new IllegalArgumentException("Not a simple identifier : '" + name + "'"); - this.name = name; - } - public void setTemplateArguments(List templateArguments) { - changeValue(this, this.templateArguments, templateArguments); - } - @Override - public void accept(Visitor visitor) { - visitor.visitSimpleIdentifier(this); - } - @Override - public Element getNextChild(Element child) { - return getNextSibling(templateArguments, child); - } - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(templateArguments, child); - } - @Override - public boolean replaceChild(Element child, Element by) { - return replaceChild(templateArguments, Expression.class, this, child, by); - } - @Override - public boolean isPlain() { - return templateArguments.isEmpty(); - } - @Override - public SimpleIdentifier resolveLastSimpleIdentifier() { - return this; - } - @Override - public List resolveSimpleIdentifiers() { - return Arrays.asList(this); - } - @Override - public Identifier resolveAllButLastIdentifier() { - return null; - } - } - public static class QualifiedIdentifier extends Identifier { - private List identifiers = new ArrayList(); - private QualificationSeparator separator; - public List getIdentifiers() { - return unmodifiableList(identifiers); - } - - @Override - public QualifiedIdentifier clone() { - return (QualifiedIdentifier)super.clone(); - } - - public void add(Identifier identifier) { - if (identifier instanceof SimpleIdentifier) - addIdentifier((SimpleIdentifier)identifier); - else { - QualifiedIdentifier oqi = (QualifiedIdentifier)identifier; - if (!SyntaxUtils.equal(oqi.getSeparator(), separator)) - throw new IllegalArgumentException("Attempting to derive qualified identifier " + this + " with mismatching separator " + separator + " and sub-name " + identifier); - - addIdentifiers(oqi.getIdentifiers()); - } - } - public QualifiedIdentifier() {} - public QualifiedIdentifier(QualificationSeparator separator) { - setSeparator(separator); - } - public QualifiedIdentifier(QualificationSeparator separator, List identifiers) { - setSeparator(separator); - setIdentifiers(identifiers); - } - public void setSeparator(QualificationSeparator separator) { - this.separator = separator; - } - public QualificationSeparator getSeparator() { - return separator; - } - public void setIdentifiers(List identifiers) { - changeValue(this, this.identifiers, identifiers); - } - @Override - public void accept(Visitor visitor) { - visitor.visitQualifiedIdentifier(this); - } - @Override - public Element getNextChild(Element child) { - return getNextSibling(identifiers, child); - } - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(identifiers, child); - } - @Override - public boolean replaceChild(Element child, Element by) { - return replaceChild(identifiers, SimpleIdentifier.class, this, child, by); - } - public void addIdentifiers(List is) { - for (SimpleIdentifier i : is) - addIdentifier(i); - } - - public void addIdentifier(SimpleIdentifier i) { - if (i == null) - return; - i.setParentElement(this); - identifiers.add(i); - } - @Override - public boolean isPlain() { - return identifiers.size() == 1 && identifiers.get(0).isPlain(); - } - @Override - public SimpleIdentifier resolveLastSimpleIdentifier() { - return identifiers.isEmpty() ? null : identifiers.get(identifiers.size() - 1); - } - @Override - public QualifiedIdentifier eraseTemplateArguments() { - return resolveAllButLastIdentifier().derive(getSeparator(), resolveLastSimpleIdentifier().eraseTemplateArguments()); - } - @Override - public List resolveSimpleIdentifiers() { - return getIdentifiers(); - } - @Override - public Identifier resolveAllButLastIdentifier() { - List si = new ArrayList(identifiers); - if (!si.isEmpty()) { - si.remove(si.size() - 1); - } - return new QualifiedIdentifier(getSeparator(), si); - } - } - - public final int compareTo(Object o) { - String s = toString(); - if (s == null) { - return o == null ? 0 : -1; - } - String os = o == null ? null : String.valueOf(o); - return os == null ? -1 : s.compareTo(os); - } - @Override - public final boolean equals(Object obj) { - return compareTo(obj) == 0; - } - @Override - public final int hashCode() { - return toString().hashCode(); - } - public abstract Identifier resolveAllButLastIdentifier(); -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifiableElement.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifiableElement.java deleted file mode 100644 index 54bf65de4..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifiableElement.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; - -public abstract class ModifiableElement extends Element { - protected final List modifiers = new ArrayList(); - - @Override - public void accept(Visitor visitor) { - visitor.visitModifiableElement(this); - } - - protected final List annotations = new ArrayList(); - public void addAnnotations(List as) { - for (Annotation a : as) - addAnnotation(a); - } - public ModifiableElement addAnnotation(Annotation a) { - if (a != null) { - annotations.add(a); - a.setParentElement(this); - } - return this; - } - - public List getAnnotations() { - return unmodifiableList(annotations); - } - public void setAnnotations(List annotations) { - changeValue(this, this.annotations, annotations); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(annotations, Annotation.class, this, child, by)) - return true; - - return false; - } - - - @Override - public Element getNextChild(Element child) { - return getNextSibling(annotations, child); - } - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(annotations, child); - } - - public ModifiableElement addModifiers(List mods) { - if (mods != null) - for (Modifier mod : mods) { - if (mod != null) - modifiers.add(mod); - } - return this; - } - - public ModifiableElement addModifiers(Modifier... mds) { - return addModifiers(Arrays.asList(mds)); - } - public Object getModifierValue(ModifierType t) { - Modifier rt = t.resolveAlias(); - if (!t.isAnyOf(ModifierKind.HasArguments, ModifierKind.VCAnnotation1Arg)) - throw new RuntimeException("Modifier type " + t + " does not hold any value."); - for (Modifier m : getModifiers()) { - if (m instanceof ValuedModifier) { - ValuedModifier vm = (ValuedModifier)m; - Modifier mm = vm.getModifier(); - if (mm == null) - continue; - mm = mm.resolveAlias(); - if (rt.equals(mm)) - return vm.getValue(); - } - } - return null; - } - public ModifiableElement reorganizeModifiers() { - setModifiers(new ArrayList(new LinkedHashSet(getModifiers()))); - return this; - } - - public List getModifiers() { - return Collections.unmodifiableList(modifiers); - } - - public List harvestModifiers() { - List mods = new ArrayList(); - mods.addAll(getModifiers()); - return mods; - } - - public boolean hasModifier(Modifier m) { - m = m.resolveAlias(); - for (Modifier mm : modifiers) - if (m.equals(mm.resolveAlias())) - return true; - return false; - } - public void removeModifiers(Modifier...modifiers) { - for (Modifier m : modifiers) - this.modifiers.remove(m); - } - public void setModifiers(List modifiers) { - this.modifiers.clear(); - if (modifiers != null) - this.modifiers.addAll(modifiers); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Modifier.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Modifier.java deleted file mode 100644 index 6e08a5f00..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Modifier.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.Collection; - -public interface Modifier { - Modifier resolveAlias(); - - boolean isA(ModifierKind kind); - boolean isAnyOf(ModifierKind...kinds); - boolean isAllOf(ModifierKind...kinds); - Collection getKinds(); - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierKind.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierKind.java deleted file mode 100644 index f7222daa2..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierKind.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -public enum ModifierKind { - - StorageClassSpecifier, - TypeQualifier, - Declspec, /// VC++ __declspec - Attribute, /// GCC __attribute__ - Publicity, - CallingConvention, - HasArguments, - COMSpecific, - MSSpecific, - - OnlyInArgDef, - - C, - OpenCL, - CPlusPlus, - ObjectiveC, - Java, - CSharp, - CPlusPlusCLI, - - Plain, - Extended, - NumericTypeQualifier, - ReferenceQualifier, - SizeModifier, - SignModifier, ///http://msdn.microsoft.com/en-us/library/cc264105.aspx - StringAnnotation, - VCAnnotationNoArg, - VCAnnotation2Args, - VCAnnotation1Arg, - VCParameterAnnotation -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierType.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierType.java deleted file mode 100644 index 39fc96fcb..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ModifierType.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import static java.util.EnumSet.of; -import java.util.HashMap; -import java.util.Map; - -import static com.ochafik.lang.jnaerator.parser.ModifierKind.*; - -/** - * @see MSDN __declspec - */ -public enum ModifierType implements Modifier { - __cdecl(of(CallingConvention)), - _cdecl(__cdecl), - - __stdcall(of(CallingConvention)), - _stdcall(__stdcall), - - __fastcall(of(CallingConvention)), - _fastcall(__fastcall), - - __thiscall(of(CallingConvention)), - _thiscall(__thiscall), - - __pascal(of(CallingConvention)), - _pascal(__pascal), - - /// VC++ annotations - /// @see http://msdn.microsoft.com/en-us/library/cc264104.aspx - - - __pre(of(VCAnnotationNoArg, VCParameterAnnotation)), - __valid(of(VCAnnotationNoArg, VCParameterAnnotation)), - __reserved(of(VCAnnotationNoArg, VCParameterAnnotation)), - __checkReturn(of(VCAnnotationNoArg, VCParameterAnnotation)), - __fallthrough(of(VCAnnotationNoArg, VCParameterAnnotation)), - __readonly(of(VCAnnotationNoArg, VCParameterAnnotation)), - __null(of(VCAnnotationNoArg, VCParameterAnnotation)), - __in(of(VCAnnotationNoArg, VCParameterAnnotation)), - __out(of(VCAnnotationNoArg, VCParameterAnnotation)), - __inout(of(VCAnnotationNoArg, VCParameterAnnotation)), - __refparam(of(VCAnnotationNoArg, VCParameterAnnotation)), - __exceptthat(of(VCAnnotationNoArg, VCParameterAnnotation)), - - _opt(of(VCAnnotationNoArg, VCParameterAnnotation)), - _deref(of(VCAnnotationNoArg, VCParameterAnnotation)), - _deref_opt(of(VCAnnotationNoArg, VCParameterAnnotation)), - _ecount(of(VCAnnotation1Arg, VCParameterAnnotation)), - _bcount(of(VCAnnotation1Arg, VCParameterAnnotation)), - _full(of(VCAnnotation1Arg, VCParameterAnnotation)), - _part(of(VCAnnotation2Args, VCParameterAnnotation)), - - __ptr64(of(TypeQualifier)), // TODO find better kind - __maybenull(of(TypeQualifier)), - - // http://msdn.microsoft.com/en-us/library/aa383701(v=vs.85).aspx - __nullterminated(of(TypeQualifier, StringAnnotation)), - __nullnullterminated(of(TypeQualifier, StringAnnotation)), - __possibly_notnullterminated(of(TypeQualifier, StringAnnotation)), - //__success, - - Auto(of(StorageClassSpecifier)), - Register(of(StorageClassSpecifier)), - Static(of(StorageClassSpecifier)), - Virtual(of(StorageClassSpecifier)), - Extern(of(StorageClassSpecifier)), - Pascal(__pascal, of(StorageClassSpecifier)), - //TypeDef(of(StorageClassSpecifier)), // TODO propagate this to everywhere : need to remove TypeDef class - - __const(of(TypeQualifier)), - Const(__const), - Volatile(of(TypeQualifier)), - Mutable(of(TypeQualifier)), - - __unsigned(of(NumericTypeQualifier, SignModifier)), - __signed(of(NumericTypeQualifier, SignModifier)), - Unsigned(__unsigned), - Signed(__signed), - Long(of(NumericTypeQualifier, SizeModifier)), - Short(of(NumericTypeQualifier, SizeModifier)), - - _Complex(of(NumericTypeQualifier)), - //Complex(_Complex), - - Typename(of(ReferenceQualifier)), - Struct(of(ReferenceQualifier)), - Class(of(ReferenceQualifier)), - - /*primSignModifier - : 'signed' | 'unsigned' | '__signed' | '__unsigned'; - */ - - //Transient(of(TypeQualifier, Java)), - - Public(of(Publicity)), - Abstract(of(Publicity)), - Final(of(Publicity)), - Private(of(Publicity)), - Protected(of(Publicity)), - Explicit(of(Publicity, StorageClassSpecifier)), - - Inline(of(C, StorageClassSpecifier)), - __inline(Inline), - __inline__(Inline), - __forceinline(of(C, StorageClassSpecifier)), - - In(of(ObjectiveC, OnlyInArgDef)), - Out(of(ObjectiveC, OnlyInArgDef)), - InOut(of(ObjectiveC, OnlyInArgDef)), - OneWay(of(ObjectiveC, OnlyInArgDef)), - ByCopy(of(ObjectiveC, OnlyInArgDef)), - ByRef(of(ObjectiveC, OnlyInArgDef)), - - Package(of(ObjectiveC)), - Optional(of(ObjectiveC)), - Required(of(ObjectiveC)), - - Align(of(Declspec, HasArguments)), - Allocate(of(Declspec, HasArguments)), - AppDomain(of(Declspec)), - Deprecated(of(Declspec, Attribute)), - DllExport(of(Declspec, StorageClassSpecifier)), - DllImport(of(Declspec, StorageClassSpecifier)), - JITIntrinsic(of(Declspec)), - Naked(of(Declspec, StorageClassSpecifier, Attribute)), - __unused__(of(Attribute)), - NoAlias(of(Declspec, StorageClassSpecifier)), - NoInline(of(Declspec)), - NoReturn(of(Declspec)), - NoThrow(of(Declspec, StorageClassSpecifier)), - NoVTable(of(Declspec)), - Process(of(Declspec)), - Property(of(Declspec, HasArguments, StorageClassSpecifier, COMSpecific)), //TODO handle args - Restrict(of(Declspec, StorageClassSpecifier)), - __restrict(Restrict), - - SelectAny(of(Declspec, StorageClassSpecifier, COMSpecific)), - Thread(of(Declspec)), - UUID(of(Declspec, Extended, HasArguments, StorageClassSpecifier, COMSpecific, VCAnnotation1Arg)), - - Alias(of(Attribute)), - Always_inline(of(Attribute)), - Cdecl(__cdecl, of(Attribute)), - //Const(of(Attribute)), - Constructor(of(Attribute)), - Destructor(of(Attribute)), - Dllexport(of(Attribute)), - Weak_import(of(Attribute)), - Dllimport(of(Attribute)), - Eightbit_data(of(Attribute)), - Exception(of(Attribute)), - Far(of(Attribute)), - Fastcall(__fastcall, of(Attribute)), - Format(of(Attribute)), - Format_arg(of(Attribute)), - Function_vector(of(Attribute)), - Interrupt(of(Attribute)), - Interrupt_handler(of(Attribute)), - Long_call(of(Attribute)), - Short_call(of(Attribute)), - Longcall(of(Attribute)), - Shortcall(of(Attribute)), - Malloc(of(Attribute)), - Model(of(Attribute)), - Near(of(Attribute)), - No_check_memory_usage(of(Attribute)), - No_instrument_function(of(Attribute)), - Noinline(of(Attribute)), - Nonnull(of(Attribute)), - Noreturn(of(Attribute)), - Nothrow(of(Attribute)), - Pure(of(Attribute)), - Regparm(of(Attribute)), - Saveall(of(Attribute)), - Section(of(Attribute)), - Signal(of(Attribute)), - Sp_switch(of(Attribute)), - Stdcall(__stdcall, of(Attribute)), - Tiny_data(of(Attribute)), - Trap_exit(of(Attribute)), - Unused(of(Attribute)), - Used(of(Attribute)), - Visibility(of(Attribute)), - Warn_unused_result(of(Attribute)), - Weak(of(Attribute)), - - //Complex(of(OpenCL)), - __kernel(of(OpenCL)), - __global(of(OpenCL)), - __read_only(of(OpenCL)), - __write_only(of(OpenCL)), - __local(of(OpenCL)), - __constant(of(OpenCL)), - __private(of(OpenCL)), - - Synchronized(of(Java)), - Native(of(Java)); - - EnumSet kinds; - Modifier alias; - - /* - Modifier(Kind... kinds) { - this.kinds = EnumSet.noneOf(Kind.class); - for (Kind kind : kinds) - this.kinds.add(kind); - } - Modifier(Modifier alias, Kind... kinds) { - this(kinds); - this.alias = alias; - } - Modifier(EnumSet kinds) { - this.alias = alias; - }*/ - ModifierType(ModifierType alias) { - this.kinds = alias.kinds; - this.alias = alias; - } - ModifierType(EnumSet kinds) { - this.kinds = kinds; - } - ModifierType(Modifier alias, EnumSet kinds) { - this.alias = alias; - this.kinds = kinds; - } - - public Modifier resolveAlias() { - if (alias == null) - return this; - return alias.resolveAlias(); - } - - public boolean isContainedBy(Collection modifiers) { - Modifier alias = resolveAlias(); - for (Modifier modifier : modifiers) - if (modifier.resolveAlias().equals(alias)) - return true; - return false; - } - public int countIn(Collection modifiers) { - Modifier alias = resolveAlias(); - int c = 0; - for (Modifier modifier : modifiers) - if (modifier.resolveAlias().equals(alias)) - c++; - return c; - } - public Modifier getAlias() { - return alias; - } - - static Map mods = new - HashMap(); - static { - for (ModifierType m : values()) { - mods.put(m.name().toLowerCase(), m); - } - } - /** - * @param name modifier name to parse - * @param kinds if not empty, returns only a modifier that matches all of the kinds - * @return Modifier that matches any of the kinds constraints - */ - public static Modifier parseModifier(String name, ModifierKind... kinds) { - try { - //Modifier modifier = Modifier.valueOf(name); - Modifier modifier = mods.get(name.toLowerCase()); - if (kinds.length == 0 || modifier == null) - return modifier; - for (ModifierKind kind : kinds) - if (modifier.isA(kind)) - return modifier; - return kinds.length > 0 ? null : modifier; - } catch (IllegalArgumentException ex) { - return null; - } - } - - /** - * Try to be smart about Kind inheritance (C => C++ or Objective-C) - */ - public boolean isA(ModifierKind k) { - if (k == Plain && !(kinds.contains(Attribute) || kinds.contains(Declspec))) - return true; - if (k == Extended && (kinds.contains(Attribute) || kinds.contains(Declspec))) - return true; - if ((k == CPlusPlus || k == CPlusPlusCLI || k == ObjectiveC) && kinds.contains(C)) - return true; - - if (kinds.contains(k)) - return true; - - //if (alias != null && alias.isA(k)) - // return true; - - return false; - } - - public boolean isAnyOf(ModifierKind...kinds) { - for (ModifierKind kind : kinds) - if (isA(kind)) - return true; - - return false; - } - - public boolean isAllOf(ModifierKind...kinds) { - for (ModifierKind kind : kinds) - if (!isA(kind)) - return false; - - return true; - } - - - public enum Compiler { - GCC, MSVC, Intel - } - - @Override - public String toString() { - return toString(null); - } - public String toString(ModifierType.Compiler compiler) { - String low = name().toLowerCase(); - - if (!kinds.contains(VCAnnotation1Arg) && !kinds.contains(VCAnnotation2Args) && !kinds.contains(VCAnnotationNoArg)) - if (kinds.contains(Declspec))// && (compiler == null || compiler == Compiler.MSVC)) - return "__declspec(" + low + ")"; - - if (kinds.contains(Attribute))// && !kin (compiler == null || compiler == Compiler.GCC)) - return "__attribute__((" + low + "))"; - - return low; - } - - public Collection getKinds() { - return kinds; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Namespace.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Namespace.java deleted file mode 100644 index d50882272..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Namespace.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * - * @author ochafik - */ -public class Namespace extends Declarations { - Identifier name; - - public Namespace() {} - public Namespace(Identifier name, Declaration... declarations) { - setName(name); - setDeclarations(declarations); - } - @Override - public void accept(Visitor visitor) { - visitor.visitNamespace(this); - } - - public Identifier getName() { - return name; - } - - public void setName(Identifier name) { - this.name = changeValue(this, this.name, name); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getName()) { - setName((Identifier) by); - return true; - } - return super.replaceChild(child, by); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/PrintScanner.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/PrintScanner.java deleted file mode 100644 index a074b3f7f..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/PrintScanner.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -import com.ochafik.util.string.StringUtils; - -public class PrintScanner extends Scanner { - StringWriter sout = new StringWriter(); - protected PrintWriter out = new PrintWriter(sout); - protected final MessageFormat invalidFormat; - protected List exceptions = new ArrayList(); - - public PrintScanner(String invalidFormatString) { - this(new MessageFormat(invalidFormatString)); - } - public PrintScanner(MessageFormat invalidFormat) { - this.invalidFormat = invalidFormat; - } - public PrintScanner() { - this("/*\nErrors occurred :\n{0}\n{1}\n*/"); - } - - String indent = ""; - public String getIndent() { - return indent; - } - public String setIndent(String indent) { - return this.indent = indent; - } - public String incrIndent() { - return setIndent(getIndent() + "\t"); - } - public String decrIndent() { - String s = getIndent(); - int len = s.length(); - if (len > 0 && s.charAt(len - 1) == '\t') - return s.substring(0, len - 1); - return s; - } - - protected void println(Object... os) { - if (os.length == 0) - out.println(); - - for (Object o : os) - out.println(o); - } - protected void print(Object... os) { - for (Object o : os) - out.print(o); - } - protected void addException(Exception ex) { - exceptions.add(ex); - } - - @Override - public String toString() { - String s = sout.toString(); - if (exceptions.isEmpty()) - return s; - else - return invalidFormat.format(new Object[] {StringUtils.implode(exceptions, "\n").replace("*/", "* /"), s.replace("*/", "* /")}, new StringBuffer(), null).toString(); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Printer.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Printer.java deleted file mode 100644 index 922974161..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Printer.java +++ /dev/null @@ -1,1167 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Statement.Delete; -import com.ochafik.lang.jnaerator.parser.TypeRef.PrecisionTypeRef; -import static com.ochafik.util.string.StringUtils.LINE_SEPARATOR; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.TreeSet; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.FunctionDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerDeclarator; -import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; -import com.ochafik.lang.jnaerator.parser.Enum.Type; -import com.ochafik.lang.jnaerator.parser.Expression.ArrayAccess; -import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; -import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.Cast; -import com.ochafik.lang.jnaerator.parser.Expression.ConditionalExpression; -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionSequence; -import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Expression.New; -import com.ochafik.lang.jnaerator.parser.Expression.NewArray; -import com.ochafik.lang.jnaerator.parser.Expression.NullExpression; -import com.ochafik.lang.jnaerator.parser.Expression.OpaqueExpression; -import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; -import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.parser.Expression.Constant.IntForm; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionsBlock; -import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -import com.ochafik.lang.jnaerator.parser.Statement.Catch; -//import com.ochafik.lang.jnaerator.parser.Statement.DeclarationStatement; -import com.ochafik.lang.jnaerator.parser.Statement.DoWhile; -import com.ochafik.lang.jnaerator.parser.Statement.ExpressionStatement; -import com.ochafik.lang.jnaerator.parser.Statement.If; -import com.ochafik.lang.jnaerator.parser.Statement.Return; -import com.ochafik.lang.jnaerator.parser.Statement.Throw; -import com.ochafik.lang.jnaerator.parser.Statement.For; -import com.ochafik.lang.jnaerator.parser.Statement.Try; -import com.ochafik.lang.jnaerator.parser.Statement.While; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; -import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.ListenableCollections; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; - -/** - * - * @author ochafik - */ -public class Printer implements Visitor { - - StringBuilder out = new StringBuilder(); - int currentLine = 0; - Stack indentStack = new Stack(); - volatile String indent = ""; - protected static boolean beginEachCommentLineWithStar = true; - - protected void indent(String indent) { - indentStack.push(this.indent = indent); - } - - protected void indent() { - indent(indent + "\t"); - } - - protected void deindent() { - indentStack.pop(); - indent = indentStack.isEmpty() ? "" : indentStack.lastElement(); - } - - public Printer() {} - public Printer(String initialIdent) { - indent = initialIdent == null ? "" : initialIdent; - } - - @Override - public String toString() { - return out.toString(); - } - - protected void expressionPre(Expression x) { - append(x.getParenthesis() ? "(" : ""); - } - protected void expressionPost(Expression x) { - append(x.getParenthesis() ? ")" : ""); - } - public void visitConstant(Constant e) { - expressionPre(e); - String txt = e.getOriginalTextualRepresentation(); - if (txt != null) { - append(txt); - } else { - Object value = e.getValue(); - if (e.getIntForm() == IntForm.Hex) - append("0x", Long.toHexString(value instanceof Long ? ((Long)value).longValue() : ((Integer)value).longValue()).toUpperCase()); - else if (e.getIntForm() == IntForm.Octal) - append(Long.toOctalString(value instanceof Long ? ((Long)value).longValue() : ((Integer)value).longValue()).toUpperCase()); - else if (e.getType() == null) - append(""); - else { - switch (e.getType()) { - case Null: - append("null"); - break; - case Byte: - case Double: - case Int: - case Short: - case UInt: - append(value); - break; - case Float: - append(value, 'F'); - break; - case ULong: - case Long: - append(value, 'L'); - break; - case String: - append('"', StringUtils.javaEscape((String)value), '"'); - break; - case Char: - append('\'', StringUtils.javaEscape(((Character)value).toString()), '\''); - break; - case IntegerString: - int intVal = ((Integer)value).intValue(); - append('\'', Constant.intStr(intVal), '\''); - break; - case LongString: - long longVal = ((Long)value).intValue(); - append( - '\'', - Constant.intStr((int)(longVal & 0xffffffffL)), - Constant.intStr((int)((longVal >>> 32) & 0xffffffffL)), - '\'' - ); - break; - case Bool: - append(((Boolean)value).toString()); - break; - default: - throw new UnsupportedOperationException("visitConstant not implemented for constqnt type " + e.getType()); - } - } - } - expressionPost(e); - } - - public void visitArg(Arg e) { - implode(e.getAnnotations(), "\n"); - if (e.getValueType() != null) { - if (e.getName() != null) { - variableDeclarationToString(e.getValueType(), e.getName(), e.isVarArg()); - if (e.getDefaultValue() != null) - append(" = ").append(e.getDefaultValue()); - } else - append(e.getValueType()).append(e.isVarArg() ? "..." : null); - } else - append("..."); - } - - public void visitEnum(Enum e) { - modifiersStringPrefix(e); - append("enum ", e.getTag()); - if (e.getTag() != null) - append(" "); - if (!e.getInterfaces().isEmpty()) - append("implements ").implode(e.getInterfaces(), ", ").append(" "); - - append("{\n"); - indent(); - List items = e.getItems(); - for (int i = 0, len = items.size(); i < len; i++) { - EnumItem item = items.get(i); - append(indent, item, i < len - 1 ? "," : (e.getBody() == null ? "" : ";"), "\n"); - } - if (e.getBody() != null) { - append(indent); - implode(e.getBody().getDeclarations(), "\n" + indent); - append("\n"); - } - deindent(); - append(indent, "}"); - } - - public void visitFunction(Function e) { - TypeRef valueType = e.getValueType(); - Identifier name = e.getName(); - List modifiers = e.getModifiers(); - - if (e.getType() == null) { - append(""); - return; - } - - formatComments(e, false, true, true); - if (!e.getAnnotations().isEmpty()) - implode(e.getAnnotations(), "\n" + indent).append("\n", indent); - - switch (e.getType()) { - case StaticInit: - implode(modifiers, " "); - space(!modifiers.isEmpty()); - append(e.getBody() == null ? ";" : e.getBody()); - break; - case CFunction: - case CppMethod: - case JavaMethod: - if (name != null && name.equals("operator") && e.getType() == Function.Type.CppMethod) { - append(name); - space(); - implode(modifiers, " "); - space(!modifiers.isEmpty()); - append(valueType); - } else { - implode(modifiers, " "); - space(!modifiers.isEmpty()); - append(valueType); - space(valueType != null); - append(name); - } - append("(").implode(e.getArgs(), ", ").append(")"); - - switch (e.getType()) { - case JavaMethod: - if (!e.getThrown().isEmpty()) - append(" throws ").implode(e.getThrown(), ", "); - break; - default: - if (e.getThrows()) { - append(" throw("); - implode(e.getThrown(), ", "); - append(")"); - } - } - - if (!e.getInitializers().isEmpty()) - append(" : ").implode(e.getInitializers(), ", "); - - if (e.getBody() == null) - append(";"); - else - append(" ", e.getBody()); - break; - case ObjCMethod: - append(modifiers.contains(ModifierType.Static) ? "+" : "-"); - space(); - if (valueType != null) - append("(", valueType, ")"); - append(name); - boolean firstArg = true; - for (Arg arg : e.getArgs()) { - if (arg.isVarArg()) { - if (!firstArg) - append(", "); - append("..."); - } else { - if (!firstArg) - append(' ', arg.getSelector()); - - append(":(", arg.createMutatedType(), ')', arg.getName()); - } - firstArg = false; - } - append(";"); - break; - default: - throw new RuntimeException(e.getType().toString()); - } - - if (e.getAsmName() != null) - append("__asm(\"", e.getAsmName(), "\") "); - - if (e.getCommentAfter() != null) - append(" ", e.getCommentAfter()); - - - } - - public void visitFunctionPointerDeclaration(FunctionPointerDeclaration e) { - modifiersStringPrefix(e); - append(e.getValueType()); - if (e.getDefaultValue() != null) - append(" = ", e.getDefaultValue()); - append(";"); - } - - public void visitStruct(Struct e) { - - formatComments(e, false, true, true); - if (!e.getAnnotations().isEmpty()) - implode(e.getAnnotations(), "\n" + indent).append("\n", indent); - - if (e.getType() != null) - switch (e.getType()) { - case CPPClass: - modifiersStringPrefix(e); - append("class ", e.getTag()); - if (!e.getParents().isEmpty()) - append(" : ").implode(e.getParents(), ", "); - break; - case CUnion: - modifiersStringPrefix(e); - append("union ", e.getTag() == null ? null : " ", e.getTag()); - break; - case JavaClass: - case JavaInterface: - modifiersStringPrefix(e); - append(e.getType() == Struct.Type.JavaClass ? "class " : "interface ", e.getTag()); - if (!e.getParents().isEmpty()) - append(" extends ").implode(e.getParents(), ", "); - if (!e.getProtocols().isEmpty()) - append(" implements ").implode(e.getProtocols(), ", "); - - break; - case ObjCClass: - modifiersStringPrefix(e); - append(e.isForwardDeclaration() ? "@class " : "@interface ", e.getTag()); - if (e.getCategoryName() != null) - append(" (", e.getCategoryName(), ")"); - break; - case ObjCProtocol: - modifiersStringPrefix(e); - append("@protocol ", e.getTag()); - break; - case CStruct: - default: - append("struct "); - modifiersStringPrefix(e); - append(e.getTag()); - if (!e.getParents().isEmpty()) - append(" : ").implode(e.getParents(), ", "); - break; - } - - if (!e.isForwardDeclaration()) { - space(e.getTag() != null).append("{\n"); - indent(); - append(indent); - implode(e.getDeclarations(), "\n" + indent); - deindent(); - append("\n", indent, "}"); - } - } - - public void visitTypeDef(TypeDef e) { - formatComments(e, false, true, true); - modifiersStringPrefix(e); - append("typedef "); - valueTypeAndStorageSuffix(e); - append(";"); - if (e.getCommentAfter() != null) - append(" ", e.getCommentAfter().trim()); - - } - - public void visitSimpleTypeRef(SimpleTypeRef e) { - formatComments(e, true, false, false).modifiersStringPrefix(e).append(e.getName()); - } - - public void visitFunctionSignature(FunctionSignature e) { - if (e.getFunction() == null) - return; - - assert e.getFunction().getBody() == null; - modifiersStringPrefix(e); - append(e.getFunction().getValueType()).space(e.getFunction().getValueType() != null); - append("("); - modifiersStringPrefix(e.getFunction()); - switch (e.getType()) { - case CFunction: - append("*"); - break; - case ObjCBlock: - append("^"); - break; - } - append(e.getFunction().getName()); - append(")("); - implode(e.getFunction().getArgs(), ", "); - append(")"); - append(e.getModifiers().isEmpty() ? "" : " "); - implode(e.getModifiers(), " "); - } - - public void visitPrimitive(Primitive e) { - modifiersStringPrefix(e, e.getName() != null); - append(e.getName()); - } - - public void visitPointer(Pointer e) { - modifiersStringPrefix(e); - append(e.getTarget()); - append(e.getPointerStyle()); - } - - public void visitArray(ArrayRef e) { - modifiersStringPrefix(e); - append(e.getTarget()); - bracketsToString(e); - } - - public void visitSourceFile(SourceFile e) { - implode(e.getDeclarations(), "\n" + indent); - } - - - - public void visitEnumItem(EnumItem e) { - formatComments(e, false, true, true); - append(e.getName()); - if (!e.getArguments().isEmpty()) { - if (e.getType() == Type.C) - append(" = ", e.getArguments().get(0)); - else { - append("("); - implode(e.getArguments(), ", "); - append(")"); - } - } - if (e.getBody() != null) { - append(" {\n\t", indent); - indent(); - implode(e.getBody().getDeclarations(), "\n" + indent); - deindent(); - append("\n", indent, "}"); - } - space(e.getCommentAfter() != null).append(e.getCommentAfter()); - } - - public void visitUnaryOp(UnaryOp e) { - expressionPre(e); - append(UnaryOp.unOpsRev.get(e.getOperator())).append(e.getOperand()); - expressionPost(e); - } - - public void visitVariableRef(VariableRef e) { - expressionPre(e); - append(e.getName()); - expressionPost(e); - } - - public void visitBinaryOp(BinaryOp e) { - expressionPre(e); - append(e.getFirstOperand()).space().append(BinaryOp.binOpsRev.get(e.getOperator())).space().append(e.getSecondOperand()); - expressionPost(e); - } - - protected Printer targetPrefix(MemberRef e) { - if (e.getTarget() == null || e.getMemberRefStyle() == null) - return this; - - String sep; - switch (e.getMemberRefStyle()) { - case Arrow: - sep = "->"; - break; - case Dot: - sep = "."; - break; - case Colons: - sep = "::"; - break; - default: - assert false; - sep = null; - } - if (sep != null) { - append(e.getTarget()); - append(sep); - } - return this; - } - public void visitFunctionCall(FunctionCall e) { - expressionPre(e); - if (e.getMemberRefStyle() == MemberRefStyle.SquareBrackets) { - /// Objective-C method call - append('['); - append(e.getTarget()); - if (e.getFunction() != null) { - append(' '); - append(e.getFunction()); - } - List> args = e.getArguments(); - for (int i = 0, len = args.size(); i < len; i++) { - Pair arg = args.get(i); - if (i > 0) { - append(' '); - append(arg.getFirst()); - } - append(':'); - append(arg.getSecond()); - } - append(']'); - } else { - targetPrefix(e); - if (e.getFunction() != null) - append(e.getFunction()); - append("("); - implode(ListenableCollections.adapt(e.getArguments(), new Adapter, Expression>() { - - public Expression adapt(Pair value) { - return value.getValue(); - } - - }), ", "); - append(")"); - } - expressionPost(e); - } - - public void visitCast(Cast e) { - expressionPre(e); - append("(").append(e.getType()).append(")").append(e.getTarget()); - expressionPost(e); - } - - public void visitDeclarator(Declarator e) { - if (e.isParenthesized()) - append('('); - - implode(e.getModifiers(), " ").space(!e.getModifiers().isEmpty()); - - if (e instanceof DirectDeclarator) - append(((DirectDeclarator)e).getName()); - else if (e instanceof PointerDeclarator) { - PointerDeclarator d = (PointerDeclarator)e; - append(d.getPointerStyle(), d.getTarget()); - } else if (e instanceof FunctionDeclarator) { - FunctionDeclarator d = (FunctionDeclarator)e; - append(d.getTarget(), '(').implode(d.getArgs(), ", ").append(")"); - } else if (e instanceof ArrayDeclarator) { - ArrayDeclarator d = (ArrayDeclarator)e; - append(d.getTarget(), '[').implode(d.getDimensions(), "][").append("]"); - } - - if (e.isParenthesized()) - append(')'); - if (e.getBits() >= 0) - append(":", e.getBits()); - if (e.getDefaultValue() != null) - append(" = ", e.getDefaultValue()); - } - - public void visitVariablesDeclaration(VariablesDeclaration e) { - formatComments(e, false, true, true); - if (!e.getAnnotations().isEmpty()) - implode(e.getAnnotations(), "\n" + indent).append("\n", indent); - - modifiersStringPrefix(e); - valueTypeAndStorageSuffix(e); - if (!(e.getParentElement() instanceof Catch)) - append(";"); - - if (e.getCommentAfter() != null) - space().append(e.getCommentAfter()); - } - - public void visitTaggedTypeRefDeclaration(TaggedTypeRefDeclaration e) { - if (e.getTaggedTypeRef() == null) - return; - - TaggedTypeRef tr = e.getTaggedTypeRef(); - formatComments(e, false, true, true); - formatComments(tr, false, true, true); - //append(tr, tr.isForwardDeclaration() ? ";" : null, e.getCommentAfter()); - append(tr, ";", e.getCommentAfter()); - } - - public void visitTaggedTypeRef(TaggedTypeRef e) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void visitEmptyArraySize(EmptyArraySize e) { - expressionPre(e); - expressionPost(e); - } - - public void visitDefine(Define e) { - append(indent, "#define ", e.getName()); - space(e.getValue() != null).append(e.getValue()); - } - - public void visitTypeRefExpression(TypeRefExpression e) { - expressionPre(e); - append(e.getType()); - expressionPost(e); - } - - public void visitNew(New e) { - expressionPre(e); - append("new ").append(e.getType()); - if (e.getConstruction() == null) - append("()"); - else - append(e.getConstruction()); - expressionPost(e); - } - - public void visitAnnotation(Annotation e) { - append("@", e.getAnnotationClass()); - if (e.getArgument() != null) - append(e.getArgument()); - else if (!e.getArguments().isEmpty()) - append("(").implode(e.getArguments(), ", ").append(")"); - space(); - } - - public void visitEmptyDeclaration(EmptyDeclaration e) { - formatComments(e, true, true, false); - } - - public void visitNewArray(NewArray e) { - expressionPre(e); - boolean noDims = e.getDimensions().isEmpty(); - boolean noVals = e.getInitialValues().isEmpty(); - append("new ").append(e.getType()).append("["); - if (noDims && noVals) - append("0"); - else - implode(e.getDimensions(), "]["); - append("]"); - if (noDims && !noVals) - append("{").implode(e.getInitialValues(), ", ").append("}"); - expressionPost(e); - } - - public void visitPointerDeclarator(PointerDeclarator e) { - visitDeclarator(e); - } - - public void visitArrayDeclarator(ArrayDeclarator e) { - visitDeclarator(e); - } - - public void visitDirectDeclarator(DirectDeclarator e) { - visitDeclarator(e); - } - - public void visitFunctionDeclarator(FunctionDeclarator e) { - visitDeclarator(e); - } - - public void visitModifiableElement(ModifiableElement e) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void visitBlock(Block e) { - append("{"); - if (!e.getStatements().isEmpty()) { - if (e.isCompact()) { - append(' '); - implode(e.getStatements(), ", "); - append(' '); - } else { - indent(); - append("\n", indent); - implode(e.getStatements(), "\n" + indent); - deindent(); - append("\n", indent); - } - } - append('}'); - } - - public void visitExpressionStatement(ExpressionStatement e) { - append(e.getExpression(), ";"); - } - - public void visitIf(If e) { - append("if (", e.getCondition(), ") "); - if (e.getThenBranch() == null) - append(""); - else { - if (e.getThenBranch() instanceof Block) { - append(e.getThenBranch()); - if (e.getElseBranch() != null) - append(" "); - } else { - indent(); - append("\n", indent, e.getThenBranch()); - deindent(); - if (e.getElseBranch() != null) - append("\n", indent); - } - } - - if (e.getElseBranch() != null) { - append("else "); - if (e.getElseBranch() instanceof Block) { - append(e.getElseBranch()); - } else { - indent(); - append("\n", indent, e.getElseBranch()); - deindent(); - } - } - } - - public void visitNullExpression(NullExpression e) { - expressionPre(e); - append("null"); - expressionPost(e); - } - - public void visitReturn(Return e) { - append("return ", e.getValue(), ";"); - } - - public void visitExternDeclarations(ExternDeclarations e) { - append("extern \"", e.getLanguage(), "\" {\n"); - indent(); - implode(e.getDeclarations(), "\n" + indent); - deindent(); - append("\n", indent, "}"); - } - - public void visitOpaqueExpression(OpaqueExpression e) { - expressionPre(e); - append(e.getOpaqueString()); - expressionPost(e); - } - - public void visitArrayAccess(ArrayAccess e) { - expressionPre(e); - append(e.getTarget()); - append("["); - append(e.getIndex()); - append("]"); - expressionPost(e); - } - - public void visitMemberRef(MemberRef e) { - expressionPre(e); - targetPrefix(e); - append(e.getName()); - expressionPost(e); - } - - public void visitAssignmentOp(AssignmentOp e) { - expressionPre(e); - append(e.getTarget()).space().append(AssignmentOp.assignOpsRev.get(e.getOperator())).space().append(e.getValue()); - expressionPost(e); - } - - public void visitConditionalExpression(ConditionalExpression e) { - expressionPre(e); - append(e.getTest()).append(" ? ").append(e.getThenValue()).append(" : ").append(e.getElseValue()); - expressionPost(e); - } - - public void visitExpressionSequence(ExpressionSequence e) { - expressionPre(e); - implode(e.getExpressions(), ", "); - expressionPost(e); - } - - public void visitExpressionsBlock(ExpressionsBlock e) { - expressionPre(e); - append("{ "); - implode(e.getExpressions(), ", "); - append(" }"); - expressionPost(e); - } - - public void visitSimpleIdentifier(SimpleIdentifier e) { - append(e.getName()); - - if (!e.getTemplateArguments().isEmpty()) { - append("<"); - implode(e.getTemplateArguments(), ", "); - append(" >"); - } - } - - public void visitQualifiedIdentifier(QualifiedIdentifier e) { - implode(e.getIdentifiers(), String.valueOf(e.getSeparator())); - } - - /*public void visitDeclarationStatement(DeclarationStatement e) { - append(e.getDeclaration()); - }*/ - - public void visitThrow(Throw e) { - append("throw ", e.getExpression(), ";"); - } - - public void visitProperty(Property e) { - append("@property"); - if (!e.getModifiers().isEmpty()) - append("(").implode(e.getModifiers(), " ").append(")"); - append(" ", e.getDeclaration()); - } - - public void visitFriendDeclaration(FriendDeclaration e) { - append("friend ", e.getFriend()); - } - - public void visitTry(Try e) { - append("try {\n"); - indent(); - append(indent, e.getTryStatement()); - deindent(); - append("\n", indent, "}"); - implode(e.getCatches(), " "); - if (e.getFinallyStatement() != null) { - append(" finally {\n"); - indent(); - append(indent); - append(e.getFinallyStatement()); - deindent(); - append("\n", indent, "}"); - } - } - - public void visitCatch(Catch e) { - append("catch (", e.getDeclaration(), ") {\n\t", indent); - if (e.getBody() != null) { - //indent(); - append(e.getBody()); - //deindent(); - } - append("\n", indent, "}"); - } - - protected Printer space() { - return space(true); - } - protected Printer space(boolean doIt) { - if (doIt) - append(" "); - return this; - } - public Printer append(Object... os) { - for (Object e : os) { - if (e instanceof Element) { - Element ee = (Element)e; - ee.accept(this); - ee.setElementLine(currentLine); - } - else if (e != null) { - String s = String.valueOf(e); - out.append(s); - int i = -1; - while ((i = s.indexOf("\n", i + 1)) >= 0) - currentLine++; - } - } - return this; - } - - protected final Printer implode(Iterable elements, Object separator) { - if (elements != null) { - String sepStr = separator.toString(); - boolean first = true; - for (Object s : elements) { - if (s == null) - continue; - - if (first) - first = false; - else - append(sepStr); - - append(s); - } - } - return this; - } - - public static String formatComments(CharSequence indent, String commentBefore, String commentAfter, boolean mergeCommentsAfter, boolean allowLineComments, boolean skipLineAfter, String... otherComments) { - if (indent == null) - indent = ""; - List nakedComments = new ArrayList(); - List src = new ArrayList(); - if (commentBefore != null) - src.add(commentBefore); - if (mergeCommentsAfter && commentAfter != null) - src.add(commentAfter); - src.addAll(Arrays.asList(otherComments)); - - if (src.isEmpty()) - return null; - - for (String c : src) { - if (c == null) - continue; - - c = Element.cleanComment(c).trim(); - nakedComments.add(c); - } - - String uniqueLine = null; - if (nakedComments.size() == 1 && !nakedComments.get(0).contains("\n")) - uniqueLine = nakedComments.get(0); - - String suffix = skipLineAfter ? "\n" + indent : ""; - if (uniqueLine != null && allowLineComments) - return "/// " + uniqueLine.replace("\\u", "\\\\u") + suffix; - - - String content = beginEachCommentLineWithStar ? - " * " + StringUtils.implode(nakedComments, "\n").replaceAll("\n", "
      \n" + indent + " * ") + "\n" + indent : - "\t" + StringUtils.implode(nakedComments, "\n").replaceAll("\n", "
      " + LINE_SEPARATOR + indent + "\t"); - - return "/**" + LINE_SEPARATOR + indent + content.replace("\\u", "\\\\u") + " */" + suffix; - } - - public Printer formatComments(Element e, boolean mergeCommentsAfter, boolean allowLineComments, boolean skipLineAfter, String... otherComments) { - String cb = e.getCommentBefore(), ca = e.getCommentAfter(); - if (cb != null || ca != null || otherComments.length > 0) - append(formatComments(indent, cb, ca, mergeCommentsAfter, allowLineComments, skipLineAfter, otherComments)); - return this; - } - - protected Printer modifiersStringPrefix(ModifiableElement e) { - return modifiersStringPrefix(e, true); - } - protected Printer modifiersStringPrefix(ModifiableElement e, boolean addSpace) { - List modifiers = e.getModifiers(); - if (modifiers != null && !modifiers.isEmpty()) { - implode(modifiers, " "); - if (addSpace) - space(); - } - return this; - } - - protected void variableDeclarationToString(TypeRef e, String varName, boolean isVarArg) { - if (e instanceof FunctionSignature) { - FunctionSignature fs = (FunctionSignature)e; - if (!isVarArg && fs.getFunction() != null && fs.getFunction().getName() != null) { - append(indent); - return; - } - } else if (e instanceof ArrayRef) { - ArrayRef ar = (ArrayRef)e; - append(ar.getTarget(), isVarArg ? "... " : " ", varName); - bracketsToString(ar); - return; - } - append(e).append(isVarArg ? "... " : " ").append(varName); - } - - protected void bracketsToString(ArrayRef e) { - append("[").implode(e.getDimensions(), "][").append("]"); - } - - protected void valueTypeAndStorageSuffix(StoredDeclarations e) { - if (e.getValueType() instanceof FunctionSignature) { - FunctionSignature sig = (FunctionSignature) e.getValueType(); - if (sig.getFunction() != null) { - Identifier name = sig.getFunction().getName(); - if (name != null && e.declarators.size() == 1) { - String stoName = e.declarators.get(0).resolveName(); - if (name.equals(stoName) || stoName == null) { - append(sig); - return; - } - } - } - } - append(e.getValueType()).space(!e.getDeclarators().isEmpty()).implode(e.getDeclarators(), ", "); - } - - public static void printJava(Identifier packageName, Identifier className, Element rootElement, PrintWriter out) { - final Map> identifiersBySimpleName = new HashMap>(); - final String outputPackage = packageName.toString(); - final String outputClassPrefix = className + "."; - - rootElement.accept(new Scanner() { - - @SuppressWarnings("unchecked") - @Override - public void visitIdentifier(Identifier e) { - super.visitIdentifier(e); - - if (e.getParentElement() instanceof QualifiedIdentifier) - return; - - Element parent = e.getParentElement(); - if (!(parent instanceof TypeRef)) - return; - - e = e.clone(); - SimpleIdentifier si = e.resolveLastSimpleIdentifier(); - si.setTemplateArguments(Collections.EMPTY_LIST); - - String name = si.getName(); - Set ids = identifiersBySimpleName.get(name); - if (ids == null) - identifiersBySimpleName.put(name, ids = new HashSet()); - - ids.add(e); - } - }); - - final Map resolvedIds = new HashMap(); - final Set importedClassesStrings = new HashSet(50); - importedClassesStrings.add(className.toString()); - - String packagePrefix = packageName + "."; - - Set importStatements = new TreeSet(); - for (Map.Entry> kv : identifiersBySimpleName.entrySet()) { - if (kv.getValue().size() == 1) { - Identifier id = kv.getValue().iterator().next(); - String ids = id.toString(); - if (ids.indexOf(".") < 0) - continue; - - SimpleIdentifier si = id.resolveLastSimpleIdentifier(); - String name = si.getName(); - resolvedIds.put(id, name); - Identifier pack = id.resolveAllButLastIdentifier(); - if (pack == null) - continue; - - String ps = pack.toString(); - importedClassesStrings.add(ids); - - if (ps.equals("java.lang") || ps.equals(outputPackage) || ids.startsWith(outputClassPrefix)) - continue; - - importStatements.add("import " + ids + ";"); - } - } - - for (String imp : importStatements) - out.println(imp); - - out.println(new Printer() { - - @SuppressWarnings("unchecked") - @Override - public void visitQualifiedIdentifier(QualifiedIdentifier e) { - - if (e.getParentElement() instanceof TypeRef) { - QualifiedIdentifier c = e.clone(); - SimpleIdentifier si = c.resolveLastSimpleIdentifier(); - - List targs = new ArrayList(si.getTemplateArguments()); - si.setTemplateArguments(Collections.EMPTY_LIST); - - List sis = new ArrayList(c.resolveSimpleIdentifiers()); - //for (String importedClassStr : importedClassesStrings) { - Printer pt = new Printer(); - for (int i = 0, n = sis.size(); i < n; i++) { - if (i != 0) - pt.append("."); - pt.append(sis.get(i)); - - String str = pt.toString(); - if (importedClassesStrings.contains(str)) { - for (int j = i; j-- != 0;) - sis.remove(j); - - c.setIdentifiers(sis); - c.resolveLastSimpleIdentifier().setTemplateArguments(targs);//clones(e.resolveLastSimpleIdentifier().getTemplateArguments())); - append(c); - return; - } - } - //} - } - - super.visitQualifiedIdentifier(e); - } - - }.append(rootElement)); - } - - public void visitTemplate(Template template) { - append("template <").implode(template.getArgs(), ", ").append(" >\n"); - append(indent, template.getDeclaration()); - } - - @Override - public void visitWhile(While whileStat) { - append("while (").append(whileStat.getCondition()).append("{\n"); - indent(); - append(whileStat.getBody()); - deindent(); - append("\n", indent, "}"); - } - - - - @Override - public void visitDoWhile(DoWhile doWhileStat) { - append("do {\n"); - indent(); - append(doWhileStat.getBody()); - deindent(); - append("\n", indent, "} while (").append(doWhileStat.getCondition()).append(");"); - } - - - @Override - public void visitNamespace(Namespace ns) { - append("namespace ").append(ns.getName()).append(" {\n"); - indent(); - implode(ns.getDeclarations(), "\n" + indent); - deindent(); - append("\n", indent, "}"); - } - - @Override - public void visitDeclarations(Declarations decls) { - implode(decls.getDeclarations(), "\n" + indent); - } - - @Override - public void visitFor(For aFor) { - append("for (").implode(aFor.getInitStatements(), ", ").append(";").append(aFor.getCondition()).append(";").implode(aFor.getPostStatements(), ", ").append(") {\n"); - indent(); - append(aFor.getBody()); - deindent(); - append("\n", indent, "}"); - } - - public void visitPrecisionTypeRef(PrecisionTypeRef tr) { - append(tr.getTarget()); - append("(", tr.getPrecision(), ")"); - } - - public void visitDelete(Delete d) { - append("delete"); - if (d.isArray()) - append("[]"); - - append(" "); - append(d.getValue()); - append(";"); - } - - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Property.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Property.java deleted file mode 100644 index 8401e2d30..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Property.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -public class Property extends Declaration { - Declaration declaration; - public Property() {} - public Property(Declaration declaration) { - setDeclaration(declaration); - } - @Override - public void accept(Visitor visitor) { - visitor.visitProperty(this); - } - - public void setDeclaration(Declaration declaration) { - this.declaration = changeValue(this, this.declaration, declaration); - } - public Declaration getDeclaration() { - return declaration; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getDeclaration()) { - setDeclaration((Declaration)by); - return true; - } - return super.replaceChild(child, by); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Scanner.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Scanner.java deleted file mode 100644 index f12f19e79..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Scanner.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Statement.Catch; -import com.ochafik.lang.jnaerator.parser.Statement.Delete; -import com.ochafik.lang.jnaerator.parser.Statement.Try; -import com.ochafik.lang.jnaerator.parser.Statement.While; -import com.ochafik.lang.jnaerator.parser.TypeRef.PrecisionTypeRef; -import java.util.ArrayList; -import java.util.Collection; - -import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.FunctionDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.TargettedDeclarator; -import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; -import com.ochafik.lang.jnaerator.parser.Expression.ArrayAccess; -import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; -import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.Cast; -import com.ochafik.lang.jnaerator.parser.Expression.ConditionalExpression; -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionSequence; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionsBlock; -import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; -import com.ochafik.lang.jnaerator.parser.Expression.New; -import com.ochafik.lang.jnaerator.parser.Expression.NewArray; -import com.ochafik.lang.jnaerator.parser.Expression.NullExpression; -import com.ochafik.lang.jnaerator.parser.Expression.OpaqueExpression; -import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; -import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -//import com.ochafik.lang.jnaerator.parser.Statement.DeclarationStatement; -import com.ochafik.lang.jnaerator.parser.Statement.DoWhile; -import com.ochafik.lang.jnaerator.parser.Statement.ExpressionStatement; -import com.ochafik.lang.jnaerator.parser.Statement.If; -import com.ochafik.lang.jnaerator.parser.Statement.For; -import com.ochafik.lang.jnaerator.parser.Statement.Return; -import com.ochafik.lang.jnaerator.parser.Statement.Throw; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; -import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TargettedTypeRef; -import com.ochafik.util.listenable.Pair; -import java.util.List; - -public class Scanner implements Visitor { - - public void visitArg(Arg arg) { - visitDeclaration(arg); - - visit(arg.getDefaultValue()); - - visit(arg.getDeclarator()); - } - - public void visitConstant(Constant constant) { - visitExpression(constant); - } - - protected void visitExpression(Expression expression) { - visitElement(expression); - } - - public void visitEnum(Enum enum1) { - visitTaggedTypeRef(enum1); - visit(enum1.getItems()); - visit(enum1.getInterfaces()); - visit(enum1.getBody()); - } - - public void visitFunction(Function function) { - visitDeclaration(function); - visit(function.getArgs()); - visit(function.getThrown()); - visit(function.getInitializers()); - - visit(function.getBody()); - visit(function.getName()); - } - - public void visitFunctionPointerDeclaration(FunctionPointerDeclaration f) { - visitDeclaration(f); - visit(f.getDefaultValue()); - } - - protected void visitDeclaration(Declaration d) { - visitStatement(d); - - visit(d.getValueType()); - } - - protected void visitElement(Element d) { - - } - - public void visitStruct(Struct struct) { - if (struct.getType() != null) { - switch (struct.getType()) { - case CPPClass: - visitCPPClass(struct); - break; - case CStruct: - visitCStruct(struct); - break; - case ObjCClass: - visitObjCClass(struct); - break; - case ObjCProtocol: - visitObjCProtocol(struct); - break; - case JavaClass: - visitJavaClass(struct); - break; - case JavaInterface: - visitJavaInterface(struct); - break; - default: - doVisitStruct(struct); - } - } else { - doVisitStruct(struct); - } - - } - - public void visitJavaClass(Struct struct) { - doVisitStruct(struct); - } - - public void visitJavaInterface(Struct struct) { - doVisitStruct(struct); - } - - protected void visitStoredDeclarations(StoredDeclarations d) { - visitDeclaration(d); - visit(d.getDeclarators()); - } - - protected void visitCPPClass(Struct struct) { - doVisitStruct(struct); - } - - protected void doVisitStruct(Struct struct) { - visitTaggedTypeRef(struct); - visit(struct.getDeclarations()); - visit(struct.getProtocols()); - visit(struct.getParents()); - } - - protected void visitCStruct(Struct struct) { - doVisitStruct(struct); - } - - protected void visitObjCClass(Struct struct) { - doVisitStruct(struct); - } - - protected void visitObjCProtocol(Struct struct) { - doVisitStruct(struct); - } - - public void visitTypeDef(TypeDef typeDef) { - visitStoredDeclarations(typeDef); - } - - public void visitArray(ArrayRef array) { - visitTargettedTypeRef(array); - visit(array.getDimensions()); - } - - protected void visitTypeRef(TypeRef typeRef) { - visitModifiableElement(typeRef); - visit(typeRef.getResolvedJavaIdentifier()); - } - - protected void visitTargettedTypeRef(TargettedTypeRef targettedTypeRef) { - visitTypeRef(targettedTypeRef); - visit(targettedTypeRef.getTarget()); - } - - public void visitFunctionSignature(FunctionSignature functionSignature) { - visitTypeRef(functionSignature); - if (functionSignature != null) - visit(functionSignature.getFunction()); - } - - public void visitPointer(Pointer pointer) { - visitTargettedTypeRef(pointer); - } - - public void visitPrimitive(Primitive primitive) { - visitSimpleTypeRef(primitive); - } - - public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { - visitTypeRef(simpleTypeRef); - - visit(simpleTypeRef.getName()); - } - - static Collection copy(Collection col) { - return new ArrayList(col); - } - public void visitSourceFile(SourceFile header) { - visitElement(header); - visit(header.getDeclarations()); - } - - public void visitEnumItem(EnumItem enumItem) { - visitElement(enumItem); - visit(enumItem.getArguments()); - visit(enumItem.getBody()); - } - - public void visitUnaryOp(UnaryOp unaryOp) { - visitExpression(unaryOp); - visit(unaryOp.getOperand()); - } - - public void visitVariableRef(VariableRef variableRef) { - visitExpression(variableRef); - visit(variableRef.getName()); - } - - public void visitBinaryOp(BinaryOp binaryOp) { - visitExpression(binaryOp); - visit(binaryOp.getFirstOperand()); - visit(binaryOp.getSecondOperand()); - } - - public void visitFunctionCall(FunctionCall functionCall) { - visitMemberRef(functionCall); - visit(functionCall.getTarget()); - visit(functionCall.getFunction()); - - for (Pair x : copy(functionCall.getArguments())) - if (x != null) - visit(x.getSecond()); - } - - public void visitMemberRef(MemberRef memberRef) { - visitExpression(memberRef); - - visit(memberRef.getTarget()); - visit(memberRef.getName()); - - } - - public void visitCast(Cast cast) { - visitExpression(cast); - visit(cast.getType()); - visit(cast.getTarget()); - } - - public void visitDeclarator(Declarator declarator) { - visitModifiableElement(declarator); - - visit(declarator.getDefaultValue()); - } - - public void visitVariablesDeclaration(VariablesDeclaration v) { - visitDeclaration(v); - visit(v.getDeclarators()); - } - - public void visitTaggedTypeRefDeclaration(TaggedTypeRefDeclaration taggedTypeRefDeclaration) { - visitDeclaration(taggedTypeRefDeclaration); - visit(taggedTypeRefDeclaration.getTaggedTypeRef()); - } - - public void visitEmptyArraySize(EmptyArraySize emptyArraySize) { - visitExpression(emptyArraySize); - } - - public void visitDefine(Define define) { - visitDeclaration(define); - visit(define.getValue()); - } - - public void visitTypeRefExpression(TypeRefExpression typeRefExpression) { - visitExpression(typeRefExpression); - visit(typeRefExpression.getType()); - } - - public void visitNew(New new1) { - visitExpression(new1); - visit(new1.getType()); - - visit(new1.getConstruction()); - } - - public void visitAnnotation(Annotation annotation) { - visitElement(annotation); - visit(annotation.getAnnotationClass()); - visit(annotation.getArguments()); - } - - public void visitEmptyDeclaration(EmptyDeclaration emptyDeclaration) { - visitDeclaration(emptyDeclaration); - } - - public void visitNewArray(NewArray newArray) { - visitExpression(newArray); - visit(newArray.getType()); - visit(newArray.getDimensions()); - visit(newArray.getInitialValues()); - } - - public void visitArrayDeclarator(ArrayDeclarator arrayDeclarator) { - visitTargettedDeclarator(arrayDeclarator); - visit(arrayDeclarator.getDimensions()); - } - - public void visitDirectDeclarator(DirectDeclarator directDeclarator) { - visitDeclarator(directDeclarator); - } - - public void visitFunctionDeclarator(FunctionDeclarator functionDeclarator) { - visitTargettedDeclarator(functionDeclarator); - visit(functionDeclarator.getArgs()); - } - - public void visitPointerDeclarator(PointerDeclarator pointerDeclarator) { - visitTargettedDeclarator(pointerDeclarator); - } - - private void visitTargettedDeclarator(TargettedDeclarator targettedDeclarator) { - visitDeclarator(targettedDeclarator); - visit(targettedDeclarator.getTarget()); - } - - public void visitModifiableElement(ModifiableElement modifiableElement) { - visitElement(modifiableElement); - visit(modifiableElement.getAnnotations()); - } - - public void visitTaggedTypeRef(TaggedTypeRef taggedTypeRef) { - visitTypeRef(taggedTypeRef); - visit(taggedTypeRef.getTag()); - visit(taggedTypeRef.getOriginalTag()); - - } - - public void visitBlock(Block block) { - visitStatement(block); - visit(block.getStatements()); - } - - public void visitExpressionStatement(ExpressionStatement expressionStatement) { - visitStatement(expressionStatement); - visit(expressionStatement.getExpression()); - } - - public void visitStatement(Statement statement) { - visitModifiableElement(statement); - //visitElement(statement); - } - - public void visitIf(If if1) { - visitControlStructure(if1); - visit(if1.getCondition()); - visit(if1.getThenBranch()); - visit(if1.getElseBranch()); - } - - public void visitNullExpression(NullExpression nullExpression) { - visitExpression(nullExpression); - } - - public void visitReturn(Return return1) { - visitSingleValueStatement(return1); - } - - public void visitOpaqueExpression(OpaqueExpression opaqueExpression) { - visitExpression(opaqueExpression); - } - - public void visitArrayAccess(ArrayAccess arrayAccess) { - visitExpression(arrayAccess); - visit(arrayAccess.getTarget()); - visit(arrayAccess.getIndex()); - } - - public void visitAssignmentOp(AssignmentOp assignment) { - visitExpression(assignment); - visit(assignment.getTarget()); - - visit(assignment.getValue()); - } - - - public void visitConditionalExpression( - ConditionalExpression conditionalExpression) { - visitExpression(conditionalExpression); - visit(conditionalExpression.getTest()); - visit(conditionalExpression.getThenValue()); - visit(conditionalExpression.getElseValue()); - - } - - - public void visitExpressionSequence(ExpressionSequence expressionSequence) { - visitExpression(expressionSequence); - visit(expressionSequence.getExpressions()); - } - - public void visitExpressionsBlock(ExpressionsBlock expressionSequence) { - visitExpression(expressionSequence); - visit(expressionSequence.getExpressions()); - } - - - public void visitSimpleIdentifier(SimpleIdentifier simpleIdentifier) { - visitIdentifier(simpleIdentifier); - visit(simpleIdentifier.getTemplateArguments()); - } - - public void visitIdentifier(Identifier identifier) { - visitElement(identifier); - } - - public void visitQualifiedIdentifier(QualifiedIdentifier qualifiedIdentifier) { - visitIdentifier(qualifiedIdentifier); - visit(qualifiedIdentifier.getIdentifiers()); - } - - /*public void visitDeclarationStatement( - DeclarationStatement declarationStatement) { - visitStatement(declarationStatement); - visit(declarationStatement.getDeclaration()); - }*/ - - protected Scanner visit(Element e) { - if (e != null) { - try { - e.accept(this); - } catch (StackOverflowError err) { - throw new RuntimeException("Overflow while visiting :\n" + e, err); - } - } - return this; - } - protected Scanner visit(List list) { - if (list != null) - for (Element e : copy(list)) - if (e != null) - e.accept(this); - return this; - } - - public void visitThrow(Throw t) { - visitStatement(t); - visit(t.getExpression()); - } - - public void visitProperty(Property property) { - visitDeclaration(property); - visit(property.getDeclaration()); - } - - public void visitFriendDeclaration(FriendDeclaration friendDeclaration) { - visitDeclaration(friendDeclaration); - visit(friendDeclaration.getFriend()); - } - - public void visitControlStructure(Statement tr) { - visitStatement(tr); - } - - public void visitTry(Try tr) { - visitControlStructure(tr); - visit(tr.getTryStatement()); - visit(tr.getFinallyStatement()); - visit(tr.getCatches()); - } - public void visitFor(For aFor) { - visitControlStructure(aFor); - visit(aFor.getInitStatements()); - visit(aFor.getCondition()); - visit(aFor.getPostStatements()); - visit(aFor.getBody()); - } - public void visitCatch(Catch ca) { - visitControlStructure(ca); - visit(ca.getDeclaration()); - visit(ca.getBody()); - } - - public void visitTemplate(Template template) { - visitDeclaration(template); - visit(template.getArgs()); - visit(template.getDeclaration()); - } - - @Override - public void visitWhile(While whileStat) { - visitControlStructure(whileStat); - visit(whileStat.getCondition()); - visit(whileStat.getBody()); - } - - @Override - public void visitDoWhile(DoWhile doWhileStat) { - visitWhile(doWhileStat); - } - - public void visitDeclarations(Declarations declarations) { - visitDeclaration(declarations); - visit(declarations.getDeclarations()); - } - - - public void visitExternDeclarations(ExternDeclarations externDeclarations) { - visitDeclarations(externDeclarations); - } - - @Override - public void visitNamespace(Namespace ns) { - visit(ns.getName()); - visitDeclarations(ns); - } - - public void visitPrecisionTypeRef(PrecisionTypeRef tr) { - visitTargettedTypeRef(tr); - visit(tr.getPrecision()); - } - - public void visitDelete(Delete aThis) { - visitSingleValueStatement(aThis); - } - - private void visitSingleValueStatement(Statement.SingleValueStatement s) { - visitStatement(s); - visit(s.getValue()); - } - - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SemiUnmodifiableList.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SemiUnmodifiableList.java deleted file mode 100644 index f19259055..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SemiUnmodifiableList.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -public class SemiUnmodifiableList implements List { - List list; - List getList() { - return list; - } - public SemiUnmodifiableList(List list) { - this.list = list; - } - public boolean add(T o) { - throw new UnsupportedOperationException(); - } - public void add(int index, T element) { - throw new UnsupportedOperationException(); - } - public boolean addAll(Collection c) { - throw new UnsupportedOperationException(); - } - public boolean addAll(int index, Collection c) { - throw new UnsupportedOperationException(); - } - public void clear() { - throw new UnsupportedOperationException(); - } - public boolean contains(Object o) { - return list.contains(o); - } - public boolean containsAll(Collection c) { - return list.containsAll(c); - } - public T get(int index) { - return list.get(index); - } - public int indexOf(Object o) { - return list.indexOf(o); - } - public boolean isEmpty() { - return list.isEmpty(); - } - public Iterator iterator() { - return new Iterator() { - Iterator it = list.iterator(); - - public boolean hasNext() { - return it.hasNext(); - } - - public T next() { - return it.next(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - public int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } - public ListIterator listIterator() { - return listIterator(0); - } - public ListIterator listIterator(final int index) { - return new ListIterator() { - ListIterator it = list.listIterator(index); - - public boolean hasNext() { - return it.hasNext(); - } - - public T next() { - return it.next(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - public void add(T o) { - throw new UnsupportedOperationException(); - } - - public boolean hasPrevious() { - return it.hasPrevious(); - } - - public int nextIndex() { - return it.nextIndex(); - } - - public T previous() { - return it.previous(); - } - - public int previousIndex() { - return it.previousIndex(); - } - - public void set(T o) { - throw new UnsupportedOperationException(); - } - }; - } - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - public T remove(int index) { - throw new UnsupportedOperationException(); - } - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - public T set(int index, T element) { - throw new UnsupportedOperationException(); - } - public int size() { - return list.size(); - } - public List subList(int fromIndex, int toIndex) { - return new SemiUnmodifiableList(list.subList(fromIndex, toIndex)); - } - public Object[] toArray() { - return list.toArray(); - } - public U[] toArray(U[] a) { - return list.toArray(a); - } - @Override - public String toString() { - return list.toString(); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SourceFile.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SourceFile.java deleted file mode 100644 index 40bb1ae09..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/SourceFile.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class SourceFile extends Element implements DeclarationsHolder { - final List declarations = new ArrayList(); - //URL file; - String framework, library; -// String pathInFramework; - -// public URL getFile() { -// return file; -// } - - @Override - public SourceFile clone() { - return (SourceFile)super.clone(); - } - - @Override - public Element getNextChild(Element child) { - return getNextSibling(declarations, child); - } - - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(declarations, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - return replaceChild(declarations, Declaration.class, this, child, by); - } - /* - public void setFile(URL file) { - this.file = file; - if (framework == null) { - Matcher matcher = frameworkPathPattern.matcher(file.toString()); - if (matcher.find()) { - framework = matcher.group(1); - pathInFramework = matcher.group(2); - } - } - } - public String getPathInFramework() { - return pathInFramework; - }*/ - - @Override - public void setElementFile(String file) { - super.setElementFile(file); - framework = null; - } -// public void setFramework(String framework) { -// this.framework = framework; -// } -// - public List getDeclarations() { - return unmodifiableList(declarations); - } - public void setDeclarations(List declarations) { - changeValue(this, this.declarations, declarations); - } - public void addDeclaration(Declaration d) { - if (d == null) - return; - - declarations.add(d); - d.setParentElement(this); - } - public void addDeclarations(Collection ds) { - for (Declaration d : ds) - addDeclaration(d); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitSourceFile(this); - } - - public void setLibrary(String library) { - this.library = library; - } - - public String getLibrary() { - return library; - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Statement.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Statement.java deleted file mode 100644 index cafe88e55..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Statement.java +++ /dev/null @@ -1,556 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public abstract class Statement extends ModifiableElement { // HACK : statement is not modifiable ! it's just so that Declaration is a Statement and a ModifiableElement (damned single inheritance !) - @Override - public Statement clone() { - return (Statement)super.clone(); - } - public static class Throw extends Statement { - Expression expression; - public Expression getExpression() { - return expression; - } - public void setExpression(Expression expression) { - this.expression = changeValue(this, this.expression, expression); - } - public Throw() {} - public Throw(Expression expression) { - setExpression(expression); - } - @Override - public void accept(Visitor visitor) { - visitor.visitThrow(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getExpression()) { - setExpression((Expression)by); - return true; - } - return false; - } - - } - /* - public static class DeclarationStatement extends Statement { - Declaration declaration; - public void setDeclaration(Declaration declaration) { - this.declaration = changeValue(this, this.declaration, declaration); - } - public Declaration getDeclaration() { - return declaration; - } - public DeclarationStatement() {} - public DeclarationStatement(Declaration declaration) { - setDeclaration(declaration); - } - @Override - public void accept(Visitor visitor) { - visitor.visitDeclarationStatement(this); - } - @Override - public Element getNextChild(Element child) { - return null; - } - @Override - public Element getPreviousChild(Element child) { - return null; - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getDeclaration()) { - setDeclaration((Declaration)by); - return true; - } - return false; - } - }*/ - public static abstract class SingleValueStatement extends Statement { - Expression value; - - public SingleValueStatement() {} - public SingleValueStatement(Expression value) { - setValue(value); - } - - public void setValue(Expression value) { - this.value = changeValue(this, this.value, value); - } - public Expression getValue() { - return value; - } - - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - return null; - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - return null; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getValue()) { - setValue((Expression)by); - return true; - } - return false; - } - - } - public static class Return extends SingleValueStatement { - public Return() {} - public Return(Expression value) { - super(value); - } - @Override - public void accept(Visitor visitor) { - visitor.visitReturn(this); - } - } - public static class Delete extends SingleValueStatement { - boolean array; - public Delete() {} - public Delete(Expression value, boolean isArray) { - super(value); - setArray(isArray); - } - - public boolean isArray() { - return array; - } - - public void setArray(boolean isArray) { - this.array = isArray; - } - - @Override - public void accept(Visitor visitor) { - visitor.visitDelete(this); - } - } - public static class If extends Statement { - public If() {} - public If(Expression condition, Statement thenBranch, Statement elseBranch) { - setCondition(condition); - setThenBranch(thenBranch); - setElseBranch(elseBranch); - } - Expression condition; - Statement thenBranch, elseBranch; - - public void setElseBranch(Statement elseBranch) { - this.elseBranch = changeValue(this, this.elseBranch, elseBranch); - } - public void setCondition(Expression condition) { - this.condition = changeValue(this, this.condition, condition); - } - public void setThenBranch(Statement thenBranch) { - this.thenBranch = changeValue(this, this.thenBranch, thenBranch); - } - public Statement getElseBranch() { - return elseBranch; - } - public Statement getThenBranch() { - return thenBranch; - } - public Expression getCondition() { - return condition; - } - @Override - public void accept(Visitor visitor) { - visitor.visitIf(this); - } - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getCondition()) { - setCondition((Expression)by); - return true; - } - if (child == getThenBranch()) { - setThenBranch((Statement)by); - return true; - } - if (child == getElseBranch()) { - setElseBranch((Statement)by); - return true; - } - return false; - } - } - - public static class For extends Statement { - public For() {} - public For(List initStatements, Expression condition, List postStatements, Statement body) { - setInitStatements(initStatements); - setCondition(condition); - setPostStatements(postStatements); - setBody(body); - } - Expression condition; - Statement body; - final List initStatements = new ArrayList(), postStatements = new ArrayList(); - - public void setPostStatements(List postStatements) { - changeValue(this, this.postStatements, postStatements); - } - public List getPostStatements() { - return unmodifiableList(postStatements); - } - public void setInitStatements(List initStatements) { - changeValue(this, this.initStatements, initStatements); - } - public List getInitStatements() { - return unmodifiableList(initStatements); - } - - public void setCondition(Expression condition) { - this.condition = changeValue(this, this.condition, condition); - } - public void setBody(Statement body) { - this.body = changeValue(this, this.body, body); - } - public Statement getBody() { - return body; - } - public Expression getCondition() { - return condition; - } - @Override - public void accept(Visitor visitor) { - visitor.visitFor(this); - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - e = getNextSibling(initStatements, child); - if (e != null) - return e; - return getNextSibling(postStatements, child); - } - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - e = getPreviousSibling(initStatements, child); - if (e != null) - return e; - return getPreviousSibling(postStatements, child); - } - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getCondition()) { - setCondition((Expression)by); - return true; - } - if (child == getBody()) { - setBody((Statement)by); - return true; - } - return - replaceChild(initStatements, Statement.class, this, child, by) || - replaceChild(postStatements, Statement.class, this, child, by); - } - } - - public static class While extends Statement { - public While() {} - public While(Expression condition, Statement body) { - setCondition(condition); - setBody(body); - } - Expression condition; - Statement body; - - public void setCondition(Expression condition) { - this.condition = changeValue(this, this.condition, condition); - } - public void setBody(Statement body) { - this.body = changeValue(this, this.body, body); - } - public Statement getBody() { - return body; - } - public Expression getCondition() { - return condition; - } - @Override - public void accept(Visitor visitor) { - visitor.visitWhile(this); - } - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getCondition()) { - setCondition((Expression)by); - return true; - } - if (child == getBody()) { - setBody((Statement)by); - return true; - } - return false; - } - } - public static class DoWhile extends While { - public DoWhile() {} - public DoWhile(Expression condition, Statement body) { - super(condition, body); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitDoWhile(this); - } - } - public static class ExpressionStatement extends Statement { - - public ExpressionStatement() {} - public ExpressionStatement(Expression expression) { - setExpression(expression); - } - - Expression expression; - - public Expression getExpression() { - return expression; - } - public void setExpression(Expression expression) { - this.expression = changeValue(this, this.expression, expression); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitExpressionStatement(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (getExpression() == child) { - setExpression((Expression)by); - return true; - } - return false; - } - } - - public static class Block extends Statement { - final List statements = new ArrayList(); - @Override - public void accept(Visitor visitor) { - visitor.visitBlock(this); - } - - boolean compact; - - @Override - public Block clone() { - return (Block)super.clone(); - } - - public Block setCompact(boolean compact) { - this.compact = compact; - return this; - } - public boolean isCompact() { - return compact; - } - public Block() {} - public Block(Statement... statements) { - addStatements(statements); - } - public Block(List statements) { - setStatements(statements); - } - public void addStatement(Statement statement) { - if (statement != null) { - statement.setParentElement(this); - statements.add(statement); - } - } - public void setStatements(List statements) { - changeValue(this, this.statements, statements); - } - public void addStatements(Statement... statements) { - setStatements(Arrays.asList(statements)); - } - public List getStatements() { - return unmodifiableList(statements); - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - return getNextSibling(statements, child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - return getPreviousSibling(statements, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - return replaceChild(statements, Statement.class, this, child, by); - } - } - - public static class Catch extends Statement { - VariablesDeclaration declaration; - Statement body; - - public Catch() {} - public Catch(VariablesDeclaration declaration, Statement body) { - setDeclaration(declaration); - setBody(body); - } - - public VariablesDeclaration getDeclaration() { - return declaration; - } - - public void setDeclaration(VariablesDeclaration declaration) { - this.declaration = changeValue(this, this.declaration, declaration); - } - - public Statement getBody() { - return body; - } - - public void setBody(Statement body) { - this.body = changeValue(this, this.body, body); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getDeclaration()) { - setDeclaration((VariablesDeclaration)by); - return true; - } - if (child == getBody()) { - setBody((Statement)by); - return true; - } - return false; - } - - @Override - public void accept(Visitor visitor) { - visitor.visitCatch(this); - } - - - } - public static class Try extends Statement { - Statement tryStatement, finallyStatement; - final List catches = new ArrayList(); - - public Try() {} - public Try(Statement tryStatement, Statement finallyStatement, Catch... catches) { - setTryStatement(tryStatement); - setFinallyStatement(finallyStatement); - setCatches(Arrays.asList(catches)); - } - - public void setTryStatement(Statement tryStatement) { - this.tryStatement = changeValue(this, this.tryStatement, tryStatement); - } - - public Statement getTryStatement() { - return tryStatement; - } - - public void setFinallyStatement(Statement finallyStatement) { - this.finallyStatement = changeValue(this, this.finallyStatement, finallyStatement); - } - - public Statement getFinallyStatement() { - return finallyStatement; - } - - public List getCatches() { - return Collections.unmodifiableList(catches); - } - - public void setCatches(List catches) { - changeValue(this, this.catches, catches); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - if (child == getTryStatement()) { - setTryStatement((Statement)by); - return true; - } - if (child == getFinallyStatement()) { - setFinallyStatement((Statement)by); - return true; - } - return replaceChild(catches, Catch.class, this, child, by); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitTry(this); - } - - - - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/StoredDeclarations.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/StoredDeclarations.java deleted file mode 100644 index 8c423cb43..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/StoredDeclarations.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public abstract class StoredDeclarations extends Declaration { - final List declarators = new ArrayList(); - - public static class TypeDef extends StoredDeclarations { - - public TypeDef() {} - public TypeDef(TypeRef valueType, Declarator... declarators) { - this(valueType, Arrays.asList(declarators)); - } - public TypeDef(TypeRef valueType, List declarators) { - setValueType(valueType); - setDeclarators(declarators); - } - @Override - public void accept(Visitor visitor) { - visitor.visitTypeDef(this); - } - - } - /* - @Override - public String toString(CharSequence indent) { - return formatComments(indent, false, true, true) + - getModifiersStringPrefix() + getValueTypeAndStorageSuffix(indent) + ";" - + (commentAfter == null ? "" : " " + commentAfter.trim()) - ; - }*/ - - public List getDeclarators() { - return unmodifiableList(declarators); - } - - public void setDeclarators(List declarators) { - changeValue(this, this.declarators, declarators); - } - public void addDeclarators(List declarators) { - for (Declarator d : declarators) - addDeclarator(d); - } - - public void addDeclarator(Declarator declarator) { - if (declarator == null) - return; - declarators.add(declarator); - declarator.setParentElement(this); - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - return getNextSibling(declarators, child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - return getPreviousSibling(declarators, child); - } - - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - - return replaceChild(declarators, Declarator.class, this, child, by); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Struct.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Struct.java deleted file mode 100644 index 580f7a851..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Struct.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; - -public class Struct extends TypeRef.TaggedTypeRef implements DeclarationsHolder {//extends StoredDeclarations { - Type type; - MemberVisibility nextMemberVisibility = MemberVisibility.Public; - final List parents = new ArrayList(); - final List protocols = new ArrayList(); - String categoryName; - final List declarations = new ArrayList(); - - public enum MemberVisibility { - Public, Private, Protected - } - public enum Type { - CStruct, - CPPClass, - ObjCClass, - ObjCProtocol, - CUnion, - JavaClass, - JavaInterface; - - public boolean isObjC() { - return this == ObjCClass || this == ObjCProtocol; - } - public boolean isCpp() { - return this == CPPClass; - } - } - - @Override - public Struct addModifiers(Modifier... mds) { - return (Struct)super.addModifiers(mds); - } - - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - e = getNextSibling(protocols, child); - if (e != null) - return e; - return getNextSibling(declarations, child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - e = getPreviousSibling(protocols, child); - if (e != null) - return e; - return getPreviousSibling(declarations, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (super.replaceChild(child, by)) - return true; - - if (replaceChild(protocols, SimpleTypeRef.class, this, child, by)) - return true; - - if (replaceChild(parents, SimpleTypeRef.class, this, child, by)) - return true; - - return replaceChild(declarations, Declaration.class, this, child, by); - } - - - public static Struct forwardDecl(SimpleIdentifier name, Type type) { - Struct s = new Struct(); - s.setForwardDeclaration(true); - s.setTag(name); - s.setType(type); - return s; - } - - public void setCategoryName(String categoryName) { - this.categoryName = categoryName; - } - public String getCategoryName() { - return categoryName; - } - - public List getParents() { - return unmodifiableList(parents); - } - public void addParent(Identifier parent) { - addParent(typeRef(parent)); - } - public void addParent(SimpleTypeRef parent) { - if (parent == null) - return; - parent.setParentElement(this); - parents.add(parent); - } - public void setParents(List parents) { - changeValue(this, this.parents, parents); - } - public List getProtocols() { - return unmodifiableList(protocols); - } - public void addProtocol(Identifier parent) { - addProtocol(typeRef(parent)); - } - public void addProtocol(SimpleTypeRef protocol) { - if (protocol == null) - return; - protocol.setParentElement(this); - protocols.add(protocol); - } - public void addProtocols(SimpleTypeRef... protocols) { - List l = new ArrayList(getProtocols()); - l.addAll(Arrays.asList(protocols)); - setProtocols(l); - } - public void setProtocols(List protocols) { - changeValue(this, this.protocols, protocols); - } - public Struct setType(Type type) { - this.type = type; - switch (type) { - case ObjCClass: - case ObjCProtocol: - break; - case CPPClass: - setNextMemberVisibility(MemberVisibility.Private); - break; - case CStruct: - case JavaClass: - case JavaInterface: - setNextMemberVisibility(MemberVisibility.Public); - break; - default: - break; - } - return this; - } - public Type getType() { - return type; - } - public List getDeclarations() { - return unmodifiableList(declarations); - } - public void addDeclaration(Declaration d) { - if (d == null) - return; - - d.setVisibility(getNextMemberVisibility()); - d.setParentElement(this); - declarations.add(d); - } - public void addDeclarations(Collection ds) { - if (ds == null) - return; - - for (Declaration d : ds) - addDeclaration(d); - } - public void setDeclarations(List declarations) { - changeValue(this, this.declarations, declarations); - } - - public void setNextMemberVisibility(MemberVisibility nextVisibility) { - this.nextMemberVisibility = nextVisibility; - } - public MemberVisibility getNextMemberVisibility() { - return nextMemberVisibility; - } - - public void accept(Visitor visitor) { - visitor.visitStruct(this); - } - - public void setParents(SimpleTypeRef... ns) { - setParents(Arrays.asList(ns)); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TaggedTypeRefDeclaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TaggedTypeRefDeclaration.java deleted file mode 100644 index 91aefbcc6..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TaggedTypeRefDeclaration.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; - -public class TaggedTypeRefDeclaration extends Declaration { - public TaggedTypeRefDeclaration(TaggedTypeRef namedTypeRef) { - setTaggedTypeRef(namedTypeRef); - } - public TaggedTypeRefDeclaration() {} - - TaggedTypeRef namedTypeRef; - - @Override - public TaggedTypeRefDeclaration addModifiers(Modifier... mds) { - return (TaggedTypeRefDeclaration) super.addModifiers(mds); - } - //public String resove - /*public String getName() { - return getTaggedTypeRef() != null ? namedTypeRef.getTag() : null; - } - public void setName(String name) { - if (getTaggedTypeRef() != null) - getTaggedTypeRef().setTag(name); - }*/ - public void setTaggedTypeRef(TaggedTypeRef namedTypeRef) { - this.namedTypeRef = changeValue(this, this.namedTypeRef, namedTypeRef); - } - public TaggedTypeRef getTaggedTypeRef() { - return namedTypeRef; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child.equals(getTaggedTypeRef())) { - setTaggedTypeRef((TaggedTypeRef)by); - return true; - } - return super.replaceChild(child, by); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitTaggedTypeRefDeclaration(this); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Template.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Template.java deleted file mode 100644 index f3b2f4758..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Template.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.ochafik.lang.jnaerator.parser; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.ident; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.jnaerator.parser.Function.Type; - -public class Template extends Declaration { - final List args = new ArrayList(); - Declaration declaration; - - public Declaration getDeclaration() { - return declaration; - } - public void setDeclaration(Declaration declaration) { - this.declaration = changeValue(this, this.declaration, declaration); - } - @Override - public Element getNextChild(Element child) { - Element e = super.getNextChild(child); - if (e != null) - return e; - return getNextSibling(args, child); - } - - @Override - public Template clone() { - return (Template) super.clone(); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = super.getPreviousChild(child); - if (e != null) - return e; - return getPreviousSibling(args, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(args, Arg.class, this, child, by)) - return true; - - if (getDeclaration() == child) { - setDeclaration((Declaration)by); - return true; - } - - return super.replaceChild(child, by); - } - - - public Arg addArg(Arg a) { - if (a != null) { - args.add(a); - a.setParentElement(this); - } - return a; - } - public List getArgs() { - return unmodifiableList(args); - } - public void setArgs(List args) { - changeValue(this, this.args, args); - } - - public void accept(Visitor visitor) { - visitor.visitTemplate(this); - } - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeMutator.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeMutator.java deleted file mode 100644 index 2f3e9b99f..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeMutator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Declarator.PointerStyle; - -public abstract class TypeMutator { - public static TypeMutator - CONST_STAR = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - type = new TypeRef.Pointer(type, PointerStyle.Pointer); - type.addModifiers(ModifierType.Const); - return type; - }}, - STAR = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - return new TypeRef.Pointer(type, PointerStyle.Pointer); - }}, - HAT = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - return new TypeRef.Pointer(type, PointerStyle.HatPointer); - }}, - AMPERSTAND = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - return new TypeRef.Pointer(type, PointerStyle.Reference); - }}, - CONST = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - type.addModifiers(ModifierType.Const); - return type; - }}, - BRACKETS = new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - return new TypeRef.ArrayRef(type, new Expression.EmptyArraySize()); - }} - ; - public abstract TypeRef mutateType(TypeRef type); - public static TypeMutator array(final Expression expression) { - return new TypeMutator() { @Override public TypeRef mutateType(TypeRef type) { - return new TypeRef.ArrayRef(type, expression); - }}; - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeRef.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeRef.java deleted file mode 100644 index 5cd8d76b3..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/TypeRef.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; -import com.ochafik.lang.jnaerator.parser.ModifierKind; - -public abstract class TypeRef extends ModifiableElement implements Declarator.MutableByDeclarator { - - protected Identifier resolvedJavaIdentifier; - - public void setResolvedJavaIdentifier(Identifier resolvedJavaIdentifier) { - this.resolvedJavaIdentifier = changeValue(this, this.resolvedJavaIdentifier, resolvedJavaIdentifier); - } - - public Identifier getResolvedJavaIdentifier() { - return resolvedJavaIdentifier; - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (getResolvedJavaIdentifier() == child) { - setResolvedJavaIdentifier((Identifier)by); - return true; - } - - return super.replaceChild(child, by); - } - - protected boolean markedAsResolved; - public TypeRef setMarkedAsResolved(boolean markedAsResolved) { - this.markedAsResolved = markedAsResolved; - return this; - } - public boolean isMarkedAsResolved() { - return markedAsResolved; - } - @Override - public TypeRef importDetails(Element from, boolean move) { - return (TypeRef) super.importDetails(from, move); - } - @Override - public TypeRef addModifiers(Modifier... mds) { - return (TypeRef) super.addModifiers(mds); - } - public static abstract class TaggedTypeRef extends TypeRef { - Identifier tag, originalTag; - public Identifier getTag() { - return tag; - } - public void setTag(Identifier tag) { -// if (tag != null && tag.equals("lc_category_struct")) -// tag = tag; -// new Exception("Recursion too deep " + tag).printStackTrace(); - - - this.tag = changeValue(this, this.tag, tag); - if (originalTag == null && tag != null) - setOriginalTag(tag.clone()); - } - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getTag()) { - setTag((Identifier)by); - return true; - } - if (child == getOriginalTag()) { - setOriginalTag((Identifier)by); - return true; - } - return super.replaceChild(child, by); - } - public void setOriginalTag(Identifier originalTag) { - this.originalTag = changeValue(this, this.originalTag, originalTag); - } - public Identifier getOriginalTag() { - return originalTag; - } - public boolean isForwardDeclaration() { - return forwardDeclaration; - } - public void setForwardDeclaration(boolean forwardDeclaration) { - this.forwardDeclaration = forwardDeclaration; - } - - boolean forwardDeclaration = false; - - @Override - public void accept(Visitor visitor) { - visitor.visitTaggedTypeRef(this); - } - } - //protected final List modifiers = new ArrayList(); - - @Override - public TypeRef clone() { - return (TypeRef) super.clone(); - } - - public static class SimpleTypeRef extends TypeRef { - protected Identifier name; - - public SimpleTypeRef(String name) { - this(); - setName(new Identifier.SimpleIdentifier(name)); - } - public SimpleTypeRef(Identifier name) { - this(); - setName(name); - } - public SimpleTypeRef() { - } - - public Identifier getName() { - return name; - } - public void setName(Identifier name) { - this.name = changeValue(this, this.name, name); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getName()) - setName((Identifier)by); - return super.replaceChild(child, by); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitSimpleTypeRef(this); - } - - - } - - public boolean acceptsModifier(Modifier modifier) { - return modifier.isAnyOf(ModifierKind.NumericTypeQualifier, ModifierKind.TypeQualifier); - } - /* - public TypeRef addModifier(String modifier) { - if (modifier != null) - modifiers.add(modifier); - return this; - } - public void addModifier(String modifier, int i) { - if (modifier != null) - modifiers.add(i, modifier); - }*/ - - public static class FunctionSignature extends TypeRef { - public enum Type { - CFunction, ObjCBlock - } - protected Type type = Type.CFunction; - protected Function function; - - public void setType(Type type) { - this.type = type; - } - - public Type getType() { - return type; - } - - - public FunctionSignature(Function function) { - this(); - setFunction(function); - } - - @Override - public FunctionSignature clone() { - return (FunctionSignature) super.clone(); - } - - public FunctionSignature() { - } - - public Function getFunction() { - return function; - } - public void setFunction(Function function) { - this.function = changeValue(this, this.function, function); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitFunctionSignature(this); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (getFunction() == child) { - setFunction((Function) by); - return true; - } - return super.replaceChild(child, by); - } - } - - public static class Primitive extends SimpleTypeRef {//TypeRef { - //protected String name; - - static Set cPrimitiveTypes = new HashSet(); - static { - cPrimitiveTypes.add("long"); - cPrimitiveTypes.add("int"); - cPrimitiveTypes.add("short"); - cPrimitiveTypes.add("bool"); - cPrimitiveTypes.add("char"); - cPrimitiveTypes.add("void"); - cPrimitiveTypes.add("double"); - cPrimitiveTypes.add("float"); - cPrimitiveTypes.add("size_t"); - cPrimitiveTypes.add("__int8"); - cPrimitiveTypes.add("__int16"); - cPrimitiveTypes.add("__int32"); - cPrimitiveTypes.add("__int64"); - cPrimitiveTypes.add("__uint8"); - cPrimitiveTypes.add("__uint16"); - cPrimitiveTypes.add("__uint32"); - cPrimitiveTypes.add("__uint64"); - - } - - public static boolean isACPrimitive(String s) { - return cPrimitiveTypes.contains(s); - } - public Primitive(String name) { - setName(name == null ? null : new Identifier.SimpleIdentifier(name)); - } - - public Primitive() {} - - @Override - public Primitive addModifiers(Modifier... mds) { - return (Primitive)super.addModifiers(mds); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitPrimitive(this); - } - } - - public static class Pointer extends TargettedTypeRef { - Declarator.PointerStyle pointerStyle; - - public Pointer(TypeRef target, Declarator.PointerStyle pointerStyle) { - this(); - setTarget(target); - setPointerStyle(pointerStyle); - } - public Pointer() { - } - public void setPointerStyle(Declarator.PointerStyle pointerStyle) { - this.pointerStyle = pointerStyle; - } - public Declarator.PointerStyle getPointerStyle() { - return pointerStyle; - } - @Override - public void accept(Visitor visitor) { - visitor.visitPointer(this); - } - } - - public static abstract class TargettedTypeRef extends TypeRef { - protected TypeRef target; - public TypeRef getTarget() { - return target; - } - public void setTarget(TypeRef target) { - this.target = changeValue(this, this.target, target); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (getTarget() == child) { - setTarget((TypeRef) by); - return true; - } - return super.replaceChild(child, by); - } - - @Override - public List harvestModifiers() { - List mods = super.harvestModifiers(); - if (getTarget() != null) - mods.addAll(getTarget().harvestModifiers()); - return mods; - } - } - - public static class PrecisionTypeRef extends TargettedTypeRef { - Expression precision; - public PrecisionTypeRef() {} - public PrecisionTypeRef(TypeRef target, Expression precision) { - setTarget(target); - setPrecision(precision); - } - - public Expression getPrecision() { - return precision; - } - - public void setPrecision(Expression precision) { - this.precision = changeValue(this, this.precision, precision); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (child == getPrecision()) { - setPrecision((Expression)by); - return true; - } - - return super.replaceChild(child, by); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitPrecisionTypeRef(this); - } - - } - - public static class ArrayRef extends TargettedTypeRef { - final List dimensions = new ArrayList(); - - public ArrayRef(TypeRef target, Expression... dimensions) { - this(target, Arrays.asList(dimensions)); - } - public ArrayRef(TypeRef target, List dimensions) { - this(); - setDimensions(dimensions); - setTarget(target); - } - - public void flattenDimensions(List out) { - out.addAll(dimensions); - } - - public List flattenDimensions() { - List dims = new ArrayList(); - if (getTarget() instanceof ArrayRef) { - ((ArrayRef)getTarget()).flattenDimensions(dims); - } - flattenDimensions(dims); - return dims; - } - - public boolean hasStaticStorageSize() { - if (dimensions.isEmpty()) - return false; - - Expression x = dimensions.get(dimensions.size() - 1); - return x != null && !(x instanceof EmptyArraySize); - } - - public ArrayRef() { - } - - @Override - public Element getNextChild(Element child) { - Element e = getNextSibling(dimensions, child); - if (e != null) - return e; - return super.getNextChild(child); - } - - @Override - public Element getPreviousChild(Element child) { - Element e = getPreviousSibling(dimensions, child); - if (e != null) - return e; - return super.getPreviousChild(child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(dimensions, Expression.class, this, child, by)) - return true; - - return super.replaceChild(child, by); - } - - public List getDimensions() { - return unmodifiableList(dimensions); - } - public void setDimensions(List dimensions) { - changeValue(this, this.dimensions, dimensions); - } - - @Override - public void accept(Visitor visitor) { - visitor.visitArray(this); - } - public void addDimension(Expression x) { - if (x == null) - return; - - x.setParentElement(this); - dimensions.add(x); - } - } - - - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ValuedModifier.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ValuedModifier.java deleted file mode 100644 index f107521cc..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/ValuedModifier.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import java.util.Collection; - -public class ValuedModifier implements Modifier { - Modifier modifier; - Constant value; - public ValuedModifier() {} - public ValuedModifier(Modifier modifier, Constant value) { - this.modifier = modifier; - this.value = value; - } - - public Collection getKinds() { - return modifier.getKinds(); - } - - - - public Modifier getModifier() { - return modifier; - } - - public void setModifier(Modifier modifier) { - this.modifier = modifier; - } - - public Constant getValue() { - return value; - } - - public void setValue(Constant value) { - this.value = value; - } - - public Modifier resolveAlias() { - - Modifier modifier = getModifier(); - if (modifier == null) - return this; - return new ValuedModifier(modifier.resolveAlias(), getValue()); - } - - public boolean isA(ModifierKind kind) { - Modifier modifier = getModifier(); - return modifier != null && modifier.isA(kind); - } - - public boolean isAnyOf(ModifierKind... kinds) { - Modifier modifier = getModifier(); - return modifier != null && modifier.isAnyOf(kinds); - } - - public boolean isAllOf(ModifierKind... kinds) { - Modifier modifier = getModifier(); - return modifier != null && modifier.isAllOf(kinds); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof ValuedModifier)) - return false; - - ValuedModifier m = (ValuedModifier)o; - if ((getModifier() == null) != (m.getModifier() == null)) - return false; - if (getModifier() != null && !getModifier().equals(m.getModifier())) - return false; - if ((getValue() == null) != (m.getValue() == null)) - return false; - if (getValue() != null && !getValue().equals(m.getValue())) - return false; - return true; - } - - @Override - public int hashCode() { - int hc = 0; - if (getModifier() != null) - hc = getModifier().hashCode(); - if (getValue() != null) - hc ^= getValue().hashCode(); - return hc; - } - - @Override - public String toString() { - - String s = getModifier() + "(" + getValue() + ")"; - Collection kinds = modifier.getKinds(); - if (modifier.getKinds().contains(ModifierKind.Declspec)) - return "__declspec(" + s + ")"; - - if (kinds.contains(ModifierKind.Attribute)) - return "__attribute__((" + s + "))"; - return s; - } - - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/VariablesDeclaration.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/VariablesDeclaration.java deleted file mode 100644 index 89786f299..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/VariablesDeclaration.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.util.Arrays; -import java.util.List; - -public class VariablesDeclaration extends StoredDeclarations { - - public VariablesDeclaration() {} - public VariablesDeclaration(TypeRef valueType, Declarator...declarators) { - this(valueType, Arrays.asList(declarators)); - } - - public VariablesDeclaration(TypeRef valueType, List declarators) { - setValueType(valueType); - setDeclarators(declarators); - } - @Override - public VariablesDeclaration addModifiers(Modifier... mod) { - return (VariablesDeclaration) super.addModifiers(mod); - } - @Override - public void accept(Visitor visitor) { - visitor.visitVariablesDeclaration(this); - } - -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Visitor.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Visitor.java deleted file mode 100644 index 39dc97b9b..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Visitor.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.FunctionDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerDeclarator; -import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionsBlock; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -import com.ochafik.lang.jnaerator.parser.Statement.Catch; -//import com.ochafik.lang.jnaerator.parser.Statement.DeclarationStatement; -import com.ochafik.lang.jnaerator.parser.Statement.Delete; -import com.ochafik.lang.jnaerator.parser.Statement.DoWhile; -import com.ochafik.lang.jnaerator.parser.Statement.If; -import com.ochafik.lang.jnaerator.parser.Statement.For; -import com.ochafik.lang.jnaerator.parser.Statement.Return; -import com.ochafik.lang.jnaerator.parser.Statement.Throw; -import com.ochafik.lang.jnaerator.parser.Expression.ArrayAccess; -import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; -import com.ochafik.lang.jnaerator.parser.Expression.Cast; -import com.ochafik.lang.jnaerator.parser.Expression.ConditionalExpression; -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; -import com.ochafik.lang.jnaerator.parser.Expression.ExpressionSequence; -import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; -import com.ochafik.lang.jnaerator.parser.Expression.New; -import com.ochafik.lang.jnaerator.parser.Expression.NewArray; -import com.ochafik.lang.jnaerator.parser.Expression.NullExpression; -import com.ochafik.lang.jnaerator.parser.Expression.OpaqueExpression; -import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; -import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.lang.jnaerator.parser.Statement.ExpressionStatement; -import com.ochafik.lang.jnaerator.parser.Statement.Try; -import com.ochafik.lang.jnaerator.parser.Statement.While; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; -import com.ochafik.lang.jnaerator.parser.TypeRef.PrecisionTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; - -public interface Visitor { - - void visitConstant(Constant constant); - - void visitArg(Arg arg); - - void visitEnum(Enum enum1); - - void visitFunction(Function function); - - void visitFunctionPointerDeclaration( - FunctionPointerDeclaration functionPointerDeclaration); - - void visitStruct(Struct struct); - - void visitTypeDef(TypeDef typeDef); - - void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef); - - void visitFunctionSignature(FunctionSignature functionSignature); - - void visitPrimitive(Primitive primitive); - - void visitPointer(Pointer pointer); - - void visitArray(ArrayRef array); - - void visitSourceFile(SourceFile sourceFile); - - void visitEnumItem(Enum.EnumItem enumItem); - - void visitUnaryOp(UnaryOp unaryOp); - - void visitVariableRef(VariableRef variableRef); - - void visitBinaryOp(BinaryOp binaryOp); - - void visitFunctionCall(FunctionCall functionCall); - - void visitCast(Cast cast); - - void visitDeclarator(Declarator variableStorage); - - void visitVariablesDeclaration(VariablesDeclaration variablesDeclaration); - - void visitTaggedTypeRefDeclaration(TaggedTypeRefDeclaration taggedTypeRefDeclaration); - - void visitTaggedTypeRef(TaggedTypeRef taggedTypeRef); - - void visitEmptyArraySize(EmptyArraySize emptyArraySize); - - void visitDefine(Define define); - - void visitTypeRefExpression(TypeRefExpression typeRefExpression); - - void visitNew(New new1); - - void visitAnnotation(Annotation annotation); - - void visitEmptyDeclaration(EmptyDeclaration emptyDeclaration); - - void visitNewArray(NewArray newArray); - - void visitPointerDeclarator(PointerDeclarator pointerDeclarator); - - void visitArrayDeclarator(com.ochafik.lang.jnaerator.parser.Declarator.PointerDeclarator.ArrayDeclarator arrayDeclarator); - - void visitDirectDeclarator(DirectDeclarator directDeclarator); - - void visitFunctionDeclarator(FunctionDeclarator functionDeclarator); - - void visitModifiableElement(ModifiableElement modifiableElement); - - void visitBlock(Block block); - - void visitExpressionStatement(ExpressionStatement expressionStatement); - - void visitIf(If if1); - - void visitNullExpression(NullExpression nullExpression); - - void visitReturn(Return return1); - - void visitExternDeclarations(ExternDeclarations externDeclarations); - - void visitOpaqueExpression(OpaqueExpression opaqueExpression); - - void visitArrayAccess(ArrayAccess arrayIncr); - - void visitMemberRef(MemberRef memberRef); - - void visitAssignmentOp(AssignmentOp assignment); - - void visitConditionalExpression(ConditionalExpression conditionalExpression); - - void visitExpressionSequence(ExpressionSequence expressionSequence); - - void visitSimpleIdentifier(SimpleIdentifier simpleIdentifier); - - void visitQualifiedIdentifier(QualifiedIdentifier qualifiedIdentifier); - - //void visitDeclarationStatement(DeclarationStatement declarationStatement); - - void visitThrow(Throw t); - - void visitProperty(Property property); - - void visitFriendDeclaration(FriendDeclaration friendDeclaration); - - public void visitTry(Try aThis); - - public void visitCatch(Catch aThis); - - void visitTemplate(Template template); - - public void visitFor(For aFor); - - public void visitWhile(While aThis); - - public void visitDoWhile(DoWhile aThis); - - public void visitNamespace(Namespace aThis); - - public void visitDeclarations(Declarations aThis); - - public void visitPrecisionTypeRef(PrecisionTypeRef aThis); - - public void visitDelete(Delete aThis); - - public void visitExpressionsBlock(ExpressionsBlock aThis); - -} diff --git a/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/MiscTest.java b/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/MiscTest.java deleted file mode 100644 index 76c32273e..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/MiscTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator.parser; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author ochafik - */ -public class MiscTest { - - @Test - public void parseMods() { - assertEquals(ModifierType.UUID, ModifierType.parseModifier("uuid"));//, ModifierKind.Extended)); - } -} diff --git a/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppElementsTest.java b/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppElementsTest.java deleted file mode 100644 index 25e4a11fb..000000000 --- a/libraries/jnaerator/jnaerator-parser/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppElementsTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.parser; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import static org.junit.Assert.*; - - -import static com.ochafik.lang.SyntaxUtils.*; - -import com.ochafik.beans.BeansUtils; -import com.ochafik.junit.ParameterizedWithDescription; -//import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; -import com.ochafik.lang.reflect.GettersAndSettersHelper; -import com.ochafik.lang.reflect.GettersAndSettersHelper.GetterAndSetterInfo; -import com.ochafik.util.listenable.Pair; - -@SuppressWarnings("unused") -//@RunWith(Parameterized.class) -@RunWith(Parameterized.class) -public class ObjCppElementsTest { - String description; - Class type; - - /// Gives the set of subclasses that implement a given abstract class or interface - Map, Set>> implementations; - - public ObjCppElementsTest(String description, Class type, Map, Set>> implementations) { - super(); - this.description = description; - this.type = type; - this.implementations = implementations; - } - - final static Set fieldsExcludedFromGetterSetterChecks = new HashSet(); - static { - fieldsExcludedFromGetterSetterChecks.add("previousSibling"); - fieldsExcludedFromGetterSetterChecks.add("nextSibling"); - fieldsExcludedFromGetterSetterChecks.add("plain"); - fieldsExcludedFromGetterSetterChecks.add("class"); - fieldsExcludedFromGetterSetterChecks.add("const"); - fieldsExcludedFromGetterSetterChecks.add("unsigned"); - fieldsExcludedFromGetterSetterChecks.add("gettersAndSetters"); - fieldsExcludedFromGetterSetterChecks.add("modifiersStringPrefix"); - fieldsExcludedFromGetterSetterChecks.add("id"); - fieldsExcludedFromGetterSetterChecks.add("varArgs"); - fieldsExcludedFromGetterSetterChecks.add("parents"); - fieldsExcludedFromGetterSetterChecks.add("pathInFramework"); - fieldsExcludedFromGetterSetterChecks.add("plainStorage"); - } - -// @Test -// public void checkDerivedClone() { -// try { -// Method m = type.getMethod("clone"); -// assertEquals(m + " must have a return type of " + type.getSimpleName(), m.getReturnType(), type); -// } catch (Exception e) { -// assertTrue("Failed to get clone method (bad visibility ?)", false); -// } -// } - @Test - public void checkGettersAndSetters() { - Element element = newElement(); - GettersAndSettersHelper helper = element.getGettersAndSetters();//new GettersAndSettersHelper(type); - - for (Map.Entry e : helper.gettersAndSetters.entrySet()) { - GetterAndSetterInfo p = e.getValue(); - String fieldName = e.getKey(); - Type fieldType = helper.getFieldType(fieldName ); - - assertNotNull("Field " + fieldName + " does not have a getter !", p.getter); - if (!fieldsExcludedFromGetterSetterChecks.contains(fieldName)) - assertNotNull("Field " + fieldName + " does not have a setter !", p.setter); - - if (p.setter == null) - continue; - - helper.assertConsistentPair(p); - -// System.err.println("Testing field " + type.getSimpleName() + "." + fieldName);// + ": "); - - if (fieldType instanceof Class && Element.class.isAssignableFrom((Class) fieldType)) { - testSetNewInstancesOf(fieldType, implementations, element, fieldName, p.setter, p.getter, null); - //System.err.println(); - } else if (fieldType instanceof ParameterizedType) { - ParameterizedType paramType = (ParameterizedType) fieldType; - Type rawType = paramType.getRawType(); - if (rawType instanceof Class) { - Class rawClass = (Class) rawType; - boolean isList = List.class.isAssignableFrom(rawClass); - if (isList || Set.class.isAssignableFrom(rawClass)) { - Collection container = isList ? new ArrayList() : new TreeSet(new Comparator() { - public int compare(Element o1, Element o2) { - return o1.toString().compareTo(o2.toString()); - } - }); - Type[] typeArguments = paramType.getActualTypeArguments(); - if (typeArguments.length == 1 && typeArguments[0] instanceof Class && Element.class.isAssignableFrom((Class) typeArguments[0])) { - Class elementType = (Class) typeArguments[0]; - testSetNewInstancesOf(elementType, implementations, element, fieldName, p.setter, p.getter, container); - } - } else { - //assertTrue("Field '" + fieldName + "' of type " + fieldType + " cannot be tested !" , false); - } - } - } else if (String.class.isAssignableFrom(as(fieldType, Class.class))) { - Element instance = newElement(); - BeansUtils.set(instance, fieldName, String.class, ""); - Object v = BeansUtils.get(instance, fieldName); - assertEquals("Testing " + fieldName + " :get(set(\"\"))", v, ""); - BeansUtils.set(instance, fieldName, String.class, null); - v = BeansUtils.get(instance, fieldName); - assertEquals(v, null); - } - } - - - } - - private void testSetNewInstancesOf(Type fieldType, Map, Set>> implementations2, Element element, String fieldName, Method setter, Method getter, Collection container) { - Set> fieldTypeImplementations = implementations.get(fieldType); - assertNotNull("Found no implementation of " + fieldType, fieldTypeImplementations); - for (Class fieldTypeImplClass : fieldTypeImplementations) { - testSetNewInstanceOf(fieldTypeImplClass, element, fieldName, setter, getter, container); - } - } - - @SuppressWarnings("unchecked") - private void testSetNewInstanceOf(Class fieldTypeImplClass, - Element element, String fieldName, Method setter, Method getter, Collection container) { - - Element arg = null, replace = null; - try { - arg = (Element) fieldTypeImplClass.newInstance(); - replace = (Element) fieldTypeImplClass.newInstance(); - } catch (Exception ex) { - ex.printStackTrace(); - assertFalse("Failed to create new " + fieldTypeImplClass.getName() + " : " + ex + "; cause : " + ex.getCause(), true); - } - -// System.err.print("setter "); - /// Setter - - Object valueToBeSet; - if (container == null) { - valueToBeSet = arg; - } else { - container.clear(); - container.add(arg); - valueToBeSet = container; - } - - try { - setter.invoke(element, valueToBeSet); - if (!fieldName.equals("parentElement")) { - assertNotNull("Parent element not set in " + setter, arg.getParentElement()); - assertEquals("Parent element not set properly in " + setter, - element, arg.getParentElement()); - } - } catch (Exception ex) { - ex.printStackTrace(); - assertFalse("Failed to call " + setter + " with a " + fieldTypeImplClass.getName() + " : " + ex + "; cause : " + ex.getCause(), true); - } - - if (!fieldName.equals("parentElement")) { - final Set visitedIds = new TreeSet(); - element.accept(new Scanner() { - @Override - protected void visitElement(Element d) { - if (d != null) - visitedIds.add(d.getId()); - - super.visitElement(d); - } - }); - assertTrue("Scanner did not visit child element " + fieldName + " with a " + fieldTypeImplClass.getName() , visitedIds.contains(arg.getId())); - } - - - if (getter != null) { -// System.err.print("getter "); - /// Getter - try { - Object got = getter.invoke(element); - Element elementGot = container == null ? (Element)got : ((Collection)got).iterator().next(); - - assertEquals("Getter of " + fieldName + " does not return same object as setter in " + type.getName(), arg, elementGot); - - if (!fieldName.equals("parentElement")) { - - if (container != null) { - container.clear(); - container.add(replace); - } - - arg.replaceBy(replace); - Object got2 = getter.invoke(element); - Element elementGot2 = container == null ? (Element)got2 : ((Collection)got2).iterator().next(); - -// if (arg != elementGot2) -// arg =arg; // debug: break here - assertFalse("Replacement of field " + fieldName + " in " + type.getName() + " failed", arg == elementGot2); - assertEquals("Replacement of field " + fieldName + " in " + type.getName() + " failed", replace, elementGot2); - assertNull("Parent element not removed in " + setter, elementGot.getParentElement()); - assertNotNull("Parent element not set in " + setter, elementGot2.getParentElement()); - - assertEquals("Parent element not set properly in " + setter, - element, elementGot2.getParentElement()); - } - - } catch (Exception ex) { - ex.printStackTrace(); - assertFalse("Failed to call " + setter + " with a " + fieldTypeImplClass.getName() + " : " + ex + "; cause : " + ex.getCause(), true); - } - - } - } - - private Element newElement() { - try { - return type.newInstance(); - } catch (Exception ex) { - ex.printStackTrace(); - assertFalse("Failed to create new " + type.getName() + " : " + ex + "; cause : " + ex.getCause(), true); - return null; - } - } - - - @Parameters - public static List getClassesToTest() throws IOException { - Set> elementClasses = new HashSet>(); - for (Method method : Scanner.class.getMethods()) { - for (Class argType : method.getParameterTypes()) - if (Element.class.isAssignableFrom(argType)) - elementClasses.add(argType); - - Class returnType = method.getReturnType(); - if (Element.class.isAssignableFrom(returnType)) - elementClasses.add(returnType); - } - - Map, Set>> implementations = new HashMap, Set>>(); - for (Class c : elementClasses) { - if ((c.getModifiers() & Modifier.ABSTRACT) != 0) - continue; - - Class s = c; - do { - Set> cs = implementations.get(s); - if (cs == null) - implementations.put(s, cs = new HashSet>()); - cs.add(c); - s = s.getSuperclass(); - } while (s != null); - } - - List ret = new ArrayList(); - for (Class c : elementClasses) { - if ((c.getModifiers() & Modifier.ABSTRACT) != 0) - continue; - ret.add(new Object[] {c.getName(), c, implementations}); - } - return ret; - } - public static class TestSiblings { - @Test - public void addSibling() { - VariablesDeclaration d = new VariablesDeclaration(); - Declarator s1 = new Declarator.DirectDeclarator(), s2 = new Declarator.DirectDeclarator(); - - d.setDeclarators(Arrays.asList(s1)); - s1.insertSibling(s2, false); - List list = d.getDeclarators(); - assertEquals("Failed to add after", 2, list.size()); - assertSame("Added, but not after", s1, list.get(0)); - assertSame(s2, list.get(1)); - - s2.replaceBy(null); - list = d.getDeclarators(); - assertEquals("Failed to remove added element", 1, list.size()); - assertSame("Removed bad element", s1, list.get(0)); - - d.setDeclarators(Arrays.asList(s1)); - s1.insertSibling(s2, true); - list = d.getDeclarators(); - assertEquals("Failed to add before", 2, list.size()); - assertSame("Added, but not before", s2, list.get(0)); - assertSame(s1, list.get(1)); - - s2.replaceBy(null); - list = d.getDeclarators(); - assertEquals("Failed to remove added element", 1, list.size()); - assertSame("Removed bad element", s1, list.get(0)); - } - } -} diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/.classpath b/libraries/jnaerator/jnaerator-rococoa-runtime/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/.gitignore b/libraries/jnaerator/jnaerator-rococoa-runtime/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/.project b/libraries/jnaerator/jnaerator-rococoa-runtime/.project deleted file mode 100644 index 2e03866d9..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - jnaerator-rococoa-runtime - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9cf8f359f..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:13 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/pom.xml b/libraries/jnaerator/jnaerator-rococoa-runtime/pom.xml deleted file mode 100644 index 64f152965..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - 4.0.0 - com.nativelibs4java - jnaerator-rococoa-runtime - JNAerator Rococoa Runtime - http://code.google.com/p/jnaerator/ - jar - - - - com.nativelibs4java - jnaerator-runtime - - - org.rococoa - rococoa-core - - - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CGFloatByReference.java b/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CGFloatByReference.java deleted file mode 100644 index 92bfbc63e..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CGFloatByReference.java +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright (c) 2007 Timothy Wall, All Rights Reserved - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - *

      - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - */ -package com.ochafik.lang.jnaerator.runtime; - -import org.rococoa.cocoa.CGFloat; - -import com.sun.jna.ptr.ByReference; - -public class CGFloatByReference extends ByReference { - public CGFloatByReference() { - this(0d); - } - - public CGFloatByReference(float value) { - super(CGFloat.SIZE); - set(value); - } - public void set(float value) { - set(new CGFloat(value)); - } - - public CGFloatByReference(double value) { - super(CGFloat.SIZE); - set(value); - } - public void set(double value) { - - set(new CGFloat(value)); - } - - public void set(CGFloat value) { - switch (CGFloat.SIZE) { - case 4: - getPointer().setFloat(0, value.floatValue()); - break; - case 8: - getPointer().setDouble(0, value.doubleValue()); - break; - default: - throw new UnsupportedOperationException("Unhandled CGFloat size : " + CGFloat.SIZE); - } - } - public CGFloat get() { - switch (CGFloat.SIZE) { - case 4: - return new CGFloat(getPointer().getFloat(0)); - case 8: - return new CGFloat(getPointer().getDouble(0)); - default: - throw new UnsupportedOperationException("Unhandled CGFloat size : " + CGFloat.SIZE); - } - } - - public CGFloatByReference(CGFloat value) { - super(CGFloat.SIZE); - set(value); - } -} diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ObjCBlock.java b/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ObjCBlock.java deleted file mode 100644 index 23b728f14..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ObjCBlock.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.PointerType; - -/** - * - * @author ochafik - */ -public class ObjCBlock extends PointerType { - -} diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCGFloat.java b/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCGFloat.java deleted file mode 100644 index 9c513ffe6..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCGFloat.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import org.rococoa.cocoa.CGFloat; - -import com.ochafik.lang.jnaerator.runtime.CGFloatByReference; -import com.sun.jna.NativeLibrary; - -public class GlobalCGFloat extends GlobalPrimitive { - public GlobalCGFloat(NativeLibrary library, String... symbols) { - super(library, CGFloatByReference.class, symbols); - } - public CGFloat get() { - return getValue().get(); - } - public void set(CGFloat v) { - getValue().set(v); - } - - public void set(float v) { - getValue().set(v); - } - - public void set(double v) { - getValue().set(v); - } -} diff --git a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/org/rococoa/cocoa/foundation/NSClass.java b/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/org/rococoa/cocoa/foundation/NSClass.java deleted file mode 100644 index 2ab47a8ca..000000000 --- a/libraries/jnaerator/jnaerator-rococoa-runtime/src/main/java/org/rococoa/cocoa/foundation/NSClass.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.rococoa.cocoa.foundation; - -import org.rococoa.ObjCClass; -import org.rococoa.cocoa.foundation.NSObject; - -public abstract class NSClass extends NSObject implements ObjCClass {} diff --git a/libraries/jnaerator/jnaerator-runtime/.classpath b/libraries/jnaerator/jnaerator-runtime/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/jnaerator-runtime/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-runtime/.gitignore b/libraries/jnaerator/jnaerator-runtime/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/jnaerator-runtime/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/jnaerator-runtime/.project b/libraries/jnaerator/jnaerator-runtime/.project deleted file mode 100644 index 3fcabea6c..000000000 --- a/libraries/jnaerator/jnaerator-runtime/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - jnaerator-runtime - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/jnaerator-runtime/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/jnaerator-runtime/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 49836caba..000000000 --- a/libraries/jnaerator/jnaerator-runtime/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:11 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/jnaerator-runtime/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/jnaerator-runtime/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/jnaerator-runtime/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/jnaerator-runtime/pom.xml b/libraries/jnaerator/jnaerator-runtime/pom.xml deleted file mode 100644 index c1f0f0c86..000000000 --- a/libraries/jnaerator/jnaerator-runtime/pom.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - jnaerator-runtime - JNAerator Runtime - http://code.google.com/p/jnaerator/ - jar - - - - com.nativelibs4java - ochafik-util - - - com.nativelibs4java - jna-jnaerator - - - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - normal-package - package - - shade - - - true - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - webstart-package - package - - shade - - - true - webstart - - - - com.jnaerator:jna-jnaerator - - - - - - **/*.so - **/*.jnilib - **/*.dll - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Bits.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Bits.java deleted file mode 100644 index 58f5be531..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Bits.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; -import java.lang.annotation.*; - -@Retention(RetentionPolicy.RUNTIME) -@Target( {ElementType.FIELD} ) -public @interface Bits { - int value(); -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CharByReference.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CharByReference.java deleted file mode 100644 index 7bc27d7d8..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/CharByReference.java +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2007 Timothy Wall, All Rights Reserved -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU Lesser General Public -* License as published by the Free Software Foundation; either -* version 2.1 of the License, or (at your option) any later version. -*

      -* This library is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* Lesser General Public License for more details. -*/ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.Native; -import com.sun.jna.ptr.ByReference; - -public class CharByReference extends ByReference { - public CharByReference() { - this((char)0); - } - - public CharByReference(char value) { - super(Native.WCHAR_SIZE); - setValue(value); - } - public void setValue(char value) { - getPointer().setChar(0, value); -// switch (Native.WCHAR_SIZE) { -// case 1: -// case 2: -// case 4: -// getPointer().setInt(0, value); -// break; -// default: -// throw new UnsupportedOperationException("Unhandled CGFloat size : " + CGFloat.SIZE); -// } - } - public char getValue() { - return getPointer().getChar(0); - } - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/FastCall.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/FastCall.java deleted file mode 100644 index 7d723fb2b..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/FastCall.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.PARAMETER}) -public @interface FastCall {} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/JNAeratorRuntime.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/JNAeratorRuntime.java deleted file mode 100644 index 9840f4e4f..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/JNAeratorRuntime.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -public class JNAeratorRuntime {} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/LibraryExtractor.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/LibraryExtractor.java deleted file mode 100644 index 2ae02aef3..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/LibraryExtractor.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.ochafik.net.URLUtils; -import com.sun.jna.Platform; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -/** - * @see SoyLatte: Java 6 Port for Mac OS X - * @author ochafik - * - */ -public class LibraryExtractor { - static { - if (Platform.isWindows()) { - String path = System.getProperty("java.library.path"); - String winPath = "c:\\Windows\\" + (Platform.is64Bit() ? "SysWOW64" : "System32"); - if (path == null) - path = winPath; - else - path = path + ";" + winPath; - System.setProperty("java.library.path", path); - } - } - public static String getCurrentOSAndArchString() { - String os = System.getProperty("os.name"), arch = System.getProperty("os.arch"); - - if (os.equals("Mac OS X")) { - os = "darwin"; - arch = "fat"; - //arch = Platform.is64Bit() ? "64" : "32"; - } else if (os.startsWith("Windows")) { - return "win" + (Platform.is64Bit() ? "64" : "32"); - } else if (os.matches("SunOS|Solaris")) - os = "solaris"; - - return os + "-" + arch; - } - public static String getLibraryPath(String libraryName, boolean extractAllLibraries, Class cl) { - try { - String customPath = System.getProperty("library." + libraryName); - if (customPath == null) - customPath = System.getenv(libraryName.toUpperCase() + "_LIBRARY"); - if (customPath != null) { - File f = new File(customPath); - if (!f.exists()) - System.err.println("Library file '" + customPath + "' does not exist !"); - else - return f.getAbsolutePath(); - } - //ClassLoader cl = LibraryExtractor.class.getClassLoader(); - String prefix = "(?i)" + (Platform.isWindows() || Platform.isWindowsCE() ? "" : "lib") + libraryName + "[^A-Za-z_].*"; - String libsuffix = "(?i).*\\.(so|dll|dylib|jnilib)"; - //String othersuffix = "(?i).*\\.(pdb)"; - - URL sourceURL = null; - List otherURLs = new ArrayList(); - - - String arch = getCurrentOSAndArchString(); - //System.out.println("libURL = " + libURL); - List list = URLUtils.listFiles(URLUtils.getResource(cl, "libraries/" + arch), null), - noArchList = URLUtils.listFiles(URLUtils.getResource(cl, "libraries/noarch"), null); - - Set names = new HashSet(); - for (URL url : list) { - String name = getFileName(url); - names.add(name); - } - for (URL url : noArchList) { - String name = getFileName(url); - if (names.add(name)) - list.add(url); - } - /*if (list.isEmpty()) { - for (URL u : URLUtils.listFiles(URLUtils.getResource(cl, "libraries"), null)) { - String f = u.getFile(); - int i = f.lastIndexOf('/'); - if (i >= 0) - f = f.substring(i + 1); - if (arch.startsWith(f)) { - list = URLUtils.listFiles(u, null); - break; - } - } - - }*/ - for (File f : new File(".").listFiles()) - if (f.isFile()) - list.add(f.toURI().toURL()); - - for (URL url : list) { - String name = getFileName(url); - boolean pref = name.matches(prefix), suff = name.matches(libsuffix); - if (pref && suff) - sourceURL = url; - else //if (suff || fileName.matches(othersuffix)) - otherURLs.add(url); - } - List files = new ArrayList(); - if (extractAllLibraries) { - for (URL url : otherURLs) - files.add(extract(url)); - } - - if (System.getProperty("javawebstart.version") != null) { - if (Platform.isWindows()) { - //File f = new File("c:\\Windows\\" + (Platform.is64Bit() ? "SysWOW64\\" : "System32\\") + libraryName + ".dll"); - File f = new File("c:\\Windows\\" + "System32\\" + libraryName + ".dll"); - if (f.exists()) - return f.toString(); - } else if (Platform.isMac()) { - File f = new File("/System/Library/Frameworks/" + libraryName + ".framework/" + libraryName); - if (f.exists()) - return f.toString(); - } - } - - - if (sourceURL == null) - return libraryName; - else { - File file = extract(sourceURL); - files.add(file); - - int lastSize; - do { - lastSize = files.size(); - for (Iterator it = files.iterator(); it.hasNext();) { - File f = it.next(); - if (!f.getName().matches(libsuffix)) - continue; - - try { - System.load(f.toString()); - it.remove(); - } catch (Throwable ex) { - System.err.println("Loading " + f.getName() + " failed (" + ex + ")"); - } - } - } while (files.size() < lastSize); - - return file.getCanonicalPath(); - } - } catch (Throwable ex) { - System.err.println("ERROR: Failed to extract library " + libraryName); - ex.printStackTrace(); - return libraryName; - } - } - private static File extract(URL url) throws IOException { - File localFile; - if ("file".equals(url.getProtocol())) - localFile = new File(URLDecoder.decode(url.getFile(), "UTF-8")); - else { - File f = new File(System.getProperty("user.home")); - f = new File(f, ".jnaerator"); - f = new File(f, "extractedLibraries"); - if (!f.exists()) - f.mkdirs(); - - localFile = new File(f, new File(url.getFile()).getName()); - URLConnection c = url.openConnection(); - if (localFile.exists() && localFile.lastModified() > c.getLastModified()) { - c.getInputStream().close(); - } else { - System.out.println("Extracting " + url); - InputStream in = c.getInputStream(); - OutputStream out = new FileOutputStream(localFile); - int len; - byte[] b = new byte[1024]; - while ((len = in.read(b)) > 0) - out.write(b, 0, len); - out.close(); - in.close(); - } - } - return localFile; - } - public static void loadLibrary(String libraryName, boolean extractAllLibraries, Class cl) { - System.loadLibrary(getLibraryPath(libraryName, extractAllLibraries, cl)); - } - - public static boolean shouldTraceCalls(String libraryName) { - return "true".equals(System.getProperty("jna.traceCalls")) || "true".equals(System.getProperty(libraryName.toLowerCase() + ".traceCalls")); - } - public static final Object getTracingLibrary(final Object original, Class libraryClass) { - try { - final String pref = "[" + libraryClass.getSimpleName() + "]"; - InvocationHandler handler = new InvocationHandler() { - - //@Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - StringBuilder b = new StringBuilder(pref); - b.append(method.getDeclaringClass().getName() + "." + method.getName() + "("); - - for (int i = 0; i < args.length; i++) { - Object arg = args[i]; - if (i != 0) - b.append(", "); - b.append(toString(arg)); - } - b.append(")"); - System.err.print(b); - Object ret = method.invoke(original, args); - if (method.getReturnType().equals(Void.class)) - return null; - - System.err.println(" => " + toString(ret)); - return ret; - } - - String toString(Object arg) { - if (arg instanceof Object[]) - return Arrays.toString((Object[])arg); - else - return String.valueOf(arg); - } - - }; - Class proxyClass = Proxy.getProxyClass(libraryClass.getClassLoader(), libraryClass); - return proxyClass.getConstructor(InvocationHandler.class).newInstance(handler); - } catch (Exception ex) { - throw new RuntimeException("Failed to create trace library"); - } - } - public static final Object getLibrary(String name, String path, final Class libraryClass) { - Object original = com.sun.jna.Native.loadLibrary(path, libraryClass, MangledFunctionMapper.DEFAULT_OPTIONS); - return shouldTraceCalls(name) ? - LibraryExtractor.getTracingLibrary(original, libraryClass) : original; - } - - private static String getFileName(URL url) { - return new File(url.getFile()).getName(); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/MangledFunctionMapper.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/MangledFunctionMapper.java deleted file mode 100644 index 9dcea44f7..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/MangledFunctionMapper.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.sun.jna.FunctionMapper; -import com.sun.jna.Library; -import com.sun.jna.NativeLibrary; -import com.sun.jna.win32.StdCallFunctionMapper; - -public class MangledFunctionMapper implements FunctionMapper { - public static final Map DEFAULT_OPTIONS; - static { - Map m = new HashMap(); - m.put(Library.OPTION_FUNCTION_MAPPER, new MangledFunctionMapper( - new StdCallFunctionMapper() - )); - - DEFAULT_OPTIONS = Collections.unmodifiableMap(m); - } - public List linked = new ArrayList(); - public MangledFunctionMapper(FunctionMapper... linked ) { - this.linked.addAll(Arrays.asList(linked)); - } - public String getFunctionName(NativeLibrary library, Method method) { - Mangling name = method.getAnnotation(Mangling.class); - if (name != null) { - for (String n : name.value()) { - try { - if (library.getGlobalVariableAddress(n) != null) - return n; - if (n.startsWith("_")) { - n = n.substring(1); - if (library.getGlobalVariableAddress(n) != null) - return n; - } - } catch (Throwable ex) { - ex = null; - } - } - } - if (linked != null) - for (FunctionMapper fm : linked) { - String n = fm.getFunctionName(library, method); - if (n != null && library.getGlobalVariableAddress(n) != null) - return n; - } - return method.getName(); - } - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Mangling.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Mangling.java deleted file mode 100644 index b3b7c1de2..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Mangling.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.PARAMETER}) -public @interface Mangling { - String[] value(); -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSize.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSize.java deleted file mode 100644 index 3a1b53b56..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSize.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.IntegerType; -import com.sun.jna.Native; - -/** - * 'size_t' C type (32 bits on 32 bits platforms, 64 bits on 64 bits platforms). - * Can be also used to model the 'long' C type for libraries known to be compiled with GCC or LLVM even on Windows. - * (NativeLong on Windows is only okay with MSVC++ libraries, as 'long' on Windows 64 bits will be 32 bits with MSVC++ and 64 bits with GCC/mingw) - * @author ochafik - */ -public class NativeSize extends IntegerType { - /** - * - */ - private static final long serialVersionUID = 2398288011955445078L; - /** Size of a size_t integer, in bytes. */ - public static int SIZE = Native.SIZE_T_SIZE;//Platform.is64Bit() ? 8 : 4; - - /** Create a zero-valued Size. */ - public NativeSize() { - this(0); - } - - /** Create a Size with the given value. */ - public NativeSize(long value) { - super(SIZE, value); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSizeByReference.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSizeByReference.java deleted file mode 100644 index 567e6edc9..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/NativeSizeByReference.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.ptr.ByReference; - -public class NativeSizeByReference extends ByReference { - public NativeSizeByReference() { - this(new NativeSize(0)); - } - - public NativeSizeByReference(NativeSize value) { - super(NativeSize.SIZE); - setValue(value); - } - - public void setValue(NativeSize value) { - if (NativeSize.SIZE == 4) - getPointer().setInt(0, value.intValue()); - else if (NativeSize.SIZE == 8) - getPointer().setLong(0, value.longValue()); - else - throw new RuntimeException("GCCLong has to be either 4 or 8 bytes."); - } - - public NativeSize getValue() { - if (NativeSize.SIZE == 4) - return new NativeSize(getPointer().getInt(0)); - else if (NativeSize.SIZE == 8) - return new NativeSize(getPointer().getLong(0)); - else - throw new RuntimeException("GCCLong has to be either 4 or 8 bytes."); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ScalaRuntime.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ScalaRuntime.java deleted file mode 100644 index 595dde47e..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ScalaRuntime.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -/* -include com/ochafik/lang/jnaerator/runtime/scala/*.scala -include com/ochafik/lang/jnaerator/runtime/scala/*.scala.part -*/ -public class ScalaRuntime { - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StringPointer.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StringPointer.java deleted file mode 100644 index 87f497d9e..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StringPointer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.Pointer; -import com.sun.jna.PointerType; - -@Deprecated -public class StringPointer extends Structure { - public String value; - public String toString() { - return value; - } - public StringPointer() {} - public StringPointer(PointerType p) { - this(p.getPointer(), 0); - } - public StringPointer(Pointer p) { - this(p, 0); - } - public StringPointer(Pointer p, int offset) { - useMemory(p, offset); - read(); - } - public StringPointer(String value) { - super(); - this.value = value; - } - public static class ByValue extends StringPointer implements com.sun.jna.Structure.ByValue {} - public static class ByReference extends StringPointer implements com.sun.jna.Structure.ByReference {} - @Override - protected ByReference newByReference() { - return new ByReference(); - } - @Override - protected ByValue newByValue() { - return new ByValue(); - } - @Override - protected StringPointer newInstance() { - return new StringPointer(); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Structure.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Structure.java deleted file mode 100644 index 36dcfb1bc..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Structure.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.nio.Buffer; - -import com.sun.jna.Memory; -import com.sun.jna.Native; -import com.sun.jna.Pointer; - -public abstract class Structure, V extends S, R extends S> - extends com.sun.jna.Structure - implements - Comparable>, - StructureType, - StructureTypeDependent -{ - public interface ByReference extends com.sun.jna.Structure.ByReference, StructureTypeDependent {} - public interface ByValue extends com.sun.jna.Structure.ByValue, StructureTypeDependent {} - - transient WeakReference dependency; - //@Override - public void setDependency(StructureType type) { - this.dependency = type == null ? null : new WeakReference(type); - } - protected void readDependency() { - StructureType dep; - if (dependency == null || (dep = dependency.get()) == null) - return; - dep.read(); - } - - @Override - public void read() { - super.read(); - readDependency(); - } - @Override - public void write() { - super.write(); - readDependency(); - } - - protected > T setupClone(T clone, StructureType dependency) { - write(); - clone.use(getPointer()); - clone.setDependency(this); - return clone; - } - - //getFieldOffset(String fieldName); - - protected abstract S newInstance(); - protected abstract V newByValue(); - protected abstract R newByReference(); - - public R byReference() { return setupClone(newByReference(), this); } - public V byValue() { return setupClone(newByValue(), this); } - public S clone() { return setupClone(newInstance(), this); } - - @SuppressWarnings("unchecked") - public static - S[] newArray(Class structClass, int arrayLength) { - try { - S first = structClass.newInstance(); - int sz = first.size(); - Memory mem = new Memory(arrayLength * sz); - first.use(mem); - S[] array = (S[])first.castToArray(arrayLength); - for (int i = 1; i < arrayLength; i++) { - S s = structClass.newInstance(); - s.use(mem, i * sz); - array[i] = s; - } - return array; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - @Override - public S[] toArray(int size) { - return (S[])super.toArray(size); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - public S[] toArray() { - return toArray(1); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - public R[] toReferenceArray(int size) { - return (R[])byReference().toArray(size); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - public V[] toValueArray(int size) { - return (V[])byValue().toArray(size); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - public R[] toReferenceArray() { - return toReferenceArray(1); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - public V[] toValueArray() { - return toValueArray(1); - } - - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - @Override - public S[] toArray(com.sun.jna.Structure[] array) { - return (S[])super.toArray(array); - } - - @SuppressWarnings("unchecked") - public S[] castToArray(int size) { - return (S[])super.toArray(size); - } - public S[] castToArray() { - return castToArray(1); - } - @SuppressWarnings({ "unchecked", "deprecation" }) - public R[] castToReferenceArray(int size) { - return (R[])byReference().toArray(size); - } - @SuppressWarnings({ "unchecked", "deprecation" }) - public V[] castToValueArray(int size) { - return (V[])byValue().toArray(size); - } - public R[] castToReferenceArray() { - return castToReferenceArray(1); - } - public V[] castToValueArray() { - return castToValueArray(1); - } - @SuppressWarnings("unchecked") - public S[] castToArray(com.sun.jna.Structure[] array) { - return (S[])super.toArray(array); - } - - - //@Override - protected Integer getBitsAnnotation(Field field) { - Bits bits = field.getAnnotation(Bits.class); - return bits == null ? null : bits.value(); - } - /** Simply does a memcmp between the two memory blocks of the two structures - */ - //@Override - public int compareTo(Structure o) { - if (o == this) - return 0; - if (!(o instanceof Structure)) - return 1; - - int size = size(); - int d = size - ((Structure)o).size(); - if (d != 0) - return d; - - Structure s = (Structure)o; - if (getPointer().equals(s.getPointer())) - return 0; - - write(); - s.write(); - - byte[] bytes1 = getPointer().getByteArray(0, size); - byte[] bytes2 = s.getPointer().getByteArray(0, size); - - for (int i = 0; i < size; i++) { - byte b1 = bytes1[i], b2 = bytes2[i]; - if (b1 != b2) - return b1 < b2 ? -1 : 1; - } - return 0; - } - - protected > T setupClone(T clone) { - write(); - clone.use(getPointer()); - return clone; - } - - public S use(Pointer m) { - return use(m, 0); - } - @SuppressWarnings("unchecked") - public S use(Pointer m, long byteOffset) { - useMemory(m, (int)byteOffset); - read(); - return (S)this; - } - public S use(Buffer m) { - return use(m, 0); - } - @SuppressWarnings("unchecked") - public S use(Buffer b, long byteOffset) { - useMemory(Native.getDirectBufferPointer(b), (int)byteOffset); - return (S)this; - } - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureType.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureType.java deleted file mode 100644 index 2a5e69502..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureType.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.Pointer; - -public interface StructureType { - int size(); - StructureType use(Pointer p); - Pointer getPointer(); - void read(); - void write(); -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureTypeDependent.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureTypeDependent.java deleted file mode 100644 index a12f8a815..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/StructureTypeDependent.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -public interface StructureTypeDependent { - void setDependency(StructureType type); -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/This.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/This.java deleted file mode 100644 index c3b998938..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/This.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.PARAMETER}) -public @interface This { - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ThisCall.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ThisCall.java deleted file mode 100644 index b0e6738f0..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/ThisCall.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.PARAMETER}) -public @interface ThisCall {} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Union.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Union.java deleted file mode 100644 index 80773159c..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/Union.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.Memory; -import java.lang.ref.WeakReference; -import java.nio.Buffer; - -import com.sun.jna.Native; -import com.sun.jna.Pointer; - -public abstract class Union, V extends S, R extends S> - extends com.sun.jna.Union - implements - StructureType, - StructureTypeDependent -{ - public interface ByReference extends com.sun.jna.Union.ByReference, StructureTypeDependent {} - public interface ByValue extends com.sun.jna.Union.ByValue, StructureTypeDependent {} - - transient WeakReference dependency; - //@Override - public void setDependency(StructureType type) { - this.dependency = type == null ? null : new WeakReference(type); - } - protected void readDependency() { - StructureType dep; - if (dependency == null || (dep = dependency.get()) == null) - return; - dep.read(); - } - @Override - public void read() { - super.read(); - readDependency(); - } - @Override - public void write() { - super.write(); - readDependency(); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - @Override - public S[] toArray(int size) { - return (S[])super.toArray(size); - } - /** - * @deprecated use castToArray instead - */ - @Deprecated - public S[] toArray() { - return toArray(1); - } - - /** - * @deprecated use castToArray instead - */ - @Deprecated - @SuppressWarnings("unchecked") - @Override - public S[] toArray(com.sun.jna.Structure[] array) { - return (S[])super.toArray(array); - } - - @SuppressWarnings("unchecked") - public S[] castToArray(int size) { - return (S[])super.toArray(size); - } - public S[] castToArray() { - return castToArray(1); - } - @SuppressWarnings("unchecked") - public S[] castToArray(com.sun.jna.Structure[] array) { - return (S[])super.toArray(array); - } - - - @SuppressWarnings("unchecked") - public static - S[] newArray(Class structClass, int arrayLength) { - try { - S first = structClass.newInstance(); - int sz = first.size(); - Memory mem = new Memory(arrayLength * sz); - first.use(mem); - S[] array = (S[])first.castToArray(arrayLength); - for (int i = 1; i < arrayLength; i++) { - S s = structClass.newInstance(); - s.use(mem, i * sz); - array[i] = s; - } - return array; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - protected abstract S newInstance(); - protected abstract V newByValue(); - protected abstract R newByReference(); - - public R byReference() { return setupClone(newByReference()); } - public V byValue() { return setupClone(newByValue()); } - public S clone() { return setupClone(newInstance()); } - - protected > T setupClone(T clone) { - write(); - clone.use(getPointer()); - return clone; - } - - public S use(Pointer m) { - return use(m, 0); - } - @SuppressWarnings("unchecked") - public S use(Pointer m, long byteOffset) { - useMemory(m, (int)byteOffset); - return (S)this; - } - public S use(Buffer m) { - return use(m, 0); - } - @SuppressWarnings("unchecked") - public S use(Buffer b, long byteOffset) { - useMemory(Native.getDirectBufferPointer(b), (int)byteOffset); - return (S)this; - } - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/VirtualTablePointer.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/VirtualTablePointer.java deleted file mode 100644 index e72ad7748..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/VirtualTablePointer.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.PointerType; - -public class VirtualTablePointer extends PointerType { - -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/WStringPointer.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/WStringPointer.java deleted file mode 100644 index 9c419ec9a..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/WStringPointer.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import com.sun.jna.Pointer; -import com.sun.jna.PointerType; -import com.sun.jna.WString; - -@Deprecated -public class WStringPointer extends Structure { - public WString value; - public String toString() { - return value.toString(); - } - - public WStringPointer() {} - public WStringPointer(PointerType p) { - this(p.getPointer(), 0); - } - public WStringPointer(Pointer p) { - this(p, 0); - } - public WStringPointer(Pointer p, int offset) { - useMemory(p, offset); - read(); - } - public WStringPointer(WString value) { - super(); - this.value = value; - } - public WStringPointer(String value) { - super(); - this.value = new WString(value); - } - public static class ByValue extends WStringPointer implements com.sun.jna.Structure.ByValue {} - public static class ByReference extends WStringPointer implements com.sun.jna.Structure.ByReference {} - @Override - protected ByReference newByReference() { - return new ByReference(); - } - @Override - protected ByValue newByValue() { - return new ByValue(); - } - @Override - protected WStringPointer newInstance() { - return new WStringPointer(); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/Global.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/Global.java deleted file mode 100644 index 201b19164..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/Global.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.Pointer; - -public abstract class Global { - protected String[] symbols; - protected NativeLibrary library; - protected Pointer pointer; - public Global(NativeLibrary library, String... symbols) { - this.symbols = symbols; - this.library = library; - } - protected Pointer getPointer() { - if (pointer == null) - for (String symbol : symbols) - if ((pointer = library.getGlobalVariableAddress(symbol)) != null) - break; - return pointer; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalByte.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalByte.java deleted file mode 100644 index 60f07c18e..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalByte.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.ByteByReference; - -public class GlobalByte extends GlobalPrimitive { - public GlobalByte(NativeLibrary library, String... symbols) { - super(library, ByteByReference.class, symbols); - } - public byte get() { - return getValue().getValue(); - } - public void set(byte v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCallback.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCallback.java deleted file mode 100644 index 3395e778e..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalCallback.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.Callback; -import com.sun.jna.CallbackReferenceHack; -import com.sun.jna.NativeLibrary; - -public class GlobalCallback extends Global { - protected final Class type; - public GlobalCallback(NativeLibrary library, Class type, String... symbols) { - super(library, symbols); - this.type = type; - } - protected T value; - @SuppressWarnings("unchecked") - public T get() { - if (value == null) { - value = (T)CallbackReferenceHack.getCallback(type, getPointer()); - } - return value; - } - public void set(T value) { - getPointer().setPointer(0, CallbackReferenceHack.getFunctionPointer(this.value = value)); - } - - @Override - public String toString() { - try { - return String.valueOf(getClass().getMethod("get").invoke(this)); - } catch (Throwable t) { - return super.toString(); - } - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalChar.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalChar.java deleted file mode 100644 index f235e53e4..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalChar.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.ochafik.lang.jnaerator.runtime.CharByReference; -import com.sun.jna.NativeLibrary; - -public class GlobalChar extends GlobalPrimitive { - public GlobalChar(NativeLibrary library, String... symbols) { - super(library, CharByReference.class, symbols); - } - public char get() { - return getValue().getValue(); - } - public void set(char v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalDouble.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalDouble.java deleted file mode 100644 index 100ff0749..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalDouble.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.DoubleByReference; - -public class GlobalDouble extends GlobalPrimitive { - public GlobalDouble(NativeLibrary library, String... symbols) { - super(library, DoubleByReference.class, symbols); - } - public double get() { - return getValue().getValue(); - } - public void set(double v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalFloat.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalFloat.java deleted file mode 100644 index 41cc0ca72..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalFloat.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.FloatByReference; - -public class GlobalFloat extends GlobalPrimitive { - public GlobalFloat(NativeLibrary library, String... symbols) { - super(library, FloatByReference.class, symbols); - } - public float get() { - return getValue().getValue(); - } - public void set(float v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalInt.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalInt.java deleted file mode 100644 index 80b595f46..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalInt.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.IntByReference; - -public class GlobalInt extends GlobalPrimitive { - public GlobalInt(NativeLibrary library, String... symbols) { - super(library, IntByReference.class, symbols); - } - public int get() { - return getValue().getValue(); - } - public void set(int v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalLong.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalLong.java deleted file mode 100644 index d91915a90..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalLong.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.LongByReference; - -public class GlobalLong extends GlobalPrimitive { - public GlobalLong(NativeLibrary library, String... symbols) { - super(library, LongByReference.class, symbols); - } - public long get() { - return getValue().getValue(); - } - public void set(long v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeLong.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeLong.java deleted file mode 100644 index 6332f3048..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeLong.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.NativeLong; -import com.sun.jna.ptr.NativeLongByReference; - -public class GlobalNativeLong extends GlobalPrimitive { - public GlobalNativeLong(NativeLibrary library, String... symbols) { - super(library, NativeLongByReference.class, symbols); - } - public NativeLong get() { - return getValue().getValue(); - } - public void set(int v) { - getValue().setValue(new NativeLong(v)); - } - public void set(long v) { - getValue().setValue(new NativeLong(v)); - } - public void set(NativeLong v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeSize.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeSize.java deleted file mode 100644 index 53c1b67cb..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeSize.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.sun.jna.NativeLibrary; - -public class GlobalNativeSize extends GlobalPrimitive { - public GlobalNativeSize(NativeLibrary library, String... symbols) { - super(library, NativeSizeByReference.class, symbols); - } - public NativeSize get() { - return getValue().getValue(); - } - public void set(int v) { - getValue().setValue(new NativeSize(v)); - } - public void set(long v) { - getValue().setValue(new NativeSize(v)); - } - public void set(NativeSize v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointer.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointer.java deleted file mode 100644 index 023354221..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.PointerByReference; - -public class GlobalPointer extends GlobalPrimitive { - public GlobalPointer(NativeLibrary library, String... symbols) { - super(library, PointerByReference.class, symbols); - } - public Pointer get() { - return getValue().getValue(); - } - public void set(Pointer v) { - getValue().setValue(v); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointerType.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointerType.java deleted file mode 100644 index eee1cdd4b..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPointerType.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.PointerType; - -public class GlobalPointerType extends GlobalPrimitive { - public GlobalPointerType(NativeLibrary library, Class type, String... symbols) { - super(library, type, symbols); - indirected = true; - } - - public T get() { - return getValue(); - } - public void set(T value) { - this.value = value; - getPointer().setPointer(0, value.getPointer()); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPrimitive.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPrimitive.java deleted file mode 100644 index e45c3723d..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalPrimitive.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.ochafik.util.string.StringUtils; -import com.sun.jna.NativeLibrary; -import com.sun.jna.Pointer; -import com.sun.jna.PointerType; - -public abstract class GlobalPrimitive extends Global { - protected final Class type; - protected boolean indirected = false; - public GlobalPrimitive(NativeLibrary library, Class type, String... symbols) { - super(library, symbols); - this.type = type; - } - protected T value; - protected T getValue() { - if (value == null) { - try { - value = type.newInstance(); - } catch (Exception e) { - throw new RuntimeException("Failed to instantiate pointer to " + StringUtils.implode(symbols, "/"), e); - } - Pointer pointer = getPointer(); - if (indirected) { - pointer = pointer.getPointer(0); - } - value.setPointer(pointer); - } - return value; - } - @Override - public String toString() { - try { - return String.valueOf(getClass().getMethod("get").invoke(this)); - } catch (Throwable t) { - return super.toString(); - } - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalShort.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalShort.java deleted file mode 100644 index 555b9b8d8..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalShort.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.sun.jna.NativeLibrary; -import com.sun.jna.ptr.ShortByReference; - -public class GlobalShort extends GlobalPrimitive { - public GlobalShort(NativeLibrary library, String... symbols) { - super(library, ShortByReference.class, symbols); - } - public short get() { - return getValue().getValue(); - } - public void set(short v) { - getValue().setValue(v); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalStruct.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalStruct.java deleted file mode 100644 index a6cc88f88..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalStruct.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime.globals; - -import com.ochafik.lang.jnaerator.runtime.Structure; -import com.sun.jna.NativeLibrary; -import com.sun.jna.Pointer; - -public class GlobalStruct> extends Global { - S value; - Class valueClass; - public GlobalStruct(NativeLibrary library, Class valueClass, String... symbols) { - super(library, symbols); - this.valueClass = valueClass; - } - public S get() { - if (value == null) { - value = newInstance(); - Pointer p = getPointer(); - if (!isByValue()) - p = p.getPointer(0); - value.use(p); - } - value.read(); - return value; - } - protected S newInstance() { - try { - return valueClass.newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - public void set(S value) { - if (isByValue()) { - Pointer p = getPointer(); - int s = value.size(); - p.write(0, value.getPointer().getByteArray(0, s), 0, s); - get(); - } else { - this.value = value; - getPointer().setPointer(0, value.getPointer()); - } - } - protected boolean isByValue() { - return com.sun.jna.Structure.ByValue.class.isAssignableFrom(valueClass); - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/net/URLUtils.java b/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/net/URLUtils.java deleted file mode 100644 index ce69ec72c..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/java/com/ochafik/net/URLUtils.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ochafik.net; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; - -import com.ochafik.util.listenable.Filter; - -public class URLUtils { - - public static URL getResource(Class cl, String path) throws IOException { - String clp = cl.getName().replace('.', '/') + ".class"; - URL clu = cl.getClassLoader().getResource(clp); - String s = clu.toString(); - if (s.endsWith(clp)) - return new URL(s.substring(0, s.length() - clp.length()) + path); - - if (s.startsWith("jar:")) { - String[] ss = s.split("!"); - return new URL(ss[1] + "!/" + path); - } - return null; - } - - public static List listFiles(URL directory, Filter pathAccepter) throws IOException { - List ret = new ArrayList(); - String s = directory.toString(); - if (s.startsWith("jar:")) { - String[] ss = s.substring("jar:".length()).split("!"); - String path = ss[1]; - URL target = new URL(ss[0]); - InputStream tin = target.openStream(); - try { - JarInputStream jin = new JarInputStream(tin); - JarEntry je; - while ((je = jin.getNextJarEntry()) != null) { - String p = "/" + je.getName(); - if (p.startsWith(path) && p.indexOf('/', path.length() + 1) < 0) - if (pathAccepter == null || pathAccepter.accept(path)) - ret.add(new URL("jar:" + target + "!" + p)); - } - } finally { - tin.close(); - } - } else if (s.startsWith("file:")) { - File f = new File(directory.getFile()); - File[] ffs = f.listFiles(); - if (ffs != null) - for (File ff : ffs) - if (pathAccepter == null || pathAccepter.accept(ff.toString())) - ret.add(ff.toURI().toURL()); - } else - throw new IOException("Cannot list contents of " + directory); - - return ret; - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNA.jnlp b/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNA.jnlp deleted file mode 100644 index 2fbc98695..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNA.jnlp +++ /dev/null @@ -1,22 +0,0 @@ - - - - JNA - JNA - - Java Native Access Library - - - - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNAeratorRuntime.jnlp b/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNAeratorRuntime.jnlp deleted file mode 100644 index e51d9b23c..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/JNAeratorRuntime.jnlp +++ /dev/null @@ -1,23 +0,0 @@ - - - - JNAerator Runtime - Olivier Chafik - - JNAerated libraries runtime support classes - JNAerated libraries runtime support classes - - - - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/jnidispatch.jnlp b/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/jnidispatch.jnlp deleted file mode 100644 index 0561bbc83..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/jnlp/jnidispatch.jnlp +++ /dev/null @@ -1,60 +0,0 @@ - - - - JNA's jnidispatch library - JNA - - JNA's jnidispatch library - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaJNA.scala.part b/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaJNA.scala.part deleted file mode 100644 index e129859c0..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaJNA.scala.part +++ /dev/null @@ -1,10 +0,0 @@ - -trait ScalaJNA { - import com.sun.jna._; - import com.sun.jna.ptr._; - - implicit def Long2NativeLong(v: Long) = { new NativeLong(v); } - implicit def Int2NativeLong(v: Int) = { new NativeLong(v); } - implicit def NativeLong2Long(v: NativeLong) = { v.longValue() } - implicit def NativeLong2Int(v: NativeLong) = { v.intValue() } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaRococoa.scala.part b/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaRococoa.scala.part deleted file mode 100644 index 0c460b26b..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/main/resources/com/ochafik/lang/jnaerator/runtime/scala/ScalaRococoa.scala.part +++ /dev/null @@ -1,12 +0,0 @@ - -trait ScalaRococoa { - import org.rococoa._; - import org.rococoa.cocoa._; - - implicit def Float2CGFloat(v: Float) = { new CGFloat(v) } - implicit def Double2CGFloat(v: Double) = { new CGFloat(v) } - - - implicit def CGFloat2Float(v: CGFloat) = { v.floatValue() } - implicit def CGFloat2Double(v: CGFloat) = { v.doubleValue() } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/RuntimeTest.java b/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/RuntimeTest.java deleted file mode 100644 index f84659b33..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/RuntimeTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.ochafik.lang.jnaerator.runtime; - -import java.lang.reflect.Field; -import java.util.Random; - -import org.junit.Assert; -import org.junit.Test; - -import com.sun.jna.Pointer; -import com.sun.jna.WString; - -public class RuntimeTest { - public static class BitFieldStruct extends com.sun.jna.Structure { - //@Override - protected Integer getBitsAnnotation(Field field) { - Bits bits = field.getAnnotation(Bits.class); - return bits == null ? null : bits.value(); - } - } - public static class TestStruct extends BitFieldStruct { - @Bits(1) public int i0; - @Bits(1) public int i1; - public short s; - @Bits(3) public int i2; - @Bits(1) public int i3; - - - public TestStruct() { super(); } - public TestStruct(Pointer p) { - super(); - useMemory(p); - } - } - public static class DummyStruct extends BitFieldStruct { - public int i; - public long l; - public short s; - public byte b; - public char c; - public boolean z; - public Pointer p; - public String str; - public WString wstr; - public int[] ii = new int[10]; - - } - @Test - public void dummyStruct() { - DummyStruct ds = new DummyStruct(); - ds.write(); - ds.read(); - - } - @Test - public void testSimpleBitField() { - TestStruct s = new TestStruct(); - s.i0 = 3; - s.s = -1; - s.i2 = -1; - s.write(); - s = new TestStruct(s.getPointer()); - s.read(); - - Assert.assertEquals(1, s.i0); // 3 & 1 - Assert.assertEquals(0, s.i1); - Assert.assertEquals(-1, s.s); - Assert.assertEquals(7, s.i2); // -1 & (1 << 3) - Assert.assertEquals(0, s.i3); - } - - public static class FloatBitOffset extends BitFieldStruct { - @Bits(5) - public int i; - public float f; - public int j; - public FloatBitOffset() { super(); } - public FloatBitOffset(Pointer p) { - super(); - useMemory(p); - } - } - @Test - public void testFloatOffsetBitField() { - FloatBitOffset s = new FloatBitOffset(); - s.i = 27; - s.f = (float)Math.PI; - s.j = -535131351; - - s.write(); - s = new FloatBitOffset(s.getPointer()); - s.read(); - - Assert.assertEquals(27, s.i); - Assert.assertEquals((float)Math.PI, s.f, 0); - Assert.assertEquals(-535131351, s.j); - } - - public static class BigBitOffset extends BitFieldStruct { - @Bits(31) - public int i; - @Bits(63) - public long l; - public int end; - public BigBitOffset() { super(); } - public BigBitOffset(Pointer p) { - super(); - useMemory(p); - } - } - Random random = new Random(System.currentTimeMillis()); - @Test - public void testBigBitField() { - for (int i = 5; i-- != 0;) { - long randl = random.nextLong(); - BigBitOffset s = new BigBitOffset(); - s.i = -1; - s.l = randl; - s.end = 8; - - s.write(); - s = new BigBitOffset(s.getPointer()); - s.read(); - -// long initRandl = randl; -// long rr = (initRandl << 1) >> 1; - randl = randl & ~(1L << 63); - Assert.assertEquals(Integer.MAX_VALUE, s.i); - Assert.assertEquals(randl, s.l); - Assert.assertEquals(8, s.end); - } - } - - - - public static class BitOffsetPointer extends BitFieldStruct { - @Bits(3) - public int i; - public Pointer p; - public int end; - public BitOffsetPointer() { super(); } - public BitOffsetPointer(Pointer p) { - super(); - useMemory(p); - } - } - - @Test - public void testBitOffsetPointer() { - Pointer pconstant = Pointer.createConstant(10); - for (int i = 5; i-- != 0;) { - BitOffsetPointer s = new BitOffsetPointer(); - s.i = -1; - s.p = pconstant; - s.end = 8; - - s.write(); - s = new BitOffsetPointer(s.getPointer()); - s.read(); - - Assert.assertEquals(pconstant, s.p); - Assert.assertEquals(7, s.i); - Assert.assertEquals(8, s.end); - } - } - public static class PaddingTest extends BitFieldStruct { - @Bits(1) - public int i; - public int afterFields; - public PaddingTest() { - super(); - } - public PaddingTest(Pointer p) { - super(); - useMemory(p); - } - } - @Test - public void testPaddingAfterBitFields() { - PaddingTest t = new PaddingTest(); - t.i = 15; - t.afterFields = 3; - t.write(); - - PaddingTest o = new PaddingTest(t.getPointer()); - o.read(); - Assert.assertEquals(1, o.i); - Assert.assertEquals(t.afterFields, o.afterFields); - Assert.assertEquals(t.afterFields, t.getPointer().getInt(4)); - - } -} diff --git a/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/StructureTest.java b/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/StructureTest.java deleted file mode 100644 index b92471d5c..000000000 --- a/libraries/jnaerator/jnaerator-runtime/src/test/java/com/ochafik/lang/jnaerator/runtime/StructureTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.runtime; - -import org.junit.*; -//import com.sun.jna.*; - -import static org.junit.Assert.*; - -public class StructureTest { - public static class TestStruct extends Structure { - public int value; - public TestStruct() { - super(); - } - public TestStruct(int value) { - super(); - this.value = value; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected TestStruct newInstance() { return new TestStruct(); } - public static TestStruct[] newArray(int arrayLength) { - return Structure.newArray(TestStruct.class, arrayLength); - } - public static class ByReference extends TestStruct implements Structure.ByReference { - - }; - public static class ByValue extends TestStruct implements Structure.ByValue { - - }; - }; - - - /// See http://code.google.com/p/jnaerator/issues/detail?id=56 - @Test - public void testByRefClone() { - TestStruct s = new TestStruct(); - s.value = 10; - - TestStruct.ByReference r = s.byReference(); - r.autoWrite(); - - assertEquals(s.value, r.value); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/.classpath b/libraries/jnaerator/jnaerator/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/jnaerator/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/jnaerator/.gitignore b/libraries/jnaerator/jnaerator/.gitignore deleted file mode 100644 index 155273cb3..000000000 --- a/libraries/jnaerator/jnaerator/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target -project/boot -project/target -*~ -test/* diff --git a/libraries/jnaerator/jnaerator/.project b/libraries/jnaerator/jnaerator/.project deleted file mode 100644 index cc57fa649..000000000 --- a/libraries/jnaerator/jnaerator/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - jnaerator - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/jnaerator/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/jnaerator/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bf858f543..000000000 --- a/libraries/jnaerator/jnaerator/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:16 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/jnaerator/jnaerator/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/jnaerator/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/jnaerator/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/jnaerator/nbactions.xml b/libraries/jnaerator/jnaerator/nbactions.xml deleted file mode 100644 index e68dd1bb0..000000000 --- a/libraries/jnaerator/jnaerator/nbactions.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - run - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.2:exec - - - runtime - -Xmx1g -classpath %classpath ${packageClassName} - java - - - - debug - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.2:exec - - - runtime - -Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -Xmx1g -classpath %classpath ${packageClassName} - true - java - - - - profile - - process-classes - org.codehaus.mojo:exec-maven-plugin:1.1.1:exec - - - ${profiler.args} -Xmx1g -classpath %classpath ${packageClassName} - profile - ${profiler.java} - - - diff --git a/libraries/jnaerator/jnaerator/pom.xml b/libraries/jnaerator/jnaerator/pom.xml deleted file mode 100644 index 30952cfaf..000000000 --- a/libraries/jnaerator/jnaerator/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - jnaerator - JNAerator CLI and Studio Tools - http://code.google.com/p/jnaerator/ - jar - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - true - com.ochafik.lang.jnaerator.JNAerator - - - -JNAerator (pronounce "generator") simply parses C and Objective-C headers and generates the corresponding JNA and Rococoa Java interfaces (it also has a very limited support for C++). - -This lets Java programmers access native libraries transparently, with full IDE support and little to no hand-tweaking. - -Users who are looking for ready-to-use libraries should check the NativeLibs4Java project instead. - - - - - jna-users - users@jna.dev.java.net - https://jna.dev.java.net/servlets/SummarizeList?listName=users - - - - - - com.nativelibs4java - ochafik-swing - - - com.nativelibs4java - jnaerator-rococoa-runtime - - - com.nativelibs4java - bridj - - - com.nativelibs4java - jnaerator-parser - - - com.nativelibs4java - anarres-jnaerator - - - org.eclipse.jdt.core.compiler - ecj - - - - - - - com.nativelibs4java - maven-velocity-plugin - - - org.apache.maven.plugins - maven-shade-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - diff --git a/libraries/jnaerator/jnaerator/runAntlr.cmd b/libraries/jnaerator/jnaerator/runAntlr.cmd deleted file mode 100644 index af6a62996..000000000 --- a/libraries/jnaerator/jnaerator/runAntlr.cmd +++ /dev/null @@ -1 +0,0 @@ -mvn org.antlr:antlr3-maven-plugin:antlr diff --git a/libraries/jnaerator/jnaerator/splitParsing.firstFailure.errors.txt b/libraries/jnaerator/jnaerator/splitParsing.firstFailure.errors.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/jnaerator/jnaerator/splitParsing.firstFailure.source.txt b/libraries/jnaerator/jnaerator/splitParsing.firstFailure.source.txt deleted file mode 100644 index 62ae143a8..000000000 --- a/libraries/jnaerator/jnaerator/splitParsing.firstFailure.source.txt +++ /dev/null @@ -1,4 +0,0 @@ - - - -char some_paper[30][30+1] diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Configuration.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Configuration.java deleted file mode 100644 index 42986f73d..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Configuration.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; - -import java.util.List; -import java.util.Set; - -public class Configuration { - public String name; - public List includes; - public Set preprocessorDefinitions; - public String outputFile; - public String outputDirectory; -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/FileConfiguration.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/FileConfiguration.java deleted file mode 100644 index 7f49036e8..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/FileConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - - -public class FileConfiguration { - public Map configurations = new HashMap(); - public File file; -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Project.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Project.java deleted file mode 100644 index d76b658ac..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Project.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; -import static com.ochafik.admin.visualstudio.VisualStudioUtils.*; - -import javax.xml.xpath.XPathExpressionException; - -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import com.ochafik.xml.XMLUtils; -import com.ochafik.xml.XPathUtils; - -public class Project implements Comparable { - public final Solution solution; - public File projectFile; - public String name, id; - public List depsIds = new ArrayList(); - public Map activeConfigurationNameBySolutionConfigurationName = new HashMap(); - - public Map configurations = new HashMap(); - public Map fileConfigurations = new HashMap(); - public List files = new ArrayList(); - - public Project(Solution solution, File projectFile, String name, String id) { - this.solution = solution; - this.projectFile = projectFile; - this.name = name; - this.id = id; - } - public int compareTo(Project o) { - return name.compareTo(o.name); - } - - String resolve(String s, Configuration configuration) { - String res = resolveVariables(s, solution, this, configuration); - return res == null || res.length() == 0 ? null : res; - } - - public String resolveStringByXPath(String xPathString, Object source, Configuration configuration) throws XPathExpressionException { - return resolve(XPathUtils.findStringByXPath(xPathString, source), configuration); - } - @SuppressWarnings("unchecked") - public List resolveListByXPath(String xPathString, Object source, String separatorPattern, Configuration configuration) throws XPathExpressionException { - String s = resolve(XPathUtils.findStringByXPath(xPathString, source), configuration); - return s == null ? Collections.EMPTY_LIST : Arrays.asList(s.split(separatorPattern)); - } - public TreeSet resolveSetByXPath(String xPathString, Object source, String separatorPattern, Configuration configuration) throws XPathExpressionException { - return new TreeSet(resolveListByXPath(xPathString, source, separatorPattern, configuration)); - } - - Configuration parseConfiguration(Node configNode) throws XPathExpressionException { - Configuration config = new Configuration(); - config.name = resolve(XPathUtils.findStringByXPath("@Name", configNode), config); - if (config.name == null) - return null; - - config.outputDirectory = resolve(XPathUtils.findStringByXPath("@OutputDirectory", configNode), config); - - Node compilerTool = XPathUtils.findNodeByXPath("Tool[@Name='VCCLCompilerTool']", configNode); - if (compilerTool != null) { - config.includes = resolveListByXPath("@AdditionalIncludeDirectories", compilerTool, ";", config); - config.preprocessorDefinitions = resolveSetByXPath("@PreprocessorDefinitions", compilerTool, ";", config); - } - config.outputFile = resolve(XPathUtils.findStringByXPath("Tool[@Name='VCLinkerTool']/@OutputFile", configNode), config); - /*if (config.outputFile == null) - config.outputFile = name + ".dll";*/ - - return config; - } - - public void parse(FileFilter fileFilter, boolean parseFileConfigurations, Solution solution) throws Exception { - if (!projectFile.exists() || !projectFile.isFile()) - throw new IOException("Cannot find project file " + projectFile); - - Document document = XMLUtils.readXML(projectFile); - File projectPath = projectFile.getParentFile(); - - for (Node configurationNode : XPathUtils.findNodesIterableByXPath("VisualStudioProject/Configurations/Configuration", document)) { - Configuration config = parseConfiguration(configurationNode); - if (config != null) - configurations.put(config.name, config); - } - for (Node fileNode : XPathUtils.findNodesIterableByXPath("//Files//File", document)) { - String relativePath = resolveStringByXPath("@RelativePath", fileNode, null); - if (relativePath == null) - continue; - - File file = relFile(projectPath, relativePath); - if (fileFilter != null && !fileFilter.accept(file)) - continue; - - files.add(file); - - if (parseFileConfigurations) { - FileConfiguration fileConfiguration = new FileConfiguration(); - fileConfiguration.file = file; - fileConfigurations.put(file, fileConfiguration); - for (Node fileConfigurationNode : XPathUtils.findNodesIterableByXPath("FileConfiguration", fileNode)) { - Configuration config = parseConfiguration(fileConfigurationNode); - if (config != null) - fileConfiguration.configurations.put(config.name, config); - } - } - } - } - - static File relFile(File base, String relPath) { - relPath = relPath.replace('\\', File.separatorChar).replace('/', File.separatorChar); - return new File(base, relPath); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Solution.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Solution.java deleted file mode 100644 index 9d635c308..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/Solution.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; - -import java.io.File; -import java.io.FileFilter; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Semaphore; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.ochafik.io.ReadText; - - -public class Solution { - private static final boolean verbose = true; - - public File solutionFile; - public Map idToProject; - public Set allFiles = new HashSet(10000); - - static Pattern solutionIdPattern = Pattern.compile("Project\\(\"\\{[^}]+\\}\"\\) = \"([^\"]+)\", \"([^\"]+)\", [^{]+\\{([^}]+)\\}\"" + - ".*?ProjectSection\\(ProjectDependencies\\)(.*?)EndProjectSection", Pattern.MULTILINE - ); - - static Pattern projectDependencyPattern = Pattern.compile("\\{[^}]+\\} = \\{([^}]+)\\}"); - - static Pattern projectConfigsForSolutionConfigPattern = Pattern.compile("^\\s*\\{([^}]+)\\}\\.([^\\.]+)\\.ActiveCfg\\s*=\\s*(.*)\\s*$"); - public Solution(File solutionFile) { - this.solutionFile = solutionFile; - } - public void parse() throws Exception { - if (idToProject == null) { - idToProject = new HashMap(); - - String solutionContent = ReadText.readText(solutionFile); - File solutionPath = solutionFile.getParentFile(); - - for (Matcher solutionIdMatcher = solutionIdPattern.matcher(solutionContent.replace('\n', ' ')); solutionIdMatcher.find();) { - Project p = new Project(this, relFile(solutionPath, solutionIdMatcher.group(2)), solutionIdMatcher.group(1), solutionIdMatcher.group(3)); - for (Matcher depM = projectDependencyPattern.matcher(solutionIdMatcher.group(4)); depM.find();) - p.depsIds.add(depM.group(1)); - idToProject.put(p.id, p); - } - - for (Matcher m = projectConfigsForSolutionConfigPattern.matcher(solutionContent); m.find();) { - String id = m.group(1), slnConfigName = m.group(2), projConfigName = m.group(3); - Project p = idToProject.get(id); - if (p == null) - continue; - - p.activeConfigurationNameBySolutionConfigurationName.put(slnConfigName, projConfigName); - } - } - } - - public String getName() { - return solutionFile == null ? null : solutionFile.getName().replaceAll("\\.[^.]+$", ""); - } - - public void parseProjects(final FileFilter fileFilter) throws Exception { - parse(); - int nThreads = Runtime.getRuntime().availableProcessors() * 2; - if (verbose) - System.out.println("Parsing Solution: " + solutionFile.getName() + " (" + nThreads + " threads)"); - - final Semaphore semaphore = new Semaphore(0); - final LinkedList projects = new LinkedList(idToProject.values()); - class Worker extends Thread { public void run() { - for (;;) { - try { - Project project = null; - synchronized (projects) { - if (projects.isEmpty()) - break; - - project = projects.removeLast(); - } - if (verbose) { - synchronized (System.out) { - System.out.println("Parsing Project: " + project.name); - } - } - - project.parse(fileFilter, false, Solution.this); - synchronized (allFiles) { - allFiles.addAll(project.files); - } - } catch (Exception ex) { - synchronized (System.err) { - ex.printStackTrace(System.err); - } - - } - } - semaphore.release(); - }}; - for (int i = nThreads; i-- != 0;) - new Worker().start(); - - semaphore.acquire(nThreads); - } - - static File relFile(File base, String relPath) { - relPath = relPath.replace('\\', File.separatorChar).replace('/', File.separatorChar); - return new File(base, relPath); - } - public Collection getProjects() { - return idToProject.values(); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioSolutionAndProjectsParser.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioSolutionAndProjectsParser.java deleted file mode 100644 index 22ba84382..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioSolutionAndProjectsParser.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; -import java.io.File; -import java.io.FileFilter; - -/* -java -cp ../classes com.ochafik.admin.visualstudio.VisualStudioSolutionAndProjectsParser "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\VSTest\VSTest.sln" - -java -cp ../classes;../libraries/antlr-runtime-3.1.jar;../libraries/trove.jar;../libraries/anarres-cpp.jar com.ochafik.lang.jnaerator.JNAerator -project "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\VSTest\VSTest.sln" "Release|Win32" -*/ - -public class VisualStudioSolutionAndProjectsParser { - static FileFilter headersFileFilter = new FileFilter() { public boolean accept(File f) { - String name = f.getName(); - return name.endsWith(".h") || name.endsWith(".hpp") || name.endsWith(".hxx"); - }}; - - public static void main(String[] args) { - try { - /*if (args.length == 0) { - args = new String[] { - "/Users/ochafik/Prog/Java/test/SlnAndVCProjs/sln/WholeRisque533.sln" - }; - }*/ - - long initTime = System.currentTimeMillis(); - File solutionFile = new File(args[0]); - - final Solution solution = new Solution(solutionFile); - - solution.parseProjects(headersFileFilter); - - System.out.println("Elapsed Time: " + (System.currentTimeMillis() - initTime) + " ms"); - System.out.println("Files Count: " + solution.allFiles.size()); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioUtils.java deleted file mode 100644 index 838a5a72b..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/admin/visualstudio/VisualStudioUtils.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.admin.visualstudio; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.string.RegexUtils; - -public class VisualStudioUtils { - private static Logger logger = Logger.getLogger(VisualStudioUtils.class.getName()); - - public static List getMicrosoftIncludes() { - return Arrays.asList(getProp("VISUAL_STUDIO_INCLUDES", - getMicrosoftVisualStudioHome() + "\\VC\\include" + ";" + getMicrosoftWindowsSDKHome() + "\\Include", - true - ).split(";")); - } - public static File getMicrosoftWindowsProgramFilesDirectory() { - String propName = com.sun.jna.Platform.is64Bit() ? "ProgramFiles(x86)" : "ProgramFiles"; - return new File(getProp(propName, "C:\\Program Files", true)); - } - public static String getMicrosoftWindowsSDKHome() { - return getProp("WINDOWS_SDK_HOME", new File(getMicrosoftWindowsProgramFilesDirectory(), "Microsoft SDKs\\Windows\\v6.0A").toString(), true); - } - private static String getMicrosoftVisualStudioHome() { - return getProp("VISUAL_STUDIO_HOME", new File(getMicrosoftWindowsProgramFilesDirectory(), "Microsoft Visual Studio 9.0").toString(), true); - } - static String getProp(String name, String defVal) { - return getProp(name, defVal, false); - } - - static String getProp(String name, String defVal, boolean remember) { - String v = System.getenv(name); - v = v == null ? System.getProperty(name, defVal) : v; - logger.log(Level.INFO, "[environment] " + name + "=" + v); - return v; - } - - static final Pattern variablePattern = Pattern.compile("$\\(([^)]+)\\)"); - enum VarType { - SolutionName, - SolutionDir, - ProjectName, - ConfigurationName, - TargetDir, - TargetPath - } - public static String resolveVariables(String string, final Solution solution, final Project project, final Configuration configuration) { - String res = RegexUtils.regexReplace(variablePattern, string, new Adapter() { - public String adapt(String[] value) { - String match = value[0]; - String variableName = value[1]; - VarType type = VarType.valueOf(variableName); - String name; - if (type != null) { - switch (type) { - case ProjectName: - return project.name == null ? match : project.name; - case TargetPath: - return configuration.outputFile == null ? match : configuration.outputFile; - case SolutionName: - name = solution.getName(); - return name == null ? match : name; - case SolutionDir: - return solution.solutionFile == null ? match : solution.solutionFile.getParent(); - case ConfigurationName: - return configuration.name; - case TargetDir: - if (configuration.outputFile == null) - return match; - - return new File(configuration.outputFile).getParent(); - default: - return match; - } - } - String v = System.getenv().get(variableName); - return v == null ? match : v; - } - }); - //System.err.println("resolved \"" + string + "\" as :\n\t\"" + res + "\""); - return res; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/CompilerUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/CompilerUtils.java deleted file mode 100644 index 3c2b9434e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/CompilerUtils.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.compiler; - -import java.util.*; -import java.util.regex.Pattern; -import java.io.*; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLDecoder; - -import javax.tools.*; -import javax.tools.Diagnostic.Kind; - -import com.ochafik.io.IOUtils; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; - -public class CompilerUtils { - public static class CompilationError extends IOException { - private static final long serialVersionUID = 4002559714569792833L; - public final String compilerClass; - //public final String bootclasspath; - public final List> diagnostics; - public final Map inputs; - private CompilationError(String text, List> diagnostics, Map inputs, String compilerClass/*, String bootclasspath*/) { - super(text); - this.diagnostics = diagnostics; - this.inputs = inputs; - this.compilerClass = compilerClass; - //this.bootclasspath = bootclasspath; - } - public static void throwErrors(List> diagnostics, Map inputs, String compilerClass/*, String bootclasspath*/) throws CompilationError, IOException { - List> errors = new ArrayList>(diagnostics.size()); - StringBuilder sb = new StringBuilder(); - - for (final Diagnostic diagnostic : diagnostics) { - if (diagnostic == null) - continue; - if (diagnostic.getKind() == Kind.ERROR) { - errors.add(diagnostic); - sb.append("Error in " + (diagnostic.getSource() == null ? "?" : diagnostic.getSource().toUri()) + " at line " + diagnostic.getLineNumber() + ", col " + diagnostic.getColumnNumber() + " :\n\t" + diagnostic.getMessage(Locale.getDefault()) + "\n");//.toUri()); - if (diagnostic.getSource() != null) - sb.append(RegexUtils.regexReplace(Pattern.compile("\n"), "\n" + diagnostic.getSource().getCharContent(true), new Adapter() { - int line = 0; - - @Override - public String adapt(String[] value) { - line++; - return "\n" + line + ":" + (diagnostic.getLineNumber() == line ? ">>>" : "") +"\t\t"; - } - }) + "\n"); - } - //System.out.println("Error on line " + diagnostic.getLineNumber() + ":" + diagnostic.getColumnNumber() + " in " + (diagnostic.getSource() == null ? "" : diagnostic.getSource().getName()) + ": " + diagnostic.getMessage(Locale.getDefault())); - } - if (errors.isEmpty()) - return; - - System.err.println("INPUTS = " + inputs); - throw new CompilationError(sb.toString(), errors, inputs, compilerClass/*, bootclasspath*/); - } - } - public static String getClassPath(Class c, File cacheDirectory) throws MalformedURLException, IOException { - - URL resource = c.getResource(c.getSimpleName() + ".class"); - if (resource != null) { - String resstr = resource.toString(); -// if (resstr.contains("Prog/")) -// resstr = "jar:http://ochafik.com/Java/jnaerator.jar!/..."; - - if (resstr.matches("jar:.*!.*")) - resstr = resstr.substring("jar:".length(), resstr.indexOf("!")); - else { - String p = '/' + c.getName().replace('.', '/') + ".class"; - if (resstr.endsWith(p)) - resstr = resstr.substring(0, resstr.length() - p.length()); - } - return getLocalFile(new URL(resstr), cacheDirectory).toString(); - } - /* - if (resource != null) { - String resstr = resource.toString(); - if (resstr.matches("jar:file:.*!.*")) - return resstr.substring("jar:file:".length(), resstr.indexOf("!")); - else if (resstr.matches("jar:http:.*!.*")) - return resstr.substring("jar:".length(), resstr.indexOf("!")); - else { - String p = '/' + c.getName().replace('.', '/') + ".class"; - if (resstr.endsWith(p)) - return resstr.substring(0, resstr.length() - p.length()); - } - }*/ - return null; - } - public static Set getClassPaths(File cacheDirectory, Class... cs) throws MalformedURLException, IOException { - Set ret = new TreeSet(); - for (Class c : cs) { - String cp ; - if (c == null || (cp = getClassPath(c, cacheDirectory)) == null) - continue; - ret.add(cp); - } - return ret; - } - static Map localURLCaches = new HashMap(); - static File getLocalFile(URL remoteFile, File cacheDirectory) throws IOException { - if ("file".equals(remoteFile.getProtocol())) - return new File(URLDecoder.decode(remoteFile.getFile(), "utf-8")); - - String remoteStr = remoteFile.toString(); - File f = localURLCaches.get(remoteStr); - if (f == null) { - String fileName = new File(remoteStr).getName(); - URLConnection con = null; - try { - con = remoteFile.openConnection(); - } catch (IOException ex) { - ex.printStackTrace(); - } - if (cacheDirectory != null) { - f = new File(cacheDirectory, fileName); - if (f.exists() && (con == null || f.lastModified() > con.getLastModified())) { - System.out.println("Reusing cached file " + f); - if (con != null) - con.getInputStream().close(); - return f; - } - } else { - f = File.createTempFile(fileName, ".jar"); - f.deleteOnExit(); - } - System.out.print("Downloading file " + remoteFile + " to " + f); - - InputStream in = new BufferedInputStream(remoteFile.openStream()); - try { - OutputStream out = new BufferedOutputStream(new FileOutputStream(f)); - try { - //System.out.print("Downloading file '" + remoteStr + "'..."); - long length = IOUtils.readWrite(in, out); - System.out.println(" OK (" + length + " bytes)"); - localURLCaches.put(remoteStr, f.getAbsoluteFile()); - } finally { - out.close(); - } - } finally { - in.close(); - } - } - return f; - } - public static void compile(JavaCompiler compiler, MemoryFileManager fileManager, DiagnosticCollector diagnostics, String sourceCompatibility, File cacheDirectory, Class...classpathHints) throws MalformedURLException, IOException { - //JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - //System.out.println("compiler = " + (compiler == null ? "" : compiler.getClass().getName())); - String bootclasspath = StringUtils.implode(getClassPaths(cacheDirectory, String.class), File.pathSeparator); - - String classpath = StringUtils.implode(getClassPaths(cacheDirectory, classpathHints), File.pathSeparator); -// System.out.println("bootclasspath = " + bootclasspath); -// System.out.println("classpath = " + classpath); - Iterable fileObjects = fileManager.getJavaFileObjects(); - List options = sourceCompatibility == null ? null : Arrays.asList( - "-target", sourceCompatibility, - "-source", sourceCompatibility, - "-bootclasspath", bootclasspath, - "-classpath", classpath - ); -// DebugUtils.println(fileManager.inputs.values()); - compiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call(); - -// for (final Diagnostic diagnostic : diagnostics.getDiagnostics()) { -// if (diagnostic == null) -// continue; -// //diagnostic.getKind() -// //System.out.format("Error on line %d in %d%n", diagnostic.getLineNumber(), diagnostic.getSource());//.toUri()); -// if (diagnostic.getKind() == Kind.ERROR) { -// System.err.println("\n" + diagnostic.getSource().toUri() + ":"); -// System.err.println(RegexUtils.regexReplace(Pattern.compile("\n"), "\n" + diagnostic.getSource().getCharContent(true), new Adapter() { -// int line = 0; -// -// @Override -// public String adapt(String[] value) { -// line++; -// return "\n" + line + ":" + (diagnostic.getLineNumber() == line ? ">>>" : "") +"\t\t"; -// } -// })); -// } -//// System.out.println("Error on line " + diagnostic.getLineNumber() + ":" + diagnostic.getColumnNumber() + " in " + (diagnostic.getSource() == null ? "" : diagnostic.getSource().getName()) + ": " + diagnostic.getMessage(Locale.getDefault())); -// } - } - - public static JavaCompiler getJavaCompiler(boolean preferJavac) throws FileNotFoundException { - JavaCompiler compiler; - if (preferJavac) { - compiler = ToolProvider.getSystemJavaCompiler(); - if (compiler != null) - return compiler; - } - try { - compiler = (JavaCompiler)Class.forName("org.eclipse.jdt.internal.compiler.tool.EclipseCompiler").newInstance(); - } catch (Exception e) { - compiler = ToolProvider.getSystemJavaCompiler(); - if (compiler == null) - throw new FileNotFoundException("No Java compiler found (not run from JDK, no Eclipse Compiler in classpath)"); - } - return compiler; - } - public static void main2(String[] args) { - try { - String jarOut = args.length == 0 ? "out.jar" : args[0]; - - JavaCompiler compiler = getJavaCompiler(false); - - DiagnosticCollector diagnostics = new DiagnosticCollector(); - MemoryFileManager fileManager = new MemoryFileManager(compiler.getStandardFileManager(diagnostics, null, null)); - fileManager.addSourceInput("test/Main.java", "package test; public class Main { }"); - fileManager.close(); - - compile(compiler, fileManager, diagnostics, null, null); - for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { - //diagnostic.getKind() - //System.out.format("Error on line %d in %d%n", diagnostic.getLineNumber(), diagnostic.getSource());//.toUri()); - System.out.format("Error on line " + diagnostic.getLineNumber() + ":" + diagnostic.getLineNumber() + " in " + diagnostic.getSource());//.toUri()); - } - - boolean outputSources = true; - System.out.println("Writing " + jarOut + (outputSources ? " with" : " without") + " sources"); - fileManager.writeJar(new FileOutputStream(jarOut), outputSources, null); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } -} - diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileManager.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileManager.java deleted file mode 100644 index ee087fab1..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileManager.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.compiler; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; - -import javax.tools.FileObject; -import javax.tools.ForwardingJavaFileManager; -import javax.tools.JavaFileManager; -import javax.tools.JavaFileObject; - -import com.ochafik.io.IOUtils; - - -public class MemoryFileManager extends ForwardingJavaFileManager { - public final Map inputs = new HashMap(); - public final Map outputs = new HashMap(); - - public void writeJar(File outputJar, boolean outputSources, Map additionalFiles) throws IOException { - - File jarDir = outputJar.getAbsoluteFile().getParentFile(); - if (!jarDir.isDirectory()) - jarDir.mkdirs(); - writeJar(new FileOutputStream(outputJar), outputSources, additionalFiles); - } - public void writeJar(OutputStream out, boolean outputSources, Map additionalFiles) throws IOException { - JarOutputStream jout = new JarOutputStream(out); - if (outputSources) - for (Map.Entry e : inputs.entrySet()) { -// if (e.getKey().contains(".class")) -// continue; - writeEntry(e.getKey(), e.getValue(), jout); - } - for (Map.Entry e : outputs.entrySet()) - writeEntry(e.getKey(), e.getValue(), jout); - - if (additionalFiles != null) - for (Map.Entry additionalFile : additionalFiles.entrySet()) { - String path = additionalFile.getKey(); - if (path.startsWith("file:///")) - path = path.substring("file:///".length()); - - FileInputStream in = new FileInputStream(additionalFile.getValue()); - JarEntry e = new JarEntry(path); - jout.putNextEntry(e); - IOUtils.readWrite(in, jout); - in.close(); - jout.closeEntry(); - } - jout.close(); - } - protected void writeEntry(String path, FileObject o, JarOutputStream jout) throws IOException { - if (path.startsWith("/")) - path = path.substring(1); - if (path.startsWith("file:///")) - path = path.substring("file:///".length()); - - if (o instanceof MemoryFileObject) { - MemoryFileObject mo = (MemoryFileObject)o; - byte[] c = mo.getContent(); - if (c == null) - return; - -// String path = mo.getPath(); -// if (path.startsWith("file:///")) -// path = path.substring("file:///".length()); - JarEntry e = new JarEntry(path); - jout.putNextEntry(e); - jout.write(c); - jout.closeEntry(); - } else if (o instanceof URLFileObject) { - URLFileObject uo = (URLFileObject)o; -// String path = uo.url.getFile(); -// if (path.startsWith("/")) -// path = path.substring(1); - - JarEntry e = new JarEntry(path); - jout.putNextEntry(e); - InputStream in = uo.url.openStream(); - if (in == null) - throw new FileNotFoundException(path); - IOUtils.readWrite(in, jout); - in.close(); - jout.closeEntry(); - } else - throw new UnsupportedOperationException("Dunno how to deal with " + o); - } - public MemoryFileManager(JavaFileManager fm) { - super(fm); - } - - public MemoryJavaFile addSourceInput(String path, String content) { - if (!path.startsWith("file:///")) - path = "file:///" + path; - - MemoryJavaFile mjf = new MemoryJavaFile(path, content, JavaFileObject.Kind.SOURCE); - inputs.put(path, mjf); - return mjf; - } - @Override - public boolean isSameFile(FileObject a, FileObject b) { - return a.toString().equals(b.toString()); - } - public Iterable getJavaFileObjects() { - return new ArrayList(inputs.values()); - } - - @Override - public JavaFileObject getJavaFileForInput(Location location, String className, JavaFileObject.Kind kind) throws IOException { -// System.out.println("getJavaFileForInput(className = " + className + ", location = " + location + ", kind = " + kind + ")"); - if (kind == JavaFileObject.Kind.SOURCE) { - return inputs.get(className); - } - return super.getJavaFileForInput(location, className, kind); - } - - public static String getFullPathForClass(String className, String extension) { - return "file:///" + getSimplePathForClass(className, extension); - } - public static String getSimplePathForClass(String className, String extension) { - return className.replace('.', '/') + "." + extension; - } - @Override - public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { -// System.out.println("getJavaFileForOutput(className = " + className + ", location = " + location + ", kind = " + kind + ")"); - MemoryJavaFile jo = null; - if (kind == JavaFileObject.Kind.CLASS) { - outputs.put(getFullPathForClass(className, "class"), jo = new MemoryJavaFile(getFullPathForClass(className, "class"), null, kind)); - } else if (kind == JavaFileObject.Kind.SOURCE) { - inputs.put(getFullPathForClass(className, "java"), jo = new MemoryJavaFile(getFullPathForClass(className, "java"), null, kind)); - } - - return jo == null ? super.getJavaFileForInput(location, className, kind) : jo; - } - @Override - public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { -// System.out.println("getFileForOutput(relativeName = " + relativeName + ")"); - if (relativeName.startsWith("file:///")) - relativeName = relativeName.substring("file:///".length()); - - FileObject out = outputs.get(relativeName); - if (out == null) { - out = new MemoryFileObject(relativeName, (String)null); - outputs.put(relativeName, out); - } - return out; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileObject.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileObject.java deleted file mode 100644 index 35cc7d80d..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryFileObject.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.compiler; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.tools.FileObject; - -public class MemoryFileObject implements FileObject { - String path; - byte[] content; - - public MemoryFileObject(String path, String content) { - this.path = path; - this.content = content == null ? null : content.getBytes(); - } - public MemoryFileObject(String path, byte[] content) { - this.path = path; - this.content = content; - } - public String getPath() { - return path; - } - public byte[] getContent() { - return content; - } - public boolean delete() { - content = null; - return true; - } - public String getCharContent(boolean ignoreEncodingErrors) { - return new String(content); - } - public long getLastModified() { - return System.currentTimeMillis(); - } - public String getName() { - return getPath(); - } - public InputStream openInputStream() { - if (content == null) - return null; - - return new ByteArrayInputStream(content); - } - public OutputStream openOutputStream() { - return new ByteArrayOutputStream() { - public void close() throws IOException { - super.close(); - content = toByteArray(); - } - }; - } - public Reader openReader(boolean ignoreEncodingErrors) { - InputStream in = openInputStream(); - return in == null ? null : new InputStreamReader(in); - } - public Writer openWriter() { - OutputStream out = openOutputStream(); - return out == null ? null : new OutputStreamWriter(out); - } - public URI toUri() { - try { - return new URI(//"file:" + - getPath()); - } catch (URISyntaxException ex) { - ex.printStackTrace(); - return null; - } - } - @Override - public String toString() { - return getPath() + ":\n" + getCharContent(true); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryJavaFile.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryJavaFile.java deleted file mode 100644 index 0d3862033..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/MemoryJavaFile.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.compiler; - -import javax.lang.model.element.Modifier; -import javax.lang.model.element.NestingKind; -import javax.tools.JavaFileObject; - -public class MemoryJavaFile extends MemoryFileObject implements JavaFileObject { - JavaFileObject.Kind kind; - public MemoryJavaFile(String path, String content, JavaFileObject.Kind kind) { - super(path, content); - this.kind = kind; - } - public Modifier getAccessLevel() { - return Modifier.PUBLIC; - } - public JavaFileObject.Kind getKind() { - return kind; - } - public NestingKind getNestingKind() { - return null; - } - public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) { - return true; // TODO - } - -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/URLFileObject.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/URLFileObject.java deleted file mode 100644 index f2944dc3e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/compiler/URLFileObject.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.ochafik.lang.compiler; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; - -import javax.tools.FileObject; - -import com.ochafik.io.ReadText; - -public class URLFileObject implements FileObject { - URL url; - - public URLFileObject(URL url) { - this.url = url; - } - - public String getPath() { - return url.getFile(); - } - - @Override - public boolean delete() { - return false; - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return ReadText.readText(url); - } - - @Override - public long getLastModified() { - try { - URLConnection con = url.openConnection(); - long lastModified = con.getLastModified(); - con.getInputStream().close(); - return lastModified; - } catch (Exception ex) { - ex.printStackTrace(); - return -1; - } - } - - @Override - public String getName() { - return new File(url.getFile()).getName(); - } - - @Override - public InputStream openInputStream() throws IOException { - return url.openStream(); - } - - @Override - public OutputStream openOutputStream() throws IOException { - return null; - } - - @Override - public Reader openReader(boolean arg0) throws IOException { - return new InputStreamReader(openInputStream()); - } - - @Override - public Writer openWriter() throws IOException { - return null; - } - - @Override - public URI toUri() { - try { - return url.toURI(); - } catch (URISyntaxException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/grammar/DummyDebugEventListener.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/grammar/DummyDebugEventListener.java deleted file mode 100644 index eaa17737f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/grammar/DummyDebugEventListener.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.grammar; - -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; -import org.antlr.runtime.debug.DebugEventListener; - -public class DummyDebugEventListener implements DebugEventListener { - - public void LT(int arg0, Token arg1) { - // TODO Auto-generated method stub - - } - - public void LT(int arg0, Object arg1) { - // TODO Auto-generated method stub - - } - - public void addChild(Object arg0, Object arg1) { - // TODO Auto-generated method stub - - } - - public void becomeRoot(Object arg0, Object arg1) { - // TODO Auto-generated method stub - - } - - public void beginBacktrack(int arg0) { - // TODO Auto-generated method stub - - } - - public void beginResync() { - // TODO Auto-generated method stub - - } - - public void commence() { - // TODO Auto-generated method stub - - } - - public void consumeHiddenToken(Token arg0) { - // TODO Auto-generated method stub - - } - - public void consumeNode(Object arg0) { - // TODO Auto-generated method stub - - } - - public void consumeToken(Token arg0) { - // TODO Auto-generated method stub - - } - - public void createNode(Object arg0) { - // TODO Auto-generated method stub - - } - - public void createNode(Object arg0, Token arg1) { - // TODO Auto-generated method stub - - } - - public void endBacktrack(int arg0, boolean arg1) { - // TODO Auto-generated method stub - - } - - public void endResync() { - // TODO Auto-generated method stub - - } - - public void enterAlt(int arg0) { - // TODO Auto-generated method stub - - } - - public void enterDecision(int arg0) { - // TODO Auto-generated method stub - - } - - public void enterRule(String arg0) { - // TODO Auto-generated method stub - - } - - public void enterSubRule(int arg0) { - // TODO Auto-generated method stub - - } - - public void exitDecision(int arg0) { - // TODO Auto-generated method stub - - } - - public void exitRule(String arg0) { - // TODO Auto-generated method stub - - } - - public void exitSubRule(int arg0) { - // TODO Auto-generated method stub - - } - - public void location(int arg0, int arg1) { - // TODO Auto-generated method stub - - } - - public void mark(int arg0) { - // TODO Auto-generated method stub - - } - - public void nilNode(Object arg0) { - // TODO Auto-generated method stub - - } - - public void recognitionException(RecognitionException arg0) { - // TODO Auto-generated method stub - - } - - public void rewind() { - // TODO Auto-generated method stub - - } - - public void rewind(int arg0) { - // TODO Auto-generated method stub - - } - - public void semanticPredicate(boolean arg0, String arg1) { - // TODO Auto-generated method stub - - } - - public void setTokenBoundaries(Object arg0, int arg1, int arg2) { - // TODO Auto-generated method stub - - } - - public void terminate() { - // TODO Auto-generated method stub - - } - - public void enterRule(String arg0, String arg1) { - // TODO Auto-generated method stub - - } - - public void errorNode(Object arg0) { - // TODO Auto-generated method stub - - } - - public void exitRule(String arg0, String arg1) { - // TODO Auto-generated method stub - - } - - public void enterDecision(int a, boolean b) { - /// whatever - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Analysis.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Analysis.java deleted file mode 100644 index 42a8d5caa..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Analysis.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.Iterator; -import java.util.Collections; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import java.util.List; -import java.util.ArrayList; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Declarator.*; - -/* -mvn -o compile exec:java -Dexec.mainClass=com.ochafik.lang.jnaerator.JNAerator - -*/ -public class Analysis { - Result result; - public Analysis(Result result) { - this.result = result; - } - - public static enum Attribute { - Type, Declaration, ContainedDeclarations - } - - public static class Resolver extends Scanner { - /*public class SymbolTable { - - SymbolTable parent; - - LinkedHashMap declarations = new LinkedHashMap(); - - } - Stack symbolTables = new Stack(); - */ - } - - List getNames(Declaration d) { - if (d instanceof StoredDeclarations) { - List ret = new ArrayList(); - for (Declarator declarator : ((StoredDeclarations)d).getDeclarators()) - ret.add(declarator.resolveName()); - return ret; - } else if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRef tr = ((TaggedTypeRefDeclaration)d).getTaggedTypeRef(); - Identifier id = tr.getTag(); - if (id instanceof SimpleIdentifier) - return Collections.singletonList(((SimpleIdentifier)id).getName()); - } - return Collections.EMPTY_LIST; - } - public Declaration resolveDown(DeclarationsHolder dh, Iterator simpleIds) { - String nextId = simpleIds.next().getName(); - for (Declaration d : dh.getDeclarations()) { - List names = getNames(d); - if (names.contains(nextId)) { - if (!simpleIds.hasNext()) - return d; - else { - DeclarationsHolder sub = null; - if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRef ttr = ((TaggedTypeRefDeclaration)d).getTaggedTypeRef(); - if (ttr instanceof DeclarationsHolder) { - sub = (DeclarationsHolder)ttr; - } - } - if (sub == null) - return null; - - return resolveDown(sub, simpleIds); - } - } - } - return null; - } - - public Declaration resolveDown(DeclarationsHolder dh, Identifier id) { - return resolveDown(dh, id.resolveSimpleIdentifiers().iterator()); - } - public Declaration resolveUp(Identifier i) { - Element p = i;// e.getParentElement(); - for (;p != null;) { - do {//while (!(p instanceof DeclarationsHolder)) { - p = p.getParentElement(); - } while (!(p instanceof DeclarationsHolder)); - - - } - return null; - } - public Declaration resolve(Identifier e) { -// if (e instanceof Declaration) -// return (Declaration)e; - Declaration decl = (Declaration)e.getAttribute(Attribute.Declaration); - if (decl == null) { - e.setAttribute(Attribute.Declaration, decl = resolveUp(e)); - } - return decl; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java deleted file mode 100644 index 77a3651e4..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java +++ /dev/null @@ -1,740 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import org.bridj.ann.Name; -import org.bridj.BridJ; -import org.bridj.FlagSet; -import org.bridj.IntValuedEnum; -import org.bridj.StructObject; -import org.bridj.cpp.CPPObject; -import org.bridj.cpp.com.IUnknown; - -import com.ochafik.lang.jnaerator.BridJTypeConversion.NL4JConversion; -//import org.bridj.structs.StructIO; -//import org.bridj.structs.Array; - -import java.io.IOException; -import java.util.*; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Function.Type; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.sun.jna.win32.StdCallLibrary; -import org.bridj.*; -import org.bridj.ann.Convention; -import org.bridj.objc.NSObject; - -public class BridJDeclarationsConverter extends DeclarationsConverter { - public BridJDeclarationsConverter(Result result) { - super(result); - } - - @Override - public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { - Struct decl = super.convertCallback(functionSignature, signatures, callerLibraryName); - if (decl != null) { - decl.setParents(Arrays.asList((SimpleTypeRef)( - FunctionSignature.Type.ObjCBlock.equals(functionSignature.getType()) ? - result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ObjCBlock) : - (SimpleTypeRef)typeRef(ident(result.config.runtime.callbackClass, expr(typeRef(decl.getTag().clone())))) - ))); - //addCallingConventionAnnotation(functionSignature.getFunction(), decl); - } - - return decl; - } - - public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { - if (e.isForwardDeclaration()) - return; - - Identifier enumName = getActualTaggedTypeName(e); - List results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); - - boolean hasEnumClass = false; - - if (enumName != null && enumName.resolveLastSimpleIdentifier().getName() != null) { - hasEnumClass = true; - - if (!signatures.addClass(enumName)) - return; - - signatures = new Signatures(); - - Enum en = new Enum(); - if (!result.config.noComments) - en.importComments(e, "enum values", getFileCommentContent(e)); - - en.setType(Enum.Type.Java); - en.setTag(enumName.clone()); - en.addModifiers(ModifierType.Public); - out.addDeclaration(new TaggedTypeRefDeclaration(en)); - Struct body = new Struct(); - en.setBody(body); - boolean hasValidItem = false; - for (EnumItemResult er : results) { - if (er.errorElement != null) { - out.addDeclaration(er.errorElement); - continue; - } - Enum.EnumItem item = new Enum.EnumItem(er.originalItem.getName(), er.value); - en.addItem(item); - hasValidItem = true; - if (!result.config.noComments) - if (item != null) {// && hasEnumClass) { - item.importComments(er.originalItem); - } - } - if (hasValidItem) { - en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); - String valueArgName = "value"; - body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( - stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) - ))); - body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); - body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( - new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) - )).addModifiers(ModifierType.Public)); - - - body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( - new Statement.Return( - methodCall( - methodCall( - expr(typeRef(Collections.class)), - MemberRefStyle.Dot, - "singleton", - thisRef() - ), - MemberRefStyle.Dot, - "iterator" - ) - ) - )).addModifiers(ModifierType.Public)); - - body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( - new Statement.Return( - methodCall( - expr(typeRef(FlagSet.class)), - MemberRefStyle.Dot, - "fromValue", - varRef(valueArgName), - methodCall( - "values" - ) - ) - ) - )).addModifiers(ModifierType.Public, ModifierType.Static)); - } - } else { - outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); - } - } - - void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { - Convention.Style cc = null; - if (originalFunction.hasModifier(ModifierType.__stdcall)) - cc = Convention.Style.StdCall; - else if (originalFunction.hasModifier(ModifierType.__fastcall)) - cc = Convention.Style.FastCall; - else if (originalFunction.hasModifier(ModifierType.__thiscall)) - cc = Convention.Style.ThisCall; - else if (originalFunction.hasModifier(ModifierType.__pascal)) - cc = Convention.Style.Pascal; - - if (cc != null) { - target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); - } - } - - @Override - public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { - Element parent = function.getParentElement(); - MemberVisibility visibility = function.getVisibility(); - boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); - boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); - boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); - boolean isInStruct = parent instanceof Struct; - if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) - return; - boolean isStatic = function.hasModifier(ModifierType.Static); - boolean isConstructor = iConstructor != -1; - - Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); - - if (result.config.synchronizedMethods && !isCallback) - nativeMethod.addModifiers(ModifierType.Synchronized); - - addCallingConventionAnnotation(function, nativeMethod); - - if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { - TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); - if (mgc != null) { - nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); - } - } - - //Map argTypes = new LinkedHashMap(); - - boolean isObjectiveC = function.getType() == Type.ObjCMethod; - int iArg = 1; - Set argNames = new TreeSet(); - - List superConstructorArgs = null; - if (isConstructor) { - superConstructorArgs = new ArrayList(); - superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); - superConstructorArgs.add(expr(iConstructor)); - } - - Identifier varArgType = null; - String varArgName = null; - NL4JConversion returnType = null; - List paramTypes = new ArrayList(); - List paramNames = new ArrayList(); - if (!isConstructor) { - returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); - } - - for (Arg arg : function.getArgs()) { - String paramName; - if (arg.isVarArg()) { - assert arg.getValueType() == null; - paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); - varArgType = ident(isObjectiveC ? NSObject.class : Object.class); - } else { - paramName = chooseJavaArgName(arg.getName(), iArg, argNames); - paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); - } - paramNames.add(paramName); - if (isConstructor) { - superConstructorArgs.add(varRef(paramName)); - } - iArg++; - } - - fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); - - Block convertedBody = null; - if (isConstructor) { - convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); - } else if (result.config.convertBodies && function.getBody() != null) - { - try { - Pair> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); - convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); - for (Declaration d : bodyAndExtraDeclarations.getSecond()) - out.addDeclaration(d); - } catch (Exception ex) { - ex.printStackTrace(System.out); - nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); - } - } - - if (!result.config.noComments) - nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); - - out.addDeclaration(nativeMethod); - - boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; - if (convertedBody == null) { - boolean forwardedToRaw = false; - if (result.config.genRawBindings && !isCallback) { - Function rawMethod = nativeMethod.clone(); - rawMethod.setArgs(Collections.EMPTY_LIST); - fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); - rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); - if (generateStaticMethod) - rawMethod.addModifiers(ModifierType.Static); - - if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { - out.addDeclaration(rawMethod); - - List followedArgs = new ArrayList(); - for (int i = 0, n = paramTypes.size(); i < n; i++) { - NL4JConversion paramType = paramTypes.get(i); - String paramName = paramNames.get(i); - Expression followedArg; - - switch (paramType.type) { - case Pointer: - followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); - break; - case Enum: - followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); - break; -// case NativeSize: -// case NativeLong: -// followedArg = methodCall(varRef(paramName), "longValue"); -// break; - default: - followedArg = varRef(paramName); - break; - } - followedArgs.add(followedArg); - } - - Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); - boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); - if (isVoid) - nativeMethod.setBody(block(stat(followedCall))); - else { - switch (returnType.type) { - case Pointer: - followedCall = methodCall(expr(typeRef(org.bridj.Pointer.class)), "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); - break; - case Enum: - followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); - break; - case NativeLong: - case NativeSize: - followedCall = new New(nativeMethod.getValueType().clone(), followedCall); - default: - break; - } - nativeMethod.setBody(block(new Statement.Return(followedCall))); - } - forwardedToRaw = true; - } - } - - if (!forwardedToRaw) - nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); - } else - nativeMethod.setBody(convertedBody); - - nativeMethod.addModifiers( - isProtected ? ModifierType.Protected : ModifierType.Public, - generateStaticMethod ? ModifierType.Static : null - ); - - } - - private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List paramTypes, List paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { - for (int i = 0, n = paramTypes.size(); i < n; i++) { - NL4JConversion paramType = paramTypes.get(i); - String paramName = paramNames.get(i); - nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); - } - if (varArgType != null) - nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); - - returnType.annotateTypedType(nativeMethod, useRawTypes);//.getTypedTypeRef()))); - nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); - - String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); - - Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); - if (!javaMethodName.equals(functionName)) { - nativeMethod.setName(javaMethodName); - } - if (!isCallback && !javaMethodName.equals(functionName)) - nativeMethod.addAnnotation(new Annotation(Name.class, expr(functionName.toString()))); - } - public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { - Identifier structName = getActualTaggedTypeName(struct); - if (structName == null) - return null; - - //if (structName.toString().contains("MonoObject")) - // structName.toString(); - - if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) - return null; - - if (!signatures.addClass(structName)) - return null; - - boolean isUnion = struct.getType() == Struct.Type.CUnion; - boolean inheritsFromStruct = false; - Identifier baseClass = null; - int parentFieldsCount = 0; - List preComments = new ArrayList(); - for (SimpleTypeRef parentName : struct.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) { - // TODO report error - continue; - } - try { - parentFieldsCount += countFieldsInStruct(parent); - } catch (UnsupportedConversionException ex) { - preComments.add("Error: " + ex); - } - baseClass = result.getTaggedTypeIdentifierInJava(parent); - if (baseClass != null) { - inheritsFromStruct = true; - break; // TODO handle multiple and virtual inheritage - } - } - boolean hasMemberFunctions = false; - for (Declaration d : struct.getDeclarations()) { - if (d instanceof Function) { - hasMemberFunctions = true; - break; - } - } - Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); - if (baseClass == null) { - switch (struct.getType()) { - case CStruct: - case CUnion: - if (!hasMemberFunctions) { - baseClass = ident(StructObject.class); - break; - } - case CPPClass: - baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); - result.hasCPlusPlus = true; - break; - default: - throw new UnsupportedOperationException(); - } - } - Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); - //if (result.config.microsoftCOM) { - if (uuid != null) { - structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); - } - structJavaClass.addToCommentBefore(preComments); - //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); - final int iChild[] = new int[] { parentFieldsCount }; - - //cl.addDeclaration(new EmptyDeclaration()) - Signatures childSignatures = new Signatures(); - - /*if (isVirtual(struct) && !onlyFields) { - String vptrName = DEFAULT_VPTR_NAME; - VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); - vptr.addModifiers(ModifierType.Public); - structJavaClass.addDeclaration(vptr); - childSignatures.variablesSignatures.add(vptrName); - // TODO add vptr grabber to constructor ! - }*/ - - // private static StructIO io = StructIO.getInstance(MyStruct.class); - - Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); - if (childSignatures.addMethod(defaultConstructor)) - structJavaClass.addDeclaration(defaultConstructor); - - if (isUnion) - structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); - - int iVirtual = 0, iConstructor = 0; - //List children = new ArrayList(); - for (Declaration d : struct.getDeclarations()) { - //if (isUnion) - // iChild[0] = 0; - - if (d instanceof VariablesDeclaration) { - convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); - } else if (!onlyFields) { - if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); - if (tr instanceof Struct) { - outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); - } else if (tr instanceof Enum) { - convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); - } - } else if (d instanceof TypeDef) { - TypeDef td = (TypeDef)d; - TypeRef tr = td.getValueType(); - if (tr instanceof Struct) { - outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); - } else if (tr instanceof FunctionSignature) { - convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); - } - } else if (result.config.genCPlusPlus && d instanceof Function) { - Function f = (Function) d; - - boolean isVirtual = f.hasModifier(ModifierType.Virtual); - boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); - if (isConstructor && f.getArgs().isEmpty()) - continue; // default constructor was already generated - - String library = result.getLibrary(struct); - if (library == null) - continue; - List decls = new ArrayList(); - convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); - for (Declaration md : decls) { - if (!(md instanceof Function)) - continue; - Function method = (Function) md; - boolean commentOut = false; - if (isVirtual) - method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); - else if (method.getValueType() == null) { - method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); - isConstructor = true; - } - if (method.getName().toString().equals("operator")) - commentOut = true; - - if (commentOut) - structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); - else - structJavaClass.addDeclaration(method); - } - if (isVirtual) - iVirtual++; - if (isConstructor) - iConstructor++; - } - } - } - - String ptrName = "pointer"; - Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); - if (childSignatures.addMethod(castConstructor)) - structJavaClass.addDeclaration(castConstructor); - - return structJavaClass; - } - Map structsVirtuality = new HashMap(); - public boolean isVirtual(Struct struct) { - Identifier name = getActualTaggedTypeName(struct); - Boolean bVirtual = structsVirtuality.get(name); - if (bVirtual == null) { - boolean hasVirtualParent = false, hasVirtualMembers = false; - for (SimpleTypeRef parentName : struct.getParents()) { - Struct parentStruct = result.structsByName.get(parentName.getName()); - if (parentStruct == null) { - if (result.config.verbose) - System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); - continue; - } - if (isVirtual(parentStruct)) { - hasVirtualParent = true; - break; - } - } - - for (Declaration mb : struct.getDeclarations()) { - if (mb.hasModifier(ModifierType.Virtual)) { - hasVirtualMembers = true; - break; - } - } - bVirtual = hasVirtualMembers && !hasVirtualParent; - structsVirtuality.put(name, bVirtual); - } - return bVirtual; - } - - protected String ioVarName = "io", ioStaticVarName = "IO"; - public List convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { - name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); - //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); - - final boolean useRawTypes = false; - //Expression initVal = null; - int fieldIndex = iChild[0]; - //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { - - NL4JConversion conv = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J( - mutatedType, - callerLibraryName, - thisField("io"), - varRef(name), - fieldIndex, - bits - ); - - if (conv == null) { - throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); - } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { - throw new UnsupportedConversionException(mutatedType, "void type !"); - //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); - } - - Function convDecl = new Function(); - conv.annotateTypedType(convDecl, useRawTypes); - convDecl.setType(Type.JavaMethod); - convDecl.addModifiers(ModifierType.Public); - - if (conv.arrayLengths != null) - convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); - if (conv.bits != null) - convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); - if (conv.byValue) - convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); - - for (Element e : toImportDetailsFrom) - convDecl.importDetails(e, false); - convDecl.importDetails(mutatedType, true); - //convDecl.importDetails(javaType, true); - -// convDecl.importDetails(v, false); -// convDecl.importDetails(vs, false); -// convDecl.importDetails(valueType, false); -// valueType.stripDetails(); - convDecl.moveAllCommentsBefore(); - - convDecl.setName(ident(name)); - - if (!isGlobal) - convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); - convDecl.setValueType(conv.getTypeRef(useRawTypes)); - - TypeRef javaType = convDecl.getValueType(); - String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); - - Expression getGlobalPointerExpr = null; - if (isGlobal) { - getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); - } - List out = new ArrayList(); - if (conv.getExpr != null) { - Function getter = convDecl.clone(); - if (isGlobal) { - getter.setBody(block( - tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))) - )); - } else { - getter.setBody(block( - new Statement.Return(conv.getExpr) - )); - } - out.add(getter); - } - - if (!conv.readOnly && conv.setExpr != null) { - Function setter = convDecl.clone(); - setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); - setter.addArg(new Arg(name, javaType)); - //setter.addModifiers(ModifierType.Native); - if (isGlobal) { - setter.setBody(block( - tryRethrow(block( - stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), - new Statement.Return(thisRef()) - )) - )); - } else { - setter.setBody(block( - stat(conv.setExpr), - new Statement.Return(thisRef()) - )); - } - out.add(setter); - - if (result.config.scalaStructSetters) { - setter = new Function(); - setter.setType(Type.JavaMethod); - setter.setName(ident(name + "_$eq")); - setter.setValueType(javaType.clone()); - setter.addArg(new Arg(name, javaType.clone())); - setter.addModifiers(ModifierType.Public, ModifierType.Final); - setter.setBody(block( - stat(methodCall(name, varRef(name))), - new Statement.Return(varRef(name)) - )); - out.add(setter); - } - } - return out; - } - public void convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { - try { - TypeRef valueType = v.getValueType(); - for (Declarator vs : v.getDeclarators()) { - if (vs.getDefaultValue() != null) - continue; - - String name = vs.resolveName(); - if (name == null || name.length() == 0) { - name = "anonymous" + (nextAnonymousFieldId++); - } - - TypeRef mutatedType = valueType; - if (!(vs instanceof DirectDeclarator)) - { - mutatedType = (TypeRef)vs.mutateTypeKeepingParent(valueType); - vs = new DirectDeclarator(vs.resolveName()); - } - //Declarator d = v.getDeclarators().get(0); - List vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); - if (vs.getBits() > 0) - for (Declaration vd : vds) - vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); - - for (Declaration vd : vds) { - if (vd instanceof Function) { - if (!signatures.addMethod((Function)vd)) - continue; - } - - vd.importDetails(mutatedType, true); - vd.moveAllCommentsBefore(); - if (!(mutatedType instanceof Primitive) && !result.config.noComments) - vd.addToCommentBefore("C type : " + mutatedType); - - out.addDeclaration(vd); - } - //} - iChild[0]++; - } - } catch (Throwable e) { - if (!(e instanceof UnsupportedConversionException)) - e.printStackTrace(); - if (!result.config.limitComments) - out.addDeclaration(new EmptyDeclaration(e.toString())); - } - } - int nextAnonymousFieldId; - - @Override - protected void configureCallbackStruct(Struct callbackStruct) { - callbackStruct.setType(Struct.Type.JavaClass); - callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); - } - - @Override - protected Struct createFakePointerClass(Identifier fakePointer) { - Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); - - String addressVarName = "address"; - ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, - new Arg(addressVarName, typeRef(long.class)) - ).addModifiers(ModifierType.Public).setBody( - block(stat(methodCall("super", varRef(addressVarName))))) - ); - ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, - new Arg(addressVarName, typeRef(org.bridj.Pointer.class)) - ).addModifiers(ModifierType.Public).setBody( - block(stat(methodCall("super", varRef(addressVarName))))) - ); - return ptClass; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJGlobalsGenerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJGlobalsGenerator.java deleted file mode 100644 index df9304606..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJGlobalsGenerator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - - -import com.ochafik.lang.jnaerator.parser.Declaration; -import java.util.ArrayList; -import java.util.Collections; - -import java.util.List; - -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrim; -import com.ochafik.lang.jnaerator.TypeConversion.TypeConversionMode; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.Statement; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerStyle; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalCallback; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointer; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointerType; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalStruct; -import com.sun.jna.ptr.ByReference; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class BridJGlobalsGenerator extends GlobalsGenerator { - - public BridJGlobalsGenerator(Result result) { - super(result); - } - - protected void convertGlobals(VariablesDeclaration globals, Signatures signatures, DeclarationsHolder out, Expression nativeLibFieldExpr, Identifier callerLibraryName, String callerLibrary) { - int[] iChild = new int[1]; - result.declarationsConverter.convertVariablesDeclaration(globals, signatures, out, iChild, true, callerLibraryName, callerLibraryName, callerLibrary);//globals, out, null, true, null, null, callerLibraryName, callerLibrary); - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJTypeConversion.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJTypeConversion.java deleted file mode 100644 index 767ac2141..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJTypeConversion.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import static com.ochafik.lang.SyntaxUtils.as; -import com.ochafik.lang.SyntaxUtils; -import org.bridj.FlagSet; -import org.bridj.ValuedEnum; -import org.bridj.SizeT; -import org.bridj.ann.CLong; -import org.bridj.ann.Ptr; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.Enum; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import org.bridj.IntValuedEnum; -/** - * - * @author ochafik - */ -public class BridJTypeConversion extends TypeConversion { - - public BridJTypeConversion(Result result) { - super(result); - } - - public Expression getEnumItemValue(Enum.EnumItem enumItem) { - Expression enumValue = findEnumItem(enumItem); - if (((Enum)enumItem.getParentElement()).getTag() != null) - enumValue = methodCall(enumValue, "value"); - - return cast(typeRef(int.class), enumValue); - } - - public class NL4JConversion { - - public ConvType type = ConvType.Default; - private TypeRef typeRef, indirectType; - public List arrayLengths; - public Expression bits; - public Expression getExpr, setExpr; - public boolean wideString, readOnly, byValue, nativeSize, cLong, isUndefined; - public Charset charset; - public final List annotations = new ArrayList(); - //public String structIOFieldGetterNameRadix; - public String pointerFieldGetterNameRadix; - - public TypeRef getTypeRef(boolean useRawTypes) { - if (useRawTypes) { - switch (type) { - case Pointer: - return typeRef(long.class); - case Enum: - return typeRef(int.class); - default: - return typeRef; - } - } else - return typeRef; - } - public Expression arrayLength() { - Expression length = null; - for (Expression m : arrayLengths) { - m.setParenthesis(true); - if (length == null) - length = m.clone(); - else - length = expr(length, Expression.BinaryOperator.Multiply, m.clone()); - } - return length.setParenthesis(arrayLengths.size() > 1); - } - public TypeRef getIndirectTypeRef() { - if (type == ConvType.Void) { - return typeRef(ident("?")); - } - if (type == ConvType.NativeSize) { - return typeRef(SizeT.class); - } - if (type == ConvType.NativeLong) { - return typeRef(org.bridj.CLong.class); - } - if (type == ConvType.ComplexDouble) { - return typeRef(org.bridj.ComplexDouble.class); - } - TypeRef t = indirectType == null ? typeRef : indirectType; - return t == null ? null : t.clone(); - } - - public M annotateRawType(M element) throws UnsupportedConversionException { - element.addAnnotations(annotations); - if (type != null) { - switch (type) { - case Enum: - case Primitive: - case Void: - break; - case NativeLong: - element.addAnnotation(new Annotation(CLong.class)); - break; - case NativeSize: - element.addAnnotation(new Annotation(Ptr.class)); - break; - case Pointer: - element.addAnnotation(new Annotation(Ptr.class)); - break; - case Struct: - case ComplexDouble: - case Default: - //throw new UnsupportedConversionException(typeRef, "Struct by value not supported yet"); - break; - default: - throw new UnsupportedConversionException(typeRef, "Not supported"); - } - } - return element; - } - - public M annotateTypedType(M element, boolean useRawTypes) throws UnsupportedConversionException { - element.addAnnotations(annotations); - if (type != ConvType.Pointer || useRawTypes) { - annotateRawType(element); - } - return element; - } - } - - public NL4JConversion convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { - - TypeRef original = valueType; - - TypeRef resolved = result.resolveType(original, false); - - //if (valueType != null && valueType.toString().contains("MonoDomain")) - // valueType = (TypeRef)valueType; - if (resolved != null) - valueType = resolved; - else - valueType = resolveTypeDef(valueType, libraryClassName, false/*true*/, true); - - //Expression offsetExpr = structIOExpr == null ? null : methodCall(structIOExpr, "getFieldOffset", expr(fieldIndex)); - //Expression bitOffsetExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitOffset", expr(fieldIndex)); - //Expression bitLengthExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitLength", expr(fieldIndex)); - - NL4JConversion conv = new NL4JConversion(); - - if (valueType == null) { - conv.type = ConvType.Void; - conv.typeRef = primRef(JavaPrim.Void); - return conv; - } - JavaPrim prim = getPrimitive(valueType, libraryClassName); - if (prim != null) { - return convertPrimitiveTypeRefToNL4J(prim, structIOExpr, fieldIndex, valueExpr); - } else if (valueType instanceof TypeRef.Pointer) { - // Treat callback pointers as callbacks. - TypeRef targetRef = ((TypeRef.Pointer)(valueType)).getTarget(); - if (targetRef instanceof TypeRef.FunctionSignature) - valueType = targetRef; - } - - if (valueType instanceof TypeRef.TargettedTypeRef) { - TypeRef targetRef = ((TypeRef.TargettedTypeRef) valueType).getTarget(); - - if (valueType instanceof TypeRef.Pointer.ArrayRef) { - TypeRef.Pointer.ArrayRef arrayRef = (TypeRef.Pointer.ArrayRef) valueType; - - List sizes = new ArrayList(); - for (Expression dim : arrayRef.flattenDimensions()) { - if (dim == null || dim instanceof Expression.EmptyArraySize) - continue; - - Expression m = convertExpressionToJava(dim, libraryClassName, false).getFirst(); - m.setParenthesis(false); - sizes.add(m); - } - if (!sizes.isEmpty()) - conv.arrayLengths = sizes; - } - - try { - NL4JConversion targetConv = convertTypeToNL4J(targetRef, libraryClassName, null, null, -1, -1); - //if (result.isFakePointer(libraryClassName)) - if (targetConv.isUndefined && allowFakePointers && original instanceof TypeRef.SimpleTypeRef) { - conv.type = ConvType.Pointer; - conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((TypeRef.SimpleTypeRef)original).getName().clone())); - if (structIOExpr != null) { - if (conv.arrayLengths == null) - conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); - } - return conv; - } - TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); - - if (pointedTypeRef != null) { - conv.type = ConvType.Pointer; - conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(pointedTypeRef.clone()))); - if (structIOExpr != null) { - if (conv.arrayLengths == null) - conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); - } - return conv; - } - } catch (UnsupportedConversionException ex) { - conv.type = ConvType.Pointer; - conv.typeRef = typeRef(result.config.runtime.pointerClass); - return conv; - } - } else if (valueType.getResolvedJavaIdentifier() != null) { - conv.typeRef = typeRef(valueType.getResolvedJavaIdentifier().clone()); - if (valueType instanceof TypeRef.FunctionSignature) { - conv.type = ConvType.Pointer; - conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(conv.typeRef))); - if (structIOExpr != null) { - conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); - } - } else if (valueType instanceof Enum) { - conv.type = ConvType.Enum; - conv.typeRef = typeRef(ident(IntValuedEnum.class, expr(conv.typeRef))); - if (structIOExpr != null) { - conv.setExpr = methodCall(structIOExpr.clone(), "setEnumField", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "getEnumField", thisRef(), expr(fieldIndex));//expr(typeRef(FlagSet.class)), "fromValue", methodCall(structPeerExpr.clone(), "getInt", expr(fieldIndex)), classLiteral(conv.typeRef.clone())); - } - } else if (valueType instanceof Struct) { - conv.type = ConvType.Struct; - if (structIOExpr != null) { - conv.setExpr = methodCall(structIOExpr.clone(), "setNativeObjectField", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "getNativeObjectField", thisRef(), expr(fieldIndex)); - //conv.getExpr = new Expression.New(conv.typeRef, (Expression)methodCall(structIOExpr.clone(), "offset", offsetExpr.clone())); - } - } else - throw new RuntimeException("Failed to recognize conversion type: " + valueType); - return conv; - } - - if (valueType instanceof TypeRef.SimpleTypeRef && allowFakePointers) { - Identifier name = ((TypeRef.SimpleTypeRef)valueType).getName(); - if (name != null) { - conv.type = ConvType.Pointer; - conv.typeRef = typeRef(result.getUndefinedType(libraryClassName, name.resolveLastSimpleIdentifier().clone())); - conv.isUndefined = true; - return conv; - } - } - throw new UnsupportedConversionException(original, "Unsupported type"); - } - - private NL4JConversion convertPrimitiveTypeRefToNL4J(JavaPrim prim, Expression structIOExpr, int fieldIndex, Expression valueExpr) { - NL4JConversion conv = new NL4JConversion(); - String radix; - switch (prim) { - case NativeLong: - conv.type = ConvType.NativeLong; - conv.typeRef = typeRef(Long.TYPE); - conv.indirectType = typeRef(org.bridj.CLong.class); - radix = "CLong"; - break; - case NativeSize: - conv.type = ConvType.NativeSize; - conv.typeRef = typeRef(Long.TYPE); - conv.indirectType = typeRef(org.bridj.SizeT.class); - radix = "SizeT"; - break; - case Void: - conv.type = ConvType.Void; - conv.typeRef = primRef(prim); - radix = null; - break; - case ComplexDouble: - conv.type = ConvType.ComplexDouble; - conv.typeRef = typeRef(org.bridj.ComplexDouble.class); - radix = "NativeObject"; - break; - default: - conv.type = ConvType.Primitive; - conv.typeRef = primRef(prim); - conv.indirectType = typeRef(prim.wrapperType); - radix = StringUtils.capitalize(prim.type.getName()); - break; - } - if (structIOExpr != null && radix != null) { - conv.setExpr = methodCall(structIOExpr.clone(), "set" + radix + "Field", thisRef(), expr(fieldIndex), valueExpr); - conv.getExpr = methodCall(structIOExpr.clone(), "get" + radix + "Field", thisRef(), expr(fieldIndex)); - } - return conv; - } - - - public Expression getFlatArraySizeExpression(TypeRef.Pointer.ArrayRef arrayRef, Identifier callerLibraryName) throws UnsupportedConversionException { - Expression mul = null; - List dims = arrayRef.flattenDimensions(); - for (int i = dims.size(); i-- != 0;) { - Expression x = dims.get(i); - - if (x == null || x instanceof Expression.EmptyArraySize) { - return null; - //javaType = jr = new ArrayRef(typeRef(Pointer.class)); - //break; - } else { - Pair c = convertExpressionToJava(x, callerLibraryName, false); - c.getFirst().setParenthesis(dims.size() > 1); - if (mul == null) { - mul = c.getFirst(); - } else { - mul = expr(c.getFirst(), Expression.BinaryOperator.Multiply, mul); - } - } - } - return mul; - } - - protected Expression sizeofToJava(TypeRef type, Identifier libraryClassName) throws UnsupportedConversionException { - type = resolveTypeDef(type, libraryClassName, true, false); -// type = type; - - Expression res = null; - if (type instanceof TypeRef.Pointer) { - res = memberRef(expr(typeRef(result.config.runtime.pointerClass)), Expression.MemberRefStyle.Dot, "SIZE"); - } else if (type instanceof TypeRef.ArrayRef) { - res = sizeofToJava(((TypeRef.ArrayRef) type).getTarget(), libraryClassName); - if (res == null) { - return null; - } - - TypeRef.ArrayRef ar = (TypeRef.ArrayRef) type; - for (Expression x : ar.getDimensions()) { - Expression c = convertExpressionToJava(x, libraryClassName, false).getFirst(); - res = expr(res, Expression.BinaryOperator.Multiply, c); - } - } else if (type instanceof TypeRef.SimpleTypeRef || type instanceof TypeRef.Primitive) { - JavaPrim prim = getPrimitive(type, libraryClassName); - if (prim != null) { - res = sizeof(prim); - } else { - SimpleTypeRef structRef = findStructRef(((TypeRef.SimpleTypeRef) type).getName(), libraryClassName); - if (structRef == null) { - structRef = findStructRef(((TypeRef.SimpleTypeRef) type).getName().resolveLastSimpleIdentifier(), libraryClassName); - } - if (structRef != null) { - return methodCall(new Expression.New(structRef), Expression.MemberRefStyle.Dot, "size"); - } - } - } else if (type instanceof Struct) { - Struct s = (Struct) type; - if (s != null) { - Identifier structName = result.declarationsConverter.getActualTaggedTypeName(s); - SimpleTypeRef structRef = findStructRef(structName, libraryClassName); - if (structRef != null) { - return methodCall(new Expression.New(structRef), Expression.MemberRefStyle.Dot, "size"); - } else { - for (Declaration d : s.getDeclarations()) { - if (d instanceof VariablesDeclaration) { - TypeRef varsType = d.getValueType(); - for (Declarator sto : ((VariablesDeclaration) d).getDeclarators()) { - Expression so = sizeofToJava(as(sto.mutateType(varsType), TypeRef.class), libraryClassName); - if (so == null) { - return null; - } - - if (res == null) { - res = so; - } else { - res = expr(res, Expression.BinaryOperator.Plus, so); - } - } - } - } - } - } - } - return res; - } - public Pair convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { - Pair res = null; - if (x instanceof Expression.Cast) { - TypeRef tpe = ((Expression.Cast) x).getType(); - Pair casted = convertExpressionToJava(((Expression.Cast) x).getTarget(), libraryClassName, promoteNativeLongToLong); - - NL4JConversion conv = convertTypeToNL4J(tpe, libraryClassName, null, null, -1, -1); - TypeRef tr = conv.typeRef; - Expression val = casted.getFirst(); - if (ConvType.Pointer.equals(conv.type)) { - if (isString(val)) - val = methodCall(expr(typeRef(result.config.runtime.pointerClass)), "pointerToCString", val); - else - val = methodCall(expr(typeRef(result.config.runtime.pointerClass)), "pointerToAddress", val); - } - res = typed(val, tr); - } else if (x instanceof Expression.FunctionCall) { - Expression.FunctionCall fc = (Expression.FunctionCall) x; - if ("sizeof".equals(String.valueOf(fc.getFunction())) && fc.getArguments().size() == 1) { - Expression.TypeRefExpression typeEx = SyntaxUtils.as(fc.getArguments().get(0).getValue(), Expression.TypeRefExpression.class); - if (typeEx != null) { - res = typed(sizeofToJava(typeEx.getType(), libraryClassName), typeRef(Integer.TYPE)); - } - } - } - if (res == null) { - return super.convertExpressionToJava(x, libraryClassName, promoteNativeLongToLong); - } - if (res.getFirst() == null) { - return null; - } - res.getFirst().setParenthesis(x.getParenthesis()); - return (Pair) res; - } - - @Override - protected JavaPrim getCppBoolMappingType() { - return JavaPrim.Boolean; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java deleted file mode 100644 index 09bbe47c0..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java +++ /dev/null @@ -1,628 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.BridJTypeConversion.NL4JConversion; -import java.util.Collections; -import java.util.Collection; -import java.io.PrintStream; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import org.bridj.BridJ; -import java.util.Map; -import java.util.HashMap; -import java.util.Set; -import java.util.HashSet; -import java.util.List; -import java.util.ArrayList; -import java.util.Arrays; -import com.ochafik.lang.jnaerator.parser.*; -import static com.ochafik.lang.jnaerator.parser.Statement.*; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.TypeConversion.*; -import static com.ochafik.lang.jnaerator.MatchingUtils.*; - -/* -mvn -o compile exec:java -Dexec.mainClass=com.ochafik.lang.jnaerator.JNAerator - -*/ -public class BridJer { - Result result; - public BridJer(Result result) { - this.result = result; - } - - - String primName(TypeRef tr) { - tr = tr.clone(); - tr.setModifiers(Collections.EMPTY_LIST); - return tr.toString(); - } - String primCapName(TypeRef tr) { - return StringUtils.capitalize(primName(tr)); - } - Expression staticPtrMethod(String name, Expression... args) { - return methodCall(expr(typeRef(ptrClass())), name, args); - } - int iFile = 0; - public Pair> convertToJava(Element element, final Identifier libraryClassName) { - //element = element.clone(); - try { - PrintStream out = new PrintStream("jnaerator-" + (iFile++) + ".out"); - out.println(element); - out.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - final List extraDeclarationsOut = new ArrayList(); - - final ReferencedElements ref = findReferencedElements(element); - - // Second pass : replacement ! - element.accept(new Scanner() { - - @Override - public void visitVariableRef(VariableRef vr) { - super.visitVariableRef(vr); - String identStr = vr.getName() + ""; - if ("NULL".equals(identStr)) - vr.replaceBy(nullExpr()); - } - - int nConstants = 0; - - @Override - public void visitConstant(Constant c) { - if (c.getValue() instanceof String) { - //Struct s = c.findParentOfType(Struct.class); - Class charClass; - String ptrMethodName; - if (c.getType() == Constant.Type.LongString) { - charClass = Short.class; - ptrMethodName = "pointerToWideCString"; - } else { - charClass = Byte.class; - ptrMethodName = "pointerToCString"; - } - String fieldName = "strConstant" + (++nConstants); - VariablesDeclaration staticConstField = new VariablesDeclaration(typeRef(ident(ptrClass(), expr(typeRef(charClass)))), new DirectDeclarator(fieldName, staticPtrMethod(ptrMethodName, c.clone()))); - staticConstField.addModifiers(ModifierType.Static, ModifierType.Private, ModifierType.Final); - //s.addDeclaration(staticConstField); - extraDeclarationsOut.add(staticConstField); - c.replaceBy(varRef(fieldName)); - return; - } - - super.visitConstant(c); - } -// -// static Map primToCapNames = new HashMap(); -// static { -// primToCapNames.put("int", "Int"); -// primToCapNames.put("long", "Long"); -// primToCapNames.put("short", "Short"); -// primToCapNames.put("byte", "Byte"); -// primToCapNames.put("double", "Double"); -// primToCapNames.put("float", "Float"); -// primToCapNames.put("char", "Char"); -// primToCapNames.put("boolean", "Boolean"); -// } - void replaceMalloc(TypeRef pointedType, Element toReplace, Expression sizeExpression) { - // TODO handle casts and sizeof expressions ! - Pair typeAndSize = recognizeSizeOfMult(sizeExpression); - if (typeAndSize != null && (pointedType == null || pointedType.equals(typeAndSize.getFirst()))) { - String tStr = String.valueOf(typeAndSize.getFirst()); - try { - JavaPrim prim = JavaPrim.getJavaPrim(tStr); - if (prim != null && prim.isPrimitive) { - String cap = StringUtils.capitalize(tStr); - toReplace.replaceBy(staticPtrMethod("allocate" + cap + "s", typeAndSize.getValue())); - return; - } - } catch (Throwable th) { - // Do nothing - } - - } - - toReplace.replaceBy(staticPtrMethod("allocateBytes", sizeExpression)); - } - - void visitAllButConstants(List elements) { - if (elements == null) - return; - for (T element : elements) { - if (element == null || (element instanceof Constant)) - continue; - - element.accept(this); - } - } - List getArgs(List> args) { - if (args == null) - return null; - List ret = new ArrayList(args.size()); - for (Pair p : args) - ret.add(p.getValue()); - - return ret; - } - - @Override - public void visitDelete(Delete d) { - d.replaceBy(stat(methodCall(d.getValue(), "release"))); - } - - @Override - public void visitFunctionCall(FunctionCall fc) { - super.visit(fc.getTarget()); - super.visit(fc.getFunction()); - List arguments = getArgs(fc.getArguments()); - - //super.visitFunctionCall(fc); - if (fc.getTarget() == null && (fc.getFunction() instanceof VariableRef)) { - Identifier ident = ((VariableRef)fc.getFunction()).getName(); - if ((ident instanceof SimpleIdentifier) && ((SimpleIdentifier)ident).getTemplateArguments().isEmpty()) { - String name = ident.toString(); - int nArgs = arguments == null ? 0 : arguments.size(); - - Expression - arg1 = nArgs > 0 ? arguments.get(0) : null, - arg2 = nArgs > 1 ? arguments.get(1) : null, - arg3 = nArgs > 2 ? arguments.get(2) : null; - - if ("printf".equals(name)) { - visitAllButConstants(arguments); - fc.replaceBy(methodCall(memberRef(expr(typeRef(System.class)), "out"), "println", formatStr(arg1, arguments, 1))); - return; - } else if ("sprintf".equals(name)) { - visitAllButConstants(arguments); - fc.replaceBy(methodCall(arg1, "setCString", formatStr(arg2, arguments, 2))); - return; - } - - switch (nArgs) { - case 1: - if ("malloc".equals(name)) { - visit(arguments); - replaceMalloc(null, fc, arg1); - return; - } else if ("free".equals(name)) { - visit(arguments); - fc.replaceBy(methodCall(arg1, "release")); - return; - } - break; - case 3: - if ("memset".equals(name)) { - visit(arguments); - Expression value = arg2, num = arg3; - if ("0".equals(value + "")) - fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num)); - else - fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num, value)); - return; - } else if ("memcpy".equals(name)) { - visit(arguments); - Expression dest = arg1, source = arg2, num = arg3; - fc.replaceBy(methodCall(source, "copyBytesAtOffsetTo", expr(0), dest, expr(0), num)); - return; - } else if ("memmov".equals(name)) { - visit(arguments); - Expression dest = arg1, source = arg2, num = arg3; - fc.replaceBy(methodCall(source, "moveBytesAtOffsetTo", expr(0), dest, expr(0), num)); - return; - } else if ("memcmp".equals(name)) { - visit(arguments); - Expression ptr1 = arg1, ptr2 = arg2, num = arg3; - fc.replaceBy(methodCall(ptr1, "compareBytes", ptr2, num)); - return; - } - break; - } - - } - } - visit(arguments); - } - - - Expression formatStr(Expression str, List arguments, int argsToSkip) { - if (arguments.isEmpty()) - return str; - - List fmtArgs = new ArrayList(); - if (!(str instanceof Constant)) - str = methodCall(str, "getCString"); - - fmtArgs.add(str); - for (int i = argsToSkip, nArgs = arguments.size(); i < nArgs; i++) - fmtArgs.add(arguments.get(i)); - - return methodCall(expr(typeRef(String.class)), "format", fmtArgs.toArray(new Expression[fmtArgs.size()])); - } - @Override - public void visitIf(If ifStat) { - super.visitIf(ifStat); - Expression cond = ifStat.getCondition(); - if (!(cond instanceof BinaryOp)) // TODO use typing rather than this hack to detect implicit boolean conversion in if statements (and not only there) - cond.replaceBy(expr(cond, BinaryOperator.IsDifferent, expr(0))); - } - - @Override - public void visitUnaryOp(UnaryOp unaryOp) { - super.visitUnaryOp(unaryOp); - - switch (unaryOp.getOperator()) { - case Dereference: - unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "get")); - break; - case Reference: - // TODO handle special case of referenced primitives, for instance - unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "getReference")); - break; - } - } - - @Override - public void visitCast(Cast cast) { - super.visitCast(cast); - if (cast.getType() instanceof TargettedTypeRef) { - cast.replaceBy(methodCall(cast.getTarget(), "as", result.typeConverter.typeLiteral(((TargettedTypeRef)cast.getType()).getTarget()))); - } - } - - @Override - public void visitArrayAccess(ArrayAccess arrayAccess) { - super.visitArrayAccess(arrayAccess); - arrayAccess.replaceBy(methodCall(arrayAccess.getTarget(), "get", arrayAccess.getIndex())); - } - - @Override - public void visitMemberRef(MemberRef memberRef) { - // TODO restrict to struct/class fields - // TODO handle global variables with explicit namespaces... - if (!(memberRef.getParentElement() instanceof FunctionCall)) { - if (memberRef.getName() != null) { - switch (memberRef.getMemberRefStyle()) { - case Colons: - memberRef.setMemberRefStyle(MemberRefStyle.Dot); - break; - case Arrow: - case Dot: - Expression rep = methodCall(memberRef.getTarget(), memberRef.getName().toString()); - if (memberRef.getMemberRefStyle() == MemberRefStyle.Arrow) - rep = methodCall(rep, "get"); - memberRef.replaceBy(rep); - rep.accept(this); - return; - } - } - } - super.visitMemberRef(memberRef); - } - - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - if (v.getDeclarators().size() == 1) { - Declarator decl = v.getDeclarators().get(0); - //DirectDeclarator decl = (DirectDeclarator); - TypeRef vt = v.getValueType(); - MutableByDeclarator mt = decl instanceof DirectDeclarator ? vt : decl.mutateTypeKeepingParent(vt); - - if (mt instanceof TypeRef) { - TypeRef mutatedType = (TypeRef)mt; - if (decl.getDefaultValue() == null) { - TypeRef actualType = mutatedType; - boolean referenced = ref.varDeclTypeRefsTransformedToPointers.contains(v) && (mutatedType instanceof Pointer); - if (referenced) { - actualType = ((Pointer)mutatedType).getTarget(); - } - if (result.symbols.isClassType(actualType)) { - decl.setDefaultValue(referenced ? staticPtrMethod("allocate", result.typeConverter.typeLiteral(actualType)) : new Expression.New(actualType.clone())); - Expression vr = varRef(new SimpleIdentifier(decl.resolveName())); - Statement deleteStat = stat(methodCall(expr(typeRef(BridJ.class)), "delete", referenced ? methodCall(vr, "get") : vr)); - deleteStat.setCommentAfter("// object would end up being deleted by the GC later, but in C++ it would be deleted here."); - - Statement.Block parentBlock = (Statement.Block)v.getParentElement(); - List stats = new ArrayList(parentBlock.getStatements()); - for (int i = stats.size(); i-- != 0;) { - Statement stat = stats.get(i); - if (!(stat instanceof Statement.Return) && !deleteStatements.contains(stat)) { - stats.add(i + 1, deleteStat); - deleteStatements.add(deleteStat); - break; - } - } - parentBlock.setStatements(stats); - } - }// else { - NL4JConversion conv = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J( - mutatedType, - libraryClassName,//callerLibraryName, - null,//thisField("io"), - null,//varRef(name), - -1,//fieldIndex, - -1//bits - ); - - v.setValueType(conv.getTypeRef(false)); - - if (conv.arrayLengths != null && (mutatedType instanceof TargettedTypeRef) && decl.getDefaultValue() == null) - v.setDeclarators(Arrays.asList((Declarator)new DirectDeclarator(decl.resolveName(), newAllocateArray(((TargettedTypeRef)mutatedType).getTarget(), conv.arrayLengths)))); - - //} - } - } - } - - Set deleteStatements = new HashSet(); - - @Override - public void visitAssignmentOp(AssignmentOp assignment) { - BinaryOperator binOp = assignment.getOperator().getCorrespondingBinaryOp(); - Expression value = assignment.getValue(); - value.setParenthesisIfNeeded(); - if (assignment.getTarget() instanceof UnaryOp) { - UnaryOp uop = (UnaryOp)assignment.getTarget(); - if (uop.getOperator() == UnaryOperator.Dereference) { - visit(uop.getOperand()); - visit(assignment.getValue()); - Expression target = uop.getOperand(); - if (binOp != null) { - value = expr(methodCall(target.clone(), "get"), binOp, value); - } - assignment.replaceBy(methodCall(target, "set", value)); - return; - } - } - if (assignment.getTarget() instanceof ArrayAccess) { - ArrayAccess aa = (ArrayAccess)assignment.getTarget(); - visit(aa.getTarget()); - visit(aa.getIndex()); - visit(assignment.getValue()); - Expression target = aa.getTarget(); - Expression index = aa.getIndex(); - if (binOp != null) { - value = expr(methodCall(target.clone(), "get", index.clone()), binOp, value); - } - assignment.replaceBy(methodCall(target, "set", index, value)); - return; - } - if (assignment.getTarget() instanceof MemberRef) { - MemberRef mr = (MemberRef)assignment.getTarget(); - boolean isArrow = mr.getMemberRefStyle() == MemberRefStyle.Arrow; - if (isArrow || mr.getMemberRefStyle() == MemberRefStyle.Dot) { - Expression target = mr.getTarget(); - String name = mr.getName().toString(); - if (binOp != null) { - value = expr(methodCall(target.clone(), name), binOp, value); - } - if (isArrow) - target = methodCall(target, "get"); - - assignment.replaceBy(methodCall(target, name, value)); - return; - } - } - super.visitAssignmentOp(assignment); - - } - - - @Override - public void visitNew(New new1) { - super.visitNew(new1); - if (new1.getConstruction() == null) - new1.replaceBy(staticPtrMethod("allocate" + primCapName(new1.getType()))); - } - - public void notSup(Element x, String msg) throws UnsupportedConversionException { - throw new UnsupportedConversionException(x, msg); - } - - /* - @Override - public void visitExpressionStatement(ExpressionStatement expressionStatement) { - super.visitExpressionStatement(expressionStatement); - if (expressionStatement.getExpression() instanceof UnaryOp) { - UnaryOp uop = (UnaryOp)expressionStatement.getExpression(); - Expression target = uop.getOperand(); - switch (uop.getOperator()) { - case PostIncr: - case PreIncr: - expressionStatement.replaceBy(expr(target)); - } - } - }*/ - - Expression newAllocateArray(TypeRef tr, Collection sizes) { - return staticPtrMethod( - "allocate" + primCapName(tr) + "s", - sizes.toArray(new Expression[sizes.size()]) - ); - } - - @Override - public void visitNewArray(NewArray newArray) { - super.visitNewArray(newArray); - if (newArray.getType() instanceof Primitive) { - if (newArray.getDimensions().size() > 3) - notSup(newArray, "TODO only dimensions 1 to 3 are supported for primitive array creations !"); - - newArray.replaceBy(newAllocateArray(newArray.getType(), newArray.getDimensions())); - } else { - if (newArray.getDimensions().size() != 1) - notSup(newArray, "TODO only dimension 1 is supported for reference array creations !"); - - newArray.replaceBy( - staticPtrMethod( - "allocateArray", - result.typeConverter.typeLiteral(newArray.getType()), - newArray.getDimensions().get(0) - ) - ); - } - } - - @Override - public void visitPointer(Pointer pointer) { - super.visitPointer(pointer); - } - - /* - @Override - protected void visitTargettedTypeRef(TargettedTypeRef targettedTypeRef) { - super.visitTargettedTypeRef(targettedTypeRef); - if (targettedTypeRef.getTarget() != null) - targettedTypeRef.replaceBy(pointerToTypeRef(targettedTypeRef.getTarget().clone())); - }*/ - }); - return new Pair>(element, extraDeclarationsOut); - } - TypeRef getWrapperType(TypeRef tr) { - JavaPrim prim = result.typeConverter.getPrimitive(tr, null); - if (prim != null) - return typeRef(prim.wrapperType); - return tr; - } - TypeRef pointerToTypeRef(TypeRef targetType) { - Identifier id = ident(ptrClass()); - id.resolveLastSimpleIdentifier().addTemplateArgument(expr(targetType)); - return typeRef(id); - } - Class ptrClass() { - return result.config.runtime.pointerClass; - } - - static class ReferencedElements { - final Set> referencedElements = new HashSet>(); - final Set varDeclTypeRefsTransformedToPointers = new HashSet(); - } - private ReferencedElements findReferencedElements(Element element) { - final ReferencedElements ret = new ReferencedElements(); - element.accept(new Scanner() { - @Override - public void visitUnaryOp(UnaryOp unaryOp) { - super.visitUnaryOp(unaryOp); - - if (unaryOp.getOperator() == UnaryOperator.Reference) { - if (unaryOp.getOperand() instanceof VariableRef) { - VariableRef vr = (VariableRef)unaryOp.getOperand(); - Element e = result.symbols.getVariable(vr.getName()); - if (e != null) - ret.referencedElements.add(new Pair(e, e.getId())); - } - } - } - }); - - - - - final Map referencedElementsChangedNames = new HashMap(); - for (Pair kv : ret.referencedElements) { - Element e = kv.getKey(); - //int id = kv - if (e instanceof DirectDeclarator) { - DirectDeclarator decl = (DirectDeclarator)e; - String name = decl.getName(); - String changedName = "p" + StringUtils.capitalize(name); - referencedElementsChangedNames.put(e.getId(), changedName); - decl.setName(changedName); - VariablesDeclaration vd = (VariablesDeclaration)decl.getParentElement(); - TypeRef tr = vd.getValueType(); - //TypeRef wrapper = getWrapperType(tr); - //vd.setValueType(pointerToTypeRef(wrapper)); - vd.setValueType(new Pointer(tr, PointerStyle.Pointer)); - ret.varDeclTypeRefsTransformedToPointers.add(vd); - Expression defVal = decl.getDefaultValue(); - if (defVal != null) { - decl.setDefaultValue(staticPtrMethod("pointerTo" + primCapName(tr), defVal)); - } else { - decl.setDefaultValue(staticPtrMethod("allocate" + primCapName(tr))); - } - } - } - - - // First pass to detect referenced variables (no replacement here) : - element.accept(new Scanner() { - @Override - public void visitIdentifier(Identifier identifier) { - super.visitIdentifier(identifier); - Element e = result.symbols.getVariable(identifier); - if (e != null && isReferenced(e)) { - String changedName = referencedElementsChangedNames.get(e.getId()); - if (changedName != null) { - Identifier replacedIdentifier = ident(changedName); - identifier.replaceBy(replacedIdentifier); - ret.referencedElements.add(new Pair(replacedIdentifier, replacedIdentifier.getId())); - } - } - } - - boolean isReferenced(Element e) { - if (e == null) - return false; - return ret.referencedElements.contains(new Pair(e, e.getId())); - } - - @Override - public void visitVariableRef(VariableRef vr) { - super.visitVariableRef(vr); - Identifier ident = vr.getName(); - if (isReferenced(ident)) { - vr.replaceBy(methodCall(varRef(ident), "get")); - } - } - - @Override - public void visitUnaryOp(UnaryOp unaryOp) { - if (unaryOp.getOperator() == UnaryOperator.Reference) { - if (unaryOp.getOperand() instanceof VariableRef) { - VariableRef vr = (VariableRef)unaryOp.getOperand(); - - Identifier ident = vr.getName(); - Element e = result.symbols.getVariable(ident); - if ((e != null || isReferenced(e)) || isReferenced(ident)) { - String changedName = referencedElementsChangedNames.get(e.getId()); - if (changedName != null) { - Element rep = varRef(changedName); - unaryOp.replaceBy(rep); - visit(rep); - return; - } - } - } - } - super.visitUnaryOp(unaryOp); - } - }); - - return ret; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridgeSupportParser.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridgeSupportParser.java deleted file mode 100644 index 456b2b214..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridgeSupportParser.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; - -import javax.xml.xpath.XPathExpressionException; - -import org.antlr.runtime.ANTLRReaderStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.ObjCDemanglingLexer; -import com.ochafik.lang.jnaerator.parser.ObjCDemanglingParser; -import com.ochafik.lang.jnaerator.parser.ObjCppParser; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TaggedTypeRefDeclaration; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Function.Type; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.xml.XMLUtils; -import com.ochafik.xml.XPathUtils; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class BridgeSupportParser { - final Result result; - SourceFiles sourceFiles; - public BridgeSupportParser(Result result, SourceFiles sourceFiles) { - this.result = result; - this.sourceFiles = sourceFiles; - } - - public static void main(String[] args) { - try { - JNAeratorConfig config = new JNAeratorConfig(); - config.verbose = true; - Result result = new Result(config, null, null); - SourceFiles sourceFiles = new SourceFiles(); - File file = new File("/System/Library/Frameworks/Foundation.framework/Resources/BridgeSupport/FoundationFull.bridgesupport"); - new BridgeSupportParser(result, sourceFiles).parseBridgeSupportFile(file); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - public void parseBridgeSupportFiles() throws FileNotFoundException { - SourceFiles sfs = new SourceFiles(); - try { - for (File bsf : result.config.bridgeSupportFiles) { - try { - sfs.add(parseBridgeSupportFile(bsf)); - } catch (Throwable e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } finally { - if (result.config.bridgesupportOutFile != null) - { - if (result.config.verbose) - System.out.println("Writing bridgesupport definitions to " + result.config.bridgesupportOutFile.getAbsolutePath()); - PrintWriter pw = new PrintWriter(result.config.bridgesupportOutFile); - pw.println(sfs); - pw.close(); - } - for (SourceFile sf : sfs.getSourceFiles()) - sourceFiles.add(sf); - } - } - - private SourceFile parseBridgeSupportFile(File bsf) throws Exception { - - String framework = bsf.getName(); - if (framework.toLowerCase().endsWith(".bridgesupport")) - framework = framework.substring(0, framework.length() - ".bridgesupport".length()); - - Document xml = XMLUtils.readXML(bsf); - - String sourceFilePath = bsf.toString(); - Node signatures = XMLUtils.getFirstNamedNode(xml, "signatures"); - if (signatures == null) - return null; - - SourceFile sf = new SourceFile(); - sf.setElementFile(sourceFilePath); - - parseStructs(signatures, sf); - parseEnums(signatures, sf); - parseConstants(signatures, sf); - parseClasses(framework, signatures, sf); - parseStringConstants(framework, signatures, sf); - parseFunctions(framework, signatures, sf); - - return sf; - } - - private void parseEnums(Node signatures, SourceFile sf) { - for (Node en : XMLUtils.getChildrenByName(signatures, "enum")) { - String name = XMLUtils.getAttribute(en, "name"); - String value = XMLUtils.getAttribute(en, "value"); - if (value != null) { - try { - try { - int i = value.matches(".*?\\.0+$") ? value.lastIndexOf('.') : -1; - String v = i > 0 ? value.substring(0, i) : value; - sf.addDeclaration(new VariablesDeclaration(typeRef("int").addModifiers(ModifierType.Const), new DirectDeclarator(name, expr(Integer.parseInt(v))))); - } catch (NumberFormatException fex) { - sf.addDeclaration(new VariablesDeclaration(typeRef("double").addModifiers(ModifierType.Const), new DirectDeclarator(name, expr(Double.parseDouble(value))))); - } - - } catch (Exception ex) { - System.err.println("Parsing of enum " + name + " with value '" + value + "' failed : " + ex); - } - } - - } - } - private void parseConstants(Node signatures, SourceFile sf) { - for (Node cn : XMLUtils.getChildrenByName(signatures, "constant")) { - String name = XMLUtils.getAttribute(cn, "name"); - try { - TypeRef tr = parseType(cn); - if (tr == null) - continue; - - sf.addDeclaration(new VariablesDeclaration(tr.addModifiers(ModifierType.Extern, ModifierType.Const), - new DirectDeclarator(name))); - } catch (Exception ex) { - System.err.println("Parsing of constant " + name + " failed : " + ex); - } - } - } - - private void parseClasses(String framework, Node signatures, SourceFile sf) throws XPathExpressionException { - for (Node classe : XMLUtils.getChildrenByName(signatures, "class")) { - Struct cs = parseClasse(classe, Struct.Type.ObjCClass, sf); - if (cs == null) - continue; - - if (!"NSObject".equals(String.valueOf(cs.getTag().toString()))) - cs.setParents(typeRef(ident("NSObject"))); - -// cs.accept(result); - } - for (Node classe : XMLUtils.getChildrenByName(signatures, "informal_protocol")) { - Struct cs = parseClasse(classe, Struct.Type.ObjCClass, sf); - if (cs == null) - continue; - - cs.setCategoryName(cs.getTag() == null ? null : cs.getTag().toString()); - cs.setTag(ident("NSObject")); -// cs.accept(result); - } - } - private Struct parseClasse(Node classe, - com.ochafik.lang.jnaerator.parser.Struct.Type type, - SourceFile sf) throws XPathExpressionException { - - Struct cs = new Struct(); - cs.setType(type); - String name = XMLUtils.getAttribute(classe, "name"); - if (result.config.verbose) - System.out.println("Parsing class " + name); - - cs.setTag(ident(name)); - - for (Node method : XPathUtils.findNodesIterableByXPath("method", classe)) { -// String mname = XMLUtils.getAttribute(method, "selector"); - try { -// if ((name.equals("NSScriptClassDescription") || name.equals("NSObject")) && mname.contains("classCode")) -// name.toString(); - cs.addDeclaration(parseFunction(Type.ObjCMethod, method, sf)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - sf.addDeclaration(new TaggedTypeRefDeclaration(cs)); - return cs; - } - - private void parseFunctions(String framework, Node signatures, SourceFile sf) throws XPathExpressionException { - for (Node function : XMLUtils.getChildrenByName(signatures, "function")) { - String name = XMLUtils.getAttribute(function, "name"); - Node retval = XMLUtils.getFirstNamedNode(function, "retval"); - String already_retained = retval != null ? XMLUtils.getAttribute(retval, "already_retained") : null; - if (already_retained != null && (already_retained = already_retained.trim()).length() > 0) - { - boolean alreadyRetained = "true".equals(already_retained); - Result.getMap(result.retainedRetValFunctions, framework).put(name, alreadyRetained); - } - if ("true".equals(XMLUtils.getAttribute(function, "inline"))) - continue; // TODO handle inline functions : link to BridgeSupport auxiliary library - - try { - Function f = parseFunction(Type.CFunction, function, sf); - if (f == null) - continue; - sf.addDeclaration(f); -// f.accept(result); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - public TypeRef parseType(Node node) throws XPathExpressionException, RecognitionException, IOException { - if (node == null) - return null; - - TypeRef declaredType = null; - try { - String dt = XMLUtils.getAttribute(node, "declared_type"); - if (dt != null) { - ObjCppParser parser = new JNAeratorParser().newObjCppParser(result.typeConverter, dt, false, null); - parser.setupScopes(); - declaredType = parser.mutableTypeRef(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - TypeRef inferredType = null; - if (declaredType == null || declaredType instanceof SimpleTypeRef) { - inferredType = parseAndReconciliateType(XMLUtils.getAttribute(node, "type"), XMLUtils.getAttribute(node, "type64")); - if (inferredType != null && declaredType instanceof SimpleTypeRef && !inferredType.toString().equals(declaredType.toString())) { - String sn = ((SimpleTypeRef)declaredType).getName().toString(); - result.addWeakTypeDef(inferredType.clone(), sn); - } - } - return declaredType != null ? declaredType : inferredType; - } - private Function parseFunction(Type cfunction, Node function, SourceFile sf) throws XPathExpressionException, RecognitionException, IOException { - TypeRef tr = parseType(XMLUtils.getFirstNamedNode(function, "retval")); - -// if (tr == null) -// tr = typeRef("id"); - - String selector = XMLUtils.getAttribute(function, "selector"); - String[] splitSelector = selector == null ? null : selector.split(":"); - String name = XMLUtils.getAttribute(function, "name"); - if (name == null && splitSelector != null && splitSelector.length > 0) - name = splitSelector[0]; - - String type = XMLUtils.getAttribute(function, "type"), type64 = XMLUtils.getAttribute(function, "type64"); - Function methodType = null; - if (type != null) { - methodType = parseAndReconciliateMethods(type, type64); - if (tr == null) - tr = methodType.getValueType(); -// System.out.println(methodType.toString()); - } - - Function f = new Function(cfunction, ident(name), tr); - - String class_method = XMLUtils.getAttribute(function, "class_method"); - if ("true".equals(class_method)) - f.addModifiers(ModifierType.Static); - -// f.setElementFile(sf); - int iArg = 0; - for (Node arg : XMLUtils.getChildrenByName(function, "arg")) {//XPathUtils.findNodesIterableByXPath("arg", function)) { - TypeRef at = parseType(arg); - if (at == null && methodType != null) { - if (iArg < methodType.getArgs().size()) - at = methodType.getArgs().get(iArg).getValueType(); - else - at = null; - } - if (at == null) - return null; - Arg a = new Arg(); - a.setName(XMLUtils.getAttribute(arg, "name")); - a.setValueType(at); - a.setSelector(splitSelector == null || iArg >= splitSelector.length ? null : splitSelector[iArg]); - f.addArg(a); - iArg++; - } - return f; - } - - TypeRef parseType(String mangled) throws RecognitionException, IOException { - return newObjCDemangler(mangled, true).mangledTypeEOF(); - } - Function parseMethod(String mangled) throws RecognitionException, IOException { - return newObjCDemangler(mangled, true).methodType(); - } - TypeRef parseAndReconciliateType(String mangled32, String mangled64) throws RecognitionException, IOException { -// System.out.println("Parsing \"" + mangled32 + "\":"); - if (mangled32 == null) - return null; - - TypeRef tr32 = parseType(mangled32); - if (mangled64 != null && mangled64.trim().length() > 0 && !mangled32.equals(mangled64)) { -// System.out.println("Parsing \"" + mangled64 + "\":"); - TypeRef tr64 = parseType(mangled64); - - try { - return (TypeRef)result.universalReconciliator.reconciliate32bitsAnd64bits(tr32, tr64); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } else - return tr32; - - } - Function parseAndReconciliateMethods(String mangled32, String mangled64) throws RecognitionException, IOException { -// System.out.println("Parsing \"" + mangled32 + "\":"); - if (mangled32 == null) - return null; - - Function tr32 = parseMethod(mangled32); - if (mangled64 != null && mangled64.trim().length() > 0 && !mangled32.equals(mangled64)) { -// System.out.println("Parsing \"" + mangled64 + "\":"); - Function tr64 = parseMethod(mangled64); - - try { - return (Function)result.universalReconciliator.reconciliate32bitsAnd64bits(tr32, tr64); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } else - return tr32; - - } - private void parseStructs(Node signatures, SourceFile sf) throws XPathExpressionException { - for (Node function : XMLUtils.getChildrenByName(signatures, "struct")) {//PathUtils.findNodesIterableByXPath("signatures/struct", xml)) { - String name = XMLUtils.getAttribute(function, "name"); -// if (name.equals("NSFastEnumerationState")) -// name.toString(); - String type32 = XMLUtils.getAttribute(function, "type"), type64 = XMLUtils.getAttribute(function, "type64"); - try { - try { - TypeRef tr = parseAndReconciliateType(type32, type64); - StoredDeclarations.TypeDef td = new StoredDeclarations.TypeDef(tr, new Declarator.DirectDeclarator(name)); - //td.addToCommentBefore("Original signature : " + type32); - sf.addDeclaration(td); - -// System.out.println(td); -// System.out.println(); - -// if (name.equals("NSRange") || name.equals("NSSize")) -// name.toString(); -// td.accept(result); - } catch (Exception ex) { - ex.printStackTrace(); - continue; - } - - } catch (Exception e) { - - e.printStackTrace(); - } - //Result.getMap(result.retainedRetValFunctions, framework).put(name, alreadyRetained); - //} - } - } - static ObjCDemanglingParser newObjCDemangler(String s, final boolean verbose) throws IOException { - return new ObjCDemanglingParser( - new CommonTokenStream( - new ObjCDemanglingLexer( - new ANTLRReaderStream(new StringReader(s)) - ) - ) -// , new DummyDebugEventListener() - ) { - @Override - public void reportError(RecognitionException arg0) { - if (verbose) { -// System.err.println(arg0 + " (next = '" + next() + "')"); - super.reportError(arg0); - } - } - }; - } - - private void parseStringConstants(String framework, Node signatures, SourceFile sf) throws XPathExpressionException { - for (Node string_constant : XMLUtils.getChildrenByName(signatures, "string_constant")) { - String name = XMLUtils.getAttribute(string_constant, "name"); - String value = XMLUtils.getAttribute(string_constant, "value"); - if (value != null) { - Result.getMap(result.stringConstants, framework).put(name, value); - } - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CPlusPlusAccess.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CPlusPlusAccess.java deleted file mode 100644 index 624a97e5f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CPlusPlusAccess.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -//https://jna.dev.java.net/servlets/ReadMsg?list=users&msgNo=1994 -public class CPlusPlusAccess { - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CSlicer.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CSlicer.java deleted file mode 100644 index ea1917556..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CSlicer.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.Declaration; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.anarres.cpp.LexerException; - -/** -mvn compile exec:java -Dexec.mainClass=com.ochafik.lang.jnaerator.CSlicer - */ -public class CSlicer { - - private CharSequence getContent() { - return content; - } - - private void pop(BlockType blockType) { - if (blocks.isEmpty()) - throw new RuntimeException("Empty blocks, got closing " + blockType); - if (blocks.pop() != blockType) - System.out.println("bad pop"); - } - - enum BlockType { - - Paren, Curly, Square - } - - enum State { - - String, Char, Normal, StringEscape, CharEscape, - NormalSlash, SingleLineComment, MultilineComment, StarInMultilineComment - } - State state = State.Normal; - Stack blocks = new Stack(); - StringBuilder content = new StringBuilder(); - int semiColonCount; - void appendLine(String s) { - for (char c : s.toCharArray()) { - append(c); - } - append('\n'); - } - - private void append(char c) { - if (state == State.NormalSlash) { - switch (c) { - case '/': - state = State.SingleLineComment; - return; - case '*': - state = State.MultilineComment; - return; - default: - content.append('/'); - state = State.Normal; - } - } - switch (state) { - case Char: - switch (c) { - case '\'': - state = State.Normal; - break; - case '\\': - state = State.CharEscape; - break; - } - break; - case String: - switch (c) { - case '"': - state = State.Normal; - break; - case '\\': - state = State.StringEscape; - break; - } - break; - case CharEscape: - state = State.Char; - break; - case StringEscape: - state = State.String; - break; - case SingleLineComment: - if (c == '\n') - state = State.Normal; - break; - case MultilineComment: - if (c == '*') - state = State.StarInMultilineComment; - break; - case StarInMultilineComment: - if (c == '/') { - state = State.Normal; - return; - } - else - state = State.MultilineComment; - break; - case Normal: - switch (c) { - case '/': - state = State.NormalSlash; - break; - case '\'': - state = State.Char; - break; - case '"': - state = State.String; - break; - case '(': - blocks.push(BlockType.Paren); - break; - case '{': - blocks.push(BlockType.Curly); - break; - case '[': - blocks.push(BlockType.Square); - break; - case ')': - pop(BlockType.Paren); - break; - case '}': - pop(BlockType.Curly); - break; - case ']': - pop(BlockType.Square); - break; - case ';': - semiColonCount++; - break; - } - break; - default: - throw new RuntimeException("state unhandled : " + state); - } - switch (state) { - case MultilineComment: - case SingleLineComment: - case NormalSlash: - case StarInMultilineComment: - break; - default: - content.append(c); - } - } - - boolean isParsable() { - return state == State.Normal && blocks.isEmpty(); - } - - public int getSemiColonCount() { - return semiColonCount; - } - - public static String removeComments(String s) { - CSlicer tester = new CSlicer(); - tester.appendLine(s); - return tester.getContent().toString(); - //return s.replaceAll("(?m)/(/.*$|\\*(\\*[^/]|[^*])*?\\*/)", " "); - } -// public static boolean[] computeCumulativeParseability(String[] lines) { -// int n = lines.length; -// boolean[] ret = new boolean[n]; -// Tester tester = new Tester(); -// for (int i = 0; i < n; i++) { -// String line = lines[i]; -// tester.append(line); -// ret[i] = tester.isParsable(); -// } -// return ret; -// } - public static String[] getLines(String source) { - String[] lines = source.split("\n"); - List ret = new ArrayList(lines.length); - for (String line : lines) { - String s = line.trim(); - if (s.length() != 0) - ret.add(s); - } - return ret.toArray(new String[ret.size()]); - - } - interface Callback { - boolean apply(CharSequence content, int semiColonCount); - } - public static void getParseableIncrements(String source, Callback cb) { - String[] lines = getLines(source); - CSlicer tester = new CSlicer(); - for (String line : lines) { - //System.out.print('.'); - tester.appendLine(line); - if (tester.isParsable()) { - if (!cb.apply(tester.getContent(), tester.getSemiColonCount())) - break; - } else { - //System.err.println("Not parseable : state = " + tester.state + ", blocks = " + StringUtils.implode(tester.blocks, ",")); - } - } - } - public static void main(String[] args) throws IOException, LexerException { - String source = preprocess(new File("test.h")); - source = removeComments(source); - - getParseableIncrements(source, new Callback() { - int lastDeclCount, lastSemiCount, lastContentLength; - int nErr; - @Override - public boolean apply(CharSequence content, int semiColonCount) { - try { - //System.out.print('c'); - if (semiColonCount == lastSemiCount) - return true; - - String source = content.toString() + ";"; - List decls = parseDeclarations(source); - int nDecls = decls.size(); - int length = content.length(); - System.out.println("Parsed " + nDecls + " declarations in " + length + " chars"); - if (nDecls == lastDeclCount) { - String diff = content.subSequence(lastContentLength, length).toString(); - String errFile = "err-" + (++nErr) + ".h"; - System.out.println("Failed to parse new declaration in : \n\t" + diff.replaceAll("\n", "\n\t") + "\nCode was saved in " + errFile); - System.out.println("Last parsed declaration :"); - System.out.println("\t" + String.valueOf(decls.get(decls.size() - 1)).replaceAll("\n", "\n\t")); - PrintStream out = new PrintStream(new FileOutputStream(errFile)); - out.println(source); - out.println("#if 0 // Here's the diff to the last compilable code :"); - out.println(diff); - out.println("#endif"); - out.println("#if 0 // Here's the last parsed declaration"); - out.println(String.valueOf(decls.get(decls.size() - 1))); - out.println("#endif"); - out.close(); - //return false; - } - lastContentLength = length; - lastSemiCount = semiColonCount; - lastDeclCount = nDecls; - return true; - } catch (Throwable ex) { - Logger.getLogger(CSlicer.class.getName()).log(Level.SEVERE, null, ex); - return false; - } - } - }); - } - static String preprocess(File source) throws IOException, LexerException { - JNAeratorConfig config = new JNAeratorConfig(); - JNAeratorConfigUtils.autoConfigure(config); - config.preprocessorConfig.includes.add("C:\\program files\\Microsoft SDKs\\Windows\\v7.0A\\Include"); - config.preprocessorConfig.includes.add("C:\\program files\\Microsoft Visual Studio 10.0\\VC\\include"); - //config.preprocessorConfig.includeStrings.add(source); - config.addSourceFile(source, null, false, true); - Result result = new Result(config, null, null); - String pre = PreprocessorUtils.preprocessSources(config, Collections.EMPTY_LIST, false, result.typeConverter, null); - return pre; - } - static List parseDeclarations(String source) throws IOException, LexerException, InterruptedException { - JNAeratorConfig config = new JNAeratorConfig(); - JNAeratorConfigUtils.autoConfigure(config); - //config.noCPlusPlus = true; - config.preprocessorConfig.includeStrings.add(source); - Result result = new Result(config, null, null); - SourceFiles parse = new JNAeratorParser().parse(config, result.typeConverter, null); - - List ret = new ArrayList(); - flatten(parse, ret); - return ret; - } - static void flatten(Element element, List out) { - if (element instanceof SourceFiles) { - for (SourceFile f : ((SourceFiles)element).getSourceFiles()) - flatten(f, out); - } - if (element instanceof DeclarationsHolder) { - for (Declaration d : ((DeclarationsHolder)element).getDeclarations()) - flatten(d, out); - } else if (element instanceof Declaration) { - out.add((Declaration)element); - } - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CToJavaPreScanner.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CToJavaPreScanner.java deleted file mode 100644 index 811ed9505..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/CToJavaPreScanner.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.*; -import static com.ochafik.lang.jnaerator.parser.Identifier.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.FunctionDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.MutableByDeclarator; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.util.string.StringUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; - -public class CToJavaPreScanner extends Scanner { - public CToJavaPreScanner() { - } - - @Override - public void visitStruct(Struct struct) { - super.visitStruct(struct); - if (struct.isForwardDeclaration() && struct.getTag() != null) { - Element parent = struct.getParentElement(); - if (!(parent instanceof TaggedTypeRefDeclaration)) { - TypeRef tr = new TypeRef.SimpleTypeRef(struct.getTag()); - for (Modifier mod : struct.getModifiers()) { - if (mod.isA(ModifierKind.StorageClassSpecifier)) - tr.addModifiers(mod); - } - struct.replaceBy(tr); - tr.accept(this); - } - } - } - - void moveModifiersOfType(ModifierKind kind, ModifiableElement source, ModifiableElement destination) { - List mods = null; - - for (Modifier m : source.getModifiers()) { - if (m.isA(kind)) { - if (mods == null) - mods = new ArrayList(); - - mods.add(m); - } - } - if (mods != null) { - Modifier[] modsArray = mods.toArray(new Modifier[mods.size()]); - source.removeModifiers(modsArray); - destination.addModifiers(modsArray); - } - } - - @Override - public void visitFunction(Function function) { - List modifiers = function.getModifiers(); - - if (function.getValueType() == null) { - for (ModifierType mod : new ModifierType[] { ModifierType.Long, ModifierType.Short }) { - if (mod.isContainedBy(modifiers)) { - function.removeModifiers(mod); - function.setValueType(typeRef(mod.toString())); - break; - } - } - if (function.getValueType() == null) { - if (!(function.getParentElement() instanceof Struct) || !((Struct)function.getParentElement()).getType().isObjC()) - function.setValueType(typeRef("int")); - } - } else { - moveModifiersOfType(ModifierKind.CallingConvention, function.getValueType(), function); - } - super.visitFunction(function); - } - - - - @Override - public void visitTaggedTypeRefDeclaration(TaggedTypeRefDeclaration taggedTypeRefDeclaration) { - super.visitTaggedTypeRefDeclaration(taggedTypeRefDeclaration); - TaggedTypeRef tr = taggedTypeRefDeclaration.getTaggedTypeRef(); - if (tr != null) { - String before = tr.getCommentBefore(); - tr.setCommentBefore(taggedTypeRefDeclaration.getCommentBefore()); - tr.addToCommentBefore(before); - taggedTypeRefDeclaration.setCommentBefore(null); - } - } - - @Override - protected void visitStoredDeclarations(StoredDeclarations d) { - super.visitStoredDeclarations(d); - if (d.getDeclarators().size() == 1) { - Declarator declarator = d.getDeclarators().get(0); - if (declarator instanceof FunctionDeclarator) { - FunctionDeclarator fd = (FunctionDeclarator)declarator; - Function f = new Function(Function.Type.CFunction, null, d.getValueType(), fd.getArgs()); - f.addModifiers(fd.getTarget().getModifiers()); - FunctionSignature fs = new FunctionSignature(f); - d.setValueType(fs); - d.setDeclarators(Arrays.asList((Declarator)new DirectDeclarator(fd.resolveName(), fd.getDefaultValue()))); - d.accept(this); - } - } - } - - @Override - public void visitPrimitive(Primitive primitive) { - super.visitPrimitive(primitive); - - if (ModifierType.Long.isContainedBy(primitive.getModifiers())) { - Identifier name = primitive.getName(); - if (name != null && name.equals("int")) { - primitive.setName(ident("long")); - primitive.removeModifiers(ModifierType.Long); - } - } else if (ModifierType.Short.isContainedBy(primitive.getModifiers())) { - Identifier name = primitive.getName(); - if (name != null && name.equals("int")) { - primitive.setName(ident("short")); - primitive.removeModifiers(ModifierType.Short); - } - } - - } - - @Override - public void visitTypeDef(TypeDef v) { - super.visitTypeDef(v); - - Element toAddAfter = v; - - TypeRef valueType = v.getValueType(); - String bestName = null, origName = null; - TaggedTypeRef ttr = null; - if (valueType instanceof TaggedTypeRef) { - ttr = (TaggedTypeRef) valueType; - bestName = JNAeratorUtils.findBestPlainStorageName(v); - if (bestName != null) - origName = ttr.getTag() != null ? ttr.getTag().toString() : null; - } - - /// Explode comma-separated variables declarations - for (Declarator vs : v.getDeclarators()) { - if (vs == null)// || vs instanceof DirectDeclarator && v.getDeclarators().size() == 1) - continue; - - String name = vs.resolveName(); - if (vs instanceof DirectDeclarator && name.equals(bestName) && ttr != null && origName != null) { - DirectDeclarator rep = new DirectDeclarator(origName); - vs.replaceBy(rep); - ttr.setTag(ident(bestName)); - vs = rep; - name = origName; - } - Declaration decl = null; - - Declarator.MutableByDeclarator type = vs.mutateType(v.getValueType()); - if (type instanceof TypeRef) { - TypeRef tr = (TypeRef)type; - decl = new StoredDeclarations.TypeDef(tr, new DirectDeclarator(name)); - decl.importDetails(v, false); - decl.importDetails(vs, false); - decl.importDetails(tr, true); - } else { - continue; - } - - toAddAfter.insertSibling(decl, false); - toAddAfter = decl; - - //decl.accept(this);//super.visitVariablesDeclaration(decl); - } - if (toAddAfter != v) - v.replaceBy(null); - } - - @Override - public void visitArg(Arg arg) { - Declarator d = arg.getDeclarator(); - if (d != null && !(d instanceof DirectDeclarator)) { - MutableByDeclarator type = d.mutateType(arg.getValueType()); - if (type instanceof TypeRef) { - arg.setValueType((TypeRef)type); - arg.setDeclarator(new DirectDeclarator(d.resolveName(), d.getBits(), arg.getDefaultValue())); - } else { - type = null; - } - } - super.visitArg(arg); - } - - private static final boolean mutateDeclaratorTypes = true; - - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - - Element toAddAfter = v; - - /// Explode comma-separated variables declarations - int nDecl = v.getDeclarators().size(); - - for (Declarator vs : v.getDeclarators()) { - if (vs == null || vs instanceof DirectDeclarator && nDecl == 1) - continue; - - Declaration decl = null; - - - Declarator.MutableByDeclarator mutatedType = vs.mutateType(v.getValueType()); - if (mutatedType instanceof Function) { - Function f = (Function)mutatedType; - f.setName(new SimpleIdentifier(vs.resolveName())); - decl = (Function)mutatedType; - decl.importDetails(v, false); - decl.importDetails(vs, false); - } else { - if (mutateDeclaratorTypes) { - if (mutatedType instanceof TypeRef) { - TypeRef tr = (TypeRef)mutatedType; - decl = new VariablesDeclaration(tr, new DirectDeclarator(vs.resolveName(), vs.getBits(), vs.getDefaultValue())); - decl.importDetails(v, false); - decl.importDetails(vs, false); - decl.importDetails(tr, true); - } else if (mutatedType instanceof Declaration) { - decl = (Declaration)mutatedType; - } - } - if (decl == null) { - TypeRef vt = v.getValueType(); - decl = new VariablesDeclaration(vt == null ? null : vt.clone(), vs.clone()); - decl.importDetails(v, false); - decl.importDetails(vs, false); - decl.importDetails(v.getValueType(), true); - } - } - - toAddAfter.insertSibling(decl, false); - toAddAfter = decl; - - //decl.accept(this);//super.visitVariablesDeclaration(decl); - } - if (toAddAfter != v) - v.replaceBy(null); - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ClassOutputter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ClassOutputter.java deleted file mode 100644 index 1f5b7e001..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ClassOutputter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.IOException; -import java.io.PrintWriter; - -public interface ClassOutputter { - public PrintWriter getClassSourceWriter(String className) throws IOException; -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsConverter.java deleted file mode 100644 index 491bf4fcf..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsConverter.java +++ /dev/null @@ -1,859 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - - -import static com.ochafik.lang.SyntaxUtils.as; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.Method; -import java.util.*; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Function.Type; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import com.ochafik.lang.jnaerator.runtime.VirtualTablePointer; -import com.ochafik.util.listenable.Pair; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.TypeConversion.*; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.ochafik.util.string.StringUtils; -import com.sun.jna.PointerType; -import org.bridj.TypedPointer; -import org.bridj.ann.Ptr; - -public abstract class DeclarationsConverter { - protected static final String DEFAULT_VPTR_NAME = "_vptr"; - - public DeclarationsConverter(Result result) { - this.result = result; - } - - protected final Result result; - - - public void convertCallback(FunctionSignature functionSignature, Signatures signatures, DeclarationsHolder out, Identifier callerLibraryName) { - Struct decl = convertCallback(functionSignature, signatures, callerLibraryName); - if (decl != null) - out.addDeclaration(new TaggedTypeRefDeclaration(decl)); - } - public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { - Identifier name = result.typeConverter.inferCallBackName(functionSignature, true, false, callerLibraryName); - if (name == null) - return null; - - name = result.typeConverter.getValidJavaArgumentName(name); - - Function function = functionSignature.getFunction(); - - int i = 1; - Identifier chosenName = name; - while (!(signatures.addClass(chosenName))) { - chosenName = ident(name.toString() + (++i)); - } - - Element parent = functionSignature.getParentElement(); - Element comel = parent != null && parent instanceof TypeDef ? parent : functionSignature; - - Struct callbackStruct = new Struct(); - configureCallbackStruct(callbackStruct); - //callbackStruct.setParents(Arrays.asList(getCallbackType(functionSignature, chosenName))); - callbackStruct.setTag(ident(chosenName)); - if (!result.config.noComments) - callbackStruct.addToCommentBefore(comel.getCommentBefore(), comel.getCommentAfter(), getFileCommentContent(comel)); - convertFunction(function, new Signatures(), true, callbackStruct, callerLibraryName, -1); - for (Declaration d : callbackStruct.getDeclarations()) { - if (d instanceof Function) { - callbackStruct.addAnnotations(callbackStruct.getAnnotations()); - callbackStruct.setAnnotations(null); - break; - } - } - return callbackStruct; - } - - public void convertCallbacks(List functionSignatures, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { - if (functionSignatures != null) { - for (FunctionSignature functionSignature : functionSignatures) { - if (functionSignature.findParentOfType(Struct.class) != null) - continue; - - Arg a = functionSignature.findParentOfType(Arg.class); - if (a != null && a.getParentElement() == null) - continue;//TODO understand why we end up having an orphan Arg here !!!! - - convertCallback(functionSignature, signatures, out, libraryClassName); - } - } - - } - - protected abstract void configureCallbackStruct(Struct callbackStruct); - - protected abstract void convertFunction(Function function, Signatures signatures, boolean callback, DeclarationsHolder objOut, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor); - - protected abstract Struct createFakePointerClass(Identifier fakePointer); - - static class EnumItemResult { - public Enum.EnumItem originalItem; - public Expression value; - public String comments; - public String exceptionMessage; - public Declaration errorElement; - } - protected List getEnumValuesAndCommentsByName(Enum e, Signatures signatures, Identifier libraryClassName) { - List ret = new ArrayList(); - Integer lastAdditiveValue = null; - Expression lastRefValue = null; - boolean failedOnceForThisEnum = false; - for (com.ochafik.lang.jnaerator.parser.Enum.EnumItem item : e.getItems()) { - EnumItemResult res = new EnumItemResult(); - res.originalItem = item; - try { - if (item.getArguments().isEmpty()) { - // no explicit value - if (lastRefValue == null) { - if (lastAdditiveValue != null) { - lastAdditiveValue++; - res.value = expr(lastAdditiveValue); - } else { - if (item == e.getItems().get(0)) { - lastAdditiveValue = 0; - res.value = expr(lastAdditiveValue); - } else - res.value = null; - } - } else { - // has a last reference value - if (lastAdditiveValue != null) - lastAdditiveValue++; - else - lastAdditiveValue = 1; - - res.value = //result.typeConverter.convertExpressionToJava( - expr( - lastRefValue.clone(), - Expression.BinaryOperator.Plus, - expr(lastAdditiveValue) - //) - ); - } - } else { - // has an explicit value - failedOnceForThisEnum = false;// reset skipping - lastAdditiveValue = null; - lastRefValue = item.getArguments().get(0); - res.value = lastRefValue; - if (lastRefValue instanceof Expression.Constant) { - try { - lastAdditiveValue = ((Expression.Constant)lastRefValue).asInteger(); - lastRefValue = null; - } catch (Exception ex) {} - } - } - - Expression convertedValue = result.typeConverter.convertExpressionToJava(res.value, libraryClassName, true).getFirst(); - res.value = convertedValue; - } catch (Exception ex) { - failedOnceForThisEnum = true; - res.exceptionMessage = ex.toString(); - } - failedOnceForThisEnum = failedOnceForThisEnum || res.errorElement != null; - if (failedOnceForThisEnum) - res.errorElement = skipDeclaration(item); - - ret.add(res); - } - return ret; - } - - public void convertConstants(String library, List defines, Element sourcesRoot, final Signatures signatures, final DeclarationsHolder out, final Identifier libraryClassName) { - //final List defines = new ArrayList(); - final Map constants = Result.getMap(result.stringConstants, library); -// - sourcesRoot.accept(new Scanner() { -// @Override -// public void visitDefine(Define define) { -// super.visitDefine(define); -// if (elementsFilter.accept(define)) -// defines.add(define); -// } - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - //if (!elementsFilter.accept(v)) - // return; - - if (v.findParentOfType(Struct.class) != null) - return; - - if (v.getValueType() instanceof FunctionSignature) - return; - - for (Declarator decl : v.getDeclarators()) { - if (!(decl instanceof DirectDeclarator)) - continue; // TODO provide a mapping of exported values - - TypeRef mutatedType = (TypeRef) decl.mutateTypeKeepingParent(v.getValueType()); - if (mutatedType == null || - !mutatedType.getModifiers().contains(ModifierType.Const) || - mutatedType.getModifiers().contains(ModifierType.Extern) || - decl.getDefaultValue() == null) - continue; - - //TypeRef type = v.getValueType(); - String name = decl.resolveName(); - - JavaPrim prim = result.typeConverter.getPrimitive(mutatedType, libraryClassName); - if (prim == null) { - if (mutatedType.toString().contains("NSString")) { - String value = constants.get(name); - if (value != null) - outputNSString(name, value, out, signatures, v, decl); - } - continue; - } - - try { - - //DirectDeclarator dd = (DirectDeclarator)decl; - Pair val = result.typeConverter.convertExpressionToJava(decl.getDefaultValue(), libraryClassName, true); - - if (!signatures.addVariable(name)) - continue; - - - // TODO - TypeRef tr = prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize ? - typeRef("long") : - result.typeConverter.convertTypeToJNA(mutatedType, TypeConversion.TypeConversionMode.FieldType, libraryClassName) - ; - VariablesDeclaration vd = new VariablesDeclaration(tr, new DirectDeclarator(name, val.getFirst())); - if (!result.config.noComments) { - vd.setCommentBefore(v.getCommentBefore()); - vd.addToCommentBefore(decl.getCommentBefore()); - vd.addToCommentBefore(decl.getCommentAfter()); - vd.addToCommentBefore(v.getCommentAfter()); - } - - if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) - vd.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final); - - out.addDeclaration(vd); - } catch (UnsupportedConversionException e) { - out.addDeclaration(skipDeclaration(v, e.toString())); - } - - } - } - - }); - - if (defines != null) { - for (Define define : reorderDefines(defines)) { - if (define.getValue() == null) - continue; - - try { - //System.out.println("Define " + define.getName() + " = " + define.getValue()); - out.addDeclaration(outputConstant(define.getName(), define.getValue(), signatures, define.getValue(), "define", libraryClassName, true, false, false)); - } catch (UnsupportedConversionException ex) { - out.addDeclaration(skipDeclaration(define, ex.toString())); - } - } - } - for (Map.Entry e : constants.entrySet()) { - outputNSString(e.getKey(), e.getValue(), out, signatures); - } - } - - - protected void outputNSString(String name, String value, DeclarationsHolder out, Signatures signatures, Element... elementsToTakeCommentsFrom) { - - if (!signatures.addVariable(name)) - return; - - TypeRef tr = typeRef(String.class); - VariablesDeclaration vd = new VariablesDeclaration(tr, new DirectDeclarator(name, expr(value))); - if (!result.config.noComments) - for (Element e : elementsToTakeCommentsFrom) { - vd.addToCommentBefore(e.getCommentBefore()); - vd.addToCommentBefore(e.getCommentAfter()); - } - vd.addModifiers(ModifierType.Public); - out.addDeclaration(vd); - } - static Map, Pair>, Set>> cachedForcedMethodsAndTheirSignatures; - - public static synchronized Pair>,Set> getMethodsAndTheirSignatures(Class originalLib) { - if (cachedForcedMethodsAndTheirSignatures == null) - cachedForcedMethodsAndTheirSignatures = new HashMap, Pair>,Set>>(); - - Pair>, Set> pair = cachedForcedMethodsAndTheirSignatures.get(originalLib); - if (pair == null) { - pair = new Pair>, Set>(new ArrayList>(), new HashSet()); - for (Method m : originalLib.getDeclaredMethods()) { - Function f = Function.fromMethod(m); - String sig = f.computeSignature(Function.SignatureType.JavaStyle); - //if (m.getDeclaringClass().equals(NSObject.class) && f.getName().equals("as")) { - // Declaration - //} - pair.getFirst().add(new Pair(f, sig)); - pair.getSecond().add(sig); - } - } - return pair; - } - - public void addMissingMethods(Class originalLib, Signatures existingSignatures, Struct outputLib) { - for (Pair f : getMethodsAndTheirSignatures(originalLib).getFirst()) - if (existingSignatures.addMethod(f.getSecond())) - outputLib.addDeclaration(f.getFirst().clone()); - } - - public EmptyDeclaration skipDeclaration(Element e, String... preMessages) { - if (result.config.limitComments) - return null; - - List mess = new ArrayList(); - if (preMessages != null) - mess.addAll(Arrays.asList(preMessages)); - mess.addAll(Arrays.asList("SKIPPED:", new Printer(null).formatComments(e, true, true, false).toString(), getFileCommentContent(e), e.toString().replace("*/", "* /"))); - return new EmptyDeclaration(mess.toArray(new String[0])); - } - - public abstract void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName); - - protected void outputEnumItemsAsConstants(List results, - DeclarationsHolder out, Signatures signatures, Identifier libraryClassName, - boolean hasEnumClass) { - - - for (EnumItemResult er : results) { - try { - if (er.errorElement != null) { - out.addDeclaration(er.errorElement); - continue; - } - Declaration ct = outputConstant( - er.originalItem.getName(), - result.typeConverter.convertExpressionToJava(er.value, libraryClassName, true), - signatures, - er.originalItem, - "enum item", - libraryClassName, - hasEnumClass, - true, - true, - true - ); - if (!result.config.noComments) - if (ct != null && hasEnumClass) { - String c = ct.getCommentBefore(); - ct.setCommentBefore(er.originalItem.getCommentBefore()); - ct.addToCommentBefore(c); - } - out.addDeclaration(ct); - } catch (Exception ex) { - out.addDeclaration(skipDeclaration(er.originalItem, ex.toString())); - } - } - } - - protected Declaration outputConstant(String name, Expression x, Signatures signatures, Element element, String elementTypeDescription, Identifier libraryClassName, boolean addFileComment, boolean signalErrors, boolean forceInteger) throws UnsupportedConversionException { - return outputConstant(name, pair(x, (TypeRef)null), signatures, element, elementTypeDescription, libraryClassName, addFileComment, signalErrors, forceInteger, false); - } - @SuppressWarnings("static-access") - protected Declaration outputConstant(String name, Pair x, Signatures signatures, Element element, String elementTypeDescription, Identifier libraryClassName, boolean addFileComment, boolean signalErrors, boolean forceInteger, boolean alreadyConverted) throws UnsupportedConversionException { - try { - if (result.typeConverter.isJavaKeyword(name)) - throw new UnsupportedConversionException(element, "The name '" + name + "' is invalid for a Java field."); - - Pair converted = alreadyConverted ? x : result.typeConverter.convertExpressionToJava(x.getFirst(), libraryClassName, true); - //TypeRef tr = result.typeConverter.inferJavaType(converted); - JavaPrim prim = result.typeConverter.getPrimitive(converted.getValue(), libraryClassName); - - if (forceInteger && prim == JavaPrim.Boolean) { - prim = JavaPrim.Int; - //tr = typeRef("int"); - converted = pair(expr("true".equals(String.valueOf(converted.toString())) ? 1 : 0), typeRef(Integer.TYPE)); - } - - if ((prim == null || converted.getValue() == null) && signalErrors) { - if (result.config.limitComments) - return null; - - return new EmptyDeclaration("Failed to infer type of " + converted); - } else if (prim != JavaPrim.Void && converted.getValue() != null) { -// if (prim == JavaPrim.Int) -// tr = typeRef("long"); - - if (signatures.addVariable(name)) { - String t = converted.toString(); - if (t.contains("sizeof")) { - converted = alreadyConverted ? x : result.typeConverter.convertExpressionToJava(x.getFirst(), libraryClassName, false); - } - //TypeRef tr = new TypeRef.SimpleTypeRef(result.typeConverter.typeToJNA(type, vs, TypeConversion.TypeConversionMode.FieldType, callerLibraryClass)); - TypeRef tr = converted.getValue(); - Expression value = converted.getFirst(); - if (result.config.castConstants) - value = new Cast(tr, value); - - - Declaration declaration = new VariablesDeclaration(tr, new DirectDeclarator(name, value)); - declaration.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final); - if (!result.config.noComments) - declaration.importComments(element, addFileComment ? getFileCommentContent(element) : null); - return declaration; - } - } - return skipDeclaration(element, elementTypeDescription); - } catch (UnsupportedConversionException e) { - return skipDeclaration(element, elementTypeDescription, e.toString()); - } - - } - - public void convertEnums(List enums, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { - if (enums != null) { - //out.println("public static class ENUMS {"); - for (com.ochafik.lang.jnaerator.parser.Enum e : enums) { - if (e.findParentOfType(Struct.class) != null) - continue; - - convertEnum(e, signatures, out, libraryClassName); - } - //out.println("}"); - } - } - - Map>> functionAlternativesByNativeSignature = new LinkedHashMap>>(); - - @SuppressWarnings("unchecked") - static E cleanClone(E e) { - E c = (E)e.clone(); - c.setCommentBefore(null); - c.setCommentAfter(null); - if (c instanceof Declaration) { - Declaration d = (Declaration)c; - d.setAnnotations(null); - } - return c; - } - void throwBadRuntime() { - throw new RuntimeException("Unhandled runtime : " + result.config.runtime.name()); - } - public void convertFunction(Function function, Signatures signatures, boolean isCallback, final DeclarationsHolder out, final Identifier libraryClassName, int iConstructor) { - if (result.config.functionsAccepter != null && !result.config.functionsAccepter.adapt(function)) - return; - - //if (function.findParentOfType(Template)) - String library = result.getLibrary(function); - Identifier functionName = function.getName(); - boolean isMethod = function.getParentElement() instanceof Struct; - if (functionName == null || isCallback) { - if (function.getParentElement() instanceof FunctionSignature) - functionName = ident(result.config.callbackInvokeMethodName); - else - return; - } - if (function.getParentElement() instanceof FriendDeclaration) - return; - - String n = functionName.toString(); - if (n.contains("<") || n.startsWith("~")) - return; - - if (result.config.beautifyNames) - functionName = ident(result.typeConverter.beautify(n, false)); - - functionName = result.typeConverter.getValidJavaMethodName(functionName); - if (functionName == null) - return; - - //if (functionName.equals("operator")) - // functionName - - String sig = function.computeSignature(SignatureType.JavaStyle); - - DeclarationsHolder objOut = - result.config.reification && - !isCallback && - !isMethod ? - new DeclarationsHolder() { - - @Override - public void addDeclaration(Declaration d) { - out.addDeclaration(d); - if (d instanceof Function) { - Function f = (Function)d; - List args = f.getArgs(); - List trs = new ArrayList(2); - trs.add(f.getValueType()); - if (!args.isEmpty()) - trs.add(args.get(0).getValueType()); - - for (TypeRef tr: trs) { - if (tr instanceof SimpleTypeRef) { - Identifier id = ((SimpleTypeRef)tr).getName(); - if (result.isFakePointer(id)) { - result.addFunctionReifiableInFakePointer(id, libraryClassName, f); - } - } - } - } - } - - @Override - public List getDeclarations() { - return out.getDeclarations(); - } - - } : - out - ; - - try { - convertFunction(function, signatures, isCallback, objOut, libraryClassName, sig, functionName, library, iConstructor); - } catch (UnsupportedConversionException ex) { - Declaration d = skipDeclaration(function); - if (d != null) { - d.addToCommentBefore(ex.toString()); - out.addDeclaration(d); - } - } - } - - protected boolean isCPlusPlusFileName(String file) { - if (file == null) - return true; - - file = file.toLowerCase(); - return !file.endsWith(".c") && !file.endsWith(".m"); - } - - protected void collectParamComments(Function f) { - for (Arg arg : f.getArgs()) { - arg.moveAllCommentsBefore(); - TypeRef argType = arg.getValueType(); - if (argType != null) { - if (!result.config.noComments) { - argType.moveAllCommentsBefore(); - arg.addToCommentBefore(argType.getCommentBefore()); - } - argType.stripDetails(); - } - if (arg.getCommentBefore() != null) { - if (!result.config.noComments) - f.addToCommentBefore("@param " + arg.getName() + " " + Element.cleanComment(arg.getCommentBefore())); - arg.stripDetails(); - } - } - } - - public void convertFunctions(List functions, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { - if (functions != null) { - //System.err.println("FUNCTIONS " + functions); - for (Function function : functions) { - convertFunction(function, signatures, false, out, libraryClassName, -1); - } - } - } - - public Identifier getActualTaggedTypeName(TaggedTypeRef struct) { - Identifier structName = null; - Identifier tag = struct.getTag(); - if (tag == null || tag.isPlain() && tag.toString().startsWith("_")) { - TypeDef parentDef = as(struct.getParentElement(), TypeDef.class); - if (parentDef != null) { - structName = new Identifier.SimpleIdentifier(JNAeratorUtils.findBestPlainStorageName(parentDef)); - } else if (tag != null) { - String better = tag.toString().substring(1); - Pair pair = result.typeDefs.get(better); - if (pair != null && pair.getFirst().getValueType() != null && pair.getSecond() instanceof DirectDeclarator) { - TypeRef tr = pair.getFirst().getValueType(); - DirectDeclarator dd = (DirectDeclarator) pair.getSecond(); - - if (tr instanceof SimpleTypeRef) { - if (tag.equals(((SimpleTypeRef)tr).getName())) - structName = ident(dd.resolveName()); - } else if (tr instanceof TaggedTypeRef) { - if (tag.equals(((TaggedTypeRef)tr).getTag())) - structName = ident(dd.resolveName()); - } - } - } - } - if (structName == null || structName.toString().equals("")) - structName = tag; - return structName == null ? null : structName.clone(); - } - public abstract Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException; - - public int countFieldsInStruct(Struct s) throws UnsupportedConversionException { - int count = 0; - for (Declaration declaration : s.getDeclarations()) { - if (declaration instanceof VariablesDeclaration) { - count += ((VariablesDeclaration)declaration).getDeclarators().size(); - } - } - for (SimpleTypeRef parentName : s.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) - throw new UnsupportedConversionException(s, "Cannot find parent " + parentName + " of struct " + s); - - count += countFieldsInStruct(parent); - } - return count; - } - - protected void outputConvertedStruct(Struct struct, Signatures signatures, DeclarationsHolder out, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { - Struct structJavaClass = convertStruct(struct, signatures, callerLibraryClass, callerLibrary, onlyFields); - if (structJavaClass == null) - return; - - if (result.config.putTopStructsInSeparateFiles && struct.findParentOfType(Struct.class) == null) { - String library = result.getLibrary(struct); - Identifier javaPackage = result.getLibraryPackage(library); - Identifier fullClassName = ident(javaPackage, structJavaClass.getTag().clone()); - - if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) - structJavaClass.addAnnotation(new Annotation(org.bridj.ann.Library.class, expr(library))); - structJavaClass.removeModifiers(ModifierType.Static); - structJavaClass = result.notifyBeforeWritingClass(fullClassName, structJavaClass, signatures, library); - if (structJavaClass != null) { - PrintWriter pout = result.classOutputter.getClassSourceWriter(fullClassName.toString()); - result.printJavaClass(javaPackage, structJavaClass, pout); - pout.close(); - } - } else - out.addDeclaration(decl(structJavaClass)); - } - - - public void convertStructs(List structs, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName, String library) throws IOException { - if (structs != null) { - for (Struct struct : structs) { - if (struct.findParentOfType(Struct.class) != null) - continue; - - if (!result.config.genCPlusPlus && struct.getType().isCpp()) - continue; - - outputConvertedStruct(struct, signatures, out, libraryClassName, library, false); - } - } - } - - public abstract void convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary); - - TaggedTypeRefDeclaration publicStaticClassDecl(Identifier name, Identifier parentName, Struct.Type type, Element toCloneCommentsFrom, Identifier... interfaces) { - return decl(publicStaticClass(name, parentName, type, toCloneCommentsFrom, interfaces)); - } - Struct publicStaticClass(Identifier name, Identifier parentName, Struct.Type type, Element toCloneCommentsFrom, Identifier... interfaces) { - Struct cl = new Struct(); - cl.setType(type); - cl.setTag(name); - if (parentName != null) - cl.setParents(typeRef(parentName)); - if (type == Struct.Type.JavaInterface) - for (Identifier inter : interfaces) - cl.addParent(typeRef(inter)); - else - for (Identifier inter : interfaces) - cl.addProtocol(typeRef(inter)); - - if (!result.config.noComments) - cl.importComments(toCloneCommentsFrom, getFileCommentContent(toCloneCommentsFrom)); - - cl.addModifiers(ModifierType.Public, ModifierType.Static); - return cl; - } - public Pair, List> getParentAndOwnDeclarations(Struct structJavaClass, Struct nativeStruct) throws IOException { - Pair, List> ret = - new Pair, List>( - new ArrayList(), - new ArrayList() - ) - ; - if (!nativeStruct.getParents().isEmpty()) { - for (SimpleTypeRef parentName : nativeStruct.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) { - // TODO report error - continue; - } - Struct parentJavaClass = convertStruct(parent, new Signatures(), null, null, true); - Pair, List> parentDecls = getParentAndOwnDeclarations(parentJavaClass, parent); - ret.getFirst().addAll(parentDecls.getFirst()); - ret.getFirst().addAll(parentDecls.getSecond()); - } - } - for (Declaration d : structJavaClass.getDeclarations()) { - if (!(d instanceof VariablesDeclaration)) - continue; - VariablesDeclaration vd = (VariablesDeclaration)d; - if (vd.getDeclarators().size() != 1) - continue; // should not happen ! - if (!isField(vd)) - continue; - - ret.getSecond().add(vd); - } - - return ret; - } - protected boolean isField(VariablesDeclaration vd) { - List mods = vd.getModifiers(); - if (vd.hasModifier(ModifierType.Final)) - return false; - if (vd.getValueType() == null || vd.getValueType().toString().equals(VirtualTablePointer.class.getName())) - return false; - return true; - } - - Statement throwIfArraySizeDifferent(String varAndFieldName) { - return new Statement.If( - expr( - memberRef(varRef(varAndFieldName), MemberRefStyle.Dot, "length"), - BinaryOperator.IsDifferent, - memberRef(memberRef(thisRef(), MemberRefStyle.Dot, varAndFieldName), MemberRefStyle.Dot, "length") - ), - new Statement.Throw(new Expression.New(typeRef(IllegalArgumentException.class), expr("Wrong array size !"))), - null - ); - } - void addConstructor(Struct s, Function f) { - Identifier structName = getActualTaggedTypeName(s); - - f.setName(structName); - s.addDeclaration(f); - } - - String getFileCommentContent(File file, Element e) { - if (file != null) { - String path = result.config.relativizeFileForSourceComments(file.getAbsolutePath()); - String inCategoryStr = ""; - if (e instanceof Function) { - Function fc = (Function)e; - Struct parent; - if (fc.getType() == Type.ObjCMethod && ((parent = as(fc.getParentElement(), Struct.class)) != null) && (parent.getCategoryName() != null)) { - inCategoryStr = "from " + parent.getCategoryName() + " "; - } - } - return "" + inCategoryStr + "native declaration : " + path + (e == null || e.getElementLine() < 0 ? "" : ":" + e.getElementLine()) + ""; - } else if (e != null && e.getElementLine() >= 0) { - return "native declaration : :" + e.getElementLine() + ""; - } - return null; - } - String getFileCommentContent(Element e) { - if (e == null || result.config.limitComments) - return null; - - String f = Element.getFileOfAscendency(e); - if (f == null && e != null && e.getElementLine() >= 0) - return "native declaration : line " + e.getElementLine() + ""; - - return f == null ? null : getFileCommentContent(new File(f), e); - } - - - public List reorderDefines(Collection defines) { - List reordered = new ArrayList(defines.size()); - HashSet added = new HashSet(), all = new HashSet(); - - - Map>> pending = new HashMap>>(); - for (Define define : defines) { - Set dependencies = new TreeSet(); - computeVariablesDependencies(define.getValue(), dependencies); - all.add(ident(define.getName())); - if (dependencies.isEmpty()) { - reordered.add(define); - added.add(ident(define.getName())); - } else { - pending.put(define.getName(), new Pair>(define, dependencies)); - } - } - - boolean progressed; - do { - progressed = false; - for (Iterator>>> it = pending.entrySet().iterator(); it.hasNext();) { - Map.Entry>> e = it.next(); - Set dependencies = e.getValue().getSecond(); - String name = e.getKey(); - boolean missesDep = false; - for (Identifier dependency : dependencies) { - if (!added.contains(dependency)) { - missesDep = true; - if (!all.contains(dependency)) { - it.remove(); - all.remove(name); - } - - break; - } - } - if (missesDep) - continue; - - it.remove(); - reordered.add(e.getValue().getFirst()); - added.add(ident(name)); - progressed = true; - } - } while (!pending.isEmpty() && progressed); - - return reordered; - } - public void computeVariablesDependencies(Element e, final Set names) { - e.accept(new Scanner() { - - @Override - public void visitVariableRef(VariableRef variableRef) { - names.add(variableRef.getName()); - } - }); - } - - protected String chooseJavaArgName(String name, int iArg, Set names) { - Identifier jan = result.typeConverter.getValidJavaArgumentName(ident(name)); - String baseArgName = jan == null ? null : jan.toString(); - int i = 1; - if (baseArgName == null) - baseArgName = "arg"; - - String argName; - do { - argName = baseArgName + (i == 1 ? "" : i + ""); - i++; - } while (names.contains(argName) || result.typeConverter.isJavaKeyword(argName)); - names.add(argName); - return argName; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsMigrator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsMigrator.java deleted file mode 100644 index 75468b857..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsMigrator.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; - -/** - * - * @author ochafik - */ -public class DeclarationsMigrator extends DeclarationsScanner { - Result result; - public DeclarationsMigrator(Result result) { - this.result = result; - } - - boolean insideTypeRef; - - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - //TODO - } - - - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsScanner.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsScanner.java deleted file mode 100644 index 93488f197..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/DeclarationsScanner.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.*; -import java.util.Stack; - -/** - * - * @author ochafik - */ -public class DeclarationsScanner extends Scanner { - - Stack declarationsHolders = new Stack(); - - @Override - public void visitStruct(Struct struct) { - declarationsHolders.push(struct); - try { - super.visitStruct(struct); - } finally { - declarationsHolders.pop(); - } - } - - @Override - public void visitSourceFile(SourceFile header) { - declarationsHolders.push(header); - try { - super.visitSourceFile(header); - } finally { - declarationsHolders.pop(); - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/GlobalsGenerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/GlobalsGenerator.java deleted file mode 100644 index 0547cf8cd..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/GlobalsGenerator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.Declaration; -import java.util.ArrayList; -import java.util.Collections; - -import java.util.List; - -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrim; -import com.ochafik.lang.jnaerator.TypeConversion.TypeConversionMode; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.Statement; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerStyle; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalCallback; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointer; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointerType; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalStruct; -import com.sun.jna.ptr.ByReference; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -public abstract class GlobalsGenerator { - public GlobalsGenerator(Result result) { - this.result = result; - } - - final Result result; - - @SuppressWarnings("unchecked") - protected abstract void convertGlobals(VariablesDeclaration globals, Signatures signatures, DeclarationsHolder out, Expression nativeLibFieldExpr, Identifier callerLibraryName, String callerLibrary) throws UnsupportedConversionException; - - public void convertGlobals(List list, Signatures signatures, DeclarationsHolder out, Expression nativeLibFieldExpr, Identifier libraryNameExpression, String library) { - if (list == null) - return; - if (result.config.skipLibraryInstanceDeclarations) - return; - for (VariablesDeclaration v : list) { - try { - convertGlobals(v, signatures, out, nativeLibFieldExpr, libraryNameExpression, library); - } catch (UnsupportedConversionException ex) { - out.addDeclaration(result.declarationsConverter.skipDeclaration(v, ex.toString())); - } - } - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNADeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNADeclarationsConverter.java deleted file mode 100644 index e9711fc76..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNADeclarationsConverter.java +++ /dev/null @@ -1,977 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.*; -import java.util.regex.Pattern; - -import org.rococoa.AlreadyRetained; -import org.rococoa.cocoa.foundation.NSObject; - -import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Function.Type; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import com.ochafik.util.CompoundCollection; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; - -import java.net.URL; -import java.net.URLConnection; -import java.text.MessageFormat; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.TypeConversion.*; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.sun.jna.PointerType; -import com.sun.jna.win32.StdCallLibrary; - -public class JNADeclarationsConverter extends DeclarationsConverter { - private static final Pattern manglingCommentPattern = Pattern.compile("@mangling (.*)$", Pattern.MULTILINE); - - public JNADeclarationsConverter(Result result) { - super(result); - } - - //protected abstract SimpleTypeRef getCallbackType(FunctionSignature functionSignature, Identifier name); - @Override - public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { - Struct decl = super.convertCallback(functionSignature, signatures, callerLibraryName); - if (decl != null) { - List mods = functionSignature.getFunction().getModifiers(); - decl.setParents(Arrays.asList((SimpleTypeRef)typeRef( - functionSignature.getFunction().hasModifier(ModifierType.__stdcall) ? - StdCallLibrary.StdCallCallback.class : - result.config.runtime.callbackClass - ))); - } - return decl; - } - - public void convertConstants(String library, List defines, Element sourcesRoot, final Signatures signatures, final DeclarationsHolder out, final Identifier libraryClassName) { - //final List defines = new ArrayList(); - final Map constants = Result.getMap(result.stringConstants, library); -// - sourcesRoot.accept(new Scanner() { -// @Override -// public void visitDefine(Define define) { -// super.visitDefine(define); -// if (elementsFilter.accept(define)) -// defines.add(define); -// } - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - //if (!elementsFilter.accept(v)) - // return; - - if (v.findParentOfType(Struct.class) != null) - return; - - if (v.getValueType() instanceof FunctionSignature) - return; - - for (Declarator decl : v.getDeclarators()) { - if (!(decl instanceof DirectDeclarator)) - continue; // TODO provide a mapping of exported values - - TypeRef mutatedType = (TypeRef) decl.mutateTypeKeepingParent(v.getValueType()); - if (mutatedType == null || - !mutatedType.getModifiers().contains(ModifierType.Const) || - mutatedType.getModifiers().contains(ModifierType.Extern) || - decl.getDefaultValue() == null) - continue; - - //TypeRef type = v.getValueType(); - String name = decl.resolveName(); - - JavaPrim prim = result.typeConverter.getPrimitive(mutatedType, libraryClassName); - if (prim == null) { - if (mutatedType.toString().contains("NSString")) { - String value = constants.get(name); - if (value != null) - outputNSString(name, value, out, signatures, v, decl); - } - continue; - } - - try { - - //DirectDeclarator dd = (DirectDeclarator)decl; - Pair val = result.typeConverter.convertExpressionToJava(decl.getDefaultValue(), libraryClassName, true); - - if (!signatures.addVariable(name)) - continue; - - TypeRef tr = prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize ? - typeRef("long") : - result.typeConverter.convertTypeToJNA(mutatedType, TypeConversion.TypeConversionMode.FieldType, libraryClassName) - ; - VariablesDeclaration vd = new VariablesDeclaration(tr, new DirectDeclarator(name, val.getFirst())); - if (!result.config.noComments) { - vd.setCommentBefore(v.getCommentBefore()); - vd.addToCommentBefore(decl.getCommentBefore()); - vd.addToCommentBefore(decl.getCommentAfter()); - vd.addToCommentBefore(v.getCommentAfter()); - } - -// if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) -// vd.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final); - - out.addDeclaration(vd); - } catch (UnsupportedConversionException e) { - out.addDeclaration(skipDeclaration(v, e.toString())); - } - - } - } - - }); - - if (defines != null) { - for (Define define : reorderDefines(defines)) { - if (define.getValue() == null) - continue; - - try { - //System.out.println("Define " + define.getName() + " = " + define.getValue()); - out.addDeclaration(outputConstant(define.getName(), define.getValue(), signatures, define.getValue(), "define", libraryClassName, true, false, false)); - } catch (UnsupportedConversionException ex) { - out.addDeclaration(skipDeclaration(define, ex.toString())); - } - } - } - for (Map.Entry e : constants.entrySet()) { - outputNSString(e.getKey(), e.getValue(), out, signatures); - } - } - - static Map, Pair>, Set>> cachedForcedMethodsAndTheirSignatures; - - public static synchronized Pair>,Set> getMethodsAndTheirSignatures(Class originalLib) { - if (cachedForcedMethodsAndTheirSignatures == null) - cachedForcedMethodsAndTheirSignatures = new HashMap, Pair>,Set>>(); - - Pair>, Set> pair = cachedForcedMethodsAndTheirSignatures.get(originalLib); - if (pair == null) { - pair = new Pair>, Set>(new ArrayList>(), new HashSet()); - for (Method m : originalLib.getDeclaredMethods()) { - Function f = Function.fromMethod(m); - String sig = f.computeSignature(SignatureType.JavaStyle); - //if (m.getDeclaringClass().equals(NSObject.class) && f.getName().equals("as")) { - // Declaration - //} - pair.getFirst().add(new Pair(f, sig)); - pair.getSecond().add(sig); - } - } - return pair; - } - - public void addMissingMethods(Class originalLib, Signatures existingSignatures, Struct outputLib) { - for (Pair f : getMethodsAndTheirSignatures(originalLib).getFirst()) - if (existingSignatures.addMethod(f.getSecond())) - outputLib.addDeclaration(f.getFirst().clone()); - } - - public EmptyDeclaration skipDeclaration(Element e, String... preMessages) { - if (result.config.limitComments) - return null; - - List mess = new ArrayList(); - if (preMessages != null) - mess.addAll(Arrays.asList(preMessages)); - mess.addAll(Arrays.asList("SKIPPED:", new Printer(null).formatComments(e, true, true, false).toString(), getFileCommentContent(e), e.toString().replace("*/", "* /"))); - return new EmptyDeclaration(mess.toArray(new String[0])); - } - - public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { - if (e.isForwardDeclaration()) - return; - - Identifier enumName = getActualTaggedTypeName(e); - List results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); - - - boolean hasEnumClass = false; - if (enumName != null && enumName.resolveLastSimpleIdentifier().getName() != null) { - if (!signatures.addClass(enumName)) - return; - - hasEnumClass = true; - - Struct struct = publicStaticClass(enumName, null, Struct.Type.JavaInterface, e); - out.addDeclaration(new TaggedTypeRefDeclaration(struct)); - if (!result.config.noComments) - struct.addToCommentBefore("enum values"); - - out = struct; - signatures = new Signatures(); - } - - outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); - } - - - Map>> functionAlternativesByNativeSignature = new LinkedHashMap>>(); - - @Override - protected void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) { - Pair> alternativesPair = functionAlternativesByNativeSignature.get(sig); - if (alternativesPair != null) { - if (result.config.choicesInputFile != null) { - for (Function alt : alternativesPair.getValue()) - out.addDeclaration(alt.clone()); - return; - } - } else { - functionAlternativesByNativeSignature.put( - sig, - alternativesPair = new Pair>( - cleanClone(function), - new ArrayList() - ) - ); - } - List alternatives = alternativesPair.getValue(); - - Function natFunc = new Function(); - - Element parent = function.getParentElement(); - List ns = new ArrayList(function.getNameSpace()); - boolean isMethod = parent instanceof Struct; - if (isMethod) { - ns.clear(); - ns.addAll(parent.getNameSpace()); - switch (((Struct)parent).getType()) { - case ObjCClass: - case ObjCProtocol: - break; - case CPPClass: - if (!result.config.genCPlusPlus && !function.hasModifier(ModifierType.Static)) - return; - ns.add(((Struct)parent).getTag().toString()); - break; - } - } - - if (!isMethod && library != null) { - Boolean alreadyRetained = Result.getMap(result.retainedRetValFunctions, library).get(functionName.toString()); - if (alreadyRetained != null && alreadyRetained) { - natFunc.addAnnotation(new Annotation(AlreadyRetained.class, expr(alreadyRetained))); - } - } - //String namespaceArrayStr = "{\"" + StringUtils.implode(ns, "\", \"") + "\"}"; - //if (!ns.isEmpty()) - // natFunc.addAnnotation(new Annotation(Namespace.class, "(value=" + namespaceArrayStr + (isMethod ? ", isClass=true" : "") + ")")); - boolean isObjectiveC = function.getType() == Type.ObjCMethod; - - natFunc.setType(Function.Type.JavaMethod); - if (result.config.synchronizedMethods && !isCallback && result.config.useJNADirectCalls) - natFunc.addModifiers(ModifierType.Synchronized); - if (result.config.useJNADirectCalls && !isCallback && !isObjectiveC) { - natFunc.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Native); - } - - try { - //StringBuilder outPrefix = new StringBuilder(); - TypeRef returnType = null; - - if (!isObjectiveC) { - returnType = function.getValueType(); - if (returnType == null) - returnType = new TypeRef.Primitive("int"); - if (returnType != null) - returnType.addModifiers(function.getModifiers()); - } else { - returnType = RococoaUtils.fixReturnType(function); - functionName = ident(RococoaUtils.getMethodName(function)); - } - - Identifier modifiedMethodName; - if (isCallback) { - modifiedMethodName = ident(result.config.callbackInvokeMethodName); - } else { - modifiedMethodName = result.typeConverter.getValidJavaMethodName(ident(StringUtils.implode(ns, result.config.cPlusPlusNameSpaceSeparator) + (ns.isEmpty() ? "" : result.config.cPlusPlusNameSpaceSeparator) + functionName)); - } - Set names = new LinkedHashSet(); - //if (ns.isEmpty()) - - if (function.getName() != null && !modifiedMethodName.equals(function.getName().toString()) && ns.isEmpty()) - names.add(function.getName().toString()); - if (function.getAsmName() != null) - names.add(function.getAsmName()); - - if (!isCallback && !modifiedMethodName.equals(functionName)) - natFunc.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name), expr(functionName.toString()))); - - natFunc.setName(modifiedMethodName); - natFunc.setValueType(result.typeConverter.convertTypeToJNA(returnType, TypeConversionMode.ReturnType, libraryClassName)); - if (!result.config.noComments) - natFunc.importComments(function, isCallback ? null : getFileCommentContent(function)); - - if (function.getName() != null) { - Object[] name = new Object[] {function.getName().toString()}; - for (Pair mf : result.config.onlineDocumentationURLFormats) { - try { - MessageFormat urlFormat = mf.getSecond(); - URL url = new URL(urlFormat.format(name)); - URLConnection con = url.openConnection(); - con.getInputStream().close(); - MessageFormat displayFormat = mf.getFirst(); - natFunc.addToCommentBefore("@see " + displayFormat.format(name) + ""); - break; - } catch (Exception ex) { - //ex.printStackTrace(); - } - } - } - - boolean alternativeOutputs = !isCallback; - - Function primOrBufFunc = alternativeOutputs ? natFunc.clone() : null; - Function natStructFunc = alternativeOutputs ? natFunc.clone() : null; - - Set argNames = new TreeSet(); -// for (Arg arg : function.getArgs()) -// if (arg.getName() != null) -// argNames.add(arg.getName()); - - int iArg = 1; - for (Arg arg : function.getArgs()) { - if (arg.isVarArg() && arg.getValueType() == null) { - //TODO choose vaname dynamically ! - Identifier vaType = ident(isObjectiveC ? NSObject.class : Object.class); - String argName = chooseJavaArgName("varargs", iArg, argNames); - natFunc.addArg(new Arg(argName, typeRef(vaType.clone()))).setVarArg(true); - if (alternativeOutputs) { - primOrBufFunc.addArg(new Arg(argName, typeRef(vaType.clone()))).setVarArg(true); - natStructFunc.addArg(new Arg(argName, typeRef(vaType.clone()))).setVarArg(true); - } - } else { - String argName = chooseJavaArgName(arg.getName(), iArg, argNames); - - TypeRef mutType = arg.createMutatedType(); - if (mutType == null) - throw new UnsupportedConversionException(function, "Argument " + arg.getName() + " cannot be converted"); - - if (mutType.toString().contains("NSOpenGLContextParameter")) { - argName = argName.toString(); - } - natFunc.addArg(new Arg(argName, result.typeConverter.convertTypeToJNA(mutType, TypeConversionMode.NativeParameter, libraryClassName))); - if (alternativeOutputs) { - primOrBufFunc.addArg(new Arg(argName, result.typeConverter.convertTypeToJNA(mutType, TypeConversionMode.PrimitiveOrBufferParameter, libraryClassName))); - natStructFunc.addArg(new Arg(argName, result.typeConverter.convertTypeToJNA(mutType, TypeConversionMode.NativeParameterWithStructsPtrPtrs, libraryClassName))); - } - } - iArg++; - } - - String natSign = natFunc.computeSignature(SignatureType.JavaStyle), - primOrBufSign = alternativeOutputs ? primOrBufFunc.computeSignature(SignatureType.JavaStyle) : null, - bufSign = alternativeOutputs ? natStructFunc.computeSignature(SignatureType.JavaStyle) : null; - - if (signatures == null || signatures.addMethod(natSign)) { - if (alternativeOutputs && !primOrBufSign.equals(natSign)) { - if (!result.config.noComments) { - if (primOrBufSign.equals(bufSign)) - natFunc.addToCommentBefore(Arrays.asList("@deprecated use the safer method {@link #" + primOrBufSign + "} instead")); - else - natFunc.addToCommentBefore(Arrays.asList("@deprecated use the safer methods {@link #" + primOrBufSign + "} and {@link #" + bufSign + "} instead")); - } - natFunc.addAnnotation(new Annotation(Deprecated.class)); - } - collectParamComments(natFunc); - out.addDeclaration(natFunc); - alternatives.add(cleanClone(natFunc)); - } - - if (alternativeOutputs) { - if (signatures == null || signatures.addMethod(primOrBufSign)) { - collectParamComments(primOrBufFunc); - out.addDeclaration(primOrBufFunc); - alternatives.add(cleanClone(primOrBufFunc)); - } - if (signatures == null || signatures.addMethod(bufSign)) { - collectParamComments(natStructFunc); - out.addDeclaration(natStructFunc); - alternatives.add(cleanClone(natStructFunc)); - } - } - } catch (UnsupportedConversionException ex) { - if (!result.config.limitComments) - out.addDeclaration(new EmptyDeclaration(getFileCommentContent(function), ex.toString())); - } - } - - @Override - public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { - Identifier structName = getActualTaggedTypeName(struct); - if (structName == null) - return null; - - //if (structName.toString().contains("MonoSymbolFile")) - // structName.toString(); - - if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) - return null; - - if (!signatures.addClass(structName)) - return null; - - boolean isUnion = struct.getType() == Struct.Type.CUnion; - boolean inheritsFromStruct = false; - Identifier baseClass = null; - if (!onlyFields) { - if (!struct.getParents().isEmpty()) { - for (SimpleTypeRef parentName : struct.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) { - // TODO report error - continue; - } - baseClass = result.getTaggedTypeIdentifierInJava(parent); - if (baseClass != null) { - inheritsFromStruct = true; - break; // TODO handle multiple and virtual inheritage - } - } - } - if (baseClass == null) { - Class c = isUnion ? result.config.runtime.unionClass : result.config.runtime.structClass; - if (result.config.runtime != JNAeratorConfig.Runtime.JNA) { - baseClass = ident( - c, - expr(typeRef(structName.clone())), - expr(typeRef(ident(structName.clone(), "ByValue"))), - expr(typeRef(ident(structName.clone(), "ByReference"))) - ); - } else - baseClass = ident(c); - } - } - Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); - - final int iChild[] = new int[] {0}; - - //cl.addDeclaration(new EmptyDeclaration()) - Signatures childSignatures = new Signatures(); - -// if (isVirtual(struct) && !onlyFields) { -// String vptrName = DEFAULT_VPTR_NAME; -// VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); -// //VariablesDeclaration vptr = new VariablesDeclaration(typeRef(result.config.runtime.pointerClass), new Declarator.DirectDeclarator(vptrName)); -// vptr.addModifiers(ModifierType.Public); -// structJavaClass.addDeclaration(vptr); -// childSignatures.variablesSignatures.add(vptrName); -// // TODO add vptr grabber to constructor ! -// } - - //List children = new ArrayList(); - for (Declaration d : struct.getDeclarations()) { - if (d instanceof VariablesDeclaration) { - convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); - } else if (!onlyFields) { - if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); - if (tr instanceof Struct) { - outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); - } else if (tr instanceof Enum) { - convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); - } - } else if (d instanceof TypeDef) { - TypeDef td = (TypeDef)d; - TypeRef tr = td.getValueType(); - if (tr instanceof Struct) { - outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); - } else if (tr instanceof FunctionSignature) { - convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); - } - } else if (result.config.genCPlusPlus && d instanceof Function) { - Function f = (Function) d; - String library = result.getLibrary(struct); - if (library == null) - continue; - List decls = new ArrayList(); - convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, -1); - for (Declaration md : decls) { - if (!(md instanceof Function)) - continue; - Function method = (Function) md; - Identifier methodImplName = method.getName().clone(); - Identifier methodName = result.typeConverter.getValidJavaMethodName(f.getName()); - method.setName(methodName); - List args = new ArrayList(); - - boolean isStatic = f.hasModifier(ModifierType.Static); - int iArg = 0; - for (Arg arg : new ArrayList(method.getArgs())) { - if (iArg == 0 && !isStatic) { - arg.replaceBy(null); - args.add(thisRef()); - } else - args.add(varRef(arg.getName())); - iArg++; - } - Expression implCall = methodCall(result.getLibraryInstanceReferenceExpression(library), MemberRefStyle.Dot, methodImplName.toString(), args.toArray(new Expression[args.size()])); - method.setBody(block( - "void".equals(String.valueOf(method.getValueType())) ? - stat(implCall) : - new Statement.Return(implCall) - )); - method.addModifiers(ModifierType.Public, isStatic ? ModifierType.Static : null); - structJavaClass.addDeclaration(method); - } - } - } - } - - if (!onlyFields) { - if (result.config.features.contains(GenFeatures.StructConstructors)) - addStructConstructors(structName, structJavaClass/*, byRef, byVal*/, struct); - - Struct byRef = publicStaticClass(ident("ByReference"), structName, Struct.Type.JavaClass, null, ident(ident(result.config.runtime.structClass), "ByReference")); - Struct byVal = publicStaticClass(ident("ByValue"), structName, Struct.Type.JavaClass, null, ident(ident(result.config.runtime.structClass), "ByValue")); - - if (result.config.runtime != JNAeratorConfig.Runtime.JNA) { - if (!inheritsFromStruct) { - structJavaClass.addDeclaration(createNewStructMethod("newByReference", byRef)); - structJavaClass.addDeclaration(createNewStructMethod("newByValue", byVal)); - } - structJavaClass.addDeclaration(createNewStructMethod("newInstance", structJavaClass)); - - structJavaClass.addDeclaration(createNewStructArrayMethod(structJavaClass, isUnion)); - } - - structJavaClass.addDeclaration(decl(byRef)); - structJavaClass.addDeclaration(decl(byVal)); - } - return structJavaClass; - } - - protected Function createNewStructMethod(String name, Struct byRef) { - TypeRef tr = typeRef(byRef.getTag().clone()); - Function f = new Function(Function.Type.JavaMethod, ident(name), tr); - String varName = "s"; - - f.addModifiers(ModifierType.Protected); - if (result.config.runtime != JNAeratorConfig.Runtime.JNA) { - f.setBody(block( - //new Statement.Return(methodCall("setupClone", new Expression.New(tr.clone(), methodCall(null)))) - new Statement.Return(new Expression.New(tr.clone(), methodCall(null))) - ).setCompact(true)); - } else { - f.setBody(block( - stat(tr.clone(), varName, new Expression.New(tr.clone(), methodCall(null))), - stat(methodCall(varRef(varName), MemberRefStyle.Dot, "useMemory", methodCall("getPointer"))), - stat(methodCall("write")), - stat(methodCall(varRef(varName), MemberRefStyle.Dot, "read")), - new Statement.Return(varRef(varName)) - )); - } - return f; - } - protected Function createNewStructArrayMethod(Struct struct, boolean isUnion) { - if (result.config.runtime == JNAeratorConfig.Runtime.JNA) - return null; - - TypeRef tr = typeRef(struct.getTag().clone()); - TypeRef ar = new TypeRef.ArrayRef(tr); - String varName = "arrayLength"; - Function f = new Function(Function.Type.JavaMethod, ident("newArray"), ar, new Arg(varName, typeRef(Integer.TYPE))); - - f.addModifiers(ModifierType.Public, ModifierType.Static); - f.setBody(block( - new Statement.Return( - methodCall( - expr(typeRef(isUnion ? result.config.runtime.unionClass : result.config.runtime.structClass)), - MemberRefStyle.Dot, - "newArray", - result.typeConverter.typeLiteral(tr), - varRef(varName) - ) - ) - )); - return f; - } - - public int countFieldsInStruct(Struct s) throws UnsupportedConversionException { - int count = 0; - for (Declaration declaration : s.getDeclarations()) { - if (declaration instanceof VariablesDeclaration) { - count += ((VariablesDeclaration)declaration).getDeclarators().size(); - } - } - for (SimpleTypeRef parentName : s.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) - throw new UnsupportedConversionException(s, "Cannot find parent " + parentName + " of struct " + s); - - count += countFieldsInStruct(parent); - } - return count; - } - - public VariablesDeclaration convertVariablesDeclarationToJNA(String name, TypeRef mutatedType, int[] iChild, Identifier callerLibraryName, Element... toImportDetailsFrom) throws UnsupportedConversionException { - name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); - //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); - - Expression initVal = null; - TypeRef javaType = result.typeConverter.convertTypeToJNA( - mutatedType, - TypeConversion.TypeConversionMode.FieldType, - callerLibraryName - ); - mutatedType = result.typeConverter.resolveTypeDef(mutatedType, callerLibraryName, true, false); - - VariablesDeclaration convDecl = new VariablesDeclaration(); - convDecl.addModifiers(ModifierType.Public); - - if (javaType instanceof ArrayRef && mutatedType instanceof ArrayRef) { - ArrayRef mr = (ArrayRef)mutatedType; - ArrayRef jr = (ArrayRef)javaType; - Expression mul = null; - List dims = mr.flattenDimensions(); - for (int i = dims.size(); i-- != 0;) { - Expression x = dims.get(i); - - if (x == null || x instanceof EmptyArraySize) { - javaType = jr = new ArrayRef(typeRef(Pointer.class)); - break; - } else { - Pair c = result.typeConverter.convertExpressionToJava(x, callerLibraryName, false); - c.getFirst().setParenthesis(dims.size() != 1); - if (mul == null) - mul = c.getFirst(); - else - mul = expr(c.getFirst(), BinaryOperator.Multiply, mul); - } - } - initVal = new Expression.NewArray(jr.getTarget(), new Expression[] { mul }, new Expression[0]); - } - if (javaType == null) { - throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); - } else if (javaType.toString().equals("void")) { - throw new UnsupportedConversionException(mutatedType, "void type !"); - //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); - } else { - for (Element e : toImportDetailsFrom) - convDecl.importDetails(e, false); - convDecl.importDetails(mutatedType, true); - convDecl.importDetails(javaType, true); - -// convDecl.importDetails(v, false); -// convDecl.importDetails(vs, false); -// convDecl.importDetails(valueType, false); -// valueType.stripDetails(); - convDecl.moveAllCommentsBefore(); - convDecl.setValueType(javaType); - convDecl.addDeclarator(new DirectDeclarator(name, initVal)); - - return convDecl;//out.addDeclaration(convDecl); - } - } - int nextAnonymousFieldId; - @Override - public void convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { - //List out = new ArrayList(); - try { - TypeRef valueType = v.getValueType(); - for (Declarator vs : v.getDeclarators()) { - String name = vs.resolveName(); - if (name == null || name.length() == 0) { - name = "anonymous" + (nextAnonymousFieldId++); - } - - TypeRef mutatedType = valueType; - if (!(vs instanceof DirectDeclarator)) - { - mutatedType = (TypeRef)vs.mutateTypeKeepingParent(valueType); - vs = new DirectDeclarator(vs.resolveName()); - } - VariablesDeclaration vd = convertVariablesDeclarationToJNA(name, mutatedType, iChild, callerLibraryClass, v, vs); - if (vd != null) { - Declarator d = v.getDeclarators().get(0); - if (d.getBits() > 0) { - int bits = d.getBits(); - if (!result.config.runtime.hasBitFields) - throw new UnsupportedConversionException(d, "This runtime does not support bit fields : " + result.config.runtime); - - vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(bits))); - String st = vd.getValueType().toString(), mst = st; - if (st.equals("int") || st.equals("long") || st.equals("short") || st.equals("long")) { - if (bits <= 8) - mst = "byte"; - else if (bits <= 16) - mst = "short"; - else if (bits <= 32) - mst = "int"; - else - mst = "long"; // should not happen - } - if (!st.equals(mst)) - vd.setValueType(new Primitive(mst)); - } - if (!(mutatedType instanceof Primitive) && !result.config.noComments) - vd.addToCommentBefore("C type : " + mutatedType); - out.addDeclaration(vd); - } - if (result.config.beanStructs) { - Function getMethod = new Function(Function.Type.JavaMethod, ident("get" + StringUtils.capitalize(name)), vd.getValueType().clone()).setBody(block( - new Statement.Return(varRef(name)) - )).addModifiers(ModifierType.Public); - if (signatures.addMethod(getMethod)) - out.addDeclaration(getMethod); - - Function setMethod = new Function(Function.Type.JavaMethod, ident("set" + StringUtils.capitalize(name)), typeRef(Void.TYPE), new Arg(name, vd.getValueType().clone())).setBody(block( - stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, ident(name)), AssignmentOperator.Equal, varRef(name))) - )).addModifiers(ModifierType.Public); - if (signatures.addMethod(setMethod)) - out.addDeclaration(setMethod); - } - iChild[0]++; - } - } catch (UnsupportedConversionException e) { - if (!result.config.limitComments) - out.addDeclaration(new EmptyDeclaration(e.toString())); - } - } - TaggedTypeRefDeclaration publicStaticClassDecl(Identifier name, Identifier parentName, Struct.Type type, Element toCloneCommentsFrom, Identifier... interfaces) { - return decl(publicStaticClass(name, parentName, type, toCloneCommentsFrom, interfaces)); - } - Struct publicStaticClass(Identifier name, Identifier parentName, Struct.Type type, Element toCloneCommentsFrom, Identifier... interfaces) { - Struct cl = new Struct(); - cl.setType(type); - cl.setTag(name); - if (parentName != null) - cl.setParents(typeRef(parentName)); - if (type == Struct.Type.JavaInterface) - for (Identifier inter : interfaces) - cl.addParent(typeRef(inter)); - else - for (Identifier inter : interfaces) - cl.addProtocol(typeRef(inter)); - - if (!result.config.noComments) - cl.importComments(toCloneCommentsFrom, getFileCommentContent(toCloneCommentsFrom)); - - cl.addModifiers(ModifierType.Public, ModifierType.Static); - return cl; - } - public Pair, List> getParentAndOwnDeclarations(Struct structJavaClass, Struct nativeStruct) throws IOException { - Pair, List> ret = - new Pair, List>( - new ArrayList(), - new ArrayList() - ) - ; - if (!nativeStruct.getParents().isEmpty()) { - for (SimpleTypeRef parentName : nativeStruct.getParents()) { - Struct parent = result.structsByName.get(parentName.getName()); - if (parent == null) { - // TODO report error - continue; - } - Struct parentJavaClass = convertStruct(parent, new Signatures(), null, null, true); - Pair, List> parentDecls = getParentAndOwnDeclarations(parentJavaClass, parent); - ret.getFirst().addAll(parentDecls.getFirst()); - ret.getFirst().addAll(parentDecls.getSecond()); - } - } - for (Declaration d : structJavaClass.getDeclarations()) { - if (!(d instanceof VariablesDeclaration)) - continue; - VariablesDeclaration vd = (VariablesDeclaration)d; - if (vd.getDeclarators().size() != 1) - continue; // should not happen ! - if (!isField(vd)) - continue; - - ret.getSecond().add(vd); - } - - return ret; - } - @SuppressWarnings("unchecked") - private void addStructConstructors(Identifier structName, Struct structJavaClass/*, Struct byRef, - Struct byVal*/, Struct nativeStruct) throws IOException { - - List initialMembers = new ArrayList(structJavaClass.getDeclarations()); - Set signatures = new TreeSet(); - - Function emptyConstructor = new Function(Function.Type.JavaMethod, structName.clone(), null).addModifiers(ModifierType.Public); - emptyConstructor.setBody(block(stat(methodCall("super")))); - addConstructor(structJavaClass, emptyConstructor); - - - boolean isUnion = nativeStruct.getType() == Struct.Type.CUnion; - if (isUnion) { - Map>>> fieldsAndCommentsByTypeStr = new HashMap>>>(); - for (Declaration d : initialMembers) { - if (!(d instanceof VariablesDeclaration)) - continue; - - VariablesDeclaration vd = (VariablesDeclaration)d; - if (vd.getDeclarators().size() != 1) - continue; // should not happen ! - String name = vd.getDeclarators().get(0).resolveName(); - TypeRef tr = vd.getValueType(); - if (!isField(vd)) - continue; - - String trStr = tr.toString(); - Pair>> pair = fieldsAndCommentsByTypeStr.get(trStr); - if (pair == null) - fieldsAndCommentsByTypeStr.put(trStr, pair = new Pair>>(tr, new ArrayList>())); - - pair.getSecond().add(new Pair(vd.getCommentBefore(), name)); - } - for (Pair>> pair : fieldsAndCommentsByTypeStr.values()) { - List commentBits = new ArrayList(), nameBits = new ArrayList(); - for (Pair p : pair.getValue()) { - if (p.getFirst() != null) - commentBits.add(p.getFirst()); - nameBits.add(p.getValue()); - } - String name = StringUtils.implode(nameBits, "_or_"); - TypeRef tr = pair.getFirst(); - Function unionValConstr = new Function(Function.Type.JavaMethod, structName.clone(), null, new Arg(name, tr.clone())); - if (!result.config.noComments) - if (!commentBits.isEmpty()) - unionValConstr.addToCommentBefore("@param " + name + " " + StringUtils.implode(commentBits, ", or ")); - - unionValConstr.addModifiers(ModifierType.Public); - - Expression assignmentExpr = varRef(name); - for (Pair p : pair.getValue()) - assignmentExpr = new Expression.AssignmentOp(memberRef(thisRef(), MemberRefStyle.Dot, ident(p.getValue())), AssignmentOperator.Equal, assignmentExpr); - - unionValConstr.setBody(block( - stat(methodCall("super")), - tr instanceof TypeRef.ArrayRef ? throwIfArraySizeDifferent(name) : null, - stat(assignmentExpr), - stat(methodCall("setType", result.typeConverter.getJavaClassLitteralExpression(tr))) - )); - - if (signatures.add(unionValConstr.computeSignature(SignatureType.JavaStyle))) { - structJavaClass.addDeclaration(unionValConstr); -// byRef.addDeclaration(unionValConstr.clone().setName(byRef.getTag().clone())); -// byVal.addDeclaration(unionValConstr.clone().setName(byVal.getTag().clone())); - } - } - } else { - Function fieldsConstr = new Function(Function.Type.JavaMethod, structName.clone(), null); - fieldsConstr.setBody(new Block()).addModifiers(ModifierType.Public); - - Pair, List> decls = getParentAndOwnDeclarations(structJavaClass, nativeStruct); - Map namesById = new TreeMap(); - Set names = new HashSet(); - List orderedFieldNames = new ArrayList(); - int iArg = 0; - for (VariablesDeclaration vd : new CompoundCollection(decls.getFirst(), decls.getSecond())) { - String name = chooseJavaArgName(vd.getDeclarators().get(0).resolveName(), iArg, names); - namesById.put(vd.getId(), name); - fieldsConstr.addArg(new Arg(name, vd.getValueType().clone())); - iArg++; - } - - FunctionCall superCall = methodCall("super"); - // Adding parent fields - for (VariablesDeclaration vd : decls.getFirst()) { - String name = vd.getDeclarators().get(0).resolveName(), uname = namesById.get(vd.getId()); - Struct parent = (Struct)vd.getParentElement(); - Identifier parentTgName = result.getTaggedTypeIdentifierInJava(parent); - if (!result.config.noComments) - fieldsConstr.addToCommentBefore("@param " + name + " @see " + parentTgName + "#" + vd.getDeclarators().get(0).resolveName()); - superCall.addArgument(varRef(uname)); - //orderedFieldNames.add(expr(name)); - } - fieldsConstr.getBody().addStatement(stat(superCall)); - - // Adding class' own fields - for (VariablesDeclaration vd : decls.getSecond()) { - String name = vd.getDeclarators().get(0).resolveName(), uname = namesById.get(vd.getId()); - if (!result.config.noComments) - if (vd.getCommentBefore() != null) - fieldsConstr.addToCommentBefore("@param " + uname + " " + vd.getCommentBefore()); - if (vd.getValueType() instanceof TypeRef.ArrayRef) - fieldsConstr.getBody().addStatement(throwIfArraySizeDifferent(uname)); - fieldsConstr.getBody().addStatement(stat( - new Expression.AssignmentOp(memberRef(thisRef(), MemberRefStyle.Dot, ident(name)), AssignmentOperator.Equal, varRef(uname)))); - - orderedFieldNames.add(expr(name)); - } - - String initOrderName = "initFieldOrder"; - Function initOrder = new Function(Type.JavaMethod, ident(initOrderName), typeRef(Void.TYPE)).setBody(block( - stat( - methodCall("setFieldOrder", new Expression.NewArray(typeRef(String.class), new Expression[0], orderedFieldNames.toArray(new Expression[orderedFieldNames.size()]))) - ) - )).addModifiers(ModifierType.Protected); - if (signatures.add(initOrder.computeSignature(SignatureType.JavaStyle))) { - structJavaClass.addDeclaration(initOrder); - Statement callInitOrder = stat(methodCall(initOrderName)); - emptyConstructor.getBody().addStatement(callInitOrder); - fieldsConstr.getBody().addStatement(callInitOrder.clone()); - } - - int nArgs = fieldsConstr.getArgs().size(); - if (nArgs == 0) - System.err.println("Struct with no field : " + structName); - - if (nArgs > 0 && nArgs < result.config.maxConstructedFields) { - if (signatures.add(fieldsConstr.computeSignature(SignatureType.JavaStyle))) { - structJavaClass.addDeclaration(fieldsConstr); - } - } - } - } - - @Override - protected void configureCallbackStruct(Struct callbackStruct) { - callbackStruct.setType(Struct.Type.JavaInterface); - callbackStruct.addModifiers(ModifierType.Public); - } - - @Override - protected Struct createFakePointerClass(Identifier fakePointer) { - Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(PointerType.class), Struct.Type.JavaClass, null); - - String pointerVarName = "address"; - ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, - new Arg(pointerVarName, typeRef(com.sun.jna.Pointer.class)) - ).addModifiers(ModifierType.Public).setBody( - block(stat(methodCall("super", varRef(pointerVarName))))) - ); - ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null) - .addModifiers(ModifierType.Public) - .setBody( - block(stat(methodCall("super"))) - )); - return ptClass; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAGlobalsGenerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAGlobalsGenerator.java deleted file mode 100644 index ae72cbc5a..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAGlobalsGenerator.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - - -import com.ochafik.lang.jnaerator.parser.Declaration; -import java.util.ArrayList; -import java.util.Collections; - -import java.util.List; - -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrim; -import com.ochafik.lang.jnaerator.TypeConversion.TypeConversionMode; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.Statement; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerStyle; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalCallback; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointer; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalPointerType; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalStruct; -import com.sun.jna.ptr.ByReference; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class JNAGlobalsGenerator extends GlobalsGenerator { - - public JNAGlobalsGenerator(Result result) { - super(result); - } - - - public void convertGlobals(VariablesDeclaration globals, Signatures signatures, DeclarationsHolder out, Expression nativeLibFieldExpr, Identifier callerLibraryName, String callerLibrary) throws UnsupportedConversionException { - for (Declarator d : globals.getDeclarators()) { - try { - Identifier name = result.typeConverter.getValidJavaArgumentName(ident(d.resolveName())); - TypeRef type = (TypeRef)d.mutateTypeKeepingParent(globals.getValueType()); - if (type == null) - continue; - - boolean isCallback = result.callbacksByName.containsKey(ident(type.toString()));//type instanceof FunctionSignature; - List modifiers = new ArrayList(type.getModifiers()); - modifiers.addAll(globals.getModifiers()); - - type.setModifiers(Collections.EMPTY_LIST); - - if ( !isCallback && - !(ModifierType.Extern.isContainedBy(modifiers) || ModifierType.Dllexport.isContainedBy(modifiers) || ModifierType.Dllimport.isContainedBy(modifiers)) - //|| Modifier.Const.isContainedBy(modifiers) && d.getDefaultValue() != null - ) { - //result.declarationsConverter.convertCon - continue; - } - - - if (true) {//!result.config.useJNADirectCalls) { - if (!signatures.addVariable(name.toString())) - continue; - - boolean isPointer = type instanceof com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; - TypeConversion.JavaPrim prim = result.typeConverter.getPrimitive(isPointer ? ((com.ochafik.lang.jnaerator.parser.TypeRef.Pointer)type).getTarget() : type, callerLibraryName); - type.setMarkedAsResolved(false); - TypeRef convertedType = result.typeConverter.convertTypeToJNA(type, TypeConversion.TypeConversionMode.NativeParameter, callerLibraryName); - String convTypStr = convertedType.toString(); - if (convTypStr.endsWith(".ByValue")) - convTypStr = convTypStr.substring(0, convTypStr.length() - ".ByValue".length()); - boolean isStruct = result.structsFullNames.contains(ident(convTypStr)); - boolean isUnion = result.unionsFullNames.contains(ident(convTypStr)); - - //if (result. convertedType) - if (prim != null || isCallback || isStruct || isUnion) { - TypeRef globalType = null; - Expression extraArg = null; - //Class optionA; - if (isUnion || isStruct) { - globalType = typeRef(ident(GlobalStruct.class, expr(convertedType.clone()))); - extraArg = memberRef(expr(convertedType.clone()), Expression.MemberRefStyle.Dot, "class"); - } else if (isCallback) { - globalType = typeRef(ident(GlobalCallback.class, expr(type.clone()))); - extraArg = memberRef(expr(type.clone()), Expression.MemberRefStyle.Dot, "class"); - } else if (isPointer) { - Class brt = result.typeConverter.primToByReference.get(prim); - if (brt != null) { - globalType = typeRef(ident(GlobalPointerType.class, expr(typeRef(ident(brt))))); - extraArg = classLiteral(brt); - } else if (prim == TypeConversion.JavaPrim.Void) { - globalType = typeRef(GlobalPointer.class); - } - } else { - Class globalClass = result.typeConverter.primToGlobal.get(prim); - if (globalClass != null) - globalType = typeRef(globalClass); - } - if (globalType != null) { - List constructorArgs = new ArrayList(); - constructorArgs.add(nativeLibFieldExpr.clone()); - if (extraArg != null) { - constructorArgs.add(extraArg); - } - constructorArgs.add(expr(name.toString())); - VariablesDeclaration vd = new VariablesDeclaration( - globalType, - new Declarator.DirectDeclarator( - name.toString(), - new Expression.New( - globalType.clone(), - constructorArgs.toArray(new Expression[constructorArgs.size()]) - ) - ) - ); - - vd.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final); - vd.importComments(globals); - - out.addDeclaration(vd); - continue; - } - } - } - - if (!signatures.addClass(name)) - continue; - - - /// We get a pointer to the global, not the global itself - Struct struct = result.declarationsConverter.publicStaticClass(name, null, Struct.Type.JavaClass, null); - struct.addModifiers(ModifierType.Final); - struct.importDetails(globals, false); - struct.moveAllCommentsBefore(); - - TypeRef pointerType = new TypeRef.Pointer(type, Declarator.PointerStyle.Pointer); - - TypeRef convPointerType = result.typeConverter.convertTypeToJNA(pointerType, TypeConversion.TypeConversionMode.FieldType, callerLibraryName); - TypeRef instType; - boolean hasOffset, isPtr = false, isByRef = false; - String convPointerTypeStr = convPointerType.toString(); - if (convPointerTypeStr.equals(result.config.runtime.pointerClass.getName())) { - isPtr = true; - instType = convPointerType; - hasOffset = false; - } else if (result.typeConverter.byReferenceClassesNames.contains(convPointerTypeStr)) { - isByRef = true; - instType = convPointerType; - hasOffset = false; - } else if (convPointerTypeStr.endsWith(".ByReference") && result.structsByName.get(convPointerTypeStr.substring(0, convPointerTypeStr.length() - ".ByReference".length())) != null) { - instType = result.typeConverter.convertTypeToJNA(type, TypeConversion.TypeConversionMode.PointedValue, callerLibraryName);//convPointerType; - hasOffset = true; - } else { - Identifier instTypeName = ident(name + "_holder"); - Struct holderStruct = result.declarationsConverter.publicStaticClass(instTypeName, ident(result.config.runtime.structClass), Struct.Type.JavaClass, null); - holderStruct.addModifiers(ModifierType.Final); - VariablesDeclaration vd = ((JNADeclarationsConverter)result.declarationsConverter).convertVariablesDeclarationToJNA("value", type, new int[1], callerLibraryName); - if (vd.getValueType().toString().equals(result.config.runtime.pointerClass.getName())) { - isByRef = true; - instType = convPointerType; - hasOffset = false; - } else { - holderStruct.addDeclaration(vd); - Function pointerConstructor = new Function(Function.Type.JavaMethod, instTypeName, null, - new Arg("pointer", new TypeRef.SimpleTypeRef(result.config.runtime.pointerClass.getName())) - ); - hasOffset = false; - pointerConstructor.setBody(new Statement.Block( - new Statement.ExpressionStatement(methodCall("super")), - new Statement.ExpressionStatement(methodCall("useMemory", varRef("pointer"), expr(0))), - new Statement.ExpressionStatement(methodCall("read")) - )); - holderStruct.addDeclaration(pointerConstructor); - - //holderStruct.addDeclaration(new VariablesDeclaration(convType, new Declarator.DirectDeclarator("value")).addModifiers(ModifierType.Public)); - instType = new TypeRef.SimpleTypeRef(instTypeName); - struct.addDeclaration(decl(holderStruct)); - } - } - Identifier instName = name;//"_"; - struct.addDeclaration(new VariablesDeclaration(instType, new Declarator.DirectDeclarator(instName.toString())).addModifiers(ModifierType.Private, ModifierType.Static)); - Expression.VariableRef instRef = new Expression.VariableRef(instName); - Expression ptrExpr = methodCall( - nativeLibFieldExpr.clone(), - Expression.MemberRefStyle.Dot, - "getGlobalVariableAddress", - expr(name.toString()) - ); - List initStats = new ArrayList(); - initStats.add(new Statement.ExpressionStatement( - expr( - instRef.clone(), - Expression.AssignmentOperator.Equal, - isPtr ? ptrExpr : - isByRef ? new Expression.New(instType) : - new Expression.New(instType, new Expression.FunctionCall(null, ptrExpr, hasOffset ? expr(0) : null)) - ) - )); - if (isByRef) - initStats.add(new Statement.ExpressionStatement(methodCall(instRef, Expression.MemberRefStyle.Dot, "setPointer", ptrExpr))); - - struct.addDeclaration(new Function(Function.Type.JavaMethod, ident("get"), instType).setBody(new Statement.Block( - new Statement.If( - expr(instRef, Expression.BinaryOperator.IsEqual, nullExpr()), - initStats.size() == 1 ? initStats.get(0) : new Statement.Block(initStats), - null - ), - new Statement.Return(instRef.clone()) - )).addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Synchronized)); - out.addDeclaration(decl(struct)); - } catch (Throwable t) { - out.addDeclaration(result.declarationsConverter.skipDeclaration(d, t.toString())); - } - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNATypeConversion.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNATypeConversion.java deleted file mode 100644 index d51ce8b70..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNATypeConversion.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.SyntaxUtils; -import com.ochafik.lang.jnaerator.parser.*; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.util.listenable.Pair; -/** - * - * @author ochafik - */ -public class JNATypeConversion extends TypeConversion { - - public JNATypeConversion(Result result) { - super(result); - } - - public Expression getEnumItemValue(com.ochafik.lang.jnaerator.parser.Enum.EnumItem enumItem) { - return cast(typeRef(int.class), findEnumItem(enumItem)); - } - - @Override - protected JavaPrim getCppBoolMappingType() { - return JavaPrim.Byte; - } - - public Pair convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { - Pair res = null; - if (x instanceof Expression.Cast) { - TypeRef tpe = ((Expression.Cast) x).getType(); - Pair casted = convertExpressionToJava(((Expression.Cast) x).getTarget(), libraryClassName, promoteNativeLongToLong); - TypeRef tr = convertTypeToJNA(tpe, TypeConversionMode.ExpressionType, libraryClassName); - JavaPrim prim = getPrimitive(tr, libraryClassName); - if (promoteNativeLongToLong && (prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize)) { - prim = JavaPrim.Long; - tr = typeRef(Long.TYPE); - } - Expression val = casted.getFirst(); - if (isString(val)) { - val = methodCall(new Expression.New(typeRef(com.ochafik.lang.jnaerator.runtime.StringPointer.class), val), "getPointer"); - } else { - if (prim == JavaPrim.NativeLong) { - val = (Expression) new Expression.New(typeRef(com.sun.jna.NativeLong.class), val); - } else if (prim == JavaPrim.NativeSize) { - val = (Expression) new Expression.New(typeRef(NativeSize.class), val); - } - } - res = typed(val, tr); - } - if (res == null) { - return super.convertExpressionToJava(x, libraryClassName, promoteNativeLongToLong); - } - if (res.getFirst() == null) { - return null; - } - res.getFirst().setParenthesis(x.getParenthesis()); - return (Pair) res; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAerator.java deleted file mode 100644 index bf810803e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAerator.java +++ /dev/null @@ -1,1725 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.JNAeratorCommandLineArgs.PathType; -import org.bridj.CRuntime; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import org.bridj.ann.Ptr; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import java.io.File; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.tools.DiagnosticCollector; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; - -import org.anarres.cpp.LexerException; -import org.antlr.runtime.RecognitionException; -//import org.junit.runner.JUnitCore; -import org.rococoa.cocoa.foundation.NSClass; -import org.rococoa.Rococoa; - -import org.bridj.BridJ; -import org.bridj.cpp.CPPRuntime; -import com.ochafik.io.FileListUtils; -import com.ochafik.io.IOUtils; -import com.ochafik.io.ReadText; -import com.ochafik.io.WriteText; -import com.ochafik.lang.compiler.CompilerUtils; -import com.ochafik.lang.compiler.MemoryFileManager; -import com.ochafik.lang.compiler.MemoryJavaFile; -import com.ochafik.lang.compiler.URLFileObject; -import com.ochafik.lang.jnaerator.JNAeratorCommandLineArgs.OptionDef; -import com.ochafik.lang.jnaerator.JNAeratorConfig.OutputMode; -import com.ochafik.lang.jnaerator.nativesupport.DllExport; -import com.ochafik.lang.jnaerator.parser.Annotation; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Declaration; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Define; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.ModifiableElement; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.ObjCppParser; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Identifier.QualificationSeparator; -import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.lang.jnaerator.parser.ModifierKind; -import com.ochafik.lang.jnaerator.parser.ObjCppLexer; -import com.ochafik.lang.jnaerator.parser.Statement; -import com.ochafik.lang.jnaerator.parser.Struct.Type; -import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; -import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; -import com.ochafik.lang.jnaerator.runtime.Mangling; -import com.ochafik.lang.jnaerator.studio.JNAeratorStudio; -import com.ochafik.lang.jnaerator.studio.JNAeratorStudio.SyntaxException; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; -import com.sun.jna.Native; -import com.sun.jna.NativeLibrary; -import com.sun.jna.win32.StdCallLibrary; -import java.io.BufferedReader; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.StringReader; -import java.text.MessageFormat; -import java.util.logging.Logger; -import org.antlr.runtime.ANTLRReaderStream; -import org.antlr.runtime.CommonTokenStream; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.nativesupport.NativeExportUtils.*; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import java.io.*; -/* -//include com/ochafik/lang/jnaerator/parser/*.mm -//include com/ochafik/lang/jnaerator/parser/ObjCpp.g - */ - - -/** - -mvn -o compile exec:java -Dexec.mainClass=com.ochafik.lang.jnaerator.JNAerator - * java -Xmx2000m -jar ../bin/jnaerator.jar `for F in /System/Library/Frameworks/*.framework ; do echo $F| sed -E 's/^.*\/([^/]+)\.framework$/-framework \1/' ; done` -out apple-frameworks.jar - */ - -public class JNAerator { - public static final String JNAERATOR_URL = "http://code.google.com/p/jnaerator/"; - public static String DONATE_URL = "http://sourceforge.net/donate/index.php?group_id=266856"; - public static String ABOUT_JNAERATOR_URL = "http://code.google.com/p/jnaerator/wiki/AboutJNAerator"; - public static String ABOUT_ROCOCOA_URL = "http://code.google.com/p/rococoa"; - public static String ABOUT_BRIDJ_URL = "http://code.google.com/p/bridj/wiki"; - public static String ABOUT_JNA_URL = "https://github.com/twall/jna"; - - public static interface Feedback { - void setStatus(final String string); - void setFinished(File toOpen); - void setFinished(Throwable e); - void sourcesParsed(SourceFiles sourceFiles); - void wrappersGenerated(Result result); - } - private static Pattern argTokenPattern = Pattern.compile("(?m)\"[^\"]*\"|[^\\s]+"); - private static Pattern argVariablePattern = Pattern.compile("\\$\\(([^)]+)\\)"); - protected final JNAeratorConfig config; - - public JNAerator(JNAeratorConfig config) { - this.config = config; - } - - protected static void fixConfig(JNAeratorConfig config) { - if (config.sourceFiles.isEmpty() && config.bridgeSupportFiles.isEmpty() && !config.libraryFiles.isEmpty()) - config.extractLibSymbols = true; - - Collection inputFiles = config.getInputFiles(); - File firstFile = inputFiles.isEmpty() ? null : inputFiles.iterator().next().getAbsoluteFile(); - String firstFileName = firstFile == null ? null : firstFile.getName(); - Set libraries = config.getLibraries(); - String entry = - config.entryName != null ? config.entryName : - libraries.size() == 1 ? libraries.iterator().next() : - null;//RegexUtils.findFirst(firstFileName, fileRadixPattern, 1); - //if (entry != null) - // entry = config.result.typeConversion.getValidJavaIdentifier(ident(entry)).toString(); - - if (config.outputDir == null) - config.outputDir = new File("."); - - if (config.sourcesOutputDir == null) { - if (config.outputMode == OutputMode.Maven) - config.sourcesOutputDir = new File(config.outputDir, "src/main/java"); - else - config.sourcesOutputDir = config.outputDir; - } - if (config.resourcesOutputDir == null) { - if (config.outputMode.isMaven()) - config.resourcesOutputDir = new File(config.outputDir, "src/main/resources"); - else - config.resourcesOutputDir = config.outputDir; - } - if (config.outputJar == null && config.outputMode.isJar()) - config.outputJar = new File(config.outputDir, (entry == null ? "out" : entry) + ".jar"); - - if (config.mavenArtifactId == null && entry != null) - config.mavenArtifactId = entry; - if (config.mavenGroupId == null && config.rootPackageName != null) - config.mavenGroupId = config.rootPackageName; - - config.cacheDir = getDir("cache"); - - } - static final Pattern definePattern = Pattern.compile("#\\s*define\\s+(\\w+)\\s+(.*)"); - static final boolean fullFilePathInComments = true; - - private static final String DEFAULT_CONFIG_FILE = "config.jnaerator"; - private static final String POM_FILENAME = "pom.xml"; - protected static final Pattern fileRadixPattern = Pattern.compile("(?:[/\\\\]|^)(.*?)(?:Full\\.bridgesupport|\\.[^.]+)$"); - private static final Pattern classAndMethodNamePattern = Pattern.compile("(.+?)::([^:]+)"); - - public static String[] getJNAeratorArgsFromPref() { - String argsPref = System.getProperty("jnaerator.args"); - if (argsPref == null) - return null; - return argsPref.split(","); - } - - static Logger logger = Logger.getLogger(JNAerator.class.getName()); - public static void main(String[] argsArray) { - //argsArray = new String[] { "/Users/ochafik/src/boost_1_48_0/config.jnaerator", "-v" }; - main(new JNAerator(new JNAeratorConfig()), argsArray); - } - - public static void main(final JNAerator jnaerator, String[] argsArray) { - final Feedback[] feedback = new Feedback[1]; - - try { - - String[] jnAeratorArgsFromPref = getJNAeratorArgsFromPref(); - if (jnAeratorArgsFromPref != null) { - ArrayList list = new ArrayList(); - list.addAll(Arrays.asList(jnAeratorArgsFromPref)); - list.addAll(Arrays.asList(argsArray)); - argsArray = list.toArray(new String[list.size()]); - } - if (argsArray.length == 0) { - if (new File(DEFAULT_CONFIG_FILE).exists()){ - argsArray = new String[] { "@", DEFAULT_CONFIG_FILE }; - } else { - argsArray = new String[] { "-studio" }; - } - } - - List args = new ArrayList(Arrays.asList(argsArray)); - - final JNAeratorConfig config = jnaerator.config;//new JNAeratorConfig(); - config.preprocessorConfig.frameworksPath.addAll(JNAeratorConfigUtils.DEFAULT_FRAMEWORKS_PATH); - new JNAeratorCommandLineArgs.ArgsParser() { - - - boolean simpleGUI = false; - NativePlatform arch = NativePlatform.getCurrentPlatform();//LibraryExtractor.getCurrentOSAndArchString(); - File libraryFileForCurrentArch = null; - String currentLibrary = null; - - @Override - List parsed(ParsedArg a) throws Exception { - switch (a.def) { - - case AddIncludePath: - File includedFile = a.getFileParam(0); - if (includedFile.isFile()) - parsedActualFile(includedFile, false); - else - config.preprocessorConfig.includes.add(includedFile.toString()); - - getPath(PathType.SourcePath).add(includedFile); - break; - case DontCastConstants: - config.castConstants = false; - break; - case CallbackInvokeName: - config.callbackInvokeMethodName = a.getStringParam(0); - break; - case AddFrameworksPath: - config.preprocessorConfig.frameworksPath.add(a.getFileParam(0).toString()); - break; - case NoPreprocessing: - config.preprocessorConfig.preprocess = false; - break; - case MaxConstructedFields: - config.maxConstructedFields = a.getIntParam(0); - break; - case BeanStructs: - config.beanStructs = true; - break; - case NoPrimitiveArrays: - config.noPrimitiveArrays = true; - break; - case IfRegexMatch: - String javaProperty = a.getStringParam(0), - regex = a.getStringParam(1), - thenCmd = a.getStringParam(2), - elseCmd = a.getStringParam(3); - String propValue = System.getProperty(javaProperty); - if (propValue == null) - propValue = ""; - return Arrays.asList(propValue.matches(regex) ? thenCmd : elseCmd); - case AddRootDir: - config.addRootDir(a.getFileParam("dir")); - break; - case ConvertBodies: - config.convertBodies = true; - break; - case NoAutoImports: - config.noAutoImports = true; - break; - case ForceOverwrite: - config.forceOverwrite = true; - break; - case MavenGroupId: - config.mavenGroupId = a.getStringParam(0); - break; - case MavenArtifactId: - config.mavenArtifactId = a.getStringParam(0); - break; - case MavenVersion: - config.mavenVersion = a.getStringParam(0); - break; - case OutputMode: - config.outputMode = a.getEnumParam(0, OutputMode.class); - break; - case NoJAR: - config.legacyNoJar = true; - break; - case NoCompile: - config.legacyNoCompile = true; - break; - case SkipLibInstance: - config.skipLibraryInstanceDeclarations = true; - break; - case COM: - config.microsoftCOM = true; - break; - case NoStringReturns: - config.stringifyConstCStringReturnValues = false; - break; - case SkipIncludedFrameworks: - config.skipIncludedFrameworks = true; - break; - case GenPrivateMembers: - config.skipPrivateMembers = false; - break; - case CPlusPlusGen: - config.genCPlusPlus = true; - break; - case CurrentLibrary: - currentLibrary = a.getStringParam(0); - break; - case CurrentPackage: - config.packageName = a.getStringParam(0); - break; - case OnlineDocURLFormat: - config.onlineDocumentationURLFormats.add(new Pair(a.getMessageFormatParam(0), a.getMessageFormatParam(1))); - break; - case BeautifyNames: - config.beautifyNames = true; - break; - case NoLibBundle: - config.bundleLibraries = false; - break; - case DefaultLibrary: - config.defaultLibrary = a.getStringParam(0); - break; - case RecursedExtensions: - config.fileFilter = "*".equals(a.getStringParam(0)) ? null : new JNAeratorConfigUtils.FileExtensionFilter(a.getStringParam(0).split("[:;")); - break; - case DefineMacro: - config.preprocessorConfig.macros.put(a.getStringParam(0), a.getStringParam(1)); - break; - case Direct: - config.useJNADirectCalls = true; - break; - case EntryName: - config.entryName = a.getStringParam(0); - break; - case ExtractSymbols: - config.extractLibSymbols = true; - break; - case Runtime: - config.runtime = a.getEnumParam(0, JNAeratorConfig.Runtime.class); - break; - case LibFile: - config.addLibraryFile(a.getFileParam(0), arch); - break; - case File: - return parsedFile(a); - case FrameworksPath: - config.preprocessorConfig.frameworksPath.clear(); - config.preprocessorConfig.frameworksPath.addAll(Arrays.asList(a.getStringParam(0).split(":"))); - break; - case GUI: - simpleGUI = true; - break; - case Help: - case WikiDoc: - JNAeratorCommandLineArgs.displayHelp(a.def == OptionDef.WikiDoc); - throw new ExitException(0); - case WCharAsShort: - config.wcharAsShort = true; - break; - case Synchronized: - config.synchronizedMethods = true; - break; - case JarOut: - config.outputJar = a.getFileParam(0); - break; - case ScalaStructSetters: - config.scalaStructSetters = true; - break; - case NoComments: - config.noComments = true; - break; - case LimitComments: - config.limitComments = true; - break; - case MacrosOut: - config.macrosOutFile = a.getFileParam(0); - break; - case GCCLong: - config.gccLong = true; - break; - case SizeAsLong: - config.sizeAsLong = true; - break; - case GenRawBindings: - config.genRawBindings = true; - break; - case Undefine: - config.undefines.add(a.getStringParam(0)); - break; - case NoAuto: - config.autoConf = false; - break; - case Reification: - config.reification = true; - break; - case NoCPP: - config.noCPlusPlus = true; - break; - case ScalaOut: - config.scalaOut = a.getFileParam(0); - break; -// case NoRuntime: -// config.bundleRuntime = false; -// break; - case OutputDir: - config.outputDir = a.getFileParam(0); - break; - case LibraryNamingPrefixes: - config.libraryNamingPrefixes = a.getStringParam(0).split(","); - break; - case PreferJavac: - config.preferJavac = true; - break; - case BridgeSupportOutFile: - config.bridgesupportOutFile = a.getFileParam(0); - break; - case ChoicesOut: - config.choicesOutFile = a.getFileParam(0); - break; - case ChoicesIn: - config.choicesInputFile = a.getFileParam(0); - break; - case PreprocessingOut: - config.preprocessingOutFile = a.getFileParam(0); - break; - case ExtractionOut: - config.extractedSymbolsOut = a.getFileParam(0); - break; - - case Project: - JNAeratorConfigUtils.readProjectConfig(a.getFileParam(0), a.getStringParam(1), config); - break; - case RootPackage: - config.rootPackageName = a.getStringParam(0); - break; - case RemoveInlineAsm: - config.removeInlineAsm = true; - break; - case StructsInLibrary: - config.putTopStructsInSeparateFiles = false; - break; - case EmptyStructsAsForwardDecls: - config.treatEmptyStructsAsForwardDecls = true; - break; - case ParseInChunks: - config.parseInChunks = true; - break; - case Studio: - try { - JNAeratorStudio.main(new String[0]); - return null; - } catch (Exception ex) { - ex.printStackTrace(); - throw new ExitException(1); - } -// case Test: -// try { -// JUnitCore.main(JNAeratorTests.class.getName()); -// System.exit(0); -// } catch (Exception ex) { -// ex.printStackTrace(); -// System.exit(1); -// } -// break; - case Verbose: - config.verbose = true; - break; - case Framework: - config.frameworks.add(a.getStringParam(0)); - break; - case IncludeArgs: - return parsedArgsInclude(a); - case Arch: - arch = a.getEnumParam(0, NativePlatform.class); - libraryFileForCurrentArch = null; - break; - - } - return Collections.emptyList(); - } - private void parsedActualFile(File file, boolean retainAsTarget) throws Exception { - String lib = currentLibrary; - String fn = file.getName(); - String lfn = fn.toLowerCase(); - if (!lfn.matches(".*?\\.(c|cpp|h|hpp|hxx|m)")) { - throw new CommandLineException("File '" + file + "' does not seem to be a C, C++ or Objective-C source file, nor a dynamic library, nor a *.jnaerator file."); - } - if (lib == null) { - String name = fn; - int i = name.indexOf('.'); - if (i >= 0) - name = name.substring(0, i).trim(); - if (name.length() > 0) - lib = name; - System.out.println("Warning: no -library option for file '" + fn + "', using \"" + lib + "\"."); - } - config.addSourceFile(file, lib, !file.isFile(), retainAsTarget); - } - private List parsedFile(ParsedArg a) throws Exception { - File file = a.getFileParam(0); - if (file != null) { - String fn = file.getName(); - if (fn.startsWith("-") && !file.exists()) { - JNAeratorCommandLineArgs.displayHelp(false); - throw new CommandLineException("Invalid switch : " + file); - } - if (file.isFile() && fn.matches(".*\\.jnaerator")) - return parsedArgsInclude(a); - else { - parsedArgs.add(Pair.create(OptionDef.File, Arrays.asList(a.getFileParam(0).toString()))); - if (file.isDirectory() && fn.matches(".*\\.framework")) - config.frameworks.add(file.toString()); - else if (fn.matches(".*\\.bridgesupport")) - config.bridgeSupportFiles.add(file); - else if (file.isFile() && isLibraryFile(file)) { - if (arch == null) { - throw new CommandLineException("No arch defined for file " + file + " !\n" + - "Please use the option " + OptionDef.Arch.clSwitch + " *on each binary file* with one of " + StringUtils.implode(NativePlatform.getPossiblePlatformsOfLibraryFile(file.toString()), ", ")); - } - if (!arch.pattern.matcher(file.toString()).matches()) { - throw new CommandLineException("File file " + file + " doesn't look like a native library for arch " + arch + " (expected file extension = '" + arch.extension + "') !"); - } - - if (config.verbose) - System.out.println("Adding file '" + file + "' for arch '" + arch +"'."); - config.addLibraryFile(file, arch); - - // if (libraryFileForCurrentArch == null) { - // if (config.verbose) - // System.out.println("Adding file '" + file + "' for arch '" + arch +"'."); - // config.addLibraryFile(currentLibrary, file, arch); - // libraryFileForCurrentArch = file; - // } else { - // if (config.verbose) - // System.out.println("Adding dependency '" + file + "' for arch '" + arch +"'."); - // config.addDependentLibraryFile(currentLibrary, file, arch); - // } - - } else { - String lib = currentLibrary; - if (file.isDirectory() && fn.endsWith(".xcode") || - file.isFile() && fn.toLowerCase().endsWith(".sln")) - { - JNAeratorConfigUtils.readProjectConfig(file, null, config); - } else { - parsedActualFile(file, true); - } - } - } - } - return Collections.emptyList(); - } - - private List parsedArgsInclude(ParsedArg a) throws IOException { - final File argsFile = a.getFileParam(0); - - String argsFileContent = ReadText.readText(argsFile); - Adapter argVariableReplacer = new Adapter() { - @Override - public String adapt(String[] value) { - String n = value[1]; - String v = System.getProperty(n); - if (v == null) - v = System.getenv(n); - if (v == null && n.equals("DIR")) - v = argsFile.getAbsoluteFile().getParent(); - return v; - } - }; - - // Strip comments out - argsFileContent = argsFileContent.replaceAll("http://", "http:\\\\"); - argsFileContent = argsFileContent.replaceAll("(?m)//[^\n]*(\n|$)", "\n"); - argsFileContent = argsFileContent.replaceAll("http:\\\\", "http://"); - argsFileContent = argsFileContent.replaceAll("(?m)/\\*([^*]|\\*[^/])*\\*/", ""); - - // Replace variables - argsFileContent = RegexUtils.regexReplace(argVariablePattern, argsFileContent, argVariableReplacer); - - List ret = new ArrayList(); - List tokens = RegexUtils.find(argsFileContent, argTokenPattern); - for (String[] tokenMatch : tokens) { - String token = tokenMatch[0]; - token = token.trim(); - if (token.startsWith("\"") && token.endsWith("\"")) - token = token.substring(1, token.length() - 1); - - if (token.length() == 0 || token.matches("^(//|#).*")) - continue; - - boolean allowMissing = token.endsWith("?"); - if (token.contains("*")) { - Collection rs = FileListUtils.resolveShellLikeFileList(allowMissing ? token.substring(0, token.length() - 1) : token); - for (String r : rs) - ret.add(allowMissing ? r + "?" : r); - if (!rs.isEmpty()) - continue; - } - ret.add(token); - } - return ret; - } - - @Override - void finished() throws IOException { - if (config.outputMode == null) { - if (config.legacyNoCompile && config.legacyNoJar) { - config.outputMode = OutputMode.Directory; - System.err.println("WARNING: legacy options " + OptionDef.NoJAR.clSwitch + " and " + OptionDef.NoCompile.clSwitch + " used, defaulting " + OptionDef.OutputMode.clSwitch + " to " + config.outputMode.name()); - } - if (config.outputMode == null) - throw new CommandLineException("Missing output mode parameter " + OptionDef.OutputMode.clSwitch + " !"); - } - - //System.out.println("Mode = " + config.outputMode.name()); - config.parsedArgs = parsedArgs; - - for (String framework : config.frameworks) - JNAeratorConfigUtils.addFramework(config, framework); - - config.addRootDir(new File(".")); - for (String i : config.preprocessorConfig.includes) { - try { - config.addRootDir(new File(i)); - } catch (Exception ex) {} - } - - fixConfig(config); - - if (config.verbose) { - if (config.rawParsedSourcesOutFile == null) - config.rawParsedSourcesOutFile = new File("_jnaerator.rawParsed.cpp"); - if (config.normalizedParsedSourcesOutFile == null) - config.normalizedParsedSourcesOutFile = new File("_jnaerator.normalizedParsed.cpp"); - if (config.macrosOutFile == null) - config.macrosOutFile = new File("_jnaerator.macros.cpp"); - if (config.choicesOutFile == null) - config.choicesOutFile = new File("_jnaerator.choices"); - if (config.preprocessingOutFile == null) - config.preprocessingOutFile = new File("_jnaerator.preprocessed.c"); - if (config.extractedSymbolsOut == null) - config.extractedSymbolsOut = new File("_jnaerator.extractedSymbols.h"); - if (config.bridgesupportOutFile == null) - config.bridgesupportOutFile = new File("_jnaerator.bridgesupport.h"); - } - - - if (simpleGUI) { - SimpleGUI gui = new SimpleGUI(config); - feedback[0] = gui; - gui.show(); - } else { - feedback[0] = new Feedback() { - - @Override - public void setStatus(String string) { - //if (config.verbose) - System.out.println(string); - } - - @Override - public void setFinished(Throwable e) { - e.fillInStackTrace(); - throw new ExitException(1, e); - } - - @Override - public void setFinished(File toOpen) { - System.out.println("#"); - System.out.println("# SUCCESS: JNAeration completed !"); - System.out.println("# Output mode is '" + config.outputMode.name() + "(" + config.outputMode.getDescription() + ")"); - System.out.println("#"); - if (config.outputMode.isMaven()) { - System.out.println("# To build the resulting Maven project, use commands like :"); - System.out.println("#\tcd " + toOpen.getAbsolutePath()); - System.out.println("#\tmvn install"); - } else { - System.out.println("# => '" + toOpen.getAbsolutePath() + "'"); - } - System.out.println("#"); - throw new ExitException(0); - } - - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - - } - - @Override - public void wrappersGenerated( - com.ochafik.lang.jnaerator.Result result) { - // TODO Auto-generated method stub - - } - }; - } - - jnaerator.jnaerate(feedback[0]); - if (!simpleGUI) - throw new ExitException(0); - } - - }.parse(args); - - } catch (ExitException e) { - if (e.errorCode != 0) { - finalError(e.getCause()); - } - } catch (Exception e) { - finalError(e); - } - } - private static void finalError(Throwable e) { - if (e != null) - e.printStackTrace(); - System.err.println("#"); - System.err.println("# ERROR: JNAeration failed !"); - System.err.println("#"); - if (e != null) { - if (e instanceof CommandLineException) { - System.err.println("#\t" + e.getMessage().replaceAll("\n", "\n#\t")); - System.err.println("#\tPlease use -h for help on the command-line options available."); - } else { - System.err.println("#\t" + e.toString().replaceAll("\n", "\n#\t")); - } - System.err.println("#"); - } - } - static class CommandLineException extends RuntimeException { - public CommandLineException(String msg) { - this(msg, null); - } - public CommandLineException(String msg, Throwable cause) { - super(msg, cause); - } - } - static class ExitException extends RuntimeException { - int errorCode; - public ExitException(int errorCode) { - this(errorCode, null); - } - public ExitException(int errorCode, Throwable cause) { - super(cause); - this.errorCode = errorCode; - } - } - - public PrintWriter getClassSourceWriter(ClassOutputter outputter, String className) throws IOException { - if (outputter == null) - return newFileWriter(new File(config.sourcesOutputDir, className.replace('.', File.separatorChar) + ".java")); - return outputter.getClassSourceWriter(className); - } - private static boolean isLibraryFile(File file) { - String arg = file.getName().toLowerCase(); - return - arg.endsWith(".dll") || - arg.endsWith(".pdb") || - arg.endsWith(".dylib") || - arg.endsWith(".so") || - arg.endsWith(".jnilib"); - } - protected void autoConfigure() { - JNAeratorConfigUtils.autoConfigure(config); - } - - PrintWriter newFileWriter(File file) throws IOException { - return newFileWriter(file, false); - } - PrintWriter newFileOverwriter(File file) throws IOException { - return newFileWriter(file, true); - } - PrintWriter newFileWriter(File file, boolean overwrite) throws IOException { - if (file.exists()) { - if (config.forceOverwrite || overwrite) - System.out.println("Overwriting file '" + file + "'"); - else - throw new IOException("File '" + file + "' already exists (use " + JNAeratorCommandLineArgs.OptionDef.ForceOverwrite.clSwitch + " to force overwrite)."); - } - file.getAbsoluteFile().getParentFile().mkdirs(); - return new PrintWriter(file) { - @Override - public void print(String s) { - super.print(s.replace("\r", "").replace("\n", StringUtils.LINE_SEPARATOR)); - } - }; - } - public void jnaerate(final Feedback feedback) { - try { - if (config.autoConf) { - feedback.setStatus("Auto-configuring parser..."); - autoConfigure(); - } - fixConfig(config); - config.preprocessorConfig.macros.keySet().removeAll(config.undefines); - - if (config.verbose) - JNAeratorConfigUtils.logger.log(Level.INFO, "Include path : \n\t" + StringUtils.implode(config.preprocessorConfig.includes, "\n\t")); - - DiagnosticCollector diagnostics = new DiagnosticCollector(); - JavaCompiler javaCompiler = null; - final MemoryFileManager javaCompilerMemoryFileManager; - - final ClassOutputter[] classOutputter = new ClassOutputter[1]; - if (config.outputMode.isJar()) { - javaCompiler = CompilerUtils.getJavaCompiler(config.preferJavac); - javaCompilerMemoryFileManager = new MemoryFileManager(javaCompiler.getStandardFileManager(diagnostics, null, null)); - classOutputter[0] = new ClassOutputter() { - @Override - public PrintWriter getClassSourceWriter(String className) throws FileNotFoundException { - String path = "file:///" + className.replace('.', '/') + ".java"; - MemoryJavaFile c = new MemoryJavaFile(path, (String)null, JavaFileObject.Kind.SOURCE); - javaCompilerMemoryFileManager.inputs.put(c.getPath().toString(), c); - return new PrintWriter(c.openWriter()); - } - }; - } else { - javaCompilerMemoryFileManager = null; - if (config.outputMode.isDirectory()) { - if (config.outputMode.isMaven()) { - String pom = config.runtime.generateMavenProjectModel(config.mavenGroupId, config.mavenArtifactId, config.mavenVersion); - PrintWriter pomOut = newFileWriter(new File(config.outputDir, POM_FILENAME)); - pomOut.println(pom); - pomOut.close(); - } - classOutputter[0] = new ClassOutputter() { - public PrintWriter getClassSourceWriter(String className) throws IOException { - File file = new File(JNAerator.this.config.sourcesOutputDir, className.replace('.', File.separatorChar) + ".java"); - File parent = file.getParentFile(); - if (!parent.exists()) - parent.mkdirs(); - - feedback.setStatus("Generating " + file.getName()); - - return newFileWriter(file); - } - }; - } - } - - Result result = createResult(new ClassOutputter() { - @Override - public PrintWriter getClassSourceWriter(String className) - throws IOException { - PrintWriter w = JNAerator.this.getClassSourceWriter(classOutputter[0], className); - return new PrintWriter(w) { - StringBuilder bout = new StringBuilder(); - @Override - public void print(String s) { - escapeUnicode(s, bout); - super.print(bout.toString()); - } - }; - } - }, feedback); - - if (config.outputMode == OutputMode.AutoGeneratedMaven) { - String[] paths = new String[] { - "src/main/java", - "src/main/resources", - "src/test/java", - "src/test/resources" - }; - for (String path : paths) - new File(config.outputDir, path).mkdirs(); - - if (config.parsedArgs != null) { - List lines = new ArrayList(); - lines.add("// Generated by JNAerator (" + JNAERATOR_URL + ")"); - for (Pair> parsedArg : config.parsedArgs) { - OptionDef opt = parsedArg.getKey(); - List switches = parsedArg.getValue(); - switch (opt) { - case OutputMode: - case OutputDir: - case ForceOverwrite: - break; - default: - lines.add(StringUtils.implode(switches, " ")); - } - } - //lines.add(OptionDef.OutputMode.format(OutputMode.AutoGeneratedMaven)); - PrintWriter out = newFileWriter(new File(config.outputDir, "src/main/jnaerator/" + DEFAULT_CONFIG_FILE)); - out.println(StringUtils.implode(lines, "\n")); - out.close(); - } - } else if (config.outputMode.generatesSources()) { - SourceFiles sourceFiles = parseSources(feedback, result.typeConverter); - if (config.extractLibSymbols) - parseLibSymbols(sourceFiles, result); - - feedback.sourcesParsed(sourceFiles); - - ScalaGenerator sgen = null; - if (config.scalaOut != null) - sgen = new ScalaGenerator(result); - - jnaerationCore(sourceFiles, result); - if (sgen != null) - sgen.jnaerationCompleted(); - - feedback.wrappersGenerated(result); - - if (javaCompiler != null) { - for (Map.Entry cnAndSrc : config.extraJavaSourceFilesContents.entrySet()) { - javaCompilerMemoryFileManager.addSourceInput(cnAndSrc.getKey(), cnAndSrc.getValue()); - } - feedback.setStatus("Compiling JNAerated files..."); - CompilerUtils.compile(javaCompiler, javaCompilerMemoryFileManager, diagnostics, "1.5", config.cacheDir, config.runtime.libraryClass, - JNAerator.class, NSClass.class, Rococoa.class, Mangling.class, - BridJ.class); - CompilerUtils.CompilationError.throwErrors(diagnostics.getDiagnostics(), javaCompilerMemoryFileManager.inputs, javaCompiler.getClass().getName()); - - if (config.outputMode == OutputMode.StandaloneJar) { - feedback.setStatus("Copying runtime classes..."); - addRuntimeClasses(result, javaCompilerMemoryFileManager); - } - } - if (config.outputMode.isJar()) { - feedback.setStatus("Generating " + config.outputJar.getName()); - javaCompilerMemoryFileManager.writeJar(config.outputJar, config.bundleSources, getResourceFiles()); - } else if (config.outputMode.isDirectory()) { - for (Map.Entry e : getResourceFiles().entrySet()) { - File inFile = e.getValue(); - File outFile = new File(config.resourcesOutputDir, e.getKey()); - outFile.getAbsoluteFile().getParentFile().mkdirs(); - - FileInputStream in = new FileInputStream(inFile); - FileOutputStream out = new FileOutputStream(outFile); - try { - IOUtils.readWrite(in, out); - } finally { - in.close(); - out.close(); - } - } - } - } -// if (true) -// throw new RuntimeException("no luck !"); - feedback.setFinished(config.outputJar != null ? config.outputJar : config.outputDir); - } catch (ExitException ex) { - throw ex; - } catch (Throwable th) { - feedback.setFinished(th); - } - } - - public void parseLibSymbols(SourceFiles sourceFiles, Result result) throws FileNotFoundException, IOException { - PrintWriter fileOut = null; - if (config.extractedSymbolsOut != null) { - if (config.verbose) - System.out.println("Writing symbols extracted from libraries to '" + config.extractedSymbolsOut + "'"); - fileOut = newFileOverwriter(config.extractedSymbolsOut); - } - - for (File libFile : config.libraryFiles) { - if (libFile.getName().toLowerCase().endsWith(".dll")) { - try { - result.feedback.setStatus("Extracting symbols from " + libFile.getName() + "..."); - - SourceFile sf = new SourceFile(); - sf.setElementFile(libFile.toString()); - List dllExports = DllExport.parseDllExports(libFile); - Map cppClasses = new HashMap(); - Pattern pubPat = Pattern.compile("(public|private|protected):(.*)"); - for (ParsedExport dllExport : dllExports) { - //dllExport.mangling - String dem = dllExport.demangled; - Matcher m = pubPat.matcher(dem); - String pub = null; - if (m.matches()) { - dem = m.group(2); - pub = m.group(1); - } - String text = "// @mangling " + dllExport.mangling + "\n" + - dem + ";"; - ObjCppParser parser = new JNAeratorParser().newObjCppParser(result.typeConverter, text, false, null);//config.verbose); - parser.setupScopes(); - Declaration decl = parser.declarationEOF(); - if (decl == null) - continue; - - //for (Declaration decl : decls) { - if (decl instanceof VariablesDeclaration && decl.getValueType() != null) - decl.getValueType().addModifiers(ModifierType.Extern); - decl.addModifiers(ModifierType.parseModifier(pub)); - if (decl instanceof Function) { - Function f = (Function)decl; - List si = new ArrayList(f.getName().resolveSimpleIdentifiers()); - Identifier ci; - if (si.size() == 1) { - String name = si.get(0) == null ? null : si.get(0).toString(); - String[] cm = name == null ? null : RegexUtils.match(name, classAndMethodNamePattern); - if (cm == null) { - sf.addDeclaration(decl); - continue; - } - ci = ident(cm[0]); - f.setName(ident(cm[1])); - } else { - si.remove(si.size() - 1); - ci = new QualifiedIdentifier(QualificationSeparator.Colons, si); - } - if (dem.contains("__thiscall")) - f.addModifiers(ModifierType.__thiscall); - if (dem.contains("__fastcall")) - f.addModifiers(ModifierType.__fastcall); - - Struct s = cppClasses.get(ci.toString()); - if (s == null) { - s = new Struct(); - cppClasses.put(ci.toString(), s); - s.setType(Struct.Type.CPPClass); - s.setTag(ci.clone()); - sf.addDeclaration(decl(s)); - } - Identifier n = f.getName().resolveLastSimpleIdentifier(); -// String ns = n.toString(); -// if (ns.startsWith("_")) -// n = ident(ns.substring(1)); - f.setName(n); - s.addDeclaration(f); - } else - sf.addDeclaration(decl); - //} - } - if (!sf.getDeclarations().isEmpty()) { - sourceFiles.add(sf); - if (fileOut != null) - fileOut.println(sf); - } - - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - } - if (fileOut != null) - fileOut.close(); - } - private Map getResourceFiles() { - - Map additionalFiles = new HashMap(); - - if (config.bundleLibraries) { - for (Map.Entry> e : config.libraryFilesByArch.entrySet()) { - NativePlatform arch = e.getKey(); - for (File libraryFile : e.getValue()) - additionalFiles.put( - "lib/" + arch.name() + "/" + libraryFile.getName(), - libraryFile - ); - } -// for (String library : new HashSet(config.libraryByFile.values())) { -// String libraryFileName = System.mapLibraryName(library); -// File libraryFile = new File(libraryFileName); -// //TODO lookup in library path -// if (!libraryFile.exists() && libraryFileName.endsWith(".jnilib")) -// libraryFile = new File(libraryFileName = libraryFileName.substring(0, libraryFileName.length() - ".jnilib".length()) + ".dylib"); -// -// String key = "libraries/" + LibraryExtractor.getCurrentOSAndArchString() + "/" + libraryFile.getName(); -// if (additionalFiles.containsKey(key)) -// continue; -// -// if (libraryFile.exists()) { -// System.out.println("Bundling " + libraryFile); -// additionalFiles.put(key, libraryFile); -// }// else { -// //System.out.println("File " + libraryFileName + " not found"); -// //} -// } - } - return additionalFiles; - } - protected static Map getRuntimeFiles(JNAeratorConfig.Runtime runtime, boolean needsObjCRuntime) throws IOException { - ClassLoader classLoader = JNAerator.class.getClassLoader(); - Map ret = new HashMap(); - - String listingFile = runtime.runtimeFilesListFileName; - if (listingFile == null) - return ret; - - List files = new ArrayList(); - for (String s : listingFile.split(",")) - files.addAll(ReadText.readLines(classLoader.getResourceAsStream(s.trim()))); - - if (files == null) { - throw new FileNotFoundException("Warning: Could not find JNAerator listing file '" + listingFile + "' : JNAerated files will need JNAerator in the path to execute."); - } - - for (String file : files) { - if (file.startsWith("Archive: ")) - continue; - - if (file.startsWith("META-INF/")) - continue; - - if (!needsObjCRuntime) { - if (file.contains("rococoa")) - continue; - } - - URL url = classLoader.getResource(file); - if (url == null) { - if (file.matches("com/sun/jna/[^/]+/(lib\\w+\\.(jnilib|so)|\\w+\\.dll)")) { - System.out.println("JNA library missing : " + file); - continue; - } - if (file.matches("com/ochafik/lang/jnaerator/runtime/scala/.*\\.part")) { - System.out.println("Scala code missing : " + file); - continue; - } - if (file.toLowerCase().contains("android")) - continue; - - throw new FileNotFoundException(file); - } - ret.put(file, url); - } - return ret; - } - protected void addRuntimeClasses(Result result, MemoryFileManager mfm) throws IOException { - - Map files = getRuntimeFiles(result.config.runtime, result.hasObjectiveC()); - - boolean needsObjCRuntime = result.hasObjectiveC(); - for (Map.Entry e : files.entrySet()) { - String file = e.getKey(); - URL url = e.getValue(); - - file = "file:///" + file; - if (!mfm.outputs.containsKey(file)) { - mfm.outputs.put(file, new URLFileObject(url)); - } - } - } - public static File getDir(String name) { - File dir = new File(getDir(), name); - dir.mkdirs(); - return dir; - } - public static File getDir() { - File dir = new File(System.getProperty("user.home")); - dir = new File(dir, ".jnaerator"); - dir = new File(dir, "temp"); - dir.mkdirs(); - return dir; - } - static boolean isHexDigit(char c) { - return - c >= 'A' && c <= 'F' || - c >= 'a' && c <= 'f' || - Character.isDigit(c); - } - static void escapeUnicode(String s, StringBuilder bout) { - if (s == null) - return; - bout.setLength(0); - char[] chars = s.toCharArray(); - for (int iChar = 0, nChars = chars.length; iChar < nChars; iChar++) { - char c = chars[iChar]; - int v = (int)c; - if (v > 127) { - bout.append("\\u"); - String h = Integer.toHexString(v); - for (int i = 4 - h.length(); i-- != 0;) - bout.append('0'); - bout.append(h); - } else { - // handle \\uXXXX -> \\uuXXXX transformation : -// if (c == '\\' && -// iChar < nChars - 5 && -// chars[iChar + 1] == 'u' && -// isHexDigit(chars[iChar + 2]) && -// isHexDigit(chars[iChar + 3]) && -// isHexDigit(chars[iChar + 4]) && -// isHexDigit(chars[iChar + 5]) -// ) { -// bout.append("\\u"); -// } - bout.append(c); - } - } - } - - public SourceFiles parseSources(Feedback feedback, TypeConversion typeConverter) throws IOException, LexerException { - feedback.setStatus("Parsing native headers..."); - return createJNAeratorParser().parse(config, typeConverter, null); - } - protected JNAeratorParser createJNAeratorParser() { - return new JNAeratorParser(); - } - - - public void addFile(File file, List out) throws IOException { - if (file.isFile()) { - out.add(file); - } else { - File[] fs = file.listFiles(); - if (fs != null) { - for (File f : fs) { - addFile(f, out); - } - } - } - } - class LibraryMapping { - public Struct interf; - } - class JNALibraryMapping extends LibraryMapping { - - } - protected void generateLibraryFiles(SourceFiles sourceFiles, Result result) throws IOException { - switch (result.config.runtime) { - case JNA: - case JNAerator: -// case JNAeratorNL4JStructs: - generateJNALibraryFiles(sourceFiles, result); - break; - case BridJ: - generateNL4JLibraryFiles(sourceFiles, result); - break; - default: - throw new UnsupportedOperationException("Unexpected runtime : " + result.config.runtime); - - } - } - protected void generateNL4JLibraryFiles(SourceFiles sourceFiles, Result result) throws IOException { - for (String library : result.libraries) { - if (library == null) - continue; // to handle code defined in macro-expanded expressions -// library = ""; - - Identifier javaPackage = result.javaPackageByLibrary.get(library); - Identifier simpleLibraryClassName = result.getLibraryClassSimpleName(library); - - Identifier fullLibraryClassName = result.getLibraryClassFullName(library);//ident(javaPackage, libraryClassName); - //if (!result.objCClasses.isEmpty()) - // out.println("import org.rococoa.ID;"); - - - Struct interf = new Struct(); - interf.setType(Type.JavaClass); - interf.addToCommentBefore("Wrapper for library " + library + "", - result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null) - ); - interf.addModifiers(ModifierType.Public); - interf.setTag(simpleLibraryClassName); - interf.addParent(ident(config.runtime.libraryClass, expr(typeRef(simpleLibraryClassName)))); - interf.addDeclaration(new Function(Function.Type.StaticInit, null, null).setBody(block( - stat(methodCall( - expr(typeRef(BridJ.class)), - MemberRefStyle.Dot, - "register" - )) - )).addModifiers(ModifierType.Static)); - -// String libFileOrDirArgName = "libraryFileOrDirectory"; -// Function constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null, new Arg(libFileOrDirArgName, typeRef(File.class))); -// constr.addModifiers(ModifierType.Public); -// constr.setBody(block(stat(methodCall("super", varRef(libFileOrDirArgName))))); -// interf.addDeclaration(constr); -// -// constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null); -// constr.addModifiers(ModifierType.Public); -// constr.addThrown(typeRef(FileNotFoundException.class)); -// constr.setBody(block(stat(methodCall("super", classLiteral(typeRef(fullLibraryClassName.clone())))))); -// interf.addDeclaration(constr); - - fillLibraryMapping(result, sourceFiles, interf, library, javaPackage, fullLibraryClassName, varRef("this")); - } - } - protected void generateJNALibraryFiles(SourceFiles sourceFiles, Result result) throws IOException { - - Struct librariesHub = null; - PrintWriter hubOut = null; - if (result.config.entryName != null) { - librariesHub = new Struct(); - librariesHub.addToCommentBefore("JNA Wrappers instances"); - librariesHub.setType(Type.JavaClass); - librariesHub.addModifiers(ModifierType.Public, ModifierType.Abstract); - Identifier hubName = result.getHubFullClassName(); - librariesHub.setTag(hubName.resolveLastSimpleIdentifier()); - hubOut = result.classOutputter.getClassSourceWriter(hubName.toString()); - hubOut.println("package " + hubName.resolveAllButLastIdentifier() + ";"); - for (Identifier pn : result.javaPackages) - if (!pn.equals("")) - hubOut.println("import " + pn + ".*;"); - } - for (String library : result.libraries) { - if (library == null) - continue; // to handle code defined in macro-expanded expressions -// library = ""; - - Identifier javaPackage = result.javaPackageByLibrary.get(library); - Identifier simpleLibraryClassName = result.getLibraryClassSimpleName(library); - - Identifier fullLibraryClassName = result.getLibraryClassFullName(library);//ident(javaPackage, libraryClassName); - //if (!result.objCClasses.isEmpty()) - // out.println("import org.rococoa.ID;"); - - - Struct interf = new Struct(); - interf.addToCommentBefore("JNA Wrapper for library " + library + "", - result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null) - ); - if (hubOut != null) - interf.addToCommentBefore("@see " + result.config.entryName + "." + library); - - interf.addModifiers(ModifierType.Public); - interf.setTag(simpleLibraryClassName); - - Expression nativeLibFieldExpr = null; - if (!result.config.skipLibraryInstanceDeclarations) { - Expression libNameExpr = opaqueExpr(result.getLibraryFileExpression(library)); - TypeRef libTypeRef = typeRef(fullLibraryClassName); - Expression libClassLiteral = result.typeConverter.typeLiteral(libTypeRef); - - boolean isJNAerator = result.config.runtime == JNAeratorConfig.Runtime.JNAerator; - - Expression libraryPathGetterExpr; - if (isJNAerator) - libraryPathGetterExpr = methodCall( - expr(typeRef(LibraryExtractor.class)), - MemberRefStyle.Dot, - "getLibraryPath", - libNameExpr, - expr(true), - libClassLiteral - ); - else - libraryPathGetterExpr = libNameExpr; - - String libNameStringFieldName = "JNA_LIBRARY_NAME", nativeLibFieldName = "JNA_NATIVE_LIB"; - interf.addDeclaration(new VariablesDeclaration(typeRef(String.class), new Declarator.DirectDeclarator( - libNameStringFieldName, - libraryPathGetterExpr - )).addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final)); - - Expression libraryNameFieldExpr = memberRef(expr(libTypeRef.clone()), MemberRefStyle.Dot, ident(libNameStringFieldName)); - Expression optionsMapExpr = memberRef(expr(typeRef(MangledFunctionMapper.class)), MemberRefStyle.Dot, "DEFAULT_OPTIONS"); - Expression[] getInstArgs = isJNAerator ? - new Expression[] { libraryNameFieldExpr.clone(), optionsMapExpr.clone() } : - new Expression[] { libraryNameFieldExpr.clone() } - ; - interf.addDeclaration(new VariablesDeclaration(typeRef(NativeLibrary.class), new Declarator.DirectDeclarator( - nativeLibFieldName, - methodCall( - expr(typeRef(NativeLibrary.class)), - MemberRefStyle.Dot, - "getInstance", - getInstArgs - ) - )).addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final)); - nativeLibFieldExpr = memberRef(expr(libTypeRef.clone()), MemberRefStyle.Dot, ident(nativeLibFieldName)); - - if (result.config.useJNADirectCalls) { - interf.addDeclaration(new Function(Function.Type.StaticInit, null, null).setBody(block( - stat(methodCall( - expr(typeRef(Native.class)), - MemberRefStyle.Dot, - "register", - libraryNameFieldExpr.clone() - )) - )).addModifiers(ModifierType.Static)); - } else { - Expression[] loadLibArgs = isJNAerator ? - new Expression[] { libraryNameFieldExpr.clone(), libClassLiteral, optionsMapExpr.clone() } : - new Expression[] { libraryNameFieldExpr.clone(), libClassLiteral } - ; - VariablesDeclaration instanceDecl = new VariablesDeclaration(libTypeRef, new Declarator.DirectDeclarator( - librariesHub == null ? "INSTANCE" : library, - cast( - libTypeRef, - methodCall( - expr(typeRef(Native.class)), - MemberRefStyle.Dot, - "loadLibrary", - loadLibArgs - ) - ) - )).addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Final); - if (librariesHub != null) { - librariesHub.addDeclaration(instanceDecl); - librariesHub.addProtocol(fullLibraryClassName.clone()); - } else - interf.addDeclaration(instanceDecl); - } - } - - boolean stdcall = false; - List functions = result.functionsByLibrary.get(library); - if (functions != null) - for (Function function : functions) - if (function.hasModifier(ModifierType.__stdcall)) { - stdcall = true; - break; - } - - Identifier libSuperInter = ident(stdcall ? StdCallLibrary.class : config.runtime.libraryClass); - - if (result.config.useJNADirectCalls) { - interf.addProtocol(libSuperInter); - interf.setType(Type.JavaClass); - } else { - interf.addParent(libSuperInter); - interf.setType(Type.JavaInterface); - } - - fillLibraryMapping(result, sourceFiles, interf, library, javaPackage, fullLibraryClassName, nativeLibFieldExpr); - } - if (hubOut != null) { - hubOut.println(librariesHub.toString()); - hubOut.close(); - } - } - - protected void fillLibraryMapping(Result result, SourceFiles sourceFiles, Struct interf, String library, Identifier javaPackage, Identifier fullLibraryClassName, Expression nativeLibFieldExpr) throws IOException { - - Signatures signatures = result.getSignaturesForOutputClass(fullLibraryClassName); - result.typeConverter.allowFakePointers = true; - result.declarationsConverter.convertEnums(result.enumsByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertConstants(library, result.definesByLibrary.get(library), sourceFiles, signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertStructs(result.structsByLibrary.get(library), signatures, interf, fullLibraryClassName, library); - result.declarationsConverter.convertCallbacks(result.callbacksByLibrary.get(library), signatures, interf, fullLibraryClassName); - result.declarationsConverter.convertFunctions(result.functionsByLibrary.get(library), signatures, interf, fullLibraryClassName); - - if (result.globalsGenerator != null) - result.globalsGenerator.convertGlobals(result.globalsByLibrary.get(library), signatures, interf, nativeLibFieldExpr, fullLibraryClassName, library); - - result.typeConverter.allowFakePointers = false; - - Set fakePointers = result.fakePointersByLibrary.get(fullLibraryClassName); - if (fakePointers != null) - for (String fakePointerName : fakePointers) { - if (fakePointerName.contains("::")) - continue; - - Identifier fakePointer = ident(fakePointerName); - if (!signatures.addClass(fakePointer)) - continue; - - Struct ptClass = result.declarationsConverter.createFakePointerClass(fakePointer); - if (result.config.noComments) - ptClass.addToCommentBefore("Pointer to unknown (opaque) type"); - - interf.addDeclaration(decl(ptClass)); - - if (result.config.reification) - result.reifier.reifyFakePointer(ptClass, fullLibraryClassName, fakePointerName, signatures); - - } - - Set undefinedTypes = result.undefinedTypesByLibrary.get(fullLibraryClassName); - if (undefinedTypes != null) - for (String undefinedTypeName : undefinedTypes) { - if (undefinedTypeName.contains("::")) - continue; - - Identifier fakePointer = ident(undefinedTypeName); - if (!signatures.addClass(fakePointer)) - continue; - - Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, null, Struct.Type.JavaInterface, null); - ptClass.addToCommentBefore("Undefined type"); - interf.addDeclaration(decl(ptClass)); - } - - if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { - interf.addAnnotation(new Annotation(org.bridj.ann.Library.class, expr(library))); - interf.addAnnotation(new Annotation(org.bridj.ann.Runtime.class, classLiteral(result.hasCPlusPlus ? CPPRuntime.class : CRuntime.class))); - } - - interf = result.notifyBeforeWritingClass(fullLibraryClassName, interf, signatures, library); - if (interf != null) { - final PrintWriter out = result.classOutputter.getClassSourceWriter(fullLibraryClassName.toString()); - - //out.println("///\n/// This file was autogenerated by JNAerator (http://jnaerator.googlecode.com/), \n/// a tool written by Olivier Chafik (http://ochafik.com/).\n///"); - result.printJavaClass(javaPackage, interf, out); - out.close(); - } - } - //Pattern rxObj1 = Pattern.compile("(\\w+)_([\\w_]+)_.*"); - /// To be overridden - public Result createResult(final ClassOutputter outputter, Feedback feedback) { - return new Result(config, outputter, feedback); - } - - public static ObjCppParser newParser(String s) throws IOException { - Result result = new Result(new JNAeratorConfig(), null, null); - ObjCppParser parser = new ObjCppParser(new CommonTokenStream(new ObjCppLexer( - new ANTLRReaderStream(new StringReader(s)))) - // , new DummyDebugEventListener() - ); - parser.objCParserHelper = result.typeConverter; - return parser; - } - protected void readChoices(Result result) throws IOException, RecognitionException { - BufferedReader in = new BufferedReader(new FileReader(result.config.choicesInputFile)); - String line; - - List functions = null; - - int iLine = 0; - while ((line = in.readLine()) != null) { - iLine++; - line = line.trim(); - if (line.startsWith("//")) - continue; - if (line.length() == 0) - functions = null; - - - - Function function = null; - if (functions == null) { - function = newParser(line).javaMethodDeclaration(); - } else { - function = newParser(line).functionDeclaration().function; - } - if (function == null) { - System.err.println("Error: failed to parse function at line " + iLine + ": '" + line + "'"); - continue; - } - if (functions == null) - result.declarationsConverter.functionAlternativesByNativeSignature.put( - function.computeSignature(SignatureType.JavaStyle), - new Pair>( - function, - functions = new ArrayList() - ) - ); - else - functions.add(function); - } - - System.err.println("Read " + result.declarationsConverter.functionAlternativesByNativeSignature.size() + " custom declarations from " + result.config.choicesInputFile); - } - - public void jnaerationCore(SourceFiles sourceFiles, Result result) throws IOException, LexerException, RecognitionException { - result.feedback.setStatus("Normalizing parsed code..."); - - if (result.config.choicesInputFile != null) - readChoices(result); - - if (config.rawParsedSourcesOutFile != null) { - if (config.verbose) - System.out.println("Writing raw parsed sources to '" + config.rawParsedSourcesOutFile + "'"); - WriteText.writeText(sourceFiles.toString(), config.rawParsedSourcesOutFile); - } - - /// Perform Objective-C-specific pre-transformation (javadoc conversion for enums + find name of enums based on next sibling integer typedefs) - sourceFiles.accept(new ObjectiveCToJavaPreScanner(result)); - - /// Explode declarations to have only one direct declarator each - sourceFiles.accept(new CToJavaPreScanner()); - - /// Give sensible names to anonymous function signatures, structs, enums, unions, and move them up one level as typedefs - sourceFiles.accept(new MissingNamesChooser(result)); - - /// Move storage modifiers up to the storage - sourceFiles.accept(new Scanner() { - @Override - protected void visitTypeRef(TypeRef tr) { - super.visitTypeRef(tr); - Element parent = tr.getParentElement(); - if (parent instanceof TypeRef) {// || parent instanceof VariablesDeclaration) { - List stoMods = getStoMods(tr.getModifiers()); - if (stoMods != null) { - List newMods = new ArrayList(tr.getModifiers()); - newMods.removeAll(stoMods); - tr.setModifiers(newMods); - ((ModifiableElement)parent).addModifiers(stoMods); - } - } - } - public List getStoMods(List mods) { - List ret = null; - for (Modifier mod : mods) { - if (mod.isA(ModifierKind.StorageClassSpecifier)) { - if (ret == null) - ret = new ArrayList(); - ret.add(mod); - } - } - return ret; - } - }); - - /// Build JavaDoc comments where applicable - sourceFiles.accept(new JavaDocCreator(result)); - - assert checkNoCycles(sourceFiles); - - if (config.normalizedParsedSourcesOutFile != null) { - if (config.verbose) - System.out.println("Writing normalized parsed sources to '" + config.normalizedParsedSourcesOutFile + "'"); - WriteText.writeText(sourceFiles.toString(), config.normalizedParsedSourcesOutFile); - } - - //################################################################## - //##### BEGINNING HERE, sourceFiles NO LONGER GETS MODIFIED ! ###### - //################################################################## - - if (!result.config.bridgeSupportFiles.isEmpty()) { - if (result.feedback != null) - result.feedback.setStatus("Parsing BridgeSupport files..."); - - new BridgeSupportParser(result, sourceFiles).parseBridgeSupportFiles(); - } - - /// Gather Objective-C classes - sourceFiles.accept(result); - result.rehabilitateWeakTypeDefs(); - - result.chooseLibraryClasses(config.packageName, config.rootPackageName); - - //TODO resolve variables in visual studio projects - //TODO Propagate unconvertible expressions, mark corresponding elements / trees as "to be commented out" - - /// Resolution's first pass : define relevant chained environment for each element -// final DefinitionsVisitor definitions = new DefinitionsVisitor(); -// sourceFiles.accept(definitions); - - /// Resolve references of variables and types (map id -> type) -// ResolutionScanner resolutions = new ResolutionScanner(definitions, originalOut); -// sourceFiles.accept(resolutions); - - - /// Filter unused symbols from implicitely included files -// if (config.symbolsAccepter != null) { -// originalOut.println("Filtering unused symbols"); -// UnusedScanner unused = new UnusedScanner(resolutions, config.symbolsAccepter, null);//originalOut); -// sourceFiles.accept(unused); -// unused.removeUnused(null); -// } - - - /// Spit Objective-C classes out - if (!result.classes.isEmpty() && result.objectiveCGenerator != null) { - result.feedback.setStatus("Generating Objective-C classes..."); - result.objectiveCGenerator.generateObjectiveCClasses(); - } - - result.feedback.setStatus("Generating libraries..."); - - if (result.libraries.size() == 1) { - List list = result.definesByLibrary.get(null); - if (list != null) { - String lib = result.libraries.iterator().next(); - Result.getList(result.definesByLibrary, lib).addAll(list); - } - } - - result.symbols = Symbols.resolveSymbols(sourceFiles); - generateLibraryFiles(sourceFiles, result); - - if (config.verbose) - for (String unknownType : result.typeConverter.unknownTypes) - System.out.println("Unknown Type: " + unknownType); - - if (result.config.choicesOutFile != null) { - PrintWriter out = newFileOverwriter(result.config.choicesOutFile); - for (Map.Entry>> e : result.declarationsConverter.functionAlternativesByNativeSignature.entrySet()) { - Function f = e.getValue().getKey(); - String ff = f.getElementFile(); - if (ff != null) - out.println("// " + ff + (f.getElementLine() > 0 ? ":" + f.getElementLine() : "")); - - out.println(f); - for (Function alt : e.getValue().getValue()) { - out.println(alt); - } - out.println(); - } - out.close(); - } - } - private boolean checkNoCycles(SourceFiles sourceFiles) { - final HashSet ids = new HashSet(new Arg().getId()); - sourceFiles.accept(new Scanner() { - @Override - protected void visitElement(Element d) { - if (d != null && !ids.add(d.getId())) - throw new RuntimeException("Cycle : " + d); - super.visitElement(d); - } - }); - return true; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorCommandLineArgs.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorCommandLineArgs.java deleted file mode 100644 index e9db96cff..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorCommandLineArgs.java +++ /dev/null @@ -1,470 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.JNAeratorConfig.OutputMode; -import com.ochafik.lang.jnaerator.JNAeratorConfig.Runtime; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import static org.bridj.Platform.*; - -public class JNAeratorCommandLineArgs { - public static abstract class ArgsParser { - Map> paths = new HashMap>(); - - public List getPath(PathType type) { - if (type == null) - return null; - List path = paths.get(type); - if (path == null) - paths.put(type, path = new ArrayList()); - return path; - } - public static class ParsedArg { - public OptionDef def; - public Object[] params; - - public File getFileParam(String name) { - return (File)params[def.getParam(name).position]; - } - public String getStringParam(String name) { - return (String)params[def.getParam(name).position]; - } - public int getIntParam(String name) { - return (Integer)params[def.getParam(name).position]; - } - public File getFileParam(int pos) { - return (File)params[pos]; - } - public String getStringParam(int pos) { - return (String)params[pos]; - } - public MessageFormat getMessageFormatParam(int pos) { - return (MessageFormat)params[pos]; - } - public int getIntParam(int pos) { - return (Integer)params[pos]; - } - - public > E getEnumParam(int pos, Class ec) { - return ec.cast(params[pos]); - } - } - - List>> parsedArgs = new ArrayList>>(); - - public void parse(List args) throws Exception { - try { - for (int i = 0; i < args.size(); i++) { - String arg = args.get(i); - OptionDef defaultOpt = null; - for (OptionDef opt : OptionDef.values()) { - if (opt.switchPattern == null) { - defaultOpt = opt; - continue; - } - - Matcher m; - boolean matches; - try { - m = opt.switchPattern.matcher(arg); - matches = m.matches(); - } catch (Throwable ex) { - throw new JNAerator.CommandLineException("Error while matching arg " + arg + " with option " + opt + " (pattern = " + opt.switchPattern + ") : " + ex, ex); - } - if (matches) { - if (opt.isDeprecated()) - System.err.println("WARNING: option " + opt.clSwitch + " is deprecated and might be removed in future versions."); - ParsedArg pa = new ParsedArg(); - pa.def = opt; - pa.params = new Object[opt.args.length]; - int iArg = 0; - for (int iGroup = 0; iGroup < m.groupCount(); iGroup++) { - String gp = m.group(iGroup + 1); - if (gp == null) - continue; - pa.params[iArg] = opt.args[iArg].convertArg(gp, this); - iArg++; - } - List parsedArg = new ArrayList(); - parsedArg.add(arg); - for (; iArg < opt.args.length; iArg++) { - String param = args.get(++i); - OptionDef.ArgDef argDef = opt.args[iArg]; - pa.params[iArg] = argDef.convertArg(param, this); - parsedArg.add(argDef.normalize(param)); - } - - //int iParsedArg = parsedArgs.size(); - parsedArgs.add(Pair.create(opt, parsedArg)); - List parsed = parsed(pa); - if (parsed == null) { - return; - } - args.addAll(i + 1, parsed); - defaultOpt = null; - break; - } - - } - - if (defaultOpt != null) { - ParsedArg pa = new ParsedArg(); - pa.def = defaultOpt; - OptionDef.ArgDef argDef = defaultOpt.args[0]; - arg = argDef.normalize(arg); - pa.params = new Object[] { argDef.convertArg(arg, this) }; - //parsedArgs.add(Pair.create(defaultOpt, Arrays.asList(arg))); - args.addAll(i + 1, parsed(pa)); - } - - } - } catch (JNAerator.ExitException ex) { - throw ex; - } catch (Throwable ex) { - JNAeratorCommandLineArgs.displayHelp(false); - throw new JNAerator.CommandLineException("Error parsing arguments :\n" + StringUtils.implode(args, " ") + " : " + ex, ex); - } - finished(); - } - - /// Returns a list that must be inserted in place of this argument - abstract List parsed(ParsedArg a) throws Exception; - abstract void finished() throws IOException; - } - - public enum PathType { - SourcePath, - LibraryPath - } - public enum OptionDef { - OutputMode( "-mode", "Choose the output mode of JNAerator", new ArgDef(Type.Enum, "mode", OutputMode.class)), - IncludeArgs( "@(.+)?", "Read command-line arguments from a file. File may contain multiple lines (those beginning with \"//\" will be skipped), file wildcards will be resolved within the file content, as well as variables substitutions : $(someEnvOrJavaVarName), with $(DIR) being the parent directory of the current arguments file.", new ArgDef(Type.ExistingFile, "argumentsFile.jnaerator")), - OutputDir( "-o", "Output directory for all artifacts", new ArgDef(Type.OutputDir, "outDir")), - ExtractSymbols( "-scanSymbols", "Extract, unmangle and parse the symbols all listed shared libraries"), - AddIncludePath( "-I(.+)?", "Add a directory to the include path or include a file. See doc of JNAERATOR_INCLUDE_PATH", new ArgDef(Type.File, "dir")), - AddFrameworksPath( "-F(.+)?", "Add a directory to the frameworks path. See doc of JNAERATOR_FRAMEWORKS_PATH", new ArgDef(Type.File, "dir")), - FrameworksPath( "-frameworksPath", "See doc of JNAERATOR_FRAMEWORKS_PATH", new ArgDef(Type.String, "path1:path2...")), - Framework( "-framework", "JNAerate a framework using its headers and its *.bridgesupport files if available", new ArgDef(Type.String, "frameworkName")), - LimitComments( "-limitComments", "Avoid useless comments (source file + line, skipped items...)"), - NoComments( "-noComments", "Don't output any member comment."), - NoMangling( "-noMangling", "Don't output any C++ name mangling information (may cause C++-decorated symbols not to be found at execution time)."), - AddRootDir( "-addRootDir", "Remove this directory from the path of descendant source files in the generated documentation.", new ArgDef(Type.ExistingDir, "dir")), - NoCPP( "-nocpp", "Do not define the __cplusplus symbol"), - Reification( "-reification", "Automatically create OO shortcuts for functions that look like methods (typedPtr.someFunc() for someFunc(typedPtr))"), - Undefine( "-U(.+)", "Undefine a preprocessor symbol after the autoconfiguration phase.", new ArgDef(Type.String, "symbolName")), - GUI( "-gui", "Show minimalist progression GUI"), - //NoRuntime( "-noRuntime", "Don't copy runtime classes to JAR output"), - Synchronized( "-synchronized", "Generate synchronized native methods"), - GenRawBindings( "-genRawBindings", "Generate raw bindings amenable for assembler optimizations."), - BeanStructs( "-beanStructs", "Generate getters and setters for struct fields (JNA & JNAerator runtimes only)"), - BeautifyNames( "-beautifyNames", "Transform C names to Java-looking names : some_func() => someFunc()"), - ConvertBodies( "-convertBodies", "Experimental conversion of function bodies to equivalent Java code (BridJ only)."), - JarOut( "-jar", "Jar file where all generated sources and the compiled classes go", new ArgDef(Type.OutputFile, "outFile")), - ScalaStructSetters( "-scalaStructSetters", "Generate Scala-style setters for BridJ structs (with a name like fieldName_$eq)"), - WCharAsShort( "-wcharAsShort", "Force treatment of wchar_t as short (char by default)"), - CallbackInvokeName( "-callbacksInvokeMethodName", "Name of the invocation method of callbacks ('apply' by default)", new ArgDef(Type.String, "methodName")), - LibraryNamingPrefixes("-libraryNamingPrefixes", "Define prefixes commonly used in the library so that reification of functions is optimal (See -reification)", new ArgDef(Type.String, "commaSeparatedPrefixes")), - //Test( "-test", "Launch JNAerator's unit tests (DEBUG option)"), - Studio( "-studio", "Launch JNAeratorStudio"), - ScalaOut( "-scalaOut", "[Experimental] Output Scala wrappers (callbacks implicits...)", new ArgDef(Type.OutputDir, "outDir")), - NoStringReturns( "-noStringReturns", "Prevent const char* and const wchar_t* return types from being converted to String and WString."), - Project( "-project", "Read Visual Studio 2008 project or solution file and use the configuration specified (e.g. \"Release|Win32\").", new ArgDef(Type.ExistingFile, "solutionFile"), new ArgDef(Type.String, "\"Config|Platform\"")), - NoAuto( "-noAuto", "No auto-configuration of preprocessor symbols and paths"), - COM( "-com", "Generate Microsoft COM (C++) bindings."), - GCCLong( "-gccLong", "Use GCC convention for size of 'long' (4 bytes on 32 bits platforms, 8 bytes on 64 bits platforms)."), - SizeAsLong( "-sizeAsLong", "Treat size_t and ptrdiff_t values as 'long' values. ONLY HERE FOR COMPATIBILITY WITH PREVIOUS VERSIONS, WILL EVENTUALLY BE REMOVED."), - Direct( "-direct", "JNAerate libraries that use JNA's faster direct call convention"), - PreferJavac( "-preferJavac", "Use Sun's Javac compiler instead of Eclipse's ecj, if possible"), - StructsInLibrary( "-structsInLibrary", "Force structs to be JNAerated as inner classes of their declaring libraries (otherwise, each top-level structure is defined as a top-level class in its library's package)"), - ParseInChunks( "-parseChunks", "Splits the pre-processor output into multiple smaller parts and parse them separately (in theory everything should be parsed in one chunk, but in practice this means errors are not isolated from the rest of the parsing)"), - OnlineDocURLFormat( "-onlineDoc", "Define a format for online documentation URLs (uses MessageFormat syntax, with arg 0 being the name of the function / structure).", new ArgDef(Type.MessageFormat, "linkDisplayFormat"), new ArgDef(Type.MessageFormat, "urlMessageFormat")), - CurrentPackage( "-package", "Set the Java package in which all the output will reside (by default, set to the library name).", new ArgDef(Type.String, "forcedPackageName")), - RecursedExtensions( "-allowedFileExts", "Colon-separated list of file extensions used to restrict files used when recursing on directories, or \"*\" to parse all files (by default = " + JNAeratorConfig.DEFAULT_HEADER_EXTENSIONS + ")", new ArgDef(Type.String, "extensions")), - SkipIncludedFrameworks( "-skipIncludedFrameworks", "Skip Included Frameworks"), - SkipLibInstance( "-skipLibraryInstance", "Skip library instance declarations"), - DontCastConstants( "-dontCastConstants", "Don't cast generated constants"), - Runtime( "-runtime", "Choose target runtime library between " + StringUtils.implode(JNAeratorConfig.Runtime.values(), ", ") + " (default: " + JNAeratorConfig.Runtime.DEFAULT + ").", new ArgDef(Type.Enum, "enum", JNAeratorConfig.Runtime.class)), - IfRegexMatch( "-ifRegexMatch", "Conditional evaluation of an argument if a java system property matches a regular expression", new ArgDef(Type.String, "javaProperty"), new ArgDef(Type.String, "regex"), new ArgDef(Type.String, "thenArg"), new ArgDef(Type.String, "elseArg")), - DefineMacro( "-D([^=]*)(?:=(.*))?", "Define a macro symbol", new ArgDef(Type.String, "name"), new ArgDef(Type.String, "value")), - NoAutoImports( "-noAutoImport", "Don't add import statements automatically to output java source files"), - RootPackage( "-root(?:Package)?", "Define the root package for all output classes", new ArgDef(Type.String, "package")), - CurrentLibrary( "-library", "Define the name of the output library. This is a state parameter, it will affect all files listed after it, until another -library switch is provided. It does not affect sources included from a project file (Visual Studio...).\n" + - "C functions exported in library \"test\" will end up in class \"TestLibrary\", for instance. \n" + - "The name of the library is the one fed to JNA to find the shared library, so library \"test\" must be in \"test.dll\" on Windows, \"libtest.dylib\" on Mac OS X and \"libtest.so\" on other Unices.\n" + - "Note that a special hack is done for library \"c\" on Windows systems : the output name is set to \"msvcrt\" instead of \"c\".\n", - new ArgDef(Type.String, "libName")), - DefaultLibrary( "-defaultLibrary", "Name of output library for elements declared in files not covered by a ${CurrentLibrary} switch", new ArgDef(Type.String, "libName")), - Help( "-?-h(?:elp)?", "Show command line arguments help"), - EntryName( "-entryClass", "Generate a class _entryclassName.EntryClassName_ that will contain all of the jnaerated libraries instances. User code will just need to static import or derive from this class to access to the instances.", new ArgDef(Type.String, "entryClassName")), -// Undefine( "-U(.*)?", "Undefine a preprocessor symbol before ", new ArgDef(Type.String, "entryClassName")), - Verbose( "-v(?:erbose)?", "Verbose output (both console and files)"), - ChoicesOut( "-choicesOut", "Write the function alternative choices made (automatically set when ${Verbose} is used).", new ArgDef(Type.OutputFile, "outFile")), - ChoicesIn( "-choices", "Read the function alternative choices from a file in the format used by -choicesOut.", new ArgDef(Type.ExistingFile, "choicesFile")), - PreprocessingOut( "-preprocessingOut", "Write the preprocessor output in a file (automatically set when ${Verbose} is used).", new ArgDef(Type.OutputFile, "outFile")), - EmptyStructsAsForwardDecls( - "-emptyStructsAsForwardDecls", "Treat empty structs as forward declarations"), - ExtractionOut( "-extractionOut", "Write the symbols extracted from libraries in a file (automatically set when ${Verbose} is used).", new ArgDef(Type.OutputFile, "outFile")), - BridgeSupportOutFile("-bridgeSupportOut", "Write the definitions extracted from bridgesupport files in a file (automatically set when ${Verbose} is used).", new ArgDef(Type.OutputFile, "outFile")), - WikiDoc( "-wikiHelp", "Output a wiki-friendly help"), - Arch( "-arch", "Define the current architecture for libraries (state variable)", new ArgDef(Type.Enum, "archName", NativePlatform.class)), - MacrosOut( "-macrosOut", "Write the preprocessor macros in a file (automatically set when ${Verbose} is used).", new ArgDef(Type.OutputFile, "outFile")), - NoPrimitiveArrays( "-noPrimitiveArrays", "Never output primitive arrays for function arguments (use NIO buffers instead)"), - File( null, "Any header (or directory containing headers at any level of hierarchy), shared library, *.bridgesupport file or *.jnaerator file", new ArgDef(Type.OptionalFile, "file", PathType.SourcePath)), - NoPreprocessing( "-fpreprocessed", "Consider source files as being already preprocessed (preprocessor won't be run)"), - @Deprecated - NoCompile( "(?i)-noComp", "Do not compile JNAerated headers"), - @Deprecated - NoJAR( "(?i)-noJar", "Do not create an output JAR"), -// EnableCPlusPlus( "-cppInstanceMethods", "Enable experimental C++ instance methods wrapping"), - NoLibBundle( "(?i)-noLibBundle", "Do not bundle libraries in output JAR"), - LibFile( "-libFile", "Bundle the provided file with the JNAerated JAR so that it is extracted with the library when it is first used.", new ArgDef(Type.ExistingFile, "resourceFile")), - RemoveInlineAsm( "-removeInlineAsm", "Remove inline asm from preprocessed source, useful when its unsupported syntax makes parsing to fail."), - ForceOverwrite( "-f", "Force the overwrite of existing files"), - MavenVersion( "-mavenVersion", "Set version of the generated Maven project", new ArgDef(Type.String, "version")), - MavenArtifactId( "-mavenArtifactId", "Set artifact id of the generated Maven project", new ArgDef(Type.String, "artifactId")), - MavenGroupId( "-mavenGroupId", "Set group id of the generated Maven project", new ArgDef(Type.String, "groupId")), - MaxConstructedFields( - "-maxConstrFields", "Maximum number of fields allowed for structure fields constructors. If a struct has more fields, it will only get a default constructor.", new ArgDef(Type.Int, "fieldCount")), - GenPrivateMembers( "-genPrivateMembers", "Generate wrappers for private fields and methods (will be protected and deprecated)."), - CPlusPlusGen( "-genCPlusPlus", "[Experimental, Not working at all] Generate C++ classes."); - - OptionDef(String clSwitch, String description, ArgDef... args) { - this.clSwitch = clSwitch; - this.description = description; - this.args = args; - switchPattern = clSwitch == null ? null : Pattern.compile(clSwitch); - for (int i = 0; i < args.length; i++) - args[i].position = i; - } - public String toString() { - return super.toString() + ": " + description(); - } - public String format(Object... fargs) { - if (fargs.length != args.length) - throw new JNAerator.CommandLineException("Expected " + args.length + " args to format " + name() + ", got " + fargs.length); - - StringBuilder b = new StringBuilder(); - b.append(clSwitch); - for (int i = 0, n = fargs.length; i < n; i++) { - Object farg = fargs[i]; - ArgDef arg = args[i]; - String f = arg.format(farg); - if (f != null) { - b.append(' '); - b.append(arg.format(farg)); - } - } - return b.toString(); - } - public final ArgDef[] args; - public final Pattern switchPattern; - public final String clSwitch; - private final String description; - - public String description() { - return isDeprecated() ? "(deprecated) " + description : description; - } - private boolean isDeprecated() { - try { - return OptionDef.class.getField(name()).isAnnotationPresent(Deprecated.class); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - public enum Type { - ExistingFile, ExistingDir, File, MessageFormat, String, Int, ExistingFileOrDir, OutputDir, OutputFile, OptionalFile, Enum - } - public static class ArgDef { - public final Type type; - public final String name; - public int position; - public final Class additionalClass; - public final PathType pathType; - public ArgDef(Type type, String name, Class additionalClass, PathType pathType) { - this.type = type; - this.name = name; - this.additionalClass = additionalClass; - this.pathType = pathType; - } - public ArgDef(Type type, String name) { - this(type, name, null, null); - } - public ArgDef(Type type, String name, Class additionalClass) { - this(type, name, additionalClass, null); - } - public ArgDef(Type type, String name, PathType pathType) { - this(type, name, null, pathType); - } - - public String normalize(String arg) { - switch (type) { - case ExistingDir: - case ExistingFile: - case ExistingFileOrDir: - case File: - case OutputDir: - case OutputFile: - case OptionalFile: - if (arg != null) - return new File(arg).getAbsolutePath(); - default: - return arg; - } - } - public String format(Object arg) { - switch (type) { - case Enum: - return ((Enum)additionalClass.cast(arg)).name(); - case ExistingDir: - case ExistingFile: - case ExistingFileOrDir: - case File: - case OutputDir: - case OutputFile: - return ((File)arg).toString(); - case OptionalFile: - return arg == null ? null : ((File)arg).toString(); - case String: - return (String)arg; - case Int: - return ((Integer)arg).toString(); - default: - throw new UnsupportedOperationException("unknown type " + type); - } - } - File findFile(String arg, ArgsParser parser) { - File f = new File(arg); - if (!f.exists()) { - List path = parser.getPath(pathType); - if (path != null) - for (File dir : path) { - File ff = new File(dir, arg); - if (ff.exists()) - return ff; - } - } - return f; - } - Object convertArg(String arg, ArgsParser parser) throws FileNotFoundException { - switch (type) { - case OptionalFile: - boolean opt = arg.endsWith("?"); - String fileName = opt ? arg.substring(0, arg.length() - 1 ) : arg; - File f = findFile(fileName, parser); - if (!f.exists()) { - if (opt) - return null; - throw new FileNotFoundException(f.toString()); - } - return f; - case File: - return findFile(arg, parser); - case Int: - return Integer.parseInt(arg); - case MessageFormat: - return new MessageFormat(arg); - case String: - return arg; - case ExistingDir: - f = findFile(arg, parser); - if (!f.isDirectory()) - throw new FileNotFoundException(f.toString()); - return f; - case ExistingFile: - f = findFile(arg, parser); - if (!f.isFile()) - throw new FileNotFoundException(f.toString()); - return f; - case ExistingFileOrDir: - f = findFile(arg, parser); - if (!f.exists()) - throw new FileNotFoundException(f.toString()); - return f; - case Enum: - try { - return Enum.valueOf((Class)additionalClass, arg); - } catch (Throwable th) { - throw new JNAerator.CommandLineException("Argument '" + arg + "' is not one of the expected values :\n\t" + StringUtils.implode(additionalClass.getEnumConstants(), ",\n\t")); - } - case OutputDir: - f = findFile(arg, parser); - if (f.isFile()) - throw new FileNotFoundException("Expected directory, found file : " + f.toString()); - f.getAbsoluteFile().getParentFile().mkdirs(); - return f; - case OutputFile: - f = findFile(arg, parser); - if (f.isDirectory()) - throw new FileNotFoundException("Expected file, found directory : " + f.toString()); - f.getAbsoluteFile().getParentFile().mkdirs(); - return f; - } - throw new UnsupportedOperationException(); - } - } - public ArgDef getParam(String name) { - for (ArgDef ad : args) - if (ad.name.equals(name)) - return ad; - throw new NoSuchElementException("Argument parameter '" + name + "' in option " + this); - } - - } - - static void displayHelp(boolean wikiFormat) { - List opts = new ArrayList(Arrays.asList(OptionDef.values())); - Collections.sort(opts, new Comparator() { - @Override - public int compare(OptionDef o1, OptionDef o2) { - if (o1.clSwitch == null) - return o2.clSwitch == null ? 0 : -1; - if (o2.clSwitch == null) - return 1; - return o1.clSwitch.compareTo(o2.clSwitch); - } - - }); - if (wikiFormat) { - for (OptionDef opt : opts) { - System.out.print(" * *" + (opt.clSwitch == null ? "" : opt.clSwitch) +"*"); - for (OptionDef.ArgDef ad : opt.args) { - String desc = - ad.type == OptionDef.Type.Enum ? StringUtils.implode(ad.additionalClass.getEnumConstants(), " | ") : - ad.type.toString(); - System.out.print(" <" + ad.name + ": " + desc + ">"); - } - System.out.println(); - System.out.println(" " + opt.description().replaceAll("\\*", "`*`").replaceAll("\n", "\n ")); - } - } else { - System.out.println("Credits: JNAerator is Copyright (c) 2008-2009 Olivier Chafik"); - System.out.println(" Includes Anarres JCPP (Apache 2.0 license), Copyright (c) 2007-2008, Shevek"); - System.out.println(" Includes Java Native Access (JNA) (LGPL license), Copyright (c) 2006-2009 Todd Fast, Timothy Wall, Wayne Meissner and others"); - System.out.println(" Includes Rococoa (LGPL license), Copyright (c) Copyright Duncan McGregor and others"); - System.out.println(" Includes ANTLR's runtime (BSD license), Copyright (c) 2003-2008, Terence Parr"); - System.out.println(" Licensing & Copyright details : http://code.google.com/p/jnaerator/wiki/CreditsAndLicense"); - - for (OptionDef opt : opts) { - System.out.print("\t" + (opt.clSwitch == null ? "" : opt.clSwitch)); - for (OptionDef.ArgDef ad : opt.args) { - String desc = - ad.type == OptionDef.Type.Enum ? StringUtils.implode(ad.additionalClass.getEnumConstants(), " | ") : - ad.type.toString(); - System.out.print(" <" + ad.name + ": " + desc + ">"); - } - System.out.println(); - System.out.println("\t\t" + opt.description()); - System.out.println(); - } - } - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfig.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfig.java deleted file mode 100644 index ae45f2423..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfig.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.io.ReadText; -import com.ochafik.lang.jnaerator.JNAeratorCommandLineArgs.OptionDef; -import org.bridj.cpp.com.IID; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.bridj.ann.Array; -import com.ochafik.lang.jnaerator.JNAeratorConfigUtils.FileExtensionFilter; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.ElementsHelper; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.util.CompoundCollection; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Filter; -import com.ochafik.util.listenable.Pair; -import java.lang.annotation.Annotation; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; - -import java.util.logging.Level; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import java.io.*; - -public class JNAeratorConfig { - public enum Compiler { - GCC4, MSVC9 - } - public enum Architecture { - x86_64, i386, PowerPC - } - public enum Platform { - Windows, Linux, MacOSX - } - public enum Runtime { - JNA(false, true, false, - com.sun.jna.Callback.class, - com.sun.jna.Pointer.class, - com.sun.jna.Memory.class, - com.sun.jna.Structure.class, - com.sun.jna.Union.class, - null, - null, - com.sun.jna.Library.class, - null, - "jna-runtime.jar.files"), - JNAerator(false, true, true, - com.sun.jna.Callback.class, - com.sun.jna.Pointer.class, - com.sun.jna.Memory.class, - com.ochafik.lang.jnaerator.runtime.Structure.class, - com.ochafik.lang.jnaerator.runtime.Union.class, - null, - null, - com.sun.jna.Library.class, - com.ochafik.lang.jnaerator.runtime.Bits.class, - "jnaerator-runtime.jar.files") { - - @Override - public String toString() { - return "JNAerator (based on JNA)"; - } - - }, - BridJ(true, false, true, - org.bridj.Callback.class, - org.bridj.Pointer.class, - null, //org.bridj.Memory.class, - null,//org.bridj.Struct.class, - null,//org.bridj.Struct.class, - null, //org.bridj.StructIO.class, - org.bridj.Pointer.class,// "array" class - null, //org.bridj.NativeLib.class, - org.bridj.ann.Bits.class, - "bridj.jar.files") { - - @Override - public String toString() { - return "BridJ (faster runtime that supports C++)"; - } - - };//, -// IPhone( -// false, -// false, -// null, -// null, -// null, -// null, -// null, -// null, -// null, -// null, -// null, -// null -// ); - - public static final Runtime DEFAULT = BridJ;//JNAerator; - public enum Ann { - Bits, - FastCall, - StdCall, - ObjCBlock, - This, - ThisCall, - Length, - ByValue, - Field, - Symbol, - Name, - Union, - Virtual, - Constructor, - IID - } - Runtime(boolean hasFastStructs, - boolean hasJNA, - boolean hasBitFields, - Class callbackClass, - Class pointerClass, - Class memoryClass, - Class structClass, - Class unionClass, - Class structIOClass, - Class arrayClass, - Class libraryClass, - Class someAnnotationClass, - String runtimeFilesListFileName) - { - this.hasFastStructs = hasFastStructs; - this.hasBitFields = hasBitFields; - this.hasJNA = hasJNA; - this.callbackClass = callbackClass; - this.pointerClass = pointerClass; - this.memoryClass = memoryClass; - this.structClass = structClass; - this.libraryClass = libraryClass; - this.unionClass = unionClass; - this.structIOClass = structIOClass; - this.arrayClass = arrayClass; - this.runtimeFilesListFileName = runtimeFilesListFileName; - annotationPackage = someAnnotationClass == null ? null : someAnnotationClass.getPackage().getName(); - } - public final String runtimeFilesListFileName; - private String annotationPackage; - public SimpleTypeRef typeRef(Ann ann) { - if (annotationPackage == null) - return null; - String n = ann.toString(); - if (this == BridJ) { - if (ann == Ann.Length) - n = Array.class.getSimpleName(); - else if (ann == Ann.IID) - return ElementsHelper.typeRef(ident(IID.class)); - } - List elts = new ArrayList(); - elts.addAll(Arrays.asList(annotationPackage.split("\\."))); - elts.add(n); - return annotationPackage == null ? null : ElementsHelper.typeRef(ident(elts.toArray(new String[elts.size()]))); - } - public final Class callbackClass, pointerClass, memoryClass, structClass, unionClass, structIOClass, arrayClass, libraryClass; - public final boolean hasFastStructs; - public final boolean hasJNA; - public final boolean hasBitFields; - - public String generateMavenProjectModel(String groupId, String artifactId, String version) throws IOException { - String res = "com/ochafik/lang/jnaerator/" + name() + "-pom.xml"; - String pom = ReadText.readText(getClass().getClassLoader().getResource(res)); - if (pom == null) - throw new FileNotFoundException(res); - pom = pom. - replaceAll("%groupId%", groupId). - replaceAll("%artifactId%", artifactId). - replaceAll("%version%", version); - - return pom; - } - } - public enum GenFeatures { - Compile, - FileComments, - UsageComments, - EnumTypeLocationComments, - LibrariesAutoExtraction, - CPlusPlusMangling, - StructConstructors, - TypedPointersForForwardDeclarations, - OriginalFunctionSignatures, - FunctionArgsJavaDoc - } - public enum OutputMode { - Jar("JAR with bindings only"), - StandaloneJar("JAR with bindings and runtime dependencies"), - Directory("Bindings sources in simple file hierarchy"), - Maven("Bindings sources in Maven project ready to build"), - AutoGeneratedMaven("Maven project that automatically regenerates its bindings"); - - private final String desc; - OutputMode(String desc) { - this.desc = desc; - } - - public String getDescription() { - return desc; - } - @Override - public String toString() { - return "'" + name() + "' : " + desc; - } - - boolean isJar() { - return this == Jar || this == StandaloneJar; - } - boolean isDirectory() { - return this == Directory || isMaven(); - } - - boolean isMaven() { - return this == Maven || this == AutoGeneratedMaven; - } - - boolean generatesSources() { - return this != AutoGeneratedMaven; - } - } - - public static final String DEFAULT_HEADER_EXTENSIONS = "h:hpp:hxx"; - public static final String DEFAULT_IMPLEMS_EXTENSIONS = "cpp:c:cxx:m:mm"; - - public final EnumSet features = EnumSet.allOf(GenFeatures.class); - - public Runtime runtime = Runtime.DEFAULT; - - public static class PreprocessorConfig { - - public boolean WORKAROUND_PP_BUGS = true; - - public final List includes = new ArrayList(); - public final Map macros = new LinkedHashMap(); - public final List frameworksPath = new ArrayList(); - - public List includeStrings = new ArrayList(); - - public boolean preprocess = true; - } - - public long fullParsingTimeout = 5000, sliceParsingTimeout = 1000; - public final JNAeratorConfig.PreprocessorConfig preprocessorConfig = new JNAeratorConfig.PreprocessorConfig(); - public boolean followIncludes; - boolean microsoftCOM; - public File preprocessingOutFile, macrosOutFile; - public File choicesOutFile, choicesInputFile; - public boolean useJNADirectCalls; - public boolean limitComments, noComments; - public boolean putTopStructsInSeparateFiles = true; - //public boolean bundleRuntime = true; - public boolean genRawBindings = true; - public boolean beautifyNames; - public boolean treatEmptyStructsAsForwardDecls; - public String[] libraryNamingPrefixes; - public boolean extractLibSymbols; - //public boolean fastStructs; - public List> onlineDocumentationURLFormats = new ArrayList>(); - public String entryName; - public int maxConstructedFields = 10; - public boolean beanStructs; - public boolean reification; - public boolean convertBodies; - public boolean removeInlineAsm; - - public Map extraJavaSourceFilesContents = new LinkedHashMap(); - public Set frameworks = new LinkedHashSet(); - boolean skipIncludedFrameworks; - public FileFilter fileFilter = new FileExtensionFilter(DEFAULT_HEADER_EXTENSIONS.split("[:;]")); - - public Map> libraryFilesByArch = new LinkedHashMap>(); - public List libraryFiles = new ArrayList(); - - public final Map libraryByDirectory = new HashMap(); - public Map libraryByFile = new LinkedHashMap(); - public void addLibraryFile(File file, NativePlatform arch) { - - List others = libraryFilesByArch.get(arch); - if (others == null) - libraryFilesByArch.put(arch, others = new ArrayList()); - - String fn = file.getName(); - int i = fn.lastIndexOf('.'); - if (i > 0) - fn = fn.substring(0, i); - - others.add(file); - libraryByFile.put(file, fn); - libraryFiles.add(file); - } - public void addSourceFile(File file, String library, boolean applyFilters, boolean retainAsTarget) throws IOException { - if (file.isFile()) { - if (fileFilter == null || !applyFilters || fileFilter.accept(file)) { - file = file.getCanonicalFile(); - if (library == null && fileToLibrary != null) - library = fileToLibrary.adapt(file); - sourceFiles.add(file); - if (retainAsTarget) { - libraryByFile.put(file, library); - - File directory = file.getParentFile().getAbsoluteFile(); - String oldLib = libraryByDirectory.put(directory, library); - if (oldLib != null && !oldLib.equals(library)) { - JNAerator.logger.log(Level.WARNING, "Directory " + directory + " contains files from different libraries, so there won't be any default library for its files (symbols defined in files from that library that were included but not explicitly listed will not be JNAerated)."); - libraryByDirectory.put(directory, ""); - } - } - } - } else { - File[] fs = file.listFiles(); - if (fs != null) { - for (File f : fs) { - addSourceFile(f, library, true, retainAsTarget); - } - } - } - } - - public JNAeratorConfig() { -// if (System.getenv("POINTER_CLASSES") == null) -// features.remove(GenFeatures.TypedPointersForForwardDeclarations); - } - public boolean verbose; - boolean parseInChunks; - public File outputDir, sourcesOutputDir, resourcesOutputDir; - public List rootDirectoriesPrefixesForSourceComments = new ArrayList(); - public Adapter functionsAccepter; - public String packageName = null, rootPackageName = null; - public String defaultLibrary; - public Map libraryProjectSources = new LinkedHashMap(); - public Adapter fileToLibrary = new Adapter() { - public String adapt(File file) { - String libraryName = null; - try { - //String canoFile = value.getCanonicalPath(); - //libraryFile = libraryByFile.get(canoFile); - file = file.getCanonicalFile(); - libraryName = libraryByFile.get(file); - - if (libraryName == null) { - libraryName = libraryByDirectory.get(file.getParentFile()); - } - //if (value.toString().startsWith("\"")) - // new Exception("Double quotes in file !").printStackTrace(); -// if (!canoFile.contains("Program Files")) { -// System.out.println("libraryByFile = " + libraryByFile); -// System.out.println("libraryByFile(" + canoFile + ") = " + libraryFile); -// System.out.println(" value = " + value); -// System.out.println("can value = " + value.getCanonicalFile()); -// System.out.println("abs value = " + value.getAbsoluteFile()); -// } - - } catch (IOException e) { - e.printStackTrace(); - } - return libraryName == null ? defaultLibrary : libraryName; - } - }; - public void addRootDir(File dir) throws IOException { - if (!dir.exists()) - return; - String str = dir.getCanonicalPath(); - if (!str.endsWith(File.separator)) - str += File.separator; - if (!rootDirectoriesPrefixesForSourceComments.contains(str)) - rootDirectoriesPrefixesForSourceComments.add(str); - } - public Filter symbolsAccepter = new Filter() { - public boolean accept(Element value) { - String s = Element.getFileOfAscendency(value); - if (s == null) - return false; - - File f = new File(s); - try { - f = f.getCanonicalFile(); - } catch (IOException e) { - e.printStackTrace(); - } - return libraryByFile.containsKey(f); - } - }; - public Set getLibraries() { - Set ret = new HashSet(); - for (Map.Entry e : libraryByFile.entrySet()) - if (e.getValue() != null) - ret.add(e.getValue()); - return ret; - } - public String libraryForElementsInNullFile; - public String cPlusPlusNameSpaceSeparator = "_"; - public boolean preferJavac; - public Set bridgeSupportFiles = new LinkedHashSet(); - public File outputJar; - public File cacheDir; - public boolean autoConf = true; - public boolean forceOverwrite; - public Set undefines = new HashSet(); - public boolean gccLong, sizeAsLong; - public OutputMode outputMode;// = OutputMode.Maven; - @Deprecated - public boolean legacyNoJar; - @Deprecated - public boolean legacyNoCompile; - public boolean noAutoImports; - public boolean bundleSources = true; - public boolean noCPlusPlus; - - public String mavenGroupId = "com.mycompany", mavenArtifactId = "my-native-bindings", mavenVersion = "1.0-SNAPSHOT"; - - public String getLibrary(String elementFile) { - if (elementFile == null) - return libraryForElementsInNullFile; - - return fileToLibrary == null ? - defaultLibrary : - fileToLibrary.adapt(new File(elementFile)); - } - - Set sourceFiles = new LinkedHashSet(); - public boolean bundleLibraries = true; - public boolean wcharAsShort; - public boolean charPtrAsString; - public boolean genCPlusPlus; - public File extractedSymbolsOut; - public boolean stringifyConstCStringReturnValues = true; - public File bridgesupportOutFile; - public boolean scalaStructSetters; - public boolean noPrimitiveArrays; - public boolean synchronizedMethods; - public File scalaOut; - public boolean skipPrivateMembers = true; - public boolean castConstants = true; - public File rawParsedSourcesOutFile, normalizedParsedSourcesOutFile; - public List>> parsedArgs; - public boolean skipLibraryInstanceDeclarations; - public String callbackInvokeMethodName = "apply"; - public Collection getFiles() { - /*return new AdaptedCollection(libraryByFile.keySet(), new Adapter() { - @Override - public File adapt(String value) { - return new File(value); - } - });*/ - return sourceFiles;//libraryByFile.keySet(); - } - public String relativizeFileForSourceComments(String path) { - if (path == null) - return null; - - for (String pref : rootDirectoriesPrefixesForSourceComments) { - if (path.startsWith(pref)) { - path = path.substring(pref.length()); - break; - } - } - return path; - } - @SuppressWarnings("unchecked") - public Collection getInputFiles() { - return new CompoundCollection(sourceFiles, bridgeSupportFiles, libraryFiles); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfigUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfigUtils.java deleted file mode 100644 index 875b44499..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorConfigUtils.java +++ /dev/null @@ -1,488 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.TreeSet; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import com.ochafik.admin.visualstudio.Configuration; -import com.ochafik.admin.visualstudio.Project; -import com.ochafik.admin.visualstudio.Solution; -import com.ochafik.admin.visualstudio.VisualStudioUtils; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.util.SystemUtils; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; - -public class JNAeratorConfigUtils { - - public static Logger logger = Logger.getLogger(JNAeratorConfigUtils.class.getName()); - - public static final class MSC_VER { - public final int - VC4 = 1000, - VC5 = 1100, - VC6 = 1200, - VC70 = 1300, - VC71 = 1310; - } - - - static String getProp(String name, String defVal, boolean verbose) { - String v = System.getenv(name); - v = v == null ? System.getProperty(name, defVal) : v; - if (verbose) - logger.log(Level.INFO, "[environment] " + name + "=" + v); - return v; - } - - //this.frameworkspath = new ArrayList(Arrays.asList(new String[] {"/System/Library/Frameworks/", "/Library/Frameworks/", "/Local/Library/Frameworks/"})); - - - static List DEFAULT_FRAMEWORKS_PATH = Arrays.asList( - "/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks", - "/System/Library/Frameworks/ApplicationServices.framework/Versions/Current/Frameworks", - "/System/Library/Frameworks", - "/Library/Frameworks", - "/Local/Library/Frameworks/", - System.getProperty("user.home") + "/Library/Frameworks" - ); - - static List DEFAULT_INCLUDE_PATH; - static { - if (SystemUtils.isMacOSX()) { - DEFAULT_INCLUDE_PATH = new ArrayList(); - for (String s : new String[] { - "/Developer/SDKs/MacOSX10.5.sdk/usr/include", - "/Developer/SDKs/MacOSX10.4u.sdk/usr/include" - }) - if (new File(s).exists()) { - DEFAULT_INCLUDE_PATH.add(s); - break; - } - - DEFAULT_INCLUDE_PATH.add("."); - } else if (SystemUtils.isWindows()) { - ArrayList list = new ArrayList(VisualStudioUtils.getMicrosoftIncludes()); - list.add("."); - DEFAULT_INCLUDE_PATH = list; - } else { - DEFAULT_INCLUDE_PATH = new ArrayList(Arrays.asList(".")); - } - if (SystemUtils.isUnix()) { - DEFAULT_INCLUDE_PATH.add("/usr/include"); - DEFAULT_INCLUDE_PATH.add("/usr/local/include"); - - /* - * /usr/include/c++ is likely to contain directories with versions such as 4.0.0, 4.4.0... - * We try to take the greatest version (in lexicographic order of matching dir names) and check that it contains "new" and "map" files - */ - File cppi = new File("/usr/include/c++"); - TreeSet versions = new TreeSet(); - if (cppi.isDirectory()) - for (File f : cppi.listFiles()) { - if (!f.isDirectory()) - continue; - String n = f.getName(); - if (!n.matches("[\\d+](\\.[\\d+])*")) - continue; - if (!(new File(f, "new").exists() && new File(f, "map").exists())) - continue; - versions.add(n); - } - if (!versions.isEmpty()) { - File d = new File(cppi, versions.last()); - DEFAULT_INCLUDE_PATH.add(d.toString()); - DEFAULT_INCLUDE_PATH.add(new File(d, "tr1").toString()); - } - } - DEFAULT_INCLUDE_PATH = Collections.unmodifiableList(DEFAULT_INCLUDE_PATH); - } - - public static class FileExtensionFilter implements FileFilter { - final Collection allowedExtensions; - public FileExtensionFilter(Collection allowedExtensions) { - this.allowedExtensions = allowedExtensions; - } - public FileExtensionFilter(String[] split) { - this(Arrays.asList(split)); - } - public boolean accept(File file) { - String name = file.getName().toLowerCase(); - int i = name.lastIndexOf('.'); - return accept(file, i > 0 ? name.substring(i + 1) : ""); - } - public boolean accept(File file, String extension) { - return allowedExtensions.contains(extension); - } - } - - public static void addCPlusPlus(JNAeratorConfig.PreprocessorConfig config) { - config.macros.put("__cplusplus", null); - } - - public static void addGCCPredefinedMacros(JNAeratorConfig.PreprocessorConfig config) { - //gcc -dM -E - < /dev/null - config.macros.put("__DBL_MIN_EXP__", "(-1021)"); - config.macros.put("__FLT_MIN__", "1.17549435e-38F"); - config.macros.put("__CHAR_BIT__", "8"); - config.macros.put("__WCHAR_MAX__", "2147483647"); - config.macros.put("__DBL_DENORM_MIN__", "4.9406564584124654e-324"); - config.macros.put("__FLT_EVAL_METHOD__", "0"); - config.macros.put("__DBL_MIN_10_EXP__", "(-307)"); - config.macros.put("__FINITE_MATH_ONLY__", "0"); - config.macros.put("__SHRT_MAX__", "32767"); - config.macros.put("__LDBL_MAX__", "1.18973149535723176502e+4932L"); - if (com.sun.jna.Platform.isMac()) { - config.macros.put("__APPLE_CC__", "5484"); - config.macros.put("__MACH__", "1"); - config.macros.put("__APPLE__", "1"); - } - config.macros.put("__UINTMAX_TYPE__", "long long unsigned int"); - config.macros.put("__SCHAR_MAX__", "127"); - config.macros.put("__USER_LABEL_PREFIX__", "_"); - config.macros.put("__STDC_HOSTED__", "1"); - config.macros.put("__DBL_DIG__", "15"); - config.macros.put("__FLT_EPSILON__", "1.19209290e-7F"); - config.macros.put("__LDBL_MIN__", "3.36210314311209350626e-4932L"); - config.macros.put("__strong", ""); - config.macros.put("__DECIMAL_DIG__", "21"); - config.macros.put("__LDBL_HAS_QUIET_NAN__", "1"); - config.macros.put("__DYNAMIC__", "1"); -// config.macros.put("__GNUC__", "4"); -// config.macros.put("__MMX__", "1"); - config.macros.put("__DBL_MAX__", "1.7976931348623157e+308"); - config.macros.put("__DBL_HAS_INFINITY__", "1"); - config.macros.put("OBJC_NEW_PROPERTIES", "1"); - config.macros.put("__weak", ""); - config.macros.put("__DBL_MAX_EXP__", "1024"); -// config.macros.put("__SSE2_MATH__", "1"); - config.macros.put("__LONG_LONG_MAX__", "9223372036854775807LL"); - config.macros.put("__GXX_ABI_VERSION", "1002"); - config.macros.put("__FLT_MIN_EXP__", "(-125)"); - config.macros.put("__DBL_MIN__", "2.2250738585072014e-308"); - config.macros.put("__DBL_HAS_QUIET_NAN__", "1"); - config.macros.put("__REGISTER_PREFIX__", ""); - config.macros.put("__NO_INLINE__", "1"); -// config.macros.put("__i386", "1"); - config.macros.put("__FLT_MANT_DIG__", "24"); - config.macros.put("__VERSION__", "\"4.0.1 (Apple Inc. build 5484)\""); -// config.macros.put("i386", "1"); -// config.macros.put("__i386__", "1"); - config.macros.put("__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", "1055"); - config.macros.put("__SIZE_TYPE__", "long unsigned int"); - config.macros.put("__FLT_RADIX__", "2"); - config.macros.put("__LDBL_EPSILON__", "1.08420217248550443401e-19L"); -// config.macros.put("__SSE_MATH__", "1"); - config.macros.put("__FLT_HAS_QUIET_NAN__", "1"); - config.macros.put("__FLT_MAX_10_EXP__", "38"); - config.macros.put("__LONG_MAX__", "2147483647L"); - config.macros.put("__FLT_HAS_INFINITY__", "1"); - - config.macros.put("__LDBL_MANT_DIG__", "64"); - config.macros.put("__CONSTANT_CFSTRINGS__", "1"); - config.macros.put("__WCHAR_TYPE__", "int"); - config.macros.put("__FLT_DIG__", "6"); - config.macros.put("__INT_MAX__", "2147483647"); - config.macros.put("__FLT_MAX_EXP__", "128"); - config.macros.put("__DBL_MANT_DIG__", "53"); - config.macros.put("__WINT_TYPE__", "int"); -// config.macros.put("__SSE__", "1"); - config.macros.put("__LDBL_MIN_EXP__", "(-16381)"); - config.macros.put("__LDBL_MAX_EXP__", "16384"); - config.macros.put("__LDBL_MAX_10_EXP__", "4932"); - config.macros.put("__DBL_EPSILON__", "2.2204460492503131e-16"); - config.macros.put("__LDBL_HAS_INFINITY__", "1"); - config.macros.put("__INTMAX_MAX__", "9223372036854775807LL"); - config.macros.put("__FLT_DENORM_MIN__", "1.40129846e-45F"); - config.macros.put("__PIC__", "1"); - config.macros.put("__FLT_MAX__", "3.40282347e+38F"); -// config.macros.put("__SSE2__", "1"); - config.macros.put("__FLT_MIN_10_EXP__", "(-37)"); - config.macros.put("__INTMAX_TYPE__", "long long int"); - config.macros.put("__GNUC_MINOR__", "0"); - config.macros.put("__DBL_MAX_10_EXP__", "308"); - config.macros.put("__LDBL_DENORM_MIN__", "3.64519953188247460253e-4951L"); -// config.macros.put("__PTRDIFF_TYPE__", "int"); - config.macros.put("__LDBL_MIN_10_EXP__", "(-4931)"); - config.macros.put("__LDBL_DIG__", "18"); -// config.macros.put("__GNUC_GNU_INLINE__", "1"); - } - - static void defaultMacro(JNAeratorConfig config, String name, String value) { - if (!config.preprocessorConfig.macros.containsKey(name)) - config.preprocessorConfig.macros.put(name, value); - } - /** - * TODO move this to a .h resource file - */ - public static void autoConfigure(final JNAeratorConfig config) - { - if (config.runtime == JNAeratorConfig.Runtime.BridJ) - config.genCPlusPlus = true; - - if (!config.noCPlusPlus) - addCPlusPlus(config.preprocessorConfig); - - if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) { - defaultMacro(config, "__BIG_ENDIAN__", "1"); - defaultMacro(config, "G_BYTE_ORDER", "4321"); //glibc: #define G_BIG_ENDIAN 4321 - } else { - defaultMacro(config, "__LITTLE_ENDIAN__", "1"); - defaultMacro(config, "G_BYTE_ORDER", "1234"); //glibc: #define G_LITTLE_ENDIAN 1234 - } - //prevent a jcpp bug to happen when expanding assert(...) : - config.preprocessorConfig.macros.put("NDEBUG", null); - - config.preprocessorConfig.macros.put("__STDC__", null); - config.preprocessorConfig.macros.put("HAVE_PROTOTYPES", null); - config.preprocessorConfig.macros.put("STDC_HEADERS", null); - - config.preprocessorConfig.includes.addAll(getDefaultIncludePath(config.verbose));//JNAeratorConfigUtils.DEFAULT_INCLUDE_PATH); - config.preprocessorConfig.frameworksPath.addAll(getDefaultFrameworkPath(config.verbose));//JNAeratorConfigUtils.DEFAULT_FRAMEWORKS_PATH); - if (SystemUtils.isWindows()) { - //http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx - - //config.preprocessorConfig.includeStrings.add("#define __declspec(x)\n"); - - //http://support.microsoft.com/kb/65472 - config.preprocessorConfig.macros.put("_CHAR_UNSIGNED", null); - - config.preprocessorConfig.macros.put("WIN32_LEAN_AND_MEAN", null); - - // http://msdn.microsoft.com/en-us/library/dh8che7s(VS.80).aspx - config.preprocessorConfig.macros.put("_WCHAR_T_DEFINED", null); - config.preprocessorConfig.macros.put("_NATIVE_WCHAR_T_DEFINED", null); - - defaultMacro(config, "_MSC_VER", "1100"); - defaultMacro(config, "WINAPI", "__stdcall"); - - config.functionsAccepter = new Adapter() { - - public Boolean adapt(Function value) { - return true; - /* - Set mods = value.getModifiers(); - - return mods.contains(ModifierType.DllExport) || - mods.contains(ModifierType.DllImport) || - mods.contains(ModifierType.Extern);*/ - } - - }; - - //config.preprocessorConfig.macros.put("") - //_CPPRTTI - //_DLL - //_M_IX86 - //_MT - //_CPPUNWIND - - } else { - config.preprocessorConfig.macros.put("__GNUC__", null); - - if (SystemUtils.isMacOSX()) { - config.preprocessorConfig.macros.put("TARGET_API_MAC_OSX", null); - config.preprocessorConfig.macros.put("__APPLE_CPP__", null); - config.preprocessorConfig.macros.put("__APPLE_CC__", null); -// config.preprocessorConfig.macros.put("FUNCTION_PASCAL", "0"); -// config.preprocessorConfig.macros.put("FUNCTION_DECLSPEC", "1"); -// config.preprocessorConfig.macros.put("FUNCTION_WIN32CC", "1"); - - } - - config.functionsAccepter = new Adapter() { - - public Boolean adapt(Function value) { - return config.convertBodies || !value.hasModifier(ModifierType.Inline); - } - }; - } - config.preprocessorConfig.includeStrings.add(0, "#define __attribute__(x)\n"); - - JNAeratorConfigUtils.autoConfigureArchitecture(config); - } - - private static Collection getDefaultFrameworkPath(boolean verbose) { - return Arrays.asList(getProp("JNAERATOR_FRAMEWORKS_PATH", StringUtils.implode(DEFAULT_FRAMEWORKS_PATH, File.pathSeparator), verbose).split(File.pathSeparator)); - } - - private static Collection getDefaultIncludePath(boolean verbose) { - return Arrays.asList(getProp("JNAERATOR_INCLUDE_PATH", StringUtils.implode(DEFAULT_INCLUDE_PATH, File.pathSeparator), verbose).split(File.pathSeparator)); - - } - - /** - * TODO move this to a .h resource file - *

        - *
      • endianness - *
      • TARGET_CPU_* : see /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/CarbonCore.framework/Headers/fp.h - *
      - * @param config - */ - static void autoConfigureArchitecture(JNAeratorConfig config) { - String arch = System.getProperty("os.arch").toLowerCase(); - if (config.verbose) - System.out.println("os.arch = " + arch); - - //protect us from inline assembly in VC++: - //config.preprocessorConfig.macros.put("_M_CEE_PURE", null); - - if (arch.equals("x86_64") || arch.equals("amd64")) { - config.preprocessorConfig.macros.put("TARGET_CPU_X86_64", null); - config.preprocessorConfig.macros.put("__i386__", null); - config.preprocessorConfig.macros.put("__x86_64__", null); - config.preprocessorConfig.macros.put("__amd64__", null); - config.preprocessorConfig.macros.put("__LITTLE_ENDIAN__", null); - config.preprocessorConfig.macros.put("M_I86", "1"); - config.preprocessorConfig.macros.put("_M_I86", "1"); - config.preprocessorConfig.macros.put("_WIN32", "1"); -// config.preprocessorConfig.macros.put("M_X64", "1"); -// config.preprocessorConfig.macros.put("_M_X64", "1"); -// config.preprocessorConfig.macros.put("_WIN64", "1"); - } else if (arch.equals("i386") || arch.equals("x86")) { - config.preprocessorConfig.macros.put("TARGET_CPU_X86", null); - config.preprocessorConfig.macros.put("__i386__", null); - config.preprocessorConfig.macros.put("__LITTLE_ENDIAN__", null); - config.preprocessorConfig.macros.put("M_I86", "1"); - config.preprocessorConfig.macros.put("_M_I86", "1"); - config.preprocessorConfig.macros.put("_WIN32", "1"); - } else if (arch.equals("ppc")) { - config.preprocessorConfig.macros.put("TARGET_CPU_PPC", null); - config.preprocessorConfig.macros.put("__PPC__", null); - config.preprocessorConfig.macros.put("__powerpc__", null); - config.preprocessorConfig.macros.put("__BIG_ENDIAN__", null); - } else if (arch.equals("ppc64")) { - config.preprocessorConfig.macros.put("TARGET_CPU_PPC64", null); - config.preprocessorConfig.macros.put("__PPC_64__", null); -// config.preprocessorConfig.macros.put("__powerpc64__", null); - config.preprocessorConfig.macros.put("__BIG_ENDIAN__", null); - } - - } - - public static void readProjectConfig(File projectFile, String configName, final JNAeratorConfig config) throws Exception { - String projectFileName = projectFile.getName(); - config.rootDirectoriesPrefixesForSourceComments.add(projectFile.getCanonicalFile().getParent() + File.separator); - - if (projectFileName.endsWith(".sln")) { - if (configName == null) - configName = "Release|Win32"; - - for (String include : VisualStudioUtils.getMicrosoftIncludes()) { - include = new File(include).getCanonicalPath(); - config.preprocessorConfig.includes.add(include); - if (!include.endsWith(File.separator)) - include = include + File.separator; - config.rootDirectoriesPrefixesForSourceComments.add(include); - } - - Solution solution = new Solution(projectFile); - solution.parseProjects(config.fileFilter); - - //final Map configsByFile = new HashMap(); - //final Map libraryDLLByFile = new HashMap(); - - for (Project project : solution.getProjects()) { - String projectConfigName = project.activeConfigurationNameBySolutionConfigurationName.get(configName); - if (projectConfigName == null) - projectConfigName = configName; - - // throw new IOException("Solution configuration with name '" + configName + "' does correspond to any configuration in project '" + project.name + "' (available configs : " + - // StringUtils.implode(project.activeConfigurationNameBySolutionConfigurationName.keySet(), ", ") + ")"); - - Configuration configuration = project.configurations.get(projectConfigName); - String libraryFile = configuration.outputFile == null ? project.name : RegexUtils.findFirst(configuration.outputFile, Pattern.compile("^(.*?)(\\.[^.]*)?$"), 1); - config.libraryProjectSources.put(libraryFile, project.projectFile.getCanonicalFile()); - - System.out.println("project " + project.name + ": library = " + libraryFile); - if (configuration != null) { - System.out.println("preprocessorDefinitions : " + configuration.preprocessorDefinitions); - for (String def : configuration.preprocessorDefinitions) - config.preprocessorConfig.macros.put(def, ""); - } - for (File file : project.files) { - try { - file = file.getCanonicalFile(); - System.out.println(file + "\n\t-> " + libraryFile); - config.addSourceFile(file, libraryFile, false, true); - - //config.preprocessorConfig - //config.libraryByFile.put(file, libraryFile) - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - - if (config.preprocessorConfig.macros.containsKey("WIN32") || config.preprocessorConfig.macros.containsKey("_WIN32")) - config.preprocessorConfig.macros.put("_M_IX86", ""); - else if (config.preprocessorConfig.macros.containsKey("WIN64") || config.preprocessorConfig.macros.containsKey("_WIN64")) - config.preprocessorConfig.macros.put("_M_AMD64", ""); - - } - } - - public static void addFramework(JNAeratorConfig config, String framework) throws IOException { - - File file = new File(framework); - if (!file.getName().matches("\\.framework$") || !file.exists()) { - for (String pathEl : config.preprocessorConfig.frameworksPath) { - File f = new File(pathEl, framework + ".framework"); - if (f.exists() && f.isDirectory()) { - file = f; - break; - } - } - } - if (!file.exists()) - throw new IOException("Could not find framework '" + framework + "' in path " + config.preprocessorConfig.frameworksPath); - - File headers = new File(file, "Headers"); - if (headers.exists()) { - config.preprocessorConfig.includes.add(headers.getAbsolutePath()); - config.addSourceFile(headers, framework, true, true); - } else - new IOException("No Headers subdirectory in framework '" + framework + "' found here : " + file).printStackTrace(); - - File naturalDir = new File(file, "Resources/BridgeSupport"); - File f; - f = new File(naturalDir, framework + ".bridgesupport"); - if (!f.exists()) - f = new File(naturalDir, framework + "Full.bridgesupport"); - - if (f.exists()) - config.bridgeSupportFiles.add(f); - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorParser.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorParser.java deleted file mode 100644 index baf5deb2f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorParser.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.regex.Pattern; - -import org.anarres.cpp.LexerException; -import org.antlr.runtime.ANTLRReaderStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; - -import com.ochafik.io.WriteText; -import com.ochafik.lang.jnaerator.PreprocessorUtils.MacroUseCallback; -import com.ochafik.lang.jnaerator.parser.ObjCppLexer; -import com.ochafik.lang.jnaerator.parser.ObjCppParser; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import com.ochafik.lang.reflect.DebugUtils; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.RegexUtils; -import java.util.Collection; - -public class JNAeratorParser { - - static class Slice { - public String file; - public int line; - public String text; - public Slice(String file, int line, String text) { - super(); - this.file = file; - this.line = line; - this.text = text; - } - } - private static final boolean EASILY_DEBUGGABLE_BUT_FRAGILE_PARSING_MODE = false; - - protected List cutSourceContentInSlices(String sourceContent, PrintStream originalOut) { - StringBuffer currentEmptyLines = new StringBuffer(); - StringBuffer currentBuffer = new StringBuffer(); - - boolean sliceGotContent = false; - - String[] lines = sourceContent.split("\n"); - int iLine = 0, nLines = lines.length, lastStart = 0; - String lastFile = null; - //int lastPercent = 0; - - - Pattern fileInLinePattern = Pattern.compile("\"([^\"]+)\""); - List slices = new ArrayList(nLines / 10); - for (String line : lines) { - /*int percent = (iLine + 1) * 100 / nLines; - if (lastPercent != percent) { - //originalOut.print("\b\b\b\b\b"); - originalOut.println(percent + "%"); - lastPercent = percent; - }*/ - if (line.startsWith("#line")) { - lastStart = iLine; - lastFile = RegexUtils.findFirst(line, fileInLinePattern, 1); - if (sliceGotContent) { - //originalOut.println("Split: " + line.substring("#line".length()).trim()); - String content = currentBuffer.toString(); - slices.add(new Slice(lastFile, lastStart, content)); - } - currentBuffer.setLength(0); - //currentBuffer.append(currentEmptyLines); - sliceGotContent = false; - } - - if (!sliceGotContent) - sliceGotContent = line.trim().length() > 0; - currentBuffer.append(line); - currentBuffer.append('\n'); - currentEmptyLines.append('\n'); - //deltaLines++; - - iLine++; - } - - if (sliceGotContent) { - String content = currentBuffer.toString(); - slices.add(new Slice(lastFile, lastStart, content)); - } - return slices; - } - - protected Callable createParsingCallable(final JNAeratorConfig config, final TypeConversion typeConverter, final String source, final Set topLevelTypeDefs, boolean isFull) { - return new Callable() { - - public SourceFile call() throws Exception { - PrintStream originalOut = System.out, originalErr = System.err; - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream pout = new PrintStream(bout); - System.setOut(pout); - System.setErr(pout); - - Exception error = null; - try { - ObjCppParser parser = newObjCppParser(typeConverter, source, config.verbose, pout); - if (topLevelTypeDefs != null) - parser.topLevelTypeIdentifiers = topLevelTypeDefs; - SourceFile sourceFile = parser.sourceFile();//.sourceFile; - if (sourceFile == null) - throw new RuntimeException("parser.sourceFile() returned null"); - return sourceFile; - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InterruptedException) - throw (InterruptedException)ex.getCause(); - - error = ex; - - } finally { - System.setOut(originalOut); - System.setErr(originalErr); - } - - pout.flush(); - String errorOut = new String(bout.toByteArray()).trim(); - if (errorOut.length() > 0 && config.verbose) - WriteText.writeText(errorOut, new File("fullParsing.errors.txt")); - - throw new ParseError(source, errorOut, error); - - } - - }; - } - public static class ParseError extends RuntimeException { - private final String source; - private final String errors; - - public ParseError(String source, String errors, Throwable cause) { - super("Failed to parse because of " + cause, cause); - this.source = source; - this.errors = errors; - } - - public String getErrors() { - return errors; - } - - public String getSource() { - return source; - } - - } - - static final Pattern asmPattern = Pattern.compile("(?s)__asm\\s*\\{.*?\\}"); - protected String removeInlineAsm(String source) { - // Hack to replace __asm blocks : - String replaced = RegexUtils.regexReplace(asmPattern, source, new RegexUtils.Replacer() { - public String replace(String[] groups) { - int i = -1; - StringBuilder b = new StringBuilder(); - for (char c : groups[0].toCharArray()) - if (c == '\n') - b.append(c); - return b.toString(); - } - }); - return replaced; - } - public SourceFiles parse(JNAeratorConfig config, TypeConversion typeConverter, MacroUseCallback macrosDependenciesOut) throws IOException, LexerException { - SourceFiles sourceFiles = new SourceFiles(); - - String sourceContent = PreprocessorUtils.preprocessSources(config, sourceFiles.defines, config.verbose, typeConverter, macrosDependenciesOut); - - if (config.removeInlineAsm) - sourceContent = removeInlineAsm(sourceContent); - - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - if (!config.parseInChunks) { - Future fut = executor.submit(createParsingCallable(config, typeConverter, sourceContent, null, true)); - try { - sourceFiles.add(fut.get(config.fullParsingTimeout, TimeUnit.MILLISECONDS)); - return sourceFiles; - } catch (Throwable ex) { - ex.printStackTrace(); - System.err.println("Parsing failed : " + ex); - fut.cancel(true); -// Thread.sleep(200); - } - - System.gc(); - } - System.err.println("Now trying to parse sources slice by slice."); - - - // compartimented parsing (at each change of file) - List slices = cutSourceContentInSlices(sourceContent, System.out); - if (config.verbose) - System.out.println("Now parsing " + slices.size() + " slices"); - - final Set topLevelTypeDefs = Collections.synchronizedSet(new HashSet()); - boolean firstFailure = true; - for (Slice slice : slices) { - try { - sourceFiles.add(executor.submit(createParsingCallable(config, typeConverter, slice.text, topLevelTypeDefs, false)).get(config.sliceParsingTimeout, TimeUnit.MILLISECONDS)); - } catch (Throwable ex) { - if (firstFailure) { - WriteText.writeText(slice.text, new File("splitParsing.firstFailure.source.txt")); - if (ex.getCause() instanceof ParseError) { - ParseError pe = (ParseError)ex.getCause(); - WriteText.writeText(pe.getErrors(), new File("splitParsing.firstFailure.errors.txt")); - //ex.printStackTrace(); - } - firstFailure = false; - } - System.gc(); - ex.printStackTrace(); - System.err.println("Parsing failed : " + ex); - } - } - return sourceFiles; - } finally { - executor.shutdown(); - } - } - protected ObjCppParser newObjCppParser(TypeConversion typeConverter, String s, final boolean verbose, final PrintStream errorOut) throws IOException { - ObjCppParser parser = new ObjCppParser( - new CommonTokenStream( - new ObjCppLexer( - new ANTLRReaderStream(new StringReader(s)) - ) - ) -// , new DummyDebugEventListener() - ) { - - @Override - public void emitErrorMessage(String msg) { - if (errorOut == null) { -// if (verbose) -// super.emitErrorMessage(msg); - } else - errorOut.println(msg); - } - - @Override - public void reportError(RecognitionException arg0) { - if (verbose) - super.reportError(arg0); - } - }; - parser.setupScopes(); - parser.objCParserHelper = typeConverter; - - return parser; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorUtils.java deleted file mode 100644 index fa0716695..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JNAeratorUtils.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.ArrayList; -import java.util.List; - -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -public class JNAeratorUtils { - static String getExactTypeDefName(Element e) { - Element parent = e.getParentElement(); - if (parent == null || !(parent instanceof TypeDef)) - return null; - TypeDef td = (TypeDef) parent; - return findBestPlainStorageName(td); - } - static List guessOwnerName(Element e) { - Element parent = e.getParentElement(); - if (parent == null) - return null; - -// StoredDeclarations td = as(parent, StoredDeclarations.class); -// String bestName = JNAeratorUtils.findBestPlainStorageName(td); -// if (bestName != null) -// return Arrays.asList(bestName); - - List ns = new ArrayList(); - - while (parent != null && !(parent instanceof DeclarationsHolder)) { - if (parent instanceof Arg) { - Arg arg = (Arg)parent; - if (arg.getName() != null) - ns.add(arg.getName()); - } else if (parent instanceof Function) { - Function f = (Function)parent; - if (f.getName() != null) - ns.add(0, f.getName().toString()); - return ns; - } else if (parent instanceof StoredDeclarations) { - StoredDeclarations sd = (StoredDeclarations)parent; - String bestName = findBestPlainStorageName(sd); - if (bestName != null) { - ns.add(0, bestName); - - } - } else if (parent instanceof Expression) { - if (!ns.contains("expression")) - ns.add("expression"); - } - parent = parent.getParentElement(); - } - return ns; - - } - - public static String findBestPlainStorageName(StoredDeclarations sd) { - if (sd == null) - return null; - - TaggedTypeRef ttr = sd.getValueType() instanceof TaggedTypeRef ? (TaggedTypeRef)sd.getValueType() : null; - String idealName = null; - if (ttr != null && ttr.getTag() != null) { - String tn = ttr.getTag().toString(); - if (tn.startsWith("_")) - idealName = tn.substring(1); - } - DirectDeclarator plainDecl = null, idealDecl = null; - boolean plainHasNiceName = false, hasMoreThanOnePlainDecl = false; - for (Declarator st : sd.getDeclarators()) { - if (st instanceof DirectDeclarator) { - DirectDeclarator decl = (DirectDeclarator)st; - String name = decl.getName(); - if (name == null) - continue; - if (name.equals(idealName)) { - idealDecl = decl; - break; - } - boolean hasNiceName = !decl.getName().endsWith("_") && !decl.getName().startsWith("_"); - if (hasMoreThanOnePlainDecl || plainDecl != null && !(!plainHasNiceName && hasNiceName)) { - hasMoreThanOnePlainDecl = true; - continue; - } - plainDecl = decl; - plainHasNiceName = hasNiceName; - } - // TODO play with other names ("pointed_by", "returned_by"...) - } - return - idealDecl != null ? idealDecl.resolveName() : - plainDecl != null && !hasMoreThanOnePlainDecl ? plainDecl.resolveName() : - null - ; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JavaDocCreator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JavaDocCreator.java deleted file mode 100644 index c0ba39bad..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/JavaDocCreator.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.util.string.StringUtils; - -public class JavaDocCreator extends Scanner { - - Result result; - public JavaDocCreator(Result result) { - this.result = result; - } - - @Override - public void visitFunction(Function function) { - if (!result.config.noComments) - if (!(function.getParentElement() instanceof FunctionSignature) && result.config.features.contains(GenFeatures.OriginalFunctionSignatures)) { - function.moveAllCommentsBefore(); - function.addToCommentBefore("Original signature : " + function.computeSignature(SignatureType.Full) + ""); - } -// function.addToCommentBefore("File : " + Element.getFileOfAscendency(function)); - super.visitFunction(function); -// if (function.getValueType() != null && !function.getValueType().toString().equals("void")) -// function.addToCommentBefore("@return " + Element.cleanComment(function.getValueType().toString())); - } - - String cleanCom(String com) { - if (com == null) - return null; - com = Element.cleanComment(com).trim().replaceAll("\n", "
      "); - if (com.trim().length() == 0) - return null; - return com; - } - @Override - public void visitArg(Arg arg) { - super.visitArg(arg); - if (arg.getName() == null) - return; - if (!result.config.features.contains(GenFeatures.FunctionArgsJavaDoc)) - return; - - String ca = arg.getCommentAfter(), cb = arg.getCommentBefore(); - if (ca == null && cb == null) - return; - Function f = arg.findParentOfType(Function.class); - if (f == null) - return; - - ca = cleanCom(ca); - cb = cleanCom(cb); - - if (!result.config.noComments) - f.addToCommentBefore("@param " + arg.getName() + " " + StringUtils.implode(new String[] { ca, cb }, "
      ")); - arg.setCommentAfter(null); - arg.setCommentBefore(null); - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MatchingUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MatchingUtils.java deleted file mode 100644 index c6dfb12c1..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MatchingUtils.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import java.util.*; -//import org.bridj.structs.StructIO; -//import org.bridj.structs.Array; - -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import com.ochafik.util.listenable.Pair; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class MatchingUtils { - public static TypeRef recognizeSizeOf(Expression e) { - if (!(e instanceof FunctionCall)) - return null; - - FunctionCall fc = (FunctionCall)e; - List> args = fc.getArguments(); - if (args.size() != 1) - return null; - - Pair arg = args.get(0); - if (arg == null) - return null; - - Expression f = fc.getFunction(); - if (!(f instanceof VariableRef)) - return null; - VariableRef vr = (VariableRef)f; - if (!"sizeof".equals(String.valueOf(vr.getName()))) - return null; - - Expression a = arg.getSecond(); - if (!(a instanceof Expression.TypeRefExpression)) - return null; - - Expression.TypeRefExpression tr = (Expression.TypeRefExpression)a; - return tr.getType(); - } - public static Pair recognizeSizeOfMult(Expression e) { - List mult = recognizeMultiply(e); - if (mult == null) - return null; - - TypeRef typeRef = null; - Expression f = null; - for (Iterator it = mult.iterator(); it.hasNext();) { - Expression x = it.next(); - TypeRef tr = recognizeSizeOf(x); - if (tr != null && typeRef == null) { // only take first sizeof - typeRef = tr; - } else { - if (f == null) - f = x; - else - f = expr(f, BinaryOperator.Multiply, x); - } - } - if (typeRef == null) - return null; - if (f == null) - f = expr(1); - return new Pair(typeRef, f); - } - - public static List recognizeMultiply(Expression e) { - List ret = new ArrayList(); - if (!recognizeMultiply(e, ret)) - return null; - - return ret; - } - public static boolean recognizeMultiply(Expression e, List out) { - if (!(e instanceof BinaryOp)) - return false; - - BinaryOp op = (BinaryOp)e; - if (op.getOperator() != BinaryOperator.Multiply) - return false; - - for (Expression sub : new Expression[] { op.getFirstOperand(), op.getSecondOperand() }) - if (!recognizeMultiply(sub, out)) - out.add(sub); - - return true; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MissingNamesChooser.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MissingNamesChooser.java deleted file mode 100644 index 65021a4a1..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/MissingNamesChooser.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import static com.ochafik.lang.SyntaxUtils.as; -import com.ochafik.lang.jnaerator.parser.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Scanner; -import java.util.*; - -public class MissingNamesChooser extends Scanner { - - public static boolean isNamedFunctionType(TypeRef tr) { - if (!(tr instanceof FunctionSignature)) - return false; - - FunctionSignature fs = (FunctionSignature) tr; - Function f = fs.getFunction(); - return f != null && f.getName() != null; - } - - public enum NameGenerationStyle { - Java, PreserveCaseAndSeparateByUnderscores - } - NameGenerationStyle nameGenerationStyle = NameGenerationStyle.PreserveCaseAndSeparateByUnderscores; - Result result; - public MissingNamesChooser(Result result) { - this.result = result; - } - - public void setNameGenerationStyle(NameGenerationStyle nameGenerationStyle) { - this.nameGenerationStyle = nameGenerationStyle; - } - - public String chooseArgNameFromType(TypeRef tr) throws UnsupportedConversionException { - if (tr instanceof TypeRef.SimpleTypeRef) { - Identifier name = ((TypeRef.SimpleTypeRef)tr).getName(); - String out; - if (isNull(name)) { - out = StringUtils.implode(tr.getModifiers(), ""); - out = out.length() > 0 ? out.substring(0, 1) : out; - } else - out = name.toString(); - return out; - } else if (tr instanceof TypeRef.Pointer) { - return chooseArgNameFromType(((TypeRef.Pointer)tr).getTarget()) + "Ptr"; - } else if (tr instanceof TypeRef.ArrayRef) { - return chooseArgNameFromType(((TypeRef.ArrayRef)tr).getTarget()) + "Arr"; - } - throw new UnsupportedConversionException(tr, String.valueOf(tr)); - } - - @Override - public void visitFunction(Function function) { - - switch (function.getType()) { - case CFunction: - case CppMethod: - Set names = new TreeSet(); - List> missing = new ArrayList>(); - int i = 0;//, n = function.getArgs().size(); - - for (Arg arg : function.getArgs()) { - String name = arg.getName(); - if (name == null && !isNamedFunctionType(arg.getValueType())) { - missing.add(new Pair(arg, i)); - } else if (name != null) - names.add(name); - i++; - } - for (Pair p : missing) { - i = 1; - String base; - if (p.getFirst().isVarArg()) - base = "varArgs"; - else - try { - base = chooseArgNameFromType(p.getFirst().getValueType()); - } catch (UnsupportedConversionException ex) { - base = "arg"; - } -// if (p.getFirst().getValueType() instanceof TypeRef.SimpleTypeRef) -// base = ((TypeRef.SimpleTypeRef)p.getFirst().getValueType()).getName(); -// else -// base = "arg"; - - //(n == 1 ? "" : p.getValue()) - String name; - while (names.contains(name = base + i)) - i++; - names.add(name); - p.getFirst().setName(name); - } - break; - } - - super.visitFunction(function); - } - - static boolean isNull(Identifier i) { - return i == null || i.resolveLastSimpleIdentifier() == null || i.resolveLastSimpleIdentifier().getName() == null; - } - - @Override - public void visitFunctionSignature(FunctionSignature functionSignature) { - Identifier origName = functionSignature.getFunction() == null ? null : functionSignature.getFunction().getName(); - if (!chooseNameIfMissing(functionSignature)) - super.visitFunctionSignature(functionSignature); - - DeclarationsHolder holder = functionSignature.findParentOfType(DeclarationsHolder.class); - Function f = functionSignature.getFunction(); - if (holder != null && f != null && !isNull(f.getName())) { - Identifier fnameClone = f.getName().clone(); - StoredDeclarations d = as(functionSignature.getParentElement(), StoredDeclarations.class); - if (d instanceof TypeDef) - return; - - if (d != null && d.getDeclarators().isEmpty()) { - if (d instanceof VariablesDeclaration) { - VariablesDeclaration pvd = (VariablesDeclaration) d; - pvd.addDeclarator(new DirectDeclarator((origName == null ? fnameClone : origName).toString())); - functionSignature.replaceBy(new TypeRef.SimpleTypeRef(fnameClone)); - } else - d.replaceBy(null); // special case of C++-like struct sub-type definition - } else - functionSignature.replaceBy(new TypeRef.SimpleTypeRef(fnameClone.clone())); - TypeDef td = new TypeDef(); - td.importDetails(functionSignature, true); - td.setValueType(functionSignature); - td.addDeclarator(new DirectDeclarator(fnameClone.toString())); - holder.addDeclaration(td); - td.accept(this); - } - } - - static boolean isUnnamed(TaggedTypeRefDeclaration d) { - return d != null && d.getTaggedTypeRef() != null && isNull(d.getTaggedTypeRef().getTag()); - } - - Set listChildIdentifiers(DeclarationsHolder h) { - List list = new ArrayList(); - for (Declaration d : h.getDeclarations()) { - if (d instanceof Function) - list.add(((Function)d).getName()); - else if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRefDeclaration td = (TaggedTypeRefDeclaration)d; - TaggedTypeRef tr = td.getTaggedTypeRef(); - if (tr != null) - list.add(tr.getTag()); - } else if (d instanceof VariablesDeclaration) - for (Declarator dc : ((VariablesDeclaration)d).getDeclarators()) - list.add(ident(dc.resolveName())); - } - Set ret = new HashSet(); - for (Identifier i : list) - if (i != null) - ret.add(i); - return ret; - } - - List getUnnamedTaggedTypeRefs(List ds) { - List ret = new ArrayList(); - for (Declaration d : ds) { - if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRefDeclaration td = (TaggedTypeRefDeclaration)d; - TaggedTypeRef tr = td.getTaggedTypeRef(); - if (tr != null && tr.getTag() == null) { - ret.add(td); - } - } - } - return ret; - } - @Override - public void visitStruct(Struct struct) { - fixUnNamedChildren(struct); - super.visitStruct(struct); - } - - //http://stackoverflow.com/questions/2503183/jnaerator-unnamed-union-missing-in-structure - private void fixUnNamedChildren(Struct struct) { - List trs = getUnnamedTaggedTypeRefs(struct.getDeclarations()); - if (trs.isEmpty()) - return; - - Set ids = listChildIdentifiers(struct); - for (TaggedTypeRefDeclaration td : trs) { - TaggedTypeRef tr = td.getTaggedTypeRef(); - if (!(tr instanceof Struct)) - continue; - - Struct s = (Struct) tr; - switch (s.getType()) { - case CStruct: - case CUnion: - String n = chooseNameSuffix(tr); - int i = 1; - Identifier fieldName; - while (!ids.add(fieldName = ident("field" + i))) - i++; - - //tr.setTag(idTag); - td.replaceBy(new VariablesDeclaration(tr, new Declarator.DirectDeclarator(fieldName.toString()))); - break; - } - } - } - - @Override - public void visitTaggedTypeRef(TaggedTypeRef taggedTypeRef) { - super.visitTaggedTypeRef(taggedTypeRef); - - chooseNameIfMissing(taggedTypeRef); - // return; - - Element parent = taggedTypeRef.getParentElement(); - - if (!(parent instanceof TaggedTypeRefDeclaration) && !(parent instanceof TypeDef)) { - DeclarationsHolder holder = taggedTypeRef.findParentOfType(DeclarationsHolder.class); - if (holder != null && holder != taggedTypeRef.getParentElement() && !(parent instanceof DeclarationsHolder)) { - TaggedTypeRefDeclaration td = new TaggedTypeRefDeclaration(); - if (parent instanceof VariablesDeclaration && ((VariablesDeclaration)parent).getDeclarators().isEmpty()) { - taggedTypeRef.importDetails(parent, false); - parent.replaceBy(null); - } else { - TypeRef tr = new TypeRef.SimpleTypeRef(taggedTypeRef.getTag().clone()); - for (Modifier mod : taggedTypeRef.getModifiers()) { - if (mod.isA(ModifierKind.StorageClassSpecifier)) - tr.addModifiers(mod); - } - taggedTypeRef.replaceBy(tr); - if (taggedTypeRef instanceof Struct) - tr.setMarkedAsResolved(true); - } - - td.setTaggedTypeRef(taggedTypeRef); - holder.addDeclaration(td); - //td.accept(this); - } - } -// -// super.visitTaggedTypeRef(taggedTypeRef); -// -// Element parent = taggedTypeRef.getParentElement(); -// boolean unnamed = -// ( -// parent instanceof TaggedTypeRefDeclaration && isUnnamed((TaggedTypeRefDeclaration)parent) || -// parent instanceof VariablesDeclaration && ((VariablesDeclaration)parent).getDeclarators().isEmpty() -// ) && -// parent.getParentElement() instanceof Struct -// ; -// // Support (non-standard) unnamed structs and unions : http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gcc/unnamed-fields.html -// if (unnamed) { -// String type = null; -// if (taggedTypeRef instanceof Struct) { -// switch (((Struct)taggedTypeRef).getType()) { -// case CStruct: -// type = "Struct"; -// break; -// case CUnion: -// type = "Union"; -// break; -// case CPPClass: -// type = "Class"; -// break; -// } -// } -// if (type != null) { -//// taggedTypeRef.setParentElement(null); -// -// VariablesDeclaration vd = new VariablesDeclaration(); -// vd.setValueType(taggedTypeRef); -// String pref; -// if (!isNull(taggedTypeRef.getTag())) { -// pref = taggedTypeRef.getTag() + "Field"; -// pref = pref.substring(0, 1).toLowerCase() + pref.substring(1); -// } else { -// pref = "unnamed" + type; -// int unnamedId = getNextUnnamedId(pref); -// if (taggedTypeRef.getTag() == null) -// taggedTypeRef.setTag(ident("Unnamed" + type + unnamedId)); -// } -// vd.addDeclarator(new DirectDeclarator(pref + getNextUnnamedId(pref))); -//// taggedTypeRef.accept(this); -// parent.replaceBy(vd); -//// vd.accept(this); -//// return; -// } -// } -// chooseNameIfMissing(taggedTypeRef); -// -//// Element parent = taggedTypeRef.getParentElement(); -// -// if (!(parent instanceof TaggedTypeRefDeclaration) && !(parent instanceof TypeDef)) -// { -// DeclarationsHolder holder = taggedTypeRef.findParentOfType(DeclarationsHolder.class); -// if (holder != null && holder != taggedTypeRef.getParentElement() && !(parent instanceof DeclarationsHolder)) { -// TaggedTypeRefDeclaration td = new TaggedTypeRefDeclaration(); -// if (unnamed) { -// String type = null; -// if (taggedTypeRef instanceof Struct) { -// switch (((Struct)taggedTypeRef).getType()) { -// case CStruct: -// type = "Struct"; -// break; -// case CUnion: -// type = "Union"; -// break; -// case CPPClass: -// type = "Class"; -// break; -// } -// } -// if (type == null) { -// taggedTypeRef.importDetails(parent, false); -// parent.replaceBy(null); -// } else { -//// } else if (unnamed && parent instanceof VariablesDeclaration && ((VariablesDeclaration)parent).getDeclarators().isEmpty()) { -//// -//// taggedTypeRef.importDetails(parent, false); -//// parent.replaceBy(null); -// -// VariablesDeclaration vd = new VariablesDeclaration(); -// vd.setValueType(taggedTypeRef); -// String pref; -// if (!isNull(taggedTypeRef.getTag())) { -// pref = taggedTypeRef.getTag() + "Field"; -// pref = pref.substring(0, 1).toLowerCase() + pref.substring(1); -// } else { -// pref = "unnamed" + type; -// int unnamedId = getNextUnnamedId(pref); -// if (taggedTypeRef.getTag() == null) -// taggedTypeRef.setTag(ident("Unnamed" + type + unnamedId)); -// } -// vd.addDeclarator(new DirectDeclarator(pref + getNextUnnamedId(pref))); -//// taggedTypeRef.accept(this); -// parent.replaceBy(vd); -// vd.accept(this); -// return; -// } -// -// } else { -// TypeRef tr = new TypeRef.SimpleTypeRef(taggedTypeRef.getTag().clone()); -// for (Modifier mod : taggedTypeRef.getModifiers()) { -// if (mod.isA(ModifierKind.StorageClassSpecifier)) -// tr.addModifiers(mod); -// } -// taggedTypeRef.replaceBy(tr); -// if (taggedTypeRef instanceof Struct) -// tr.setMarkedAsResolved(true); -// } -// -// td.setTaggedTypeRef(taggedTypeRef); -// holder.addDeclaration(td); -// td.accept(this); -// } -// } - } - - /** - * @return true if the functionSignature changed and triggerered revisitation - */ - private boolean chooseNameIfMissing(FunctionSignature functionSignature) { - Function function = functionSignature.getFunction(); - Element parent = functionSignature.getParentElement(); - if (function != null && (isNull(function.getName()) || parent instanceof VariablesDeclaration || parent instanceof Arg)) { - String name = null; - String exact = JNAeratorUtils.getExactTypeDefName(functionSignature); - if (exact != null) - name = exact; - else { - List ownerNames = JNAeratorUtils.guessOwnerName(function); - if (function.getName() != null) - ownerNames.add(function.getName().toString()); - name = chooseName(functionSignature, ownerNames, true); - } - if (name != null) { - function.setName(ident(name)); - function.accept(this); - return true; - } - } - return false; - } - - Map nextUnnamedId = new HashMap(); - - /** - * @return true if changed and revisited on change results (caller can give up) - */ - private boolean chooseNameIfMissing(TaggedTypeRef taggedTypeRef) { -// String tag = taggedTypeRef.getTag(); -// taggedTypeRef.setTag(result.declarationsConverter.getActualTaggedTypeName(taggedTypeRef)); -// if (!SyntaxUtils.equal(tag, taggedTypeRef.getTag())) { -// taggedTypeRef.accept(this); -// return true; -// } - //String betterTag = result.declarationsConverter.getActualTaggedTypeName(taggedTypeRef); - if (isNull(taggedTypeRef.getTag()) && !(taggedTypeRef.getParentElement() instanceof TaggedTypeRefDeclaration)) { - Identifier tag = result.declarationsConverter.getActualTaggedTypeName(taggedTypeRef); - if (isNull(tag)) { - List ownerNames = JNAeratorUtils.guessOwnerName(taggedTypeRef);//.getParentElement() instanceof StructTypeRef ? struct.getParentElement() : struct); - tag = ident(chooseName(taggedTypeRef, ownerNames, true)); - } - - if (!isNull(tag)) { - taggedTypeRef.setTag(tag.clone()); -// taggedTypeRef.accept(this); - return true; - } - } - return false; - } - - private int getNextUnnamedId(String type) { - - Integer i = nextUnnamedId.get(type); - int unnamedId; - if (i == null) - unnamedId = 1; - else - unnamedId = i; - - nextUnnamedId.put(type, unnamedId + 1); - return unnamedId; - } - - int nextAnonymous = 1; - public String chooseName(Element e, List ownerNames, boolean isType) { - String s = chooseNameSuffix(e); - if (s == null) - return null; - - String n; - - List names = new ArrayList(); - if (ownerNames != null) - names.addAll(ownerNames); - if (ownerNames.isEmpty()) - n = s + (nextAnonymous++); - else { - names.add(s); - switch (nameGenerationStyle) { - case Java: - n = StringUtils.capitalize(ownerNames, ""); - break; - case PreserveCaseAndSeparateByUnderscores: - n = StringUtils.implode(names, "_"); - break; - default: - throw new UnsupportedOperationException("Unknown name generation style " + nameGenerationStyle); - } - } - - if (result.config.beautifyNames) { - n = result.typeConverter.beautify(n, isType); - } - return n; - } - public String chooseNameSuffix(Element e) { - if (e instanceof Struct) { - Struct struct = (Struct)e; - if (struct.getType() == Struct.Type.CStruct) { - return "struct"; - } else if (struct.getType() == Struct.Type.CUnion) { - return "union"; - } - } else if (e instanceof Enum) { - return "enum"; - } else if (e instanceof FunctionSignature) - return "callback"; - return null; - } - - static T importDetails(T t, Element e, boolean move) { - t.importDetails(e, move); - return t; - } - -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/NativePlatform.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/NativePlatform.java deleted file mode 100644 index 9fa8c6887..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/NativePlatform.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.util.EnumSet; -import java.util.NoSuchElementException; -import java.util.regex.Pattern; -import static org.bridj.Platform.*; - -/** - * - * @author ochafik - */ -public enum NativePlatform { - // Linux - linux_x64("so"), linux_x86("so"), - - // Android - armeabi("so"), - - // Solaris - sunos_x86("so"), sunos_sparc("so"), - - // MacOS X - darwin_universal("dylib"), - - // Windows - win32("dll"), win64("dll"); - - final Pattern pattern; - final String extension; - NativePlatform(String extension) { - this.extension = extension; - this.pattern = Pattern.compile(".*?\\." + Pattern.quote(extension)); - } - - public static EnumSet getPossiblePlatformsOfLibraryFile(String path) { - String name = new File(path).getName(); - EnumSet set = EnumSet.noneOf(NativePlatform.class); - for (NativePlatform p : values()) { - if (p.pattern.matcher(name).matches()) { - set.add(p); - } - } - return set; - } - - public static NativePlatform getCurrentPlatform() { - if (isWindows()) { - return is64Bits() ? win64 : win32; - } else if (isAndroid()) { - return isArm() ? armeabi : linux_x86; - } else if (isLinux()) { - return is64Bits() ? linux_x64 : linux_x86; - } else if (isSolaris()) { - if (isSparc()) { - return sunos_sparc; - } else { - return sunos_x86; - } - } else if (isMacOSX()) - return darwin_universal; - - return null; - //throw new NoSuchElementException("Unknown platform !"); - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCGenerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCGenerator.java deleted file mode 100644 index 37c09d51e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCGenerator.java +++ /dev/null @@ -1,627 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.IOException; -import java.io.InputStream; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.Set; -import com.ochafik.util.string.StringUtils; - -import org.rococoa.cocoa.foundation.NSObject; -//import org.rococoa.cocoa.foundation.NSString; -import org.rococoa.Rococoa; -import org.rococoa.ObjCObject; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -import com.ochafik.io.ReadText; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Declaration; -import com.ochafik.lang.jnaerator.parser.DeclarationsHolder; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.Statement; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TaggedTypeRefDeclaration; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; -import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOperator; -import com.ochafik.lang.jnaerator.parser.Expression.BinaryOperator; -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.ochafik.lang.jnaerator.parser.Statement.Block; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.Struct.Type; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import java.util.*; -import org.rococoa.ObjCClass; -import org.rococoa.cocoa.foundation.NSClass; - -/* -include com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data -include com/ochafik/lang/jnaerator/ObjectiveCProtocolsForcedInheritanceList.data - */ -public class ObjectiveCGenerator { - String - classClassName = "_class_", - classInterfaceNameInCategoriesAndProtocols = "_static_", - classInstanceName = "_NSCLASS_", - classInstanceGetterName = "getNSClass"; - boolean AUTO_RELEASE_IN_FACTORIES = false; - - static Map> protocolsForcedInheritance; - public static Set getForcedProtocolParents(String protocolName) { - if (protocolsForcedInheritance == null) { - protocolsForcedInheritance = new HashMap>(); - try { - InputStream in = ObjectiveCGenerator.class.getClassLoader().getResourceAsStream("com/ochafik/lang/jnaerator/ObjectiveCProtocolsForcedInheritanceList.data"); - List lines = ReadText.readLines(in); - for (String line : lines) { - line = line.trim(); - if (line.startsWith("//") || line.startsWith("#") || line.length() == 0) - continue; - String[] tks = line.split(":"); - protocolsForcedInheritance.put(tks[0], new TreeSet(Arrays.asList(tks[1].split(",")))); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } - Set ret = protocolsForcedInheritance.get(protocolName); - return ret == null ? Collections.EMPTY_SET : ret; - - } - static Map> methodsExcludedFromStaticForwarding; - public static boolean isMethodExcludedFromStaticForwarding(Function m) { - if (methodsExcludedFromStaticForwarding == null) { - methodsExcludedFromStaticForwarding = new HashMap>(); - try { - InputStream in = ObjectiveCGenerator.class.getClassLoader().getResourceAsStream("com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data"); -// InputStream in = new FileInputStream("/Users/ochafik/Prog/Java/sources/com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data"); - List lines = ReadText.readLines(in); - for (String line : lines) { - line = line.trim(); - if (line.startsWith("//") || line.startsWith("#") || line.length() == 0) - continue; - String[] tks = line.split("\\|"); - String className = tks[0].trim(), methodSignature = tks[1].trim(); - Set set = methodsExcludedFromStaticForwarding.get(className); - if (set == null) - methodsExcludedFromStaticForwarding.put(className, set = new HashSet()); - set.add(methodSignature); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - if (!(m.getParentElement() instanceof Struct)) - return false; - - Struct s = (Struct)m.getParentElement(); - Identifier n = s.getTag(); - if (n != null && n.equals("NSObject"))// || n.equals("NSClass")) - return true; - - String sig = m.computeSignature(SignatureType.JavaStyle); - if (DeclarationsConverter.getMethodsAndTheirSignatures(NSObject.class).getSecond().contains(sig)) - return true; - - String cn = s.getTag() == null ? "" : s.getTag().toString(); - Set set = methodsExcludedFromStaticForwarding.get(cn); - if (set != null && set.contains(sig)) - return true; - - set = methodsExcludedFromStaticForwarding.get(""); - if (set != null && set.contains(sig)) - return true; - - return false; - } - public ObjectiveCGenerator(Result result) { - this.result = result; - } - - final Result result; - - public Struct getStruct(Identifier className, Struct.Type type) { - return Result.getMap(result.classes, type).get(className); - } - public Identifier getPackageName(Struct struct) { - if (struct == null) - return null; - - String library = result.getLibrary(struct); - Identifier javaPackage = result.getLibraryPackage(library); - - //if (struct.getType() == Struct.Type.ObjCClass) { - // String name = String.valueOf(struct.getTag()); - //if (name.equals("NSObject")) - // javaPackage = ident(NSObject.class.getPackage().getName().split("\\.")); - //else if (name.equals("NSClass")) - // javaPackage = ident(NSClass.class.getPackage().getName().split("\\.")); - //else if (name.equals("NSString")) - // javaPackage = ident(NSString.class.getPackage().getName().split("\\.")); - //} - - if (struct.getType() == Type.ObjCProtocol) - javaPackage = ident(javaPackage, "protocols"); - else if (struct.getCategoryName() != null) - javaPackage = ident(javaPackage, "categories"); - return javaPackage; - } - public Identifier getFullClassName(Struct struct) { - if (struct == null) - return null; - Identifier javaPackage = getPackageName(struct); - Identifier tag = struct.getTag(); - String categ = struct.getCategoryName(); - return ident(javaPackage, categ == null ? tag.clone() : ident(categ)); - } - public void generateObjectiveCClasses() throws IOException { - for (Struct in : Result.getMap(result.classes, Type.ObjCClass).values()) { - outputObjectiveCClass(in); - } - for (Struct protocol : Result.getMap(result.classes, Type.ObjCProtocol).values()) { - for (String parent : getForcedProtocolParents(String.valueOf(protocol.getTag()))) - protocol.addParent(ident(parent)); - outputObjectiveCClass(protocol); - } - } - public void outputObjectiveCClass(Struct in) throws IOException { - Identifier fullClassName = getFullClassName(in); - Signatures signatures = new Signatures(); - - Struct s = generateObjectiveCClass(in, signatures); - result.notifyBeforeWritingClass(fullClassName, s, signatures, result.getLibrary(in)); - - PrintWriter out = result.classOutputter.getClassSourceWriter(fullClassName.toString()); - result.printJavaClass(getPackageName(in), s, out); - out.close(); - } - static Identifier - NSObjectIdent = ident(NSObject.class), - ObjCObjectIdent = ident(ObjCObject.class), - ObjCClassIdent = ident(ObjCClass.class); - //NSClassIdent = ident(NSClass.class); - public Struct generateObjectiveCClass(Struct in, Signatures signatures) throws IOException { - boolean isProtocol = in.getType() == Type.ObjCProtocol, isCategory = in.getCategoryName() != null; - - Struct instanceStruct = new Struct().addModifiers(ModifierType.Public); - - instanceStruct.setCommentBefore(in.getCommentBefore()); - instanceStruct.addToCommentBefore(in.getCommentAfter()); - instanceStruct.setTag(isCategory ? ident(in.getCategoryName()) : in.getTag().clone()); - if (isProtocol || isCategory) - instanceStruct.setType(Type.JavaInterface); - else - instanceStruct.addModifiers(ModifierType.Abstract).setType(Type.JavaClass); - - Struct classStruct = new Struct(); - classStruct.setTag(ident(classClassName)); - classStruct.setType(Struct.Type.JavaClass); - classStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); - - List - interfacesForInstance = new ArrayList(); - - List - parentsForInstance = new ArrayList(in.getParents()); - - //for (Identifier p : parentsForInstance) - // parentsForClass - boolean isNSObject = in.getTag().equals(NSObject.class.getSimpleName()); - /*if (parentsForInstance.isEmpty()) { - if (isProtocol || isCategory) - parentsForInstance.add(ObjCObjectIdent); - else - if (!isNSObject) - parentsForInstance.add(NSObjectIdent); - }*/ - //interfacesForClass.add(ObjCClassIdent); - - if (!(isCategory || isProtocol)) - for (Struct catIn : Result.getMap(result.objCCategoriesByTargetType, in.getTag()).values()) { - Identifier catId = getFullClassName(catIn); - - Identifier sim = catId.resolveLastSimpleIdentifier(); - String categName = catIn.getTag() + "_" + sim; - if (add(instanceStruct, createCastMethod(ident(categName), catId, false), signatures)) - classStruct.addDeclaration(createCastMethod(ident(categName), ident(catId, classInterfaceNameInCategoriesAndProtocols), true)); - - //interfacesForInstance.add(catId); - //interfacesForClass.add(ident(catId, classInterfaceNameInCategoriesAndProtocols)); - outputObjectiveCClass(catIn); - } - - for (SimpleTypeRef sp : parentsForInstance) { - Identifier p = sp.getName(); - String ps = p.toString(); - boolean basic = ps.toString().equals(ObjCObject.class.getName()) || ps.equals(NSObject.class.getName()); - Identifier id = basic ? p : result.typeConverter.findObjCClassIdent(p); - //Identifier id = result.typeConverter.findObjCClassIdent(p); - if (id != null || (!p.isPlain() && (id = p) != null)) { - if (ps.toString().equals("NSObject")) - instanceStruct.addProtocol(ident(ObjCObject.class)); - else - instanceStruct.addParent(id.clone()); - if (!basic) - classStruct.addParent(ident(id, classClassName)); - } - } - /*for (Identifier p : interfacesForClass) { - boolean basic = p == ObjCClassIdent || p == NSObjectIdent; - Identifier id = basic ? p : result.typeConverter.findObjCClassIdent(p); - if (id != null) - classStruct.addProtocol(p); - }*/ - boolean isInterface = isProtocol || isCategory; - - if (instanceStruct.getParents().isEmpty()) { - if (isInterface) - instanceStruct.addParent(ident(ObjCObject.class)); - else if (isNSObject) - instanceStruct.addProtocol(ident(ObjCObject.class)); - else - instanceStruct.addParent(ident(NSObject.class)); - } - if (classStruct.getParents().isEmpty()) { - if (isNSObject) - classStruct.addParent(ident(NSClass.class)); - else - classStruct.addParent(ident(ident(NSObject.class), classClassName)); - //classStruct.addProtocol(ident(ObjCClass.class)); - } - - for (SimpleTypeRef p : in.getProtocols()) { - Identifier id = getFullClassName(getStruct(p.getName(), Type.ObjCProtocol)); - if (id != null) - interfacesForInstance.add(typeRef(id)); - } - for (SimpleTypeRef id : interfacesForInstance) { - if (isProtocol || isCategory) - instanceStruct.addParent(id); - else - instanceStruct.addProtocol(id); - } - -// CompoundCollection declarations = new CompoundCollection(); -// declarations.addComponent(in.getDeclarations()); -// for (Struct catIn : Result.getMap(result.objCCategoriesByTargetType, in.getTag()).values()) { -// for (Declaration d : catIn.getDeclarations()) -// d.addToCommentBefore("From category " + catIn.getCategoryName()); -// declarations.addComponent(catIn.getDeclarations()); -// -// if (catIn.getCommentBefore() != null) -// instanceStruct.addToCommentBefore("

      Category " + catIn.getTag()+ " : " + catIn.getCommentBefore() +"

      "); -// } - - - StoredDeclarations classHolder = new VariablesDeclaration(); - if (!(isProtocol || isCategory)) - classHolder.addModifiers(ModifierType.Private, ModifierType.Static); - - classHolder.setValueType(typeRef(classClassName)); - - Expression.FunctionCall call = methodCall(expr(typeRef(Rococoa.class)), MemberRefStyle.Dot, "createClass"); - call.addArgument(expr(in.getTag().toString())); - call.addArgument(memberRef(expr(typeRef(classClassName)), MemberRefStyle.Dot, "class")); - - Function classGetter; - if (isProtocol || isCategory) { - classGetter = null; - classHolder.addDeclarator(new Declarator.DirectDeclarator(classInstanceName, call)); - } else { - classHolder.addDeclarator(new Declarator.DirectDeclarator(classInstanceName)); - - classGetter = new Function(Function.Type.JavaMethod, ident(classInstanceGetterName), typeRef(classClassName)); - classGetter.addModifiers(ModifierType.Public, ModifierType.Static); - classGetter.setBody(new Block( - new Statement.If( - expr( - varRef(classInstanceName), - BinaryOperator.IsEqual, - Constant.newNull() - ), - new Statement.ExpressionStatement( - new AssignmentOp( - varRef(classInstanceName), - AssignmentOperator.Equal, - call - ) - ), - null - ), - new Statement.Return(varRef(classInstanceName)) - )); - } - - Struct classInterfaceStruct = null, structThatReceivesStaticMethods; - if (isProtocol || isCategory) { - structThatReceivesStaticMethods = classInterfaceStruct = new Struct(); - classInterfaceStruct.setType(Struct.Type.JavaInterface); - classInterfaceStruct.setTag(ident(classInterfaceNameInCategoriesAndProtocols)); - classInterfaceStruct.addParent(ident(ObjCClass.class)); - classStruct.addProtocol(ident(classInterfaceNameInCategoriesAndProtocols)); - } else - structThatReceivesStaticMethods = classStruct; - - if (!(isProtocol || isCategory)) { - addAllocIfMissing(in, "alloc"); - addAllocIfMissing(in, "new_"); - } - - outputMembers(signatures, in, instanceStruct, structThatReceivesStaticMethods, in.getDeclarations(), isProtocol || isCategory); - Identifier fullClassName = getFullClassName(in); - - /* - if (!isProtocol && !isCategory) { - // Output static proxies for static category methods - for (Struct catIn : Result.getMap(result.objCCategoriesByTargetType, in.getTag()).values()) { - for (Declaration d : catIn.getDeclarations()) { - if (!(d instanceof Function)) - continue; - Function f = (Function)d; - if (!f.hasModifier(ModifierType.Static)) - continue; - - List decls = new ArrayList(); - result.declarationsConverter.convertFunction(f, null, false, new DeclarationsHolder.ListWrapper(decls), fullClassName); - - if (f.getModifiers().contains(ModifierType.Static)) { - for (Declaration decl : decls) { - if (!(decl instanceof Function)) - continue; - - Function pf = (Function)decl; - if (!signatures.methodsSignatures.add(pf.computeSignature(false))) - continue; - - //if (!add(classStruct, decl, signatures, objSigs, clasSigs)) - // continue; - instanceStruct.addDeclaration(createProxyCopy(pf, (Function)decl)); - } - } - } - } - }*/ - - instanceStruct.addDeclaration(decl(classInterfaceStruct)); - if (!isCategory) {// && !structThatReceivesStaticMethods.getDeclarations().isEmpty()) { - instanceStruct.addDeclaration(new TaggedTypeRefDeclaration(classStruct)); - instanceStruct.addDeclaration(classGetter); - instanceStruct.addDeclaration(classHolder); - } - return instanceStruct; - } - - Function createCastMethod(Identifier name, Identifier classId, boolean isStatic) { - Function m = new Function(); - m.setType(Function.Type.JavaMethod); - m.addModifiers(ModifierType.Public); - m.setName(ident("as" + (isStatic ? "Static_" : "_") + name)); - m.setValueType(typeRef(classId.clone())); - m.setBody(block( - new Statement.Return( - methodCall( - expr(typeRef(Rococoa.class)), - MemberRefStyle.Dot, - "cast", - varRef("this"), - result.typeConverter.typeLiteral(typeRef(classId.clone())) - ) - ) - )); - return m; - } - private void addAllocIfMissing(Struct in, String allocName) { - Identifier n = in.getTag(); - if (n.equals("NSObject") || n.equals("NSClass")) - return; - - boolean hasAlloc = false; - for (Declaration d : in.getDeclarations()) { - if (d instanceof Function) { - Function f = (Function)d; - if (f.getArgs().isEmpty() && allocName.equals(f.getName())) { - hasAlloc = true; - break; - } - } - } - if (!hasAlloc) - in.addDeclaration(new Function(Function.Type.ObjCMethod, ident(allocName), typeRef(in.getTag())).addModifiers(ModifierType.Static)); - - } - - private void outputMembers(Signatures signatures, Struct in, Struct instanceStruct, - Struct classStruct, List declarations, boolean isProtocol) throws IOException { - - Identifier fullClassName = getFullClassName(in); - - Set objSigs = DeclarationsConverter.getMethodsAndTheirSignatures(NSObject.class).getSecond(), - clasSigs = new HashSet();//DeclarationsConverter.getMethodsAndTheirSignatures(NSClass.class).getSecond(); - - int[] iChild = new int[1]; - for (Declaration d : declarations) { - if (d instanceof Function) { - Function f = (Function)d; - List decls = new ArrayList(); - result.declarationsConverter.convertFunction(f, null/*signatures*/, false, new DeclarationsHolder.ListWrapper(decls), fullClassName, -1); - - if (f.hasModifier(ModifierType.Static)) { - for (Declaration decl : decls) { - if (!add(classStruct, decl, signatures, objSigs, clasSigs)) - continue; - - if (!isProtocol && decl instanceof Function) { - instanceStruct.addDeclaration(createProxyCopy(f, (Function)decl)); - signatures.addMethod((Function)decl); - } - - if (classStruct.getType() == Type.JavaClass) { - decl.addModifiers(ModifierType.Public, ModifierType.Abstract); - decl.reorganizeModifiers(); - } - } - } else { - for (Declaration decl : decls) { - if (!add(instanceStruct, decl, signatures, objSigs)) - continue; - - if (!isProtocol && decl instanceof Function) { -// - Function addedF = createCreateCopyFromInit((Function)decl, instanceStruct); - signatures.addMethod((Function)decl); - instanceStruct.addDeclaration(addedF); - - if (instanceStruct.getType() == Type.JavaClass) { - decl.addModifiers(ModifierType.Public, ModifierType.Abstract); - decl.reorganizeModifiers(); - } - } - } - } -// } else if (d instanceof VariablesDeclaration) { -// result.declarationsConverter.convertVariablesDeclaration((VariablesDeclaration)d, instanceStruct, iChild, fullClassName); - } else if (d instanceof TaggedTypeRefDeclaration) { - TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); - if (tr instanceof Struct) { - result.declarationsConverter.outputConvertedStruct((Struct)tr, signatures, instanceStruct, fullClassName, null, false); - } else if (tr instanceof Enum) { - result.declarationsConverter.convertEnum((Enum)tr, signatures, instanceStruct, fullClassName); - } - } else if (d instanceof TypeDef) { - TypeDef td = (TypeDef)d; - TypeRef tr = td.getValueType(); - if (tr instanceof Struct) { - result.declarationsConverter.outputConvertedStruct((Struct)tr, signatures, instanceStruct, fullClassName, null, false); - } else if (tr instanceof FunctionSignature) { - result.declarationsConverter.convertCallback((FunctionSignature)tr, signatures, instanceStruct, fullClassName); - } - } - iChild[0]++; - } - } - - private boolean add(Struct classStruct, Declaration decl, Signatures signatures, Set... additionalMethodSignatures) { - if (decl instanceof Function) { - String sig = ((Function)decl).computeSignature(SignatureType.JavaStyle); - for (Set sigs : additionalMethodSignatures) - if (sigs.contains(sig)) - return false; - if (signatures.addMethod(sig)) { - classStruct.addDeclaration(decl); - return true; - } else - return false; - } - classStruct.addDeclaration(decl); - return true; - } - /** - * Create a createXXXWithYYY factory - * @param meth - * @param instanceStruct - * @return - */ - private Function createCreateCopyFromInit(Function meth, TaggedTypeRef instanceStruct) { - String name = meth.getName().toString(); - if (!name.matches("^init([A-Z].*|)$")) - return null; - //if (name.startsWith("init") && (name.equals("init") || !Character.isUpperCase(name.charAt("init".length())))) - - Function createCopy = meth.clone(); - createCopy.setCommentBefore("Factory method"); - createCopy.addToCommentBefore("@see #" + meth.computeSignature(SignatureType.JavaStyle)); - createCopy.setName(ident("create" + name.substring("init".length()))); - createCopy.addModifiers(ModifierType.Public, ModifierType.Static); - createCopy.reorganizeModifiers(); - - Expression[] args = new Expression[meth.getArgs().size()]; - int i = 0; - for (Arg arg : meth.getArgs()) - args[i++] = varRef(arg.getName()); - - Expression val = methodCall( - methodCall( - methodCall(null, null, classInstanceGetterName), - Expression.MemberRefStyle.Dot, - "alloc" - ), - Expression.MemberRefStyle.Dot, - meth.getName().toString(), - args - ); - - if (AUTO_RELEASE_IN_FACTORIES) { - val = methodCall(val, MemberRefStyle.Dot, "autorelease"); - val = - methodCall(expr(typeRef(Rococoa.class)), MemberRefStyle.Dot, "cast", - val, - memberRef(expr(typeRef(instanceStruct.getTag())), MemberRefStyle.Dot, "class") - ) - ; - } - createCopy.setBody(new Block(new Statement.Return(val))); - return createCopy; - } - private Function createProxyCopy(Function originalMethod, Function meth) { - if (isMethodExcludedFromStaticForwarding(originalMethod)) - return null; - - Function proxyCopy = meth.clone(); - proxyCopy.addModifiers(ModifierType.Public, ModifierType.Static); - proxyCopy.reorganizeModifiers(); - - Expression[] args = new Expression[meth.getArgs().size()]; - int i = 0; - for (Arg arg : meth.getArgs()) - args[i++] = varRef(arg.getName()); - - Expression val = methodCall(methodCall(null, null, classInstanceGetterName), Expression.MemberRefStyle.Dot, meth.getName().toString(), args); - proxyCopy.setBody(new Block( - meth.getValueType() == null || "void".equals(meth.getValueType().toString()) ? stat(val) : new Statement.Return(val) - )); - return proxyCopy; - } - -// protected static _class_ _CLASS_ = org.rococoa.Rococoa.createClass("NSURL", _class_.class); -// public abstract class _class_ extends -// org.rococoa.NSClass { -// //org.rococoa.NSObject._class_ { -// } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCToJavaPreScanner.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCToJavaPreScanner.java deleted file mode 100644 index 70872b725..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ObjectiveCToJavaPreScanner.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.Declaration; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.TaggedTypeRefDeclaration; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.util.string.StringUtils; - -/** - *
        - *
      • Cocoa enums usually don't have names, but they are followed by a typedef that maps an enum-like name to integer. This scanner removes this fake typedef and imports back the name of the enum. - *
      • - *
      - * @author ochafik - */ -public class ObjectiveCToJavaPreScanner extends Scanner { -// @Override -// public void visitStruct(Struct struct) { -// if (struct.isForwardDeclaration()) -// struct.replaceBy(null); -// else -// super.visitStruct(struct); -// } - Result result; - public ObjectiveCToJavaPreScanner(Result result) { - this.result = result; - } - @Override - public void visitEnum(Enum e) { - Element parent = e.getParentElement(); - if (e.getTag() == null && !(parent instanceof TypeDef)) { - // Hack to infer the enum name from the next typedef NSUInteger NSSomethingThatLooksLikeTheEnumsIdentifiers - Element base = parent instanceof Declaration ? e.getParentElement() : e; - Element next = base.getNextSibling(); - if (!handleAppleEnumTypeDef(next, e)) { - Element previous = base.getPreviousSibling(); - Element beforePrevious = previous == null ? null : previous.getPreviousSibling(); - if (previous != null && !(beforePrevious instanceof TaggedTypeRefDeclaration && ((TaggedTypeRefDeclaration)beforePrevious).getTaggedTypeRef() instanceof Enum)) { - handleAppleEnumTypeDef(previous, e); - } - } - } - String comment = e.getCommentBefore(); - if (comment != null) { - // TODO parse cocoa comments here - } - super.visitEnum(e); - } - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - if (v.getDeclarators().isEmpty() && v.getValueType() instanceof TaggedTypeRef) { - TaggedTypeRefDeclaration d = new TaggedTypeRefDeclaration((TaggedTypeRef)v.getValueType()); - d.importComments(v); - v.replaceBy(d); - d.accept(this); - } else - super.visitVariablesDeclaration(v); - } - private boolean handleAppleEnumTypeDef(Element nextDeclaration, Enum e) { - if (!(nextDeclaration instanceof TypeDef)) - return false; - - TypeDef typeDef = (TypeDef) nextDeclaration; - if (typeDef.getDeclarators().size() != 1) - return false; - - Declarator decl = typeDef.getDeclarators().get(0); - if (!(decl instanceof DirectDeclarator)) - return false; - - TypeRef type = typeDef.getValueType(); - if (!(type instanceof TypeRef.SimpleTypeRef)) - return false; - - Identifier simpleType = ((TypeRef.SimpleTypeRef)type).getName(); - if (simpleType == null || - !( - simpleType.equals("NSUInteger") || - simpleType.equals("NSInteger") || - simpleType.equals("int32_t") || - simpleType.equals("uint32_t") || - simpleType.equals("CFIndex") - )) - return false; - - String name = decl.resolveName(); - if (e.getTag() != null && !StringUtils.trimUnderscores(e.getTag().toString()).equals(name)) - return false; - - Element ep = e.getParentElement(); - ep.addToCommentBefore(typeDef.getCommentBefore()); - ep.addToCommentBefore(typeDef.getCommentAfter()); - typeDef.importDetails(ep, true); - ep.replaceBy(null); - typeDef.setValueType(e); - - if (result.config.verbose) - System.err.println("Inferred enum name : " + name); - return false; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/PreprocessorUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/PreprocessorUtils.java deleted file mode 100644 index 8cd8d9d28..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/PreprocessorUtils.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.IOException; -import java.util.HashSet; -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import java.util.regex.Matcher; -import org.anarres.cpp.CppReader; -import org.anarres.cpp.Feature; -import org.anarres.cpp.FileLexerSource; -import org.anarres.cpp.LexerException; -import org.anarres.cpp.Macro; -import org.anarres.cpp.Preprocessor; -import org.anarres.cpp.PreprocessorListener; -import org.anarres.cpp.Source; -import org.anarres.cpp.StringLexerSource; -import org.anarres.cpp.Token; -import org.anarres.cpp.Warning; - -import com.ochafik.io.ReadText; -import com.ochafik.io.WriteText; -import com.ochafik.lang.jnaerator.parser.Define; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.util.string.StringUtils; -import java.util.HashMap; -import java.util.regex.Pattern; -import org.anarres.cpp.VirtualFile; - -public class PreprocessorUtils { - - public static interface MacroUseCallback { - void macroUsed(String path, String macroName); - } - public static String preprocessSources(JNAeratorConfig config, List defines, boolean verbose, TypeConversion typeConverter, MacroUseCallback macrosDependenciesOut) throws IOException, LexerException { - return preprocessSources(config, config.preprocessorConfig.includeStrings, config.getFiles(), defines, verbose, typeConverter, macrosDependenciesOut, null); - } - - public static String preprocessSources(JNAeratorConfig config, Collection includeStrings, Collection files, List defines, boolean verbose, TypeConversion typeConverter, MacroUseCallback macrosDependenciesOut, Map macros) throws IOException, LexerException { - Preprocessor preProcessor = PreprocessorUtils.createPreProcessor(config.preprocessorConfig, macrosDependenciesOut); - for (String content : includeStrings) - preProcessor.addInput(new StringLexerSource(content, true)); - - for (File file : files) - preProcessor.addInput(file); - - boolean isTopLevel = macros == null; - - if (!isTopLevel) - for (Macro macro : macros.values()) - preProcessor.addMacro(macro); - - String sourceContent = ReadText.readText(new CppReader(preProcessor)); - preProcessor.close(); - - //Map - macros = preProcessor.getMacros(); - - if (isTopLevel) { - if (config.preprocessingOutFile != null) { - if (config.verbose) - System.out.println("Writing preprocessor output to '" + config.preprocessingOutFile + "'"); - WriteText.writeText(sourceContent, config.preprocessingOutFile); - } - - if (config.macrosOutFile != null) { - if (config.verbose) - System.out.println("Writing preprocessor macros to '" + config.macrosOutFile + "'"); - WriteText.writeText(StringUtils.implode(macros.entrySet(), "\n"), config.macrosOutFile); - } - } - - for (String k : config.preprocessorConfig.macros.keySet()) - macros.remove(k); - - if (defines != null) - PreprocessorUtils.addDefines(config, macros, defines, verbose, typeConverter); - - return sourceContent; - } - - public static Preprocessor createPreProcessor(JNAeratorConfig.PreprocessorConfig config, final MacroUseCallback macrosDependenciesOut) throws IOException, LexerException { - Preprocessor preprocessor = new Preprocessor() { - HashSet filesAlreadyIncluded = new HashSet(); - - - protected boolean include(VirtualFile file) throws IOException, LexerException { - if (!filesAlreadyIncluded.add(file)) - return true; - - return super.include(file); - } - Set pragmaOnces = new HashSet(); - @Override - protected void pragma(Token name, List value) - throws IOException, LexerException { - if ("once".equals(name.getText())) { - if (!pragmaOnces.add(getSource().toString())) - pop_source(); - } else - super.pragma(name, value); - } - @Override - protected void pop_source() throws IOException { - if (getSource() instanceof FileLexerSource) { - - } - super.pop_source(); - } - - - @Override - protected Map createMacro() { - return new HashMap() { - - @Override - public boolean containsKey(Object key) { - if (key instanceof String) - used((String)key); - return super.containsKey(key); - } - - @Override - public Macro get(Object key) { - if (key instanceof String) - used((String)key); - return super.get(key); - } - - @Override - public void clear() { - super.clear(); - } - - @Override - public Macro put(String key, Macro value) { - if (key != null) - used(key); - return super.put(key, value); - } - - - }; - } - - void used(String name) { - if (macrosDependenciesOut != null) { - Source src = getSource(); - macrosDependenciesOut.macroUsed(src == null ? null : src.getPath(), name); - } - } - - }; - preprocessor.setProperStringTokensInLinePragmas(true); - //preprocessor.addFeatures(EnumSet.allOf(Feature.class)); - if (config.preprocess) { - preprocessor.addFeature(Feature.KEEPCOMMENTS); - preprocessor.addFeature(Feature.DIGRAPHS); - preprocessor.addFeature(Feature.INCLUDENEXT); - preprocessor.addFeature(Feature.OBJCSYNTAX); - preprocessor.addFeature(Feature.TRIGRAPHS); - //preprocessor.addFeature(Feature.CSYNTAX); - preprocessor.addFeature(Feature.LINEMARKERS); - //preprocessor.addFeature(Feature.DEBUG); - - - preprocessor.addWarning(Warning.IMPORT); - } else { - preprocessor.getFeatures().clear(); - } - - preprocessor.setListener(new PreprocessorListener() { - @Override - public void handleWarning(Source source, int line, int column, - String msg) throws LexerException { - if (msg.contains("Unnecessary escape character ")) - return; - - if (msg.contains("#pragma")) - return; - - super.handleWarning(source, line, column, msg); - } - }); - - preprocessor.getSystemIncludePath().addAll(config.includes); - //preprocessor.getSystemIncludePath().addAll(Arrays.asList(DEFAULT_INCLUDE_PATH.split(":"))); - preprocessor.getQuoteIncludePath().addAll(config.includes); - //preprocessor.getFrameworksPath().addAll(Arrays.asList(DEFAULT_FRAMEWORKS_PATH.split(":"))); - preprocessor.getFrameworksPath().addAll(config.frameworksPath); - for (Map.Entry e : config.macros.entrySet()) { - String name = e.getKey(); - String value = e.getValue(); - Matcher matcher = macroFuncNamePattern.matcher(name); - if (matcher.matches()) { - name = matcher.group(1); - Macro macro = new Macro(new StringLexerSource(value), name); - String argsStr = matcher.group(2); - List args = new ArrayList(); - for (String arg : argsStr.split(",")) - args.add(arg.trim()); - macro.setArgs(args); - preprocessor.addMacro(macro); - } else { - if (e.getValue() != null) - preprocessor.addMacro(name, value); - else - preprocessor.addMacro(name); - } - } - return preprocessor; - } - static Pattern macroFuncNamePattern = Pattern.compile("(\\w+)\\(([^)]+)\\)"); - - public static String removePreprocessorDirectives(String s) { - s = s.replaceAll(";#line", ";\n#line"); /// hack ! - - s = s.replaceAll("(?s)#\\s*(pragma|if|endif|error|ifdef|ifndef|else|elif|define|undef).*?\n", "\n"); - s = s.replaceAll("(?s)#\\s*(import|include).*?\n", "\n"); - return s; - } - - public static String removeNastyDefines(String s) { - /// Mac OS X - s = s.replaceAll("DEPRECATED_IN_MAC_OS_X_VERSION_[A-Z0-9_]+_AND_LATER", " "); - s = s.replaceAll("AVAILABLE_MAC_OS_X_VERSION_[A-Z0-9_]+_AND_LATER(_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_[A-Z0-9_]+)?", " "); - s = s.replaceAll("NS_REQUIRES_NIL_TERMINATION", " "); - s = s.replaceAll("__MATH_H_ALWAYS_INLINE__", " "); - s = s.replace("CSEXTERN", "extern"); - - /// Windows - s = s.replace("__inner_fallthrough_dec", " "); - - /// Others - //s = s.replaceAll("__strong", " "); - return s; - } - - //static void addDefines(Preprocessor preProcessor, List defines) { - // for (Map.Entry e : preProcessor.getMacros().entrySet()) { - static void addDefines(JNAeratorConfig config, Map macros, List defines, boolean verbose, TypeConversion typeConverter) { - for (Map.Entry e : macros.entrySet()) { - Macro macro = e.getValue(); - if (macro.getText() == null) - continue; - - if (macro.isFunctionLike() && macro.getArgs() > 0) - continue; - - //if (macro.getFile() == null) - // continue; - - try { - String preprocessedMacro = preprocessSources(config, Collections.singletonList(macro.getText()), Collections.EMPTY_LIST, null, verbose, typeConverter, null, macros); - Expression expression = new JNAeratorParser().newObjCppParser(typeConverter, preprocessedMacro, verbose, null).expression();//.expr; - if (expression == null) - continue; - - Define define = new Define(e.getKey(), expression); - if (macro.getSource() != null) - define.setElementFile(macro.getSource().getPath()); - defines.add(define); - } catch (Exception ex) { - if (verbose) - System.err.println("Failed to convert define '" + e.getValue() + ":\n" + ex); - //ex.printStackTrace(); - } - } - } - - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Reifier.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Reifier.java deleted file mode 100644 index 64b1d1c63..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Reifier.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import static com.ochafik.lang.jnaerator.TypeConversion.*; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.bridj.ann.Ptr; - -/** - * - * @author ochafik - */ -public class Reifier { - final Result result; - - public Reifier(Result result) { - this.result = result; - } - - - void toDirectFakePointer(Result result, Declaration decl) { - decl.setValueType(typeRef(long.class)); - decl.addAnnotation(new Annotation(typeRef(Ptr.class))); - } - - boolean isFakePointerRef(Result result, TypeRef tr) { - if (tr instanceof TypeRef.SimpleTypeRef) { - Identifier id = ((TypeRef.SimpleTypeRef)tr).getName(); - if (result.isFakePointer(id)) - //if (id.equals(ident(result.config.runtime.pointerClass))) - return true; - } - return false; - } - - - private void privatize(Declaration d) { - List modifiers = new ArrayList(d.getModifiers()); - modifiers.remove(ModifierType.Public); - modifiers.remove(ModifierType.Protected); - modifiers.add(0, ModifierType.Private); - d.setModifiers(modifiers); - } - - static String trimAny(String s, String[] prefixes, String[] suffixes) { - String l = s.toLowerCase(); - if (prefixes != null) - for (String prefix : prefixes) { - if (l.startsWith(prefix.toLowerCase())) { - s = s.substring(prefix.length()); - break; - } - } - if (suffixes != null) - for (String suffix : suffixes) { - if (l.endsWith(suffix.toLowerCase())) { - s = s.substring(0, s.length() - suffix.length()); - break; - } - } - return s; - } - public String reifyFunctionName(Result result, String fakePointerName, String functionName) { - String simplifiedPointerName = StringUtils.trimUnderscores(trimAny(fakePointerName, result.config.libraryNamingPrefixes, null)); - List prefs = new ArrayList(); - if (result.config.libraryNamingPrefixes != null) - prefs.addAll(Arrays.asList(result.config.libraryNamingPrefixes)); - prefs.add(fakePointerName); - prefs.add(simplifiedPointerName); - String s = StringUtils.uncapitalize(StringUtils.trimUnderscores(trimAny(functionName, prefs.toArray(new String[prefs.size()]), new String[] { - simplifiedPointerName, - simplifiedPointerName.replaceAll("_", "") - }))); - if (s.length() == 0 || result.typeConverter.isJavaKeyword(s)) - return functionName; - return s; - } - - public void reifyFakePointer(Struct ptClass, Identifier fullLibraryClassName, String fakePointerName, Signatures signatures) { - Identifier resolvedFakePointer = result.getFakePointer(fullLibraryClassName, ident(fakePointerName)); - List> functionsReifiableInFakePointers = result.getFunctionsReifiableInFakePointer(resolvedFakePointer); - String thisFakePtrRefStr = typeRef(resolvedFakePointer).toString(); - - if (functionsReifiableInFakePointers == null) - return; - - for (Pair p : functionsReifiableInFakePointers) { - Function original = p.getSecond(); - Function fDirect = original.clone(); - - int thisLocation = -1; - List fakePointersLocations = new ArrayList(); - int iArg = 0; - for (Arg arg : fDirect.getArgs()) { - if (isFakePointerRef(result, arg.getValueType())) { - if (iArg == 0 && arg.getValueType().toString().equals(thisFakePtrRefStr)) - thisLocation = iArg; - fakePointersLocations.add(iArg); - toDirectFakePointer(result, arg); - } - iArg++; - } - - - String indirectRetVarName = "$"; - boolean returnsFakePointer = isFakePointerRef(result, fDirect.getValueType()); - boolean needsDirect = !fakePointersLocations.isEmpty() || returnsFakePointer; - - Expression finalCall = null; - //boolean needsDirect = fDirect.toString().equals(original.toString()); - String directFunctionName = null; - if (needsDirect) { - if (returnsFakePointer) { - finalCall = new Expression.New(fDirect.getValueType(), varRef(indirectRetVarName)); - toDirectFakePointer(result, fDirect); - } - privatize(fDirect); - if (signatures.addMethod(fDirect)) - ((DeclarationsHolder)original.getParentElement()).addDeclaration(fDirect); - if (original.computeSignature(SignatureType.JavaStyle).equals(fDirect.computeSignature(SignatureType.JavaStyle))) { - fDirect.setName(ident(original.getName() + "$direct")); - } - directFunctionName = fDirect.getName().toString(); - } - - - // TODO private - // TODO -reify:ptrname - // TODO -reify:function=name - // - - Function f = original.clone(); - List args = new ArrayList(f.getArgs()); - f.setModifiers(Collections.EMPTY_LIST); - f.addModifiers(ModifierType.Public); - if (thisLocation < 0) - f.addModifiers(ModifierType.Static); - String functionName = f.getName().toString(); - f.setName(ident(reifyFunctionName(result, fakePointerName, functionName))); - Identifier id = p.getFirst(); - List followedArgs = new ArrayList(); - //followedArgs.add(thisRef()); - - iArg = 0; - for (Arg arg : args) { - if (iArg == thisLocation) - followedArgs.add(methodCall(thisRef(), "getPeer")); - else if (fakePointersLocations.contains(iArg)) - followedArgs.add(methodCall(varRef(arg.getName()), "getPeer")); - else - followedArgs.add(varRef(arg.getName())); - iArg++; - } - if (thisLocation >= 0) - args.remove(thisLocation); - f.setArgs(args); - - Expression nlib = expr(typeRef(p.getFirst().clone()));//nativeLibFieldExpr.clone(); // expr(typeRef(id.clone())) - Expression x = methodCall(nlib, needsDirect ? directFunctionName : functionName, followedArgs.toArray(new Expression[followedArgs.size()])); - boolean retVoid = "void".equals(String.valueOf(f.getValueType())); - if (retVoid) - f.setBody(block(stat(x))); - else if (needsDirect && finalCall != null) { - VariablesDeclaration vd = new VariablesDeclaration(typeRef(long.class), new Declarator.DirectDeclarator(indirectRetVarName, x)); - Expression.ConditionalExpression ce = new Expression.ConditionalExpression(); - ce.setTest(expr(varRef(indirectRetVarName), Expression.BinaryOperator.IsEqual, expr(0))); - ce.setThenValue(nullExpr()); - ce.setElseValue(finalCall); - f.setBody(block(stat(vd), new Statement.Return(ce))); - } else { - f.setBody(block(new Statement.Return(x))); - } - ptClass.addDeclaration(f); - } - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Result.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Result.java deleted file mode 100644 index e078a823e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Result.java +++ /dev/null @@ -1,917 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -//import org.rococoa.cocoa.foundation.FoundationLibrary; -//import org.rococoa.cocoa.foundation.NSClass; -//import org.rococoa.cocoa.foundation.NSInvocation; -//import org.rococoa.cocoa.foundation.NSMethodSignature; -import org.rococoa.cocoa.foundation.NSObject; -//import org.rococoa.cocoa.foundation.NSString; - -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.TypeConversion.JavaPrim; -import com.ochafik.lang.jnaerator.parser.Define; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.Expression; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; -import com.ochafik.lang.jnaerator.parser.Declarator.DirectDeclarator; -import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Printer; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.util.SystemUtils; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import java.util.LinkedHashMap; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.TaggedTypeRefDeclaration; - -public class Result extends Scanner { - - public final JNAeratorConfig config; - public final Feedback feedback; - public final ClassOutputter classOutputter; - - public TypeConversion typeConverter; - public DeclarationsConverter declarationsConverter; - public GlobalsGenerator globalsGenerator; - public ObjectiveCGenerator objectiveCGenerator; - public UniversalReconciliator universalReconciliator; - public Reifier reifier; - public BridJer bridjer; - public Symbols symbols; - public boolean hasCPlusPlus; - - public final Set - structsFullNames = new HashSet(), - enumsFullNames = new HashSet(), - unionsFullNames = new HashSet(), - callbacksFullNames = new HashSet(); - - /** - * @param config - * @param classOutputter - * @param feedback - */ - public Result(JNAeratorConfig config, ClassOutputter classOutputter, Feedback feedback) { - if (config == null) - throw new IllegalArgumentException("No config in result !"); - this.config = config; - this.classOutputter = classOutputter; - this.feedback = feedback; - - init(); - } - public void init() { - if (config.runtime == JNAeratorConfig.Runtime.BridJ) { - declarationsConverter = new BridJDeclarationsConverter(this); - globalsGenerator = new BridJGlobalsGenerator(this); - typeConverter = new BridJTypeConversion(this); - - } else { - declarationsConverter = new JNADeclarationsConverter(this); - globalsGenerator = new JNAGlobalsGenerator(this); - typeConverter = new JNATypeConversion(this); - - } - reifier = new Reifier(this); - objectiveCGenerator = new ObjectiveCGenerator(this); - universalReconciliator = new UniversalReconciliator(); - bridjer = new BridJer(this); - } - - Set javaPackages = new TreeSet(); - - //Map objCClasses = new HashMap(); - Map> classes = new TreeMap>(); - Map> objCCategoriesByTargetType = new HashMap>(); - Map objCCategoriesByName = new HashMap(); - - Map> stringConstants = new HashMap>(); - Map> retainedRetValFunctions = new HashMap>(); - - //Set - //cStructNames = new HashSet(), - //enumNames = new HashSet(); - - public Map> missingPointersByUsingLibrary = new HashMap>(); - public Map> structsByLibrary = new HashMap>(); - public Map> callbacksByLibrary = new HashMap>(); - - public Map> globalsByLibrary = new HashMap>(); - public Map globalVariablesByName = new HashMap(); - - public Map structsByName = new HashMap(); - public Map callbacksByName = new HashMap(); - - public Map> enumsByLibrary = new HashMap>(); - public Map enumsByName = new HashMap(); - public Map enumItems = new HashMap(); - public Map defines = new LinkedHashMap(); - public Map> definesByLibrary = new HashMap>(); - public Map> fakePointersByLibrary = new HashMap>(); - public Map> undefinedTypesByLibrary = new HashMap>(); - - public Map> functionsByLibrary = new HashMap>(); - //Map defines = new LinkedHashMap(); - public Map signaturesByOutputClass = new HashMap(); - - public Map> typeDefs = new HashMap>(); - - static List getList(Map> m, String key) { - List list = m.get(key); - if (list == null) - m.put(key, list = new ArrayList()); - return list; - } - static Map getMap(Map> m, T key) { - Map map = m.get(key); - if (map == null) - m.put(key, map = new LinkedHashMap()); - return map; - } - - public Identifier findFakePointer(Identifier name) { - name = getFakePointerName(name); - if (name == null) - return null; - String s = name.toString(); - for (Map.Entry> e : fakePointersByLibrary.entrySet()) { - if (e.getValue().contains(s)) - return ident(ident(e.getKey()), name); - } - return null; - } - public Identifier findUndefinedType(Identifier name) { - name = getUndefinedTypeName(name); - if (name == null) - return null; - String s = name.toString(); - for (Map.Entry> e : undefinedTypesByLibrary.entrySet()) { - if (e.getValue().contains(s)) - return ident(ident(e.getKey()), name); - } - return null; - } - public boolean isFakePointer(Identifier id) { - return resolvedFakePointers.contains(id); - } - public boolean isUndefinedType(Identifier id) { - return resolvedUndefinedTypes.contains(id); - } - public boolean isUndefinedType(TypeRef tpe) { - return tpe instanceof SimpleTypeRef && isUndefinedType(((SimpleTypeRef)tpe).getName()); - } - - Map>> functionsReifiableInFakePointers = new HashMap>>(); - Set resolvedFakePointers = new HashSet(); - Set resolvedUndefinedTypes = new HashSet(); - public Identifier getFakePointer(Identifier libraryToUseIfNotDefinedYet, Identifier name) { - Identifier lib = findFakePointer(name); - if (lib != null) - return lib; - name = getFakePointerName(name); - Set set = fakePointersByLibrary.get(libraryToUseIfNotDefinedYet); - if (set == null && libraryToUseIfNotDefinedYet != null) - fakePointersByLibrary.put(libraryToUseIfNotDefinedYet.toString(), set = new HashSet()); - set.add(name.toString()); - Identifier id = libraryToUseIfNotDefinedYet == null ? ident(name) : ident(libraryToUseIfNotDefinedYet, name); - resolvedFakePointers.add(id); - return id; - } - public Identifier getUndefinedType(Identifier libraryToUseIfNotDefinedYet, Identifier name) { - Identifier lib = findUndefinedType(name); - if (lib != null) - return lib; - name = getUndefinedTypeName(name); - Set set = undefinedTypesByLibrary.get(libraryToUseIfNotDefinedYet); - if (set == null) - undefinedTypesByLibrary.put(libraryToUseIfNotDefinedYet.toString(), set = new HashSet()); - set.add(name.toString()); - Identifier id = ident(libraryToUseIfNotDefinedYet, name); - resolvedUndefinedTypes.add(id); - return id; - } - private Identifier getFakePointerName(Identifier name) { - - String nameStr = name == null ? null : name.toString(); - String trimmed = StringUtils.trimUnderscores(nameStr); - if (trimmed != null && !nameStr.equals(trimmed)) { - String nicerName = trimmed; - Pair pair = typeDefs.get(nicerName); - if (pair != null) { - TypeRef targetType = pair.getFirst().getValueType(); - String target = targetType.toString(); - if (target.equals(nameStr+"*") || target.equals(nameStr)) - name = ident(nameStr = nicerName); - } - } - return name; - } - private Identifier getUndefinedTypeName(Identifier name) { - - String nameStr = name == null ? null : name.toString(); - String trimmed = StringUtils.trimUnderscores(nameStr); - if (trimmed != null && !nameStr.equals(trimmed)) { - String nicerName = trimmed; - Pair pair = typeDefs.get(nicerName); - if (pair != null) { - String target = pair.getFirst().getValueType().toString(); - if (target.equals(nameStr))// || target.equals(nameStr+"*")) - name = ident(nameStr = nicerName); - } - } - return name; - } - public Signatures getSignaturesForOutputClass(Identifier name) { - Signatures s = signaturesByOutputClass.get(name); - if (s == null) - signaturesByOutputClass.put(name, s = new Signatures()); - return s; - } - /* - public void addDefine(String name, Expression ex) { - defines.put(name, ex); - String library = getLibrary(ex); - if (library.equals("")) - library = library.toString(); - - getList(definesByLibrary, getLibrary(ex)).add(new Pair(name, ex)); - }*/ - - @Override - public void visitDefine(Define define) { - super.visitDefine(define); - defines.put(define.getName(), define); - getList(definesByLibrary, getLibrary(define)).add(define); - } - - - @Override - public void visitEnum(Enum e) { - super.visitEnum(e); - if (e.getTag() == null) { - // Hack to infer the enum name from the next typedef NSUInteger NSSomethingThatLooksLikeTheEnumsIdentifiers - Element nextDeclaration = e.getNextSibling(); - if (nextDeclaration != null && (nextDeclaration instanceof TypeDef)) { - TypeDef typeDef = (TypeDef) nextDeclaration; - TypeRef type = typeDef.getValueType(); - if (type instanceof TypeRef.SimpleTypeRef) { - String simpleTypeStr = ((TypeRef.SimpleTypeRef)type).getName().toString(); - if (simpleTypeStr.equals("NSUInteger") || - simpleTypeStr.equals("NSInteger") || - simpleTypeStr.equals("CFIndex")) - { - Declarator bestPlainStorage = null; - for (Declarator st : typeDef.getDeclarators()) { - if (st instanceof DirectDeclarator) { - String name = st.resolveName(); - boolean niceName = StringUtils.trimUnderscores(name).equals(name);; - if (bestPlainStorage == null || niceName) { - bestPlainStorage = st; - if (niceName) - break; - } - } - } - if (bestPlainStorage != null) { - String name = bestPlainStorage.resolveName(); - System.err.println("Automatic struct name matching : " + name); - e.setTag(ident(name)); - } - } - } - } - } - - Identifier name = e.getTag(); - String lib = getLibrary(e); - if (name == null) - getList(enumsByLibrary, lib).add(e); - else { - Enum oldEnum = enumsByName.get(name); - - if (declarativePower(e) > declarativePower(oldEnum)) { - enumsByName.put(name, e); - e.setResolvedJavaIdentifier(computeTaggedTypeIdentifierInJava(e)); - - //if (e.getTag() != null) { - // enumsByName.put(e.getTag(), e); - //} - getList(enumsByLibrary, lib).add(e); - - Identifier identifier = getTaggedTypeIdentifierInJava(e); - if (identifier != null) { - enumsFullNames.add(identifier); - } - } - } - } - - static int declarativePower(TaggedTypeRef e) { - if (e == null) - return 0; - Element p = e.getParentElement(); - if (p instanceof TypeDef) - return 4; - if (p instanceof TaggedTypeRefDeclaration) - return 3; - if (e.isForwardDeclaration()) - return 2; - return 1; - } - - @Override - public void visitEnumItem(EnumItem enumItem) { - super.visitEnumItem(enumItem); - enumItems.put(enumItem.getName(), enumItem); - - String library = getLibrary(enumItem); - if (library == null) - return; - - Element parent = enumItem.getParentElement(); - if (parent == null || !(parent instanceof Enum)) - return; - - Enum e = (Enum)parent; - Identifier ident = ident(getLibraryClassFullName(library), declarationsConverter.getActualTaggedTypeName(e), ident(enumItem.getName())); - enumItemsFullName.add(ident); - } - - - @Override - public void visitVariablesDeclaration(VariablesDeclaration v) { - super.visitVariablesDeclaration(v); - if (v.findParentOfTypes(Struct.class, Function.class, Enum.class) != null) - return; - - for (Declarator d : v.getDeclarators()) - globalVariablesByName.put(ident(d.resolveName()), v); - getList(globalsByLibrary, getLibrary(v)).add(v); - } - @Override - public void visitTypeDef(TypeDef typeDef) { - super.visitTypeDef(typeDef); - for (Declarator vs : typeDef.getDeclarators()) - typeDefs.put(vs.resolveName(), new Pair(typeDef, vs)); - } - - private static Pattern frameworkPathPattern = Pattern.compile(".*/(\\w+)\\.framework/(?:.*/)?Headers/(?:.*/)?([^/]+)\\.[^/.]+$"); - private static Pattern bridgesupportFrameworkPattern = Pattern.compile("(?:^|/)(\\w+?)(?:Full)?\\.bridgesupport$"); - - String guessFramework(String file) { - Matcher matcher = frameworkPathPattern.matcher(file); - if (matcher.find() || (matcher = bridgesupportFrameworkPattern.matcher(file)).find()) { - return matcher.group(1); - } - return null; - } - String getLibrary(Element decl) { - String file = resolveFile(decl); - String library = config.getLibrary(file); - if (library == null) { - SourceFile f = decl.findParentOfType(SourceFile.class); - if (f != null) { - //library = config.getLibrary(f.getElementFile()); - //if (library == null) { - library = guessFramework(file); - if (library == null) - library = f.getLibrary(); - //} - } - } - return library; - } - - public String resolveFile(Element e) { - String file = null; - while (e != null && (file = e.getElementFile()) == null) { - e = e.getParentElement(); - } - return file; - } - @Override - public void visitFunction(Function function) { - super.visitFunction(function); - Element parent = function.getParentElement(); - if (parent != null) { - if (parent instanceof FunctionSignature) - return; - if (parent instanceof Struct) { - Struct parentStruct = (Struct)parent; - switch (parentStruct.getType()) { - case CPPClass: -// if (config.genCPlusPlus) -// break; - case JavaClass: - case JavaInterface: - case ObjCClass: - case ObjCProtocol: - case CStruct: - return; - } - } - } - - getList(functionsByLibrary, getLibrary(function)).add(function); - } - public Expression getLibraryInstanceReferenceExpression(String libraryName) { - Identifier hub = getHubFullClassName(); - Identifier classIdent; - String fieldName; - if (hub != null) { - classIdent = hub; - fieldName = libraryName; - } else { - classIdent = getLibraryClassFullName(libraryName); - fieldName = "INSTANCE"; - } - return memberRef(expr(typeRef(classIdent)), MemberRefStyle.Dot, fieldName); - } - public Identifier getHubFullClassName() { - return config.entryName == null ? null : ident(config.entryName.toLowerCase(), config.entryName); - } - - public Identifier getTaggedTypeIdentifierInJava(TaggedTypeRef s) { - Identifier tag = s.getTag(); - if (tag != null && s.getResolvedJavaIdentifier() == null) { - TaggedTypeRef rep = null; - if (s instanceof Struct) { - rep = structsByName.get(tag); - } else if (s instanceof Enum) { - rep = enumsByName.get(tag); - } - if (rep != null && rep != s) - s = rep; - } - return s.getResolvedJavaIdentifier(); - } - public Identifier computeTaggedTypeIdentifierInJava(TaggedTypeRef s) { - Identifier name = declarationsConverter.getActualTaggedTypeName(s); - if (name == null) - return null; - - String library = getLibrary(s); - if (library == null) - return null; - - name = name.clone(); - Struct parentStruct = s.findParentOfType(Struct.class); - //Struct parentStruct = s.findParentOfType(Struct.class); - if (parentStruct != null && parentStruct != s) - return ident(getTaggedTypeIdentifierInJava(parentStruct), name); - else if ((s instanceof Struct) && (config.putTopStructsInSeparateFiles || config.runtime == JNAeratorConfig.Runtime.BridJ)) - return ident(getLibraryPackage(library), name); - else - return typeConverter.libMember(getLibraryClassFullName(library), null, name); - } - - @Override - public void visitStruct(Struct struct) { - Identifier name = struct.getTag(); - if (name != null) { - switch (struct.getType()) { - case CPPClass: - if (!config.runtime.equals(JNAeratorConfig.Runtime.BridJ) && !config.genCPlusPlus) - break; - case CStruct: - case CUnion: - - boolean isFwd = struct.isForwardDeclaration(); - if (!isFwd && struct.getDeclarations().isEmpty() && config.treatEmptyStructsAsForwardDecls) { - List parents = struct.getParents(); - Struct p; - if (parents.isEmpty() || parents.size() == 1 && ((p = structsByName.get(parents.get(0))) == null || p.isForwardDeclaration())) - isFwd = true; - } - - if (isFwd) - break; - - if (config.skipIncludedFrameworks) { - String lib = getLibrary(struct); - if (lib != null) { - if (!config.frameworks.contains(lib)) - break; - } - } - Struct oldStruct = structsByName.get(name); - - if (declarativePower(struct) > declarativePower(oldStruct)) { - structsByName.put(name, struct); - - Identifier resolvedJavaIdentifier = computeTaggedTypeIdentifierInJava(struct); - struct.setResolvedJavaIdentifier(resolvedJavaIdentifier); - - if (struct.findParentOfType(Struct.class) == null) - getList(structsByLibrary, getLibrary(struct)).add(struct); - Identifier identifier = getTaggedTypeIdentifierInJava(struct); - if (identifier != null) { - if (struct.getType() == Struct.Type.CUnion) - unionsFullNames.add(identifier); - structsFullNames.add(identifier); - } - } - - break; - case ObjCClass: - case ObjCProtocol: -// if (name.equals("NSObject")) -// name = name.clone(); - - if (struct.isForwardDeclaration()) - break; - - if (struct.getCategoryName() != null) { - getMap(objCCategoriesByTargetType, struct.getTag()).put(struct.getCategoryName(), struct); - objCCategoriesByName.put(struct.getCategoryName(), struct); - } else - getMap(classes, struct.getType()).put(struct.getTag(), struct); - - break; - default: - struct = null; - } - } - super.visitStruct(struct); - } - - @Override - public void visitFunctionSignature(FunctionSignature functionSignature) { - super.visitFunctionSignature(functionSignature); - Function function = functionSignature.getFunction(); - Identifier name = typeConverter.inferCallBackName(functionSignature, false, false, null); - Identifier identifier = computeCallbackIdentifierInJava(functionSignature); - functionSignature.setResolvedJavaIdentifier(identifier); - if (function != null) { - if (functionSignature.findParentOfType(Struct.class) == null) { - getList(callbacksByLibrary, getLibrary(functionSignature)).add(functionSignature); - } - if (name != null) { - callbacksByName.put(name, functionSignature); - if (identifier != null) - callbacksFullNames.add(identifier); - - } - } - } - - public Identifier computeCallbackIdentifierInJava(FunctionSignature fs) { - Identifier name = typeConverter.inferCallBackName(fs, false, false, null); - if (name == null) - return null; - - String library = getLibrary(fs); - if (library == null) - return null; - - name = name.clone(); - Struct parentStruct = fs.findParentOfType(Struct.class); - //Struct parentStruct = s.findParentOfType(Struct.class); - if (parentStruct != null) - return ident(getTaggedTypeIdentifierInJava(parentStruct), name); - else - return typeConverter.libMember(getLibraryClassFullName(library), null, name); - } - - public Identifier getLibraryClassSimpleName(String library) { - return ident(StringUtils.capitalize(library) + "Library"); - } - public Identifier getLibraryClassFullName(String library) { - return ident(getLibraryPackage(library), getLibraryClassSimpleName(library)); - } - public String getLibraryFileExpression(String library) { - Class platformClass = config.runtime.hasJNA ? com.sun.jna.Platform.class : SystemUtils.class; - if (library.equals("c")) - return "(" + platformClass.getName() + ".isWindows() ? \"msvcrt\" : \"c\")"; - - return "\"" + library + "\""; - } - - Set libraries = new HashSet(); - Map javaPackageByLibrary = new HashMap(); - public Set enumItemsFullName = new HashSet(); - - public Identifier getLibraryPackage(String library) { - if (library == null) - return null; - return config.packageName == null ? - ident(ident(config.rootPackageName), library.toLowerCase()) : - ident(config.packageName); - } - public void chooseLibraryClasses(String packageName, String rootPackageName) { - libraries.clear(); - javaPackages.clear(); - javaPackageByLibrary.clear(); - - libraries.addAll(structsByLibrary.keySet()); - libraries.addAll(callbacksByLibrary.keySet()); - libraries.addAll(functionsByLibrary.keySet()); - libraries.addAll(enumsByLibrary.keySet()); - libraries.addAll(globalsByLibrary.keySet()); - libraries.addAll(definesByLibrary.keySet()); - libraries.addAll(stringConstants.keySet()); - - for (String library : libraries) { - Identifier javaPackage = getLibraryPackage(library); - if (javaPackage != null) - javaPackageByLibrary.put(library, javaPackage); - } - javaPackages.addAll(javaPackageByLibrary.values()); - - } - public Struct resolveObjCClass(Identifier name) { - if (name == null) - return null; - Struct s = getMap(classes, Struct.Type.ObjCClass).get(name); - if (s == null) - s = getMap(classes, Struct.Type.ObjCProtocol).get(name); - if (s == null) - s = objCCategoriesByName.get(name.toString()); - return s; - } - - Class[] overwrittenClassesThatNeedToKeepAllTheirMethods = new Class[] { - NSObject.class, - //NSClass.class, - //NSMethodSignature.class, - //NSInvocation.class, - //FoundationLibrary.class - }; - - public void addFunctionReifiableInFakePointer(Identifier resolvedFakePointer, Identifier libraryClassName, Function f) { - List> list = functionsReifiableInFakePointers.get(resolvedFakePointer); - if (list == null) - functionsReifiableInFakePointers.put(resolvedFakePointer, list = new ArrayList>()); - list.add(new Pair(libraryClassName, f)); - } - public List> getFunctionsReifiableInFakePointer(Identifier resolvedFakePointer) { - return functionsReifiableInFakePointers.get(resolvedFakePointer); - } - - public JavaPrim resolvePrimitive(String name) { - return name == null ? null : javaPrims.get(name); - } - - private boolean isPrimitive(TypeRef tr) { - // TODO un-hack me - return javaPrims.containsKey(tr.toString()); - } - - public interface ClassWritingNotifiable { - Struct writingClass(Identifier fullClassName, Struct interf, Signatures signatures, String currentLibrary); - } - public Struct notifyBeforeWritingClass(Identifier fullClassName, Struct interf, Signatures signatures, String currentLibrary) { - for (Class c : overwrittenClassesThatNeedToKeepAllTheirMethods) { - if (fullClassName.equals(c.getName())) { - declarationsConverter.addMissingMethods(c, signatures, interf); - break; - } - } - - if (fullClassName.resolveLastSimpleIdentifier().equals("char")) - return null; - - //if (fullClassName.equals(NSString.class)) { - /* - @Override - public String toString() { - return Foundation.toString(id()); - } - - public static NSString getGlobalString(String libraryName, String globalVarName) { - return Rococoa.wrap(ID.getGlobal(libraryName, globalVarName), NSString.class); - } - - public static NSString getGlobalString(String globalVarName) { - return getGlobalString("AppKit", globalVarName); - }*/ - //} - - String runtimeSpecificHelp = config.runtime == JNAeratorConfig.Runtime.BridJ ? - "or BridJ " : - ", Rococoa, " + - "or JNA" - ; - interf.addToCommentBefore( - "This file was autogenerated by JNAerator, ", - "a tool written by Olivier Chafik that uses a few opensource projects..", - "For help, please visit NativeLibs4Java " + - runtimeSpecificHelp + "." - ); - - for (ClassWritingNotifiable n : classWritingNotifiables) { - interf = n.writingClass(fullClassName, interf, signatures, currentLibrary); - if (interf == null) - return null; - } - return interf; - } - public List classWritingNotifiables = new ArrayList(); - - public void printJavaClass(Identifier javaPackage, Struct javaClass, PrintWriter out) { - - if (javaPackage != null) - out.println("package " + javaPackage + ";"); - - if (config.noAutoImports) - out.println(javaClass); - else - Printer.printJava(javaPackage, ident(javaPackage == null ? null : javaPackage.clone(), javaClass.getTag().clone()), javaClass, out); -// out.println("@SuppressWarnings(\"unused\")"); - } - public boolean hasObjectiveC() { - if (!objCCategoriesByName.isEmpty()) - return true; - - Map m; - - if ((m = classes.get(Struct.Type.ObjCClass)) != null && !m.isEmpty()) - return true; - - if ((m = classes.get(Struct.Type.ObjCProtocol)) != null && !m.isEmpty()) - return true; - return false; - } - public final Map weakTypeDefs = new HashMap(); - public void addWeakTypeDef(TypeRef clone, String sn) { - weakTypeDefs.put(sn, clone); - } - public void rehabilitateWeakTypeDefs() { - for (Map.Entry e : weakTypeDefs.entrySet()) { - if (typeDefs.get(e.getKey()) == null) { - DirectDeclarator dd = new DirectDeclarator(e.getKey()); - TypeDef td = new TypeDef(e.getValue(), dd); - typeDefs.put(e.getKey(), new Pair(td, dd)); - } - } - } - - - Map manualTypeDefs = new HashMap(); - - public TypeRef getTypeDef(Identifier name) { - if (name == null) { - return null; - } - - Pair p = typeDefs.get(name); - if (p == null) { - return manualTypeDefs.get(name.toString()); - } - - Declarator value = p.getValue(); - String rname = value == null ? null : value.resolveName(); - if (rname != null) { - if (name.equals("id")) { - return null; - } - - if (name.equals("SEL")) { - return null; - } - - if (name.equals("IMP")) { - return null; - } - - if (name.equals("Class")) { - return null; - } - - if (name.equals("BOOL")) { - if (rname.equals("byte")) { - return null; - } - } - } - - Declarator.MutableByDeclarator mt = p.getValue().mutateType(p.getFirst().getValueType()); - return mt instanceof TypeRef ? (TypeRef)mt : null; - } - public void addManualTypeDef(String name, TypeRef tr) { - manualTypeDefs.put(name, tr); - } - - public TypeRef resolveType(TypeRef tr, boolean keepUnresolvedIdentifiers) { - return resolveType(tr, keepUnresolvedIdentifiers, new HashSet()); - } - protected TypeRef resolveType(TypeRef tr, boolean keepUnresolvedIdentifiers, Set resolvedTypeDefs) { - if (tr instanceof TypeRef.TargettedTypeRef) { - TypeRef.TargettedTypeRef ttr = (TypeRef.TargettedTypeRef)tr; - TypeRef originalTarget = ttr.getTarget(); - TypeRef resolvedTarget = resolveType(originalTarget, keepUnresolvedIdentifiers, resolvedTypeDefs); - if (resolvedTarget == null) - return null; - - ttr.setTarget(null); - TypeRef.TargettedTypeRef clone = (TypeRef.TargettedTypeRef)ttr.clone(); - ttr.setTarget(originalTarget); - clone.setTarget(resolvedTarget.clone()); - - clone.setParentElement(ttr.findParentOfType(Struct.class)); - return clone; - } - - if (isPrimitive(tr)) - return tr; - if (tr instanceof SimpleTypeRef) { - TypeRef resolved = resolveType(((SimpleTypeRef)tr).getName(), keepUnresolvedIdentifiers, resolvedTypeDefs); - if (resolved != null || !keepUnresolvedIdentifiers) - return resolved; - } - - return tr; - } - protected TypeRef resolveType(Identifier name, boolean keepUnresolvedIdentifiers, Set resolvedTypeDefs) { - TypeRef res; - res = resolveStruct(name); - if (res != null) - return res; - - res = resolveEnum(name); - if (res != null) - return res; - - res = resolveCallback(name); - if (res != null) - return res; - - res = resolveObjCClass(name); - if (res != null) - return res; - - if (resolvedTypeDefs.add(name)) { - res = getTypeDef(name); - if (res != null) - return resolveType(res, keepUnresolvedIdentifiers, resolvedTypeDefs); - } - - return null; - } - - public FunctionSignature resolveCallback(Identifier name) { - return callbacksByName.get(name); - } - - public Enum resolveEnum(Identifier name) { - return enumsByName.get(name); - } - - public Struct resolveStruct(Identifier name) { - return structsByName.get(name); - } - - - Map javaPrims = new TreeMap(); - - public boolean isObjCppPrimitive(String s) { - return javaPrims.containsKey(s); - } - - protected void prim(String from, TypeConversion.JavaPrim to) { - javaPrims.put(from, to); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/RococoaUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/RococoaUtils.java deleted file mode 100644 index e22d92e93..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/RococoaUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.Declarator.PointerStyle; -import com.ochafik.util.string.StringUtils; - -public class RococoaUtils { - static TypeRef ROCOCOA_ID_TYPEREF = new TypeRef.SimpleTypeRef("id"); - - //static Pattern methodNameMatchesStaticConstructorPattern = Pattern.compile("^NS.*?([A-Z][a-z]+)$"); - static Pattern shortNamesPattern = Pattern.compile("([A-Z]+?[a-z]*)(?:[A-Z][a-z]|$)"); - - public static List getShortNames(Struct type) { - String name = type.getTag().toString(); - List shortNames = new ArrayList(); - String base = name.startsWith("NS") ? name.substring(2) : name; - - Matcher matcher = shortNamesPattern.matcher(base); - int i = 0; - while (matcher.find(i)) { - String n = matcher.group(1); - shortNames.add(base.substring(matcher.start())); - i = matcher.start() + n.length(); - } - return shortNames; - } - public static String getMethodName(Function function) { - StringBuilder nb = new StringBuilder(); - nb.append(function.getName()); - boolean firstArg = true; - for (Arg arg : function.getArgs()) { - if (arg.isVarArg()) - continue; - - if (firstArg) - firstArg = false; - else { - nb.append("_"); - nb.append(arg.getSelector()); - } - } - return nb.toString(); - } - public static boolean methodNameMatchesObjcStaticConstructor(Struct type, Identifier identifier) { - String name = identifier.toString(); - for (String shortName : getShortNames(type)) { - if (name.matches(StringUtils.uncapitalize(shortName) + "(With.*)?"))//"([A-Z]\\w*)?")) - return true; - - if (name.matches("[a-z]+" + StringUtils.capitalize(shortName) + "(With.*)?"))//"([A-Z]\\w*)?")) - return true; - } - return false; - } - public static TypeRef fixReturnType(Function function) { - TypeRef returnType = function.getValueType(); - - if (returnType == null) - returnType = RococoaUtils.ROCOCOA_ID_TYPEREF; - - Struct declaringClass = function.findParentOfType(Struct.class); - if (returnType.toString().equals("id")) { - String pointedClassName; - if (function.getName().toString().matches("^(alloc|(init|copy|mutableCopy)([A-Z].*)?)$") || RococoaUtils.methodNameMatchesObjcStaticConstructor(declaringClass, function.getName())) - pointedClassName = declaringClass.getTag().toString(); - else - /// Lets subclasses redefine method return type when parent method return type is ID - pointedClassName = "NSObject"; - - returnType = new TypeRef.Pointer(new TypeRef.SimpleTypeRef(pointedClassName), PointerStyle.Pointer); - } - return returnType; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ScalaGenerator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ScalaGenerator.java deleted file mode 100644 index ddae0bf1b..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/ScalaGenerator.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import com.ochafik.io.ReadText; -import com.ochafik.lang.jnaerator.Result.ClassWritingNotifiable; -import com.ochafik.lang.jnaerator.parser.Arg; -import com.ochafik.lang.jnaerator.parser.Declaration; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Identifier; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.Struct; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.runtime.JNAeratorRuntime; -import com.ochafik.util.string.StringUtils; -import com.sun.jna.Callback; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -/* -include com/ochafik/lang/jnaerator/runtime/scala/*.scala.part -*/ -public class ScalaGenerator implements ClassWritingNotifiable { - - class ScalaClassFile { - public String path, name; - public StringWriter content = new StringWriter(); - } - Map outByLib = new HashMap(); - Result result; - public ScalaGenerator(Result result) throws FileNotFoundException { - this.result = result; - result.classWritingNotifiables.add(this); - } - - @Override - public Struct writingClass(Identifier fullClassName, Struct interf, Signatures signatures, String currentLibrary) { - - try { - visit(fullClassName, interf, currentLibrary); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return interf; - } - - PrintWriter openFile(File f) throws FileNotFoundException { - File p = f.getAbsoluteFile().getParentFile(); - if (!p.exists()) - p.mkdirs(); - result.feedback.setStatus("Generating " + f); - return new PrintWriter(f); - } - StringWriter getLibOut(String pack, String lib) throws FileNotFoundException { - ScalaClassFile out = outByLib.get(lib); - if (out == null) { - outByLib.put(lib, out = new ScalaClassFile()); - out.name = getLibScalaClassName(lib); - out.path = pack.replace('.', '/').replace('\\', '/') + '/' + StringUtils.capitalize(lib) + ".scala"; - } - return out.content; - } - private String getLibScalaClassName(String lib) { - return lib;// + "_scala"; - } - - private void visit(final Identifier fullClassName, Element interf, String currentLibrary) throws FileNotFoundException { - final Identifier pack = fullClassName.resolveAllButLastIdentifier(); - String spack = result.getLibraryPackage(currentLibrary).toString(); - final PrintWriter out = new PrintWriter(getLibOut(spack, currentLibrary)); - interf.accept(new Scanner() { - Stack path = new Stack(); - { - path.add(pack); - } - @Override - public void visitStruct(Struct struct) { - path.push(ident(path.peek(), struct.getTag())); - super.visitStruct(struct); - path.pop(); - } - @Override - public void visitJavaInterface(Struct struct) { - super.visitJavaInterface(struct); - - if (struct.getParents().contains(ident(Callback.class))) { - Function f = null; - for (Declaration d : struct.getDeclarations()) { - if (d instanceof Function) { - f = (Function) d; - break; - } - } - if (f != null) { - List args = f.getArgs(); - List argTypes = new ArrayList(), - argNames = new ArrayList(), - argDefs = new ArrayList(); - String rt = getScalaType(f.getValueType()); - for (Arg a : args) { - String vt = getScalaType(a.getValueType()); - String n = a.getName(); - argTypes.add(vt); - argNames.add(n); - argDefs.add(n + ": " + vt); - } - String cbClassName = struct.getTag().toString(), scbClassName = cbClassName + "_scala"; - String cbClassPath = path.peek().toString(); - int ac = argTypes.size(); - String fsig = (ac == 0 ? "" : ac == 1 ? argTypes.get(0) : "(" + StringUtils.implode(argTypes, ", ") + ")") + " => " + rt; - out.println("class " + scbClassName + "(scala_func: " + fsig + ") extends " + cbClassPath + " {"); - out.println("\toverride def " + f.getName() + "(" + StringUtils.implode(argDefs, ", ") + "): " + rt + " = {"); - out.println("\t\tscala_func(" + StringUtils.implode(argNames, ", ") + ")"); - out.println("\t}"); - out.println("}"); - out.println("implicit def scala_func2" + scbClassName + "(scala_func: " + fsig + ") = {"); - out.println("\tnew " + scbClassName + "(scala_func)"); - out.println("}"); - } - } - } - }); - out.flush(); - } - protected String getScalaType(TypeRef valueType) { - String vt = valueType.toString(); - if (vt.equals("void")) - vt = "Unit"; - return vt; - } - public void jnaerationCompleted() throws IOException { - List availableLibs = new ArrayList(); - for (Map.Entry e : outByLib.entrySet()) { - ScalaClassFile f = e.getValue(); - String lib = e.getKey(); - f.content.close(); - String s = f.content.toString().trim(); - if (s.length() == 0) - continue; - availableLibs.add(lib); - PrintWriter out = openFile(new File(result.config.scalaOut, f.path)); - out.println("trait " + f.name + " extends " + result.getLibraryClassFullName(lib) + " {"); - out.println(s); - out.println("}"); - out.close(); - } - outputSampleScalaSource(availableLibs); - outputScalaRuntime(availableLibs); - - } - - URL getScalaPartResource(String name) throws IOException { - String path = "com/ochafik/lang/jnaerator/runtime/scala/" + name + ".scala.part"; - URL url = JNAeratorRuntime.class.getClassLoader().getResource(path); - return url; - } - static final String SCALA_JNAERATOR_RT_CLASS_NAME = "ScalaJNAerator"; - static final String SCALA_JNA_RT_CLASS_NAME = "ScalaJNA"; - static final String SCALA_ROCOCOA_RT_CLASS_NAME = "ScalaRococoa"; - - private void outputScalaRuntime(List availableLibs) throws IOException { - PrintWriter out = openFile(new File(result.config.scalaOut, SCALA_JNAERATOR_RT_CLASS_NAME + ".scala")); - out.println(ReadText.readText(getScalaPartResource(SCALA_JNA_RT_CLASS_NAME))); - boolean objc = result.hasObjectiveC(); - - if (objc) - out.println(ReadText.readText(getScalaPartResource(SCALA_ROCOCOA_RT_CLASS_NAME))); - out.print("trait " + SCALA_JNAERATOR_RT_CLASS_NAME + " extends " + SCALA_JNA_RT_CLASS_NAME); - if (objc) - out.print(" with " + SCALA_ROCOCOA_RT_CLASS_NAME); - //out.println(" {"); - out.close(); - } - - private void outputSampleScalaSource(List availableLibs) throws FileNotFoundException { - - PrintWriter out = openFile(new File(result.config.scalaOut, "JNAeratorSample.scala")); - out.println("import com.sun.jna._;"); - out.println("import com.sun.jna.ptr._;"); - if (result.hasObjectiveC()) - out.println("import org.rococoa._;"); - out.println(); - out.println("import com.ochafik.lang.jnaerator.runtime._;"); - out.println("import com.ochafik.lang.jnaerator.runtime.globals._;"); - out.println(); - out.println("import " + SCALA_JNAERATOR_RT_CLASS_NAME + "._;"); - for (String lib : availableLibs) { - String scn = getLibScalaClassName(lib); -// out.println("import " + scn + ";"); - out.println("import " + scn + "._;"); - -// Identifier fn = result.getLibraryClassFullName(lib); -// out.println("import " + fn + "._;"); -// Identifier pack = fn.resolveAllButLastIdentifier(); -// if (pack != null) -// out.println("import " + pack + "._;"); - } - out.println(); - - out.println("object ExampleApp extends Application {"); - //out.println("\twith " + SCALA_JNAERATOR_RT_CLASS_NAME); -// for (String lib : availableLibs) -// out.println("\twith " + getLibScalaClassName(lib)); -// out.println("{"); - out.println(" override def main(args : Array[String]) : Unit = {"); - out.println(" "); - out.println(" }"); - out.println("}"); - out.close(); - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Signatures.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Signatures.java deleted file mode 100644 index 884b2ae88..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Signatures.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.HashSet; -import java.util.Set; - -import com.ochafik.lang.jnaerator.parser.Identifier; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; -import com.ochafik.lang.jnaerator.parser.Function; -import com.ochafik.lang.jnaerator.parser.Function.SignatureType; - -public class Signatures { - private final Set - classSignatures = new HashSet(); - - private final Set - variablesSignatures = new HashSet(), - methodsSignatures = new HashSet(); - - public boolean addClass(Identifier sig) { - return classSignatures.add(sig); - } - public boolean addMethod(Function fun) { - return addMethod(fun.computeSignature(SignatureType.JavaStyle)); - } - public boolean addMethod(String sig) { - return methodsSignatures.add(sig); - } - public boolean addVariable(String sig) { - return variablesSignatures.add(sig); - } - /** - * TODO: CLEAN THIS UGLY HACK - * Rewrites function name until its signature doesn't collide anymore with existing signatures - */ - public Identifier findNextMethodName(String originalSignature, Identifier originalName) { - String signature = originalSignature; - Identifier name = originalName; - int n = 1; - while (!methodsSignatures.add(signature)) { - String suffix = "$" + (++n); - name = ident(originalName + suffix); - int i = originalSignature.indexOf("("); - signature = originalSignature.substring(0, i) + suffix + originalSignature.substring(i); - } - return name; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SimpleGUI.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SimpleGUI.java deleted file mode 100644 index 36a4905c8..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SimpleGUI.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.SwingUtilities; - -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.studio.JNAeratorStudio; -import com.ochafik.lang.reflect.DebugUtils; -import com.ochafik.swing.candy.JLinkLabel; -import com.ochafik.util.SystemUtils; - -public class SimpleGUI implements Feedback { - JFrame frame; - JLabel status; - JButton cancelButton; - final JNAeratorConfig config; - final Thread threadToCancel; - private String title; - private String ftitle; - public SimpleGUI(JNAeratorConfig config) { - this.config = config; - frame = new JFrame("JNAerator"); - this.threadToCancel = Thread.currentThread(); - title = config.entryName; - if (title == null) { - //title = StringUtils.implode(conf.libraryByFile.keySet(), ", "); - //if (title.length() == 0) - title = ""; - } - ftitle = "JNAerator : " + title; - frame.getContentPane().add("North", new JLinkLabel(title, new Runnable() {public void run() { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream pout = new PrintStream(bout); - DebugUtils.println(SimpleGUI.this.config, pout); - JTextArea ta = new JTextArea(); - ta.setWrapStyleWord(true); - ta.setLineWrap(true); - ta.setText(new String(bout.toByteArray())); - JScrollPane sp = new JScrollPane(ta); - Dimension s = new Dimension(500, 400); - ta.setMaximumSize(new Dimension(s.width, Integer.MAX_VALUE)); - sp.setMaximumSize(s); - sp.setMinimumSize(s); - sp.setPreferredSize(s); - JOptionPane.showMessageDialog(frame, sp, ftitle, JOptionPane.INFORMATION_MESSAGE); - }})); - frame.getContentPane().add("Center", status = new JLabel("Initializing...")); - frame.setMinimumSize(new Dimension(400, 0)); - frame.getContentPane().add("South", cancelButton = new JButton("Cancel")); - cancelButton.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (finished) { - if (toOpenWhenFinished instanceof File) { - try { - File f = (File)toOpenWhenFinished; - f = f.getAbsoluteFile(); - if (f.isDirectory()) - SystemUtils.runSystemOpenDirectory(f); - else - SystemUtils.runSystemOpenFileParent(f); - - } catch (NoSuchMethodException e1) { - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } else if (toOpenWhenFinished instanceof Throwable) { - - JNAeratorStudio.error(frame, null, null, (Throwable)toOpenWhenFinished); - } - } else { - tryCancel(); - } - } - - }); - cancelButton.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) - tryQuit(); - } - }); - frame.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - tryQuit(); - } - }); - } - void tryQuit() { - if (finished) - System.exit(0); - tryCancel(); - } - - private void tryCancel() { - if (JOptionPane.showConfirmDialog(frame, "Are you sure you want to cancel ?", ftitle, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) { - threadToCancel.interrupt(); - System.exit(0); - } - } - Object toOpenWhenFinished; - boolean finished; - - void show() { - frame.pack(); - frame.setVisible(true); - } - void hide() { - frame.setVisible(false); - } - - public void setStatus(final String string) { - SwingUtilities.invokeLater(new Runnable() { public void run() { - status.setText(string); - }}); - } - - public void setFinished(final File fileToOpen) { - toOpenWhenFinished = fileToOpen; - finished = true; - setStatus("JNAeration completed (hit Escape to quit)"); - SwingUtilities.invokeLater(new Runnable() { public void run() { - String name = fileToOpen.getName(); - cancelButton.setText(fileToOpen.isDirectory() ? - "Open output directory" : - "Show file '" + name + "'" - ); - cancelButton.setToolTipText(fileToOpen.getAbsolutePath()); - }}); - } - @Override - public void setFinished(final Throwable e) { - finished = true; - toOpenWhenFinished = e; - setStatus("JNAeration failed !"); - SwingUtilities.invokeLater(new Runnable() { public void run() { - cancelButton.setText("Show error details"); - cancelButton.setToolTipText(e.toString()); - }}); - } - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - - } - @Override - public void wrappersGenerated(Result result) { - - } - -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SourceFiles.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SourceFiles.java deleted file mode 100644 index ebed9bb12..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/SourceFiles.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.ArrayList; -import java.util.List; - -import com.ochafik.lang.jnaerator.parser.Define; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.SourceFile; -import com.ochafik.lang.jnaerator.parser.Visitor; -import com.ochafik.util.string.StringUtils; - -public class SourceFiles extends Element { - public List defines = new ArrayList(); - public List sourceFiles = new ArrayList(); - - public SourceFiles() { - } - - public SourceFiles(SourceFile sourceFile) { - add(sourceFile); - } - - - @Override - public SourceFiles clone() { - return (SourceFiles) super.clone(); - } - public void accept(Visitor visitor) { - for (SourceFile sourceFile : sourceFiles) - sourceFile.accept(visitor); - - for (Define define : defines) - define.accept(visitor); - } - - public List getSourceFiles() { - return sourceFiles; - } - public List getDefines() { - return defines; - } - public void add(SourceFile sourceFile) { - sourceFiles.add(sourceFile); - } - - @Override - public String toString() { - return StringUtils.implode(sourceFiles, "\n"); - } - - @Override - public Element getNextChild(Element child) { - return getNextSibling(sourceFiles, child); - } - - @Override - public Element getPreviousChild(Element child) { - return getPreviousSibling(sourceFiles, child); - } - - @Override - public boolean replaceChild(Element child, Element by) { - if (replaceChild(defines, Define.class, this, child, by)) - return true; - - return replaceChild(sourceFiles, SourceFile.class, this, child, by); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Symbols.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Symbols.java deleted file mode 100644 index 1db8bdaf7..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/Symbols.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.util.Map; -import java.util.HashMap; -import com.ochafik.lang.jnaerator.parser.*; -import static com.ochafik.lang.jnaerator.parser.Statement.*; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; -import com.ochafik.lang.jnaerator.parser.TypeRef.*; -import com.ochafik.lang.jnaerator.parser.Expression.*; -import com.ochafik.lang.jnaerator.parser.Declarator.*; -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -public class Symbols { - public final Map resolvedVariables = new HashMap(); - public final Map resolvedTypes = new HashMap(); - public final Map elementTables = new HashMap(); - public Element getType(Identifier ident) { - return resolvedTypes.get(ident.getId()); - } - public Element getVariable(Identifier ident) { - return resolvedVariables.get(ident.getId()); - } - public SymbolTable getEnclosingSymbolTable(Element element) { - while (element != null) { - SymbolTable st = elementTables.get(element); - if (st != null) - return st; - element = element.getParentElement(); - } - return null; - } - public boolean isClassType(TypeRef tr) { - if (tr instanceof SimpleTypeRef) - return getType(((SimpleTypeRef)tr).getName()) instanceof Struct; - return false; - } - public boolean isEnumType(TypeRef tr) { - if (tr instanceof SimpleTypeRef) - return getType(((SimpleTypeRef)tr).getName()) instanceof com.ochafik.lang.jnaerator.parser.Enum; - return false; - } - public boolean isEnumItem(Identifier ident) { - Element v = getVariable(ident); - if (v instanceof Declarator) - v = ((Declarator)v).getParentElement(); - if (v instanceof Declaration) - v = ((Declaration)v).getValueType(); - - Element type; - if (v instanceof SimpleTypeRef) - return getType(((SimpleTypeRef)v).getName()) instanceof com.ochafik.lang.jnaerator.parser.Enum; - - return false; // TODO ? - } - public static class SymbolTable { - public final SymbolTable parent; - public final Symbols symbols; - public final Map variableDefinitions = new HashMap(); - public final Map typeDefinitions = new HashMap(); - public final Identifier subNamespace; - public final Element owner; - - public SymbolTable(Symbols symbols) { - this.parent = null; - this.symbols = symbols; - this.owner = null; - this.subNamespace = null; - } - public SymbolTable(SymbolTable parent, Identifier subNamespace, Element owner) { - this.parent = parent; - this.symbols = parent.symbols; - this.subNamespace = subNamespace; - this.owner = owner; - if (owner != null) - symbols.elementTables.put(owner, this); - } - public void defineVariable(String name, Element element) { - defineVariable(ident(name), element); - } - public void defineVariable(Identifier name, Element element) { - variableDefinitions.put(name, element); - } - public void defineType(Identifier name, Element element) { - typeDefinitions.put(name, element); - } - public Element resolveVariable(Identifier ident) { - return resolve(ident, true); - } - public Element resolveType(Identifier ident) { - return resolve(ident, false); - } - private Element resolve(Identifier ident, boolean varOrType) { - if (ident == null) - return null; - // TODO handle new namespace - Identifier lastIdent = ident.resolveLastSimpleIdentifier(); - Element resolved = (varOrType ? variableDefinitions : typeDefinitions).get(lastIdent); - if (resolved == null) { - if (parent != null) - return parent.resolve(ident, varOrType); - //if (ident.getParentElement() instanceof TypeRef && ident.getParentElement().getParentElement() instanceof VariablesDeclaration) - // System.out.println("hehehe"); - return null; - } - //System.out.println("Resolved " + ident + " as " + resolved); - //System.err.println("Resolved " + ident + " as " + resolved); - (varOrType ? symbols.resolvedVariables : symbols.resolvedTypes).put(ident.getId(), resolved); - return resolved; - } - } - static Symbols resolveSymbols(Element root) { - Symbols symbols = new Symbols(); - final SymbolTable rootTable = new SymbolTable(symbols); - root.accept(new Scanner() { - SymbolTable currentTable = rootTable; - - /*public void visitTypeRef(TypeRef element) { - super.visitTypeRef(element); - }*/ - public void visitSimpleTypeRef(SimpleTypeRef element) { - super.visitSimpleTypeRef(element); - currentTable.resolveType(element.getName()); - } - public void visitVariableRef(VariableRef element) { - super.visitVariableRef(element); - currentTable.resolveVariable(element.getName()); - } - - @Override - public void visitArg(final Arg element) { - super.visitArg(element); - currentTable.defineVariable(element.getName(), element); - } - @Override - public void visitDirectDeclarator(final DirectDeclarator element) { - super.visitDirectDeclarator(element); - currentTable.defineVariable(element.getName(), element); - } - @Override - public void visitBlock(final Block element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitBlock(element); - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitFunction(final Function element) { - currentTable.defineVariable(element.getName(), element); - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitFunction(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitStruct(final Struct element) { - currentTable.defineType(element.getTag(), element); - currentTable = new SymbolTable(currentTable, element.getTag(), element); - try { - super.visitStruct(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitNamespace(final Namespace element) { - currentTable = new SymbolTable(currentTable, element.getName(), element); - try { - super.visitNamespace(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitFor(final For element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitFor(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitIf(final If element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitIf(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitTry(final Try element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitTry(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitCatch(final Catch element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitCatch(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitWhile(final While element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitWhile(element); - - } finally { - currentTable = currentTable.parent; - } - } - @Override - public void visitDoWhile(final DoWhile element) { - currentTable = new SymbolTable(currentTable, null, element); - try { - super.visitDoWhile(element); - - } finally { - currentTable = currentTable.parent; - } - } - }); - - return symbols; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java deleted file mode 100644 index 753d76185..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java +++ /dev/null @@ -1,1849 +0,0 @@ -/* -Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - -This file is part of JNAerator (http://jnaerator.googlecode.com/). - -JNAerator is free software: you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -JNAerator is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with JNAerator. If not, see . - */ -package com.ochafik.lang.jnaerator; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; - -import java.lang.reflect.Method; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Pattern; - -import org.rococoa.ObjCClass; -import org.rococoa.ObjCObject; -import org.rococoa.cocoa.foundation.NSObject; - -import org.bridj.util.DefaultParameterizedType; -import com.ochafik.lang.SyntaxUtils; -import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; -import com.ochafik.lang.jnaerator.parser.Enum; -import com.ochafik.lang.jnaerator.parser.*; -import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; -import com.ochafik.lang.jnaerator.parser.Declarator.MutableByDeclarator; -import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; -import com.ochafik.lang.jnaerator.parser.Expression.Constant; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; -import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; -import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; -import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; -import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; -import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; -import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; -import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.TargettedTypeRef; -import com.ochafik.lang.jnaerator.runtime.CGFloatByReference; -import com.ochafik.lang.jnaerator.runtime.CharByReference; -import com.ochafik.lang.jnaerator.runtime.NativeSize; -import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; -import com.ochafik.lang.jnaerator.runtime.globals.Global; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalByte; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalCGFloat; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalChar; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalFloat; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalLong; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeLong; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeSize; -import com.ochafik.lang.jnaerator.runtime.globals.GlobalShort; -import com.ochafik.util.listenable.Pair; -import com.ochafik.util.string.StringUtils; -import com.sun.jna.Native; -import com.sun.jna.WString; -import com.sun.jna.ptr.ByReference; -import com.sun.jna.ptr.ByteByReference; -import com.sun.jna.ptr.DoubleByReference; -import com.sun.jna.ptr.FloatByReference; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.LongByReference; -import com.sun.jna.ptr.NativeLongByReference; -import com.sun.jna.ptr.PointerByReference; -import com.sun.jna.ptr.ShortByReference; - -public abstract class TypeConversion implements ObjCppParser.ObjCParserHelper { - - Result result; - public boolean allowUnknownPointers = true, allowFakePointers = false; - - public TypeConversion(Result result) { - super(); - this.result = result; - initTypes(); - } - - //public Set fakePointersSink; - public enum TypeConversionMode { - - PrimitiveOrBufferParameter, - NativeParameter, - NativeParameterWithStructsPtrPtrs, - FieldType, - ReturnType, - ExpressionType, - StaticallySizedArrayField, - PrimitiveReturnType, - PointedValue - } - public Map> primToByReference = new HashMap>(); - public Map> primToGlobal = new HashMap>(); - public Map> primToBuffer = new HashMap>(); - public final Set byReferenceClassesNames = new HashSet(); - - public boolean isObjCppPrimitive(String s) { - return result.isObjCppPrimitive(s); - } - - public enum JavaPrim { - - Void(java.lang.Void.TYPE, null, ESize.Zero), - Char(Character.TYPE, Character.class, ESize.CharSize), - Long(java.lang.Long.TYPE, java.lang.Long.class, ESize.Eight), - Int(Integer.TYPE, Integer.class, ESize.Four), - Short(java.lang.Short.TYPE, java.lang.Short.class, ESize.Two), - Byte(java.lang.Byte.TYPE, java.lang.Byte.class, ESize.One), - Boolean(java.lang.Boolean.TYPE, java.lang.Boolean.class, ESize.One), - Float(java.lang.Float.TYPE, java.lang.Float.class, ESize.Four), - Double(java.lang.Double.TYPE, java.lang.Double.class, ESize.Eight), - ComplexDouble(null, null, ESize.Sixteen), - NativeLong(com.sun.jna.NativeLong.class, com.sun.jna.NativeLong.class, ESize.StaticSizeField), - NativeSize(NativeSize.class, NativeSize.class, ESize.StaticSizeField), - NSInteger(org.rococoa.cocoa.foundation.NSInteger.class, org.rococoa.cocoa.foundation.NSInteger.class, ESize.StaticSizeField), - NSUInteger(org.rococoa.cocoa.foundation.NSUInteger.class, org.rococoa.cocoa.foundation.NSUInteger.class, ESize.StaticSizeField), - CGFloat(org.rococoa.cocoa.CGFloat.class, org.rococoa.cocoa.CGFloat.class, ESize.StaticSizeField); - public final Class type, wrapperType; - public final String simpleName, name; - public final boolean isPrimitive; - - public enum ESize { - - One(expr(1)), - Two(expr(2)), - Four(expr(4)), - Eight(expr(8)), - Sixteen(expr(16)), - StaticSizeField(null) { - - @Override - public Expression sizeof(JavaPrim p) { - return staticField(p.type, "SIZE"); - } - }, - CharSize(null) { - - @Override - public Expression sizeof(JavaPrim p) { - return staticField(Native.class, "WCHAR_SIZE"); - } - }, - Zero(expr(0)); - private final Expression sizeOfExpression; - - ESize(Expression sizeOfExpression) { - this.sizeOfExpression = sizeOfExpression; - } - - public Expression sizeof(JavaPrim p) { - return sizeOfExpression.clone(); - } - } - public final ESize size; - private static Map nameToPrim; - - public static JavaPrim getJavaPrim(String name) { - if (nameToPrim == null) { - nameToPrim = new HashMap(); - for (JavaPrim p : values()) { - nameToPrim.put(p.simpleName, p); - } - } - return nameToPrim.get(name); - } - - JavaPrim(Class type, Class wrapperType, ESize size) { - this.type = type; - this.wrapperType = wrapperType; - this.size = size; - this.name = type == null ? null : type.getName(); - this.isPrimitive = type == null || type.isPrimitive(); - this.simpleName = type == null ? null : type.getSimpleName(); - } - } - - public Expression typeLiteral(TypeRef c) { - if (c != null && c.toString().equals("?")) - return Constant.newNull(); - - if (c instanceof SimpleTypeRef && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { - Identifier id = ((SimpleTypeRef) c).getName(); - SimpleIdentifier sid = id.resolveLastSimpleIdentifier(); - if (!sid.getTemplateArguments().isEmpty()) { - Identifier erased = id.eraseTemplateArguments(); - - List exprs = new ArrayList(); - exprs.add(typeLiteral(typeRef(erased.clone()))); - for (Expression t : sid.getTemplateArguments()) { - if (t instanceof Expression.TypeRefExpression) { - exprs.add(typeLiteral(((Expression.TypeRefExpression) t).getType().clone())); - } - } - return methodCall(expr(typeRef(DefaultParameterizedType.class)), "paramType", exprs.toArray(new Expression[exprs.size()])); - } - } - return memberRef(expr(c), MemberRefStyle.Dot, "class"); - } - - protected abstract JavaPrim getCppBoolMappingType(); - - public void initTypes() { - - result.prim("void", JavaPrim.Void); - - result.prim("UTF32Char", JavaPrim.Char); - result.prim("unichar", JavaPrim.Char); - - result.prim("int64_t", JavaPrim.Long); - result.prim("uint64_t", JavaPrim.Long); - result.prim("u_int64_t", JavaPrim.Long); - result.prim("long long", JavaPrim.Long); - result.prim("long long int", JavaPrim.Long); - result.prim("long int", JavaPrim.Int); - result.prim("LONGLONG", JavaPrim.Long); - result.prim("ULONGLONG", JavaPrim.Long); - result.prim("INT", JavaPrim.Int); - result.prim("UINT", JavaPrim.Int); - result.prim("SHORT", JavaPrim.Short); - result.prim("USHORT", JavaPrim.Short); - result.prim("BYTE", JavaPrim.Byte); - result.prim("UBYTE", JavaPrim.Byte); - result.prim("DOUBLE", JavaPrim.Double); - result.prim("FLOAT", JavaPrim.Float); - result.prim("WORD", JavaPrim.Short); - result.prim("DWORD", JavaPrim.Int); - - if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) - result.prim("BOOL", JavaPrim.Int); - else - result.prim("BOOL", JavaPrim.Boolean); - - - result.prim("DWORD64", JavaPrim.Long); - result.prim("LONG64", JavaPrim.Long); - result.prim("UInt64", JavaPrim.Long); - result.prim("SInt64", JavaPrim.Long); - result.prim("__int64", JavaPrim.Long); - result.prim("__int64_t", JavaPrim.Long); - - result.prim("int32_t", JavaPrim.Int); - result.prim("uint32_t", JavaPrim.Int); - result.prim("__int32_t", JavaPrim.Int); - result.prim("__uint32_t", JavaPrim.Int); - result.prim("u_int32_t", JavaPrim.Int); - result.prim("uint32", JavaPrim.Int); - result.prim("int32", JavaPrim.Int); - result.prim("int", JavaPrim.Int); - //prim("NSUInteger", JavaPrim.NativeSize); - //prim("NSInteger", JavaPrim.NativeSize); - result.prim("SInt32", JavaPrim.Int); - result.prim("UInt32", JavaPrim.Int); - result.prim("GLint", JavaPrim.Int); - result.prim("GLuint", JavaPrim.Int); - result.prim("GLenum", JavaPrim.Int); - result.prim("GLsizei", JavaPrim.Int); - result.prim("__darwin_size_t", JavaPrim.Int); - - result.prim("__int32", JavaPrim.Int); - - result.prim("NSInteger", JavaPrim.NSInteger); - result.prim("NSUInteger", JavaPrim.NSUInteger); - result.prim("CGFloat", JavaPrim.CGFloat); - - JavaPrim longPrim = result.config.gccLong ? JavaPrim.NativeSize : JavaPrim.NativeLong; - result.prim("long", longPrim); - result.prim("LONG", longPrim); - result.prim("ULONG", longPrim); - - JavaPrim sizePrim = result.config.sizeAsLong ? longPrim : JavaPrim.NativeSize; - result.prim("size_t", sizePrim); - result.prim("ptrdiff_t", sizePrim); - - result.prim("complex double", JavaPrim.ComplexDouble); - - result.prim("int16_t", JavaPrim.Short); - result.prim("uint16_t", JavaPrim.Short); - result.prim("__int16_t", JavaPrim.Short); - result.prim("__uint16_t", JavaPrim.Short); - result.prim("u_int16_t", JavaPrim.Short); - result.prim("uint16", JavaPrim.Short); - result.prim("int16", JavaPrim.Short); - result.prim("SInt16", JavaPrim.Short); - result.prim("UInt16", JavaPrim.Short); - result.prim("short", JavaPrim.Short); - result.prim("WCHAR", JavaPrim.Short); - result.prim("wchar_t", result.config.wcharAsShort ? JavaPrim.Short : JavaPrim.Char); - - result.prim("__int16", JavaPrim.Short); - - - result.prim("int8_t", JavaPrim.Byte); - result.prim("uint8_t", JavaPrim.Byte); - result.prim("u_int8_t", JavaPrim.Byte); - result.prim("__uint8_t", JavaPrim.Byte); - result.prim("__int8_t", JavaPrim.Byte); - result.prim("SInt8", JavaPrim.Byte); - result.prim("UInt8", JavaPrim.Byte); - result.prim("char", JavaPrim.Byte); - result.prim("unsigned char", JavaPrim.Byte); - result.prim("__unsigned char", JavaPrim.Byte); - result.prim("signed char", JavaPrim.Byte); - result.prim("__signed char", JavaPrim.Byte); - result.prim("SignedByte", JavaPrim.Byte); - - result.prim("__int8", JavaPrim.Byte); - - result.prim("float", JavaPrim.Float); - result.prim("NSFloat", JavaPrim.Float); - result.prim("CGFloat", JavaPrim.Float); - - result.prim("double_t", JavaPrim.Double); - result.prim("double", JavaPrim.Double); - result.prim("NSDouble", JavaPrim.Double); - result.prim("CGDouble", JavaPrim.Double); - - JavaPrim cppBoolType = getCppBoolMappingType(); - result.prim("bool", cppBoolType); - result.prim("Boolean", cppBoolType); - result.prim("boolean_t", cppBoolType); - - - - primToByReference.put(JavaPrim.Int, IntByReference.class); - primToByReference.put(JavaPrim.Char, CharByReference.class); - primToByReference.put(JavaPrim.Short, ShortByReference.class); - primToByReference.put(JavaPrim.Byte, ByteByReference.class); - primToByReference.put(JavaPrim.Long, LongByReference.class); - primToByReference.put(JavaPrim.Float, FloatByReference.class); - primToByReference.put(JavaPrim.Double, DoubleByReference.class); - primToByReference.put(JavaPrim.NativeLong, NativeLongByReference.class); - primToByReference.put(JavaPrim.NativeSize, NativeSizeByReference.class); - primToByReference.put(JavaPrim.NSInteger, NativeSizeByReference.class); - primToByReference.put(JavaPrim.NSUInteger, NativeSizeByReference.class); - primToByReference.put(JavaPrim.CGFloat, CGFloatByReference.class); - - //primsByReference.put(JavaPrim.Void, PointerByReference.class); - for (Class c : primToByReference.values()) { - byReferenceClassesNames.add(c.getName()); - } -// byReferenceClassesNames.add(PointerByReference.class.getName()); - - primToGlobal.put(JavaPrim.Int, GlobalInt.class); - primToGlobal.put(JavaPrim.Char, GlobalChar.class); - primToGlobal.put(JavaPrim.Short, GlobalShort.class); - primToGlobal.put(JavaPrim.Byte, GlobalByte.class); - primToGlobal.put(JavaPrim.Long, GlobalLong.class); - primToGlobal.put(JavaPrim.Float, GlobalFloat.class); - primToGlobal.put(JavaPrim.Double, GlobalDouble.class); - primToGlobal.put(JavaPrim.NativeLong, GlobalNativeLong.class); - primToGlobal.put(JavaPrim.NativeSize, GlobalNativeSize.class); - primToGlobal.put(JavaPrim.NSInteger, GlobalNativeSize.class); - primToGlobal.put(JavaPrim.NSUInteger, GlobalNativeSize.class); - primToGlobal.put(JavaPrim.CGFloat, GlobalCGFloat.class); - - primToBuffer.put(JavaPrim.Int, IntBuffer.class); - primToBuffer.put(JavaPrim.Char, CharBuffer.class); - primToBuffer.put(JavaPrim.Short, ShortBuffer.class); - primToBuffer.put(JavaPrim.Byte, ByteBuffer.class); - primToBuffer.put(JavaPrim.Long, LongBuffer.class); - primToBuffer.put(JavaPrim.Float, FloatBuffer.class); - primToBuffer.put(JavaPrim.Double, DoubleBuffer.class); - //primToBuffer.put(JavaPrim.NativeLong, NativeLongByReference.class); - - TypeRef pInt = new TypeRef.Pointer(new Primitive("int"), Declarator.PointerStyle.Pointer); - result.addManualTypeDef("intptr_t", pInt); - result.addManualTypeDef("uintptr_t", pInt); - } - - protected TypeRef findTypeRef(Identifier name, Identifier libraryClassName) { - TypeRef tr; - tr = findStructRef(name, libraryClassName); - if (tr != null) - return tr; - - tr = findEnum(name, libraryClassName); - if (tr != null) - return tr; - - tr = findCallbackRef(name, libraryClassName); - if (tr != null) - return tr; - - tr = findObjCClass(name); - if (tr != null) - return tr; - - tr = result.manualTypeDefs.get(name); - if (tr != null) - return tr; - - return null; - } - boolean isResoluble(TypeRef tr, Identifier libraryClassName) { - return isResoluble(tr, libraryClassName, new HashSet()); - } - boolean isResoluble(TypeRef tr, Identifier libraryClassName, Set typeDefsEncountered) { - if (tr instanceof Primitive || - tr instanceof FunctionSignature || - tr instanceof TaggedTypeRef) - { - return true; - } else if (tr instanceof TargettedTypeRef) { - return isResoluble(((TargettedTypeRef)tr).getTarget(), libraryClassName, typeDefsEncountered); - } else if (tr instanceof SimpleTypeRef) { - Identifier name = ((SimpleTypeRef)tr).getName(); - TypeRef tdt = typeDefsEncountered.add(name) ? result.getTypeDef(name) : null; - if (tdt != null) { - return isResoluble(tdt, libraryClassName, typeDefsEncountered); - } else { - TypeRef ft = findTypeRef(name, libraryClassName); - return ft != null; - } - } - return false; - } - public TypeRef resolveTypeDef(TypeRef valueType, final Identifier libraryClassName, final boolean convertToJavaRef, final boolean convertEnumToJavaRef) { - return resolveTypeDef(valueType, libraryClassName, convertToJavaRef, convertEnumToJavaRef, new HashSet()); - } - public TypeRef resolveTypeDef(TypeRef valueType, final Identifier libraryClassName, final boolean convertToJavaRef, final boolean convertEnumToJavaRef, final Set typeDefsEncountered) { - if (valueType == null) { - return null; - } - -// if (valueType.toString().equals("CGFunctionEvaluateCallback")) -// valueType = valueType; - - if (valueType instanceof TaggedTypeRef && convertToJavaRef) { - TaggedTypeRef ttr = (TaggedTypeRef) valueType; - if (ttr.getTag() != null) { - - TypeRef ref = ttr instanceof Struct ? findStructRef(ttr.getTag(), libraryClassName) - : ttr instanceof Enum && convertEnumToJavaRef ? findEnum(ttr.getTag(), libraryClassName) : null; - if (ref == null && convertEnumToJavaRef) { - return ref; - } - } - } - final TypeRef valueTypeCl = valueType.clone(); - Arg holder = new Arg(); - holder.setValueType(valueTypeCl); - holder.setParentElement(valueType.getParentElement()); - holder.accept(new Scanner() { - - java.util.Stack names = new java.util.Stack(); - int depth = 0; - - @Override - public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { - depth++; - - try { - Identifier name = ((SimpleTypeRef) simpleTypeRef).getName(); - if (name == null) { - return; - } - - String nameStr = name.toString(); - if (nameStr == null) { - return; - } - - if (JavaPrim.getJavaPrim(nameStr) != null) { - return; - } - - if (names.contains(nameStr)) { - return; - } - names.push(nameStr); - - try { - if (result.resolvePrimitive(nameStr) != null) { - return; - } - - super.visitSimpleTypeRef(simpleTypeRef); - if (simpleTypeRef.isMarkedAsResolved()) { - return; - } - - // Identifier oc = findObjCClassIdent(name); - // if (oc != null) { - // name.replaceBy(oc); - // } - - if (convertToJavaRef) { - TypeRef t = findTypeRef(name, libraryClassName); - if (t != null) { - if (!convertToJavaRef || (t instanceof Enum) && !convertEnumToJavaRef) { - return; - } - simpleTypeRef.replaceBy(t); - } - } - - Define define = result.defines.get(name); - Expression expression = define == null ? null : define.getValue(); - if (expression != null) { - if (!convertToJavaRef) { - return; - } - Identifier fieldName = null; - if (expression instanceof Expression.VariableRef) { - fieldName = ((Expression.VariableRef) expression).getName(); - } else if (expression instanceof MemberRef) { - fieldName = ((MemberRef) expression).getName(); - } - - if (fieldName != null && !fieldName.equals(name)) { - simpleTypeRef.replaceBy(resolveTypeDef(new TypeRef.SimpleTypeRef(fieldName), libraryClassName, true /*convertToJavaRef*/, convertEnumToJavaRef, typeDefsEncountered)); - return; - } - } - - TypeRef tr = typeDefsEncountered.add(name) ? result.getTypeDef(name) : null; - if (tr != null) { - if (!isResoluble(tr, libraryClassName)) { - simpleTypeRef.replaceBy(typeRef(result.getFakePointer(libraryClassName, name))); - return; - } - - if (tr instanceof Enum && !convertEnumToJavaRef) { - simpleTypeRef.replaceBy(typeRef(int.class)); - return; - } - if (tr instanceof TaggedTypeRef) { - Identifier name2 = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) tr); - if (name2 != null) { - name = name2; - } - } - if (convertToJavaRef) { - if (tr instanceof TaggedTypeRef) { - TaggedTypeRef s = (TaggedTypeRef) tr; - if (s.isForwardDeclaration()) { - return; - } - -// if (tr instanceof Enum) { -// tr = typeRef(s.getTag().clone()); -// } else { - Identifier ident = result.getTaggedTypeIdentifierInJava(s); - if (ident != null) { - tr = typeRef(ident);//findRef(name, s, libraryClassName)); - }// } - } else if (tr instanceof FunctionSignature) { - tr = findCallbackRef((FunctionSignature) tr, libraryClassName); - } - } - String strs = simpleTypeRef.toString(); - String trs = tr == null ? null : tr.toString(); - if (trs != null && !strs.equals(trs)) { - TypeRef clo = tr.clone(); - simpleTypeRef.replaceBy(clo); - if (depth < 30) { - clo.accept(this); - } else { - System.err.println("Infinite loop in type conversion ? " + tr); - } - } - return; - } - } finally { - names.pop(); - } - } finally { - depth--; - } - } - - - }); - TypeRef tr = holder.getValueType(); -// tr.setParentElement(valueType.getParentElement()); - return tr == null ? null : tr == valueTypeCl ? valueType : tr.clone(); - } -// TypeRef getPrimitiveRef(TypeRef valueType, String callerLibraryClass) { -// JavaPrim prim = getPrimitive(valueType, callerLibraryClass); -// if (prim == null) -// return null; -// -// TypeRef tr = typeRef(prim); -// if (valueType.isUnsigned()) -// tr.addAnnotation(new Annotation(Unsigned.class)); -// if (valueType.isUnsigned()) -// tr.addAnnotation(new Annotation(Unsigned.class)); -// -// return tr; -// } - - public static class JavaPrimitive extends Primitive { - - JavaPrim javaPrim; - - public JavaPrimitive() { - } - - public JavaPrimitive(JavaPrim javaPrim) { - super(); - setName(ident(javaPrim == JavaPrim.Void ? Void.TYPE : javaPrim.type)); - this.javaPrim = javaPrim; - } - - public JavaPrim getJavaPrim() { - return javaPrim; - } - - public void setJavaPrim(JavaPrim javaPrim) { - this.javaPrim = javaPrim; - } - } - - public JavaPrim getPrimitive(TypeRef valueType, Identifier libraryClassName) { - if (!(valueType instanceof Primitive) && !(valueType instanceof JavaPrimitive)) { - valueType = resolveTypeDef(valueType, libraryClassName, true, true); - } - if (valueType == null) { - return null; - } - Identifier name = null; - List mods = valueType.getModifiers(); - int longCount = ModifierType.Long.countIn(mods); - if (valueType instanceof JavaPrimitive) { - return ((JavaPrimitive) valueType).getJavaPrim(); - } - if (valueType instanceof Primitive) { - name = ((Primitive) valueType).getName(); - if (name == null) { - if (longCount == 1) { - name = ident("long"); - } else if (longCount > 1) { - name = ident("long long"); - } else if (valueType.hasModifier(ModifierType.Short)) { - name = ident("short"); - } else { - name = ident("int"); - } - } - } else if (valueType instanceof SimpleTypeRef) { - name = ((SimpleTypeRef) valueType).getName(); - } - - - if (name == null) { - return null; - } - - JavaPrim p = JavaPrim.getJavaPrim(name.toString()); - if (p != null && !p.isPrimitive) { - return p; - } - - boolean isLong = false; - String str; -// if ((isLong = valueType.hasModifier(ModifierType.Long)) || valueType.hasModifier(ModifierType.Short)) { -// //if ((isLong = valueType.hasModifier(ModifierType.Long)) || valueType.hasModifier(ModifierType.Short)) { -// str = (isLong ? "long " : "short ") + name; -// } else { - str = name.toString(); -// } - - JavaPrim type = result.resolvePrimitive(str); - if (type == JavaPrim.Int && longCount > 1) { - return JavaPrim.Long; - } - - if (type == JavaPrim.Double && valueType.hasModifier(ModifierType._Complex)) { - return JavaPrim.ComplexDouble; - } - return type; - } - - public SimpleTypeRef findStructRef(Identifier name, Identifier libraryClassName) { - return findStructRef(result.resolveStruct(name), libraryClassName); - } - - public SimpleTypeRef findStructRef(Struct s, Identifier name, Identifier libraryClassName) { - if (s == null || s.isForwardDeclaration()) { - TypeRef td = result.getTypeDef(name); - if (!(td instanceof Struct)) { - return null; - } - s = (Struct) td; - } - if (s == null && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { - String ns = name.toString(); - Class cl = null; - if (ns.equals("IUnknown")) - cl = org.bridj.cpp.com.IUnknown.class; - else if (ns.equals("GUID")) - cl = org.bridj.cpp.com.GUID.class; - else if (ns.equals("RECT")) - cl = org.bridj.cpp.com.RECT.class; - - if (cl != null) - return typeRef(ident(cl)); - } - return typeRef(result.getTaggedTypeIdentifierInJava(s)); - /* - name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) pair.getFirst().getValueType()); - - return findRef(name, s, libraryClassName, !result.config.putTopStructsInSeparateFiles); - } else { - return result.getTaggedTypeIdentifierInJava(s); - //name = result.declarationsConverter.getActualTaggedTypeName(s); - }*/ - } - - public SimpleTypeRef findStructRef(Struct s, Identifier libraryClassName) { - if (s == null) - return null; - switch (s.getType()) { - case ObjCClass: - case ObjCProtocol: - return typeRef(result.objectiveCGenerator.getFullClassName(s)); - default: - return findStructRef(s, result.declarationsConverter.getActualTaggedTypeName(s), libraryClassName); - } - } -// public String find(String name, Element e, String callerLibraryClass) { -// if (e == null) -// return null; -// String library = result.getLibrary(e); -// if (library == null) -// return null; -// SimpleIdentifier libClass = result.getLibraryClassFullName(library); -// return SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name; -// } - - public Identifier libMember(Identifier libClass, Identifier libraryClassName, Identifier member) { - //return ident(SyntaxUtils.equal(libClass, libraryClassName) ? null : libClass, member); - return ident(libClass, member); - //return member; //TODODODODODODODODOoOOOOO - } - - public Identifier findRef(Identifier name, Element e, Identifier libraryClassName, boolean inLibClass) { - if (e == null || !name.isPlain()) { - return null; - } - String library = result.getLibrary(e); - if (library == null) { - return null; - } - -// e = e.getParentElement(); - Struct parentStruct = e instanceof Struct ? (Struct) e : e.findParentOfType(Struct.class); - if (!inLibClass && parentStruct != null) { - if (parentStruct == e) { - return ident(result.getLibraryPackage(library), name); - } - - return ident(result.getTaggedTypeIdentifierInJava(parentStruct), name); - } - return libMember(result.getLibraryClassFullName(library), libraryClassName, name); - } - public SimpleTypeRef findEnum(Identifier name, Identifier libraryClassName) { - return findEnum(result.resolveEnum(name), libraryClassName); - } - - public SimpleTypeRef findEnum(Enum s, Identifier libraryClassName) { - if (s == null) - return null; - - if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) - return typeRef(result.getTaggedTypeIdentifierInJava(s)); - - Identifier name = result.declarationsConverter.getActualTaggedTypeName(s); - - String library = result.getLibrary(s); - if (library == null) { - return null; - } - Identifier libClass = result.getLibraryClassFullName(library); - //return new SimpleTypeRef(SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name); - - /*if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { - return typeRef(findRef(name, s, libraryClassName, result.config.putTopStructsInSeparateFiles)); - }*/ - SimpleTypeRef tr = new SimpleTypeRef("int"); - if (result.config.features.contains(JNAeratorConfig.GenFeatures.EnumTypeLocationComments)) { - tr.setCommentBefore("@see " + (SyntaxUtils.equal(libClass, libraryClassName) ? name : libClass + "#" + name)); - } -// if (s.getTag() != null) -// tr.setCommentBefore("@see enums in " + s.getTag()); - return tr; - } - - public static Expression javaStaticFieldRef(Identifier javaClass, Identifier fieldName) { - return memberRef( - expr(typeRef(javaClass)), - MemberRefStyle.Dot, - fieldName); - } - - public Expression findDefine(Identifier name) { - Define s = result.defines.get(name); - String library = s == null ? null : result.getLibrary(s); - return library == null ? null : javaStaticFieldRef(result.getLibraryClassFullName(library), name); - } - - public Identifier inferCallBackName(FunctionSignature functionSignature, boolean prependNamespaces, boolean qualify, Identifier libraryClassName) { - List nameElements = new ArrayList(); - Identifier name = functionSignature.getFunction().getName(); - if (name != null) { - name = name.clone(); - } - - Identifier parentIdent = null; - - Element parent = functionSignature.getParentElement(); - - boolean firstParent = true; - while (parent != null) { - if (parent instanceof Struct) { - SimpleTypeRef parentRef = findStructRef((Struct) parent, null); - if (parentRef != null) { - parentIdent = parentRef.getName(); - break; - } - } - if (firstParent) { - if (name == null && parent instanceof TypeDef) { - Declarator simpleSto = null; - for (Declarator sto : ((TypeDef) parent).getDeclarators()) { - String stoName = sto.resolveName(); - if (stoName == null) { - continue; - } - - if (!(sto instanceof ArrayDeclarator)) { - boolean weirdName = stoName.startsWith("_") || stoName.endsWith("_"); - if (simpleSto == null || (simpleSto.resolveName().startsWith("_") || simpleSto.resolveName().endsWith("_")) && !weirdName) { - simpleSto = sto; - } - - if (!weirdName) { - break; - } - } - if (stoName != null) { - name = new SimpleIdentifier(stoName); - } - } - } else if (name == null && parent instanceof Arg) { - Arg arg = (Arg) parent; - Function f = SyntaxUtils.as(arg.getParentElement(), Function.class); - if (f != null) { - name = new SimpleIdentifier(f.getName() + "_" + arg.getName()); - break; - } - } else if (firstParent) { -// if (//parent instanceof VariablesDeclaration || -// parent instanceof FunctionPointerDeclaration -// //|| parent instanceof TypeDef -// ) { -// nameElements.add("Callback"); -// } - } - } - parent = parent.getParentElement(); - firstParent = false; - } - - if (qualify && parentIdent == null) { - //if (libraryClassName != null) - // parentIdent = libraryClassName; - //else { - String library = result.getLibrary(functionSignature); - if (library != null) { - parentIdent = result.getLibraryClassFullName(library); - } - //} - } - - if (prependNamespaces) { - if (name == null) { - name = new SimpleIdentifier("callback"); - } - - nameElements.add(name.toString()); - return ident(qualify ? parentIdent : null, StringUtils.implode(nameElements, "_")); - } else { - return ident(qualify ? parentIdent : null, name); - } - } - - public TypeRef findCallbackRef(Identifier name, Identifier libraryClassName) { - FunctionSignature s = result.resolveCallback(name); - if (s == null) { - return null; - } - -// Struct parentStruct = s.findParentOfType(Struct.class); -// if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { -// //Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); -// return //result.result.getObjCClass(parentStruct.getName()). -// typeRef(//libMember(structName, libraryClassName, -// inferCallBackName(s, true, true)//) -// ); -// } - return findCallbackRef(s, libraryClassName); - } - - public TypeRef findCallbackRef(FunctionSignature s, Identifier callerLibraryClass) { - String library = s == null ? null : result.getLibrary(s); - if (library == null) { - return null; - } - -// Struct parentStruct = s.findParentOfType(Struct.class); -// if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { -// Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); -// return -// typeRef(ident(structName, inferCallBackName(s, true, true))); -// } - Identifier identifier = s.getResolvedJavaIdentifier(); - if (identifier == null) - throw new UnsupportedConversionException(s, null); - return typeRef(identifier); -// return typeRef(libMember(result.getLibraryClassFullName(library), callerLibraryClass, inferCallBackName(s, true, true))); - //typeRef(ident(result.getLibraryClassFullName(library), inferCallBackName(s, true))); - } - - static TypeRef primRef(JavaPrim p) { - if (p == null) { - return null; - } - - return new JavaPrimitive(p); -// return new SimpleTypeRef(toString(p)); - } - - boolean isResolved(SimpleTypeRef tr) { - return tr != null && (tr.isMarkedAsResolved() || isResolved(tr.getName())); - } - - boolean isResolved(Identifier i) { - if (i == null || i.isPlain()) { - return false; - } - return (i instanceof Identifier.QualifiedIdentifier) - && Identifier.QualificationSeparator.Dot.equals(((Identifier.QualifiedIdentifier) i).getSeparator()); - } - - public enum ConvType { - Enum, - Pointer, - Primitive, - Struct, - NativeLong, - NativeSize, - ComplexDouble, - Void, - Callback, - Default - } - - static Map>> buffersAndArityByType = new HashMap>>(); - static Map>> arraysAndArityByType = new HashMap>>(); - static Map pointerFieldGetterNameRadixByType = new HashMap(); - static Set objectMethodNames = new HashSet(); - static { - for (Method method : Object.class.getDeclaredMethods()) - objectMethodNames.add(method.getName()); - - Object[] data = new Object[]{ - "char", Byte.TYPE, byte[].class, ByteBuffer.class, "Char", - "long", Long.TYPE, long[].class, LongBuffer.class, "Long", - "int", Integer.TYPE, int[].class, IntBuffer.class, "Int", - "short", Short.TYPE, short[].class, ShortBuffer.class, "Short", - "wchar_t", Character.TYPE, char[].class, CharBuffer.class, "WChar", - "double", Double.TYPE, double[].class, DoubleBuffer.class, "Double", - "float", Float.TYPE, float[].class, FloatBuffer.class, "Float", - "bool", Boolean.TYPE, boolean[].class, null, "Bool" - }; - for (int arity : new int[]{1, 2, 4, 8, 16}) { - String suffix = arity == 1 ? "" : arity + ""; - for (int i = 0; i < data.length; i += 5) { - String rawType = (String) data[i]; - Class scalClass = (Class) data[i + 1]; - Class arrClass = (Class) data[i + 2]; - Class buffClass = (Class) data[i + 3]; - String radix = (String) data[i + 4]; - - Pair> buffPair = new Pair>(arity, arity == 1 ? scalClass : buffClass), - arrPair = new Pair>(arity, arity == 1 ? scalClass : arrClass); - - for (String type : new String[]{rawType + suffix, "u" + rawType + suffix}) { - buffersAndArityByType.put(type, buffPair); - arraysAndArityByType.put(type, arrPair); - pointerFieldGetterNameRadixByType.put(type, radix); - } - } - } - } - - - Pattern wstringPat = Pattern.compile("(__)?const wchar_t\\*"), - stringPat = Pattern.compile("(__)?const char\\*"), - wstringPtrPtrPat = Pattern.compile("(__)?const wchar_t\\*\\*"), - stringPtrPtrPat = Pattern.compile("(__)?const char\\*\\*"); - - protected boolean isString(String typeRefAsString, boolean wide) { - if (wide) { - return wstringPat.matcher(typeRefAsString).matches() - || result.config.charPtrAsString && typeRefAsString.equals("wchar_t*"); - } else { - return stringPat.matcher(typeRefAsString).matches() - || result.config.charPtrAsString && typeRefAsString.equals("char*"); - } - } - - protected boolean isStringPtrPtr(String typeRefAsString, boolean wide) { - if (wide) { - return wstringPtrPtrPat.matcher(typeRefAsString).matches() - || result.config.charPtrAsString && typeRefAsString.equals("wchar_t**"); - } else { - return stringPtrPtrPat.matcher(typeRefAsString).matches() - || result.config.charPtrAsString && typeRefAsString.equals("char**"); - } - } - - public TypeRef convertTypeToJNA(TypeRef valueType, TypeConversionMode conversionMode, Identifier libraryClassName) throws UnsupportedConversionException { - -// if (String.valueOf(valueType).contains("MonoImageOpenStatus")) -// valueType.toString(); - - TypeRef original = valueType; - TypeRef resolvedTypeRef = resolveTypeDef(valueType, libraryClassName, true, false); - if (resolvedTypeRef != null) - valueType = resolvedTypeRef; - -// if (String.valueOf(valueType).contains("MonoObject")) -// valueType.toString(); - String valueTypeString = String.valueOf(valueType); - - if (valueTypeString.matches("void\\s*\\*") || valueTypeString.matches("const\\s*void\\s*\\*")) { - //valueType = (TypeRef)valueType; - if (original instanceof Pointer && result.config.features.contains(GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers) { - Pointer p = (Pointer) original; - if (p.getTarget() instanceof SimpleTypeRef) { - if (isResolved((SimpleTypeRef) p.getTarget())) { - return p.getTarget(); - } - - Identifier name = ((SimpleTypeRef) p.getTarget()).getName(); - if (!"void".equals(name.toString()) && name.isPlain()) { -// int i = name.lastIndexOf('.'); -// if (i >= 0) -// name = name.substring(i + 1); - return typeRef(result.getFakePointer(libraryClassName, name)); - } - } - } - } else { - if (conversionMode == TypeConversionMode.ReturnType && result.config.stringifyConstCStringReturnValues) { - if (isString(valueTypeString, false)) { - return typeRef(String.class); - } else if (isString(valueTypeString, true)) { - return typeRef(WString.class); - } - - } else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { - if (isString(valueTypeString, false)) { - return typeRef(String.class); - } else if (isString(valueTypeString, true)) { - return typeRef(WString.class); - } else if (isStringPtrPtr(valueTypeString, false)) { - return arrayRef(typeRef(String.class)); - } else if (isStringPtrPtr(valueTypeString, true)) { - return arrayRef(typeRef(WString.class)); - } - /*else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { - if (valueTypeString.matches("char\\*")) - return typeRef(StringPointer.ByValue.class); - else if (valueTypeString.matches("wchar_t\\*")) - return typeRef(WStringPointer.ByValue.class); - }*/ - } - } - - if (valueType instanceof Primitive) { - JavaPrim prim = getPrimitive(valueType, libraryClassName); - if (prim != null) { - return primRef(prim); - } - -// if (!valueType.getModifiers().contains("long")) -// return valueType.toString(); - } - if (valueType instanceof TaggedTypeRef) { - Identifier name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) valueType); - if (name != null) { - if (valueType instanceof Enum) { - TypeRef tr = findEnum(name, libraryClassName); - if (tr != null) { - TypeRef intRef = primRef(JavaPrim.Int); - intRef.setCommentBefore(tr.getCommentBefore()); - return intRef; - } - } else if (valueType instanceof Struct) { - SimpleTypeRef tr = findStructRef(name, libraryClassName); - if (tr != null) { - switch (conversionMode) { - case PointedValue: - case NativeParameterWithStructsPtrPtrs: - case NativeParameter: - case PrimitiveOrBufferParameter: - case ReturnType: - case PrimitiveReturnType: - case FieldType: - return tr; - case StaticallySizedArrayField: - case ExpressionType: - default: - return subType(tr, ident("ByValue")); - } - } - } - } - } - - if (valueType instanceof FunctionSignature) { - TypeRef tr = findCallbackRef((FunctionSignature)valueType, libraryClassName); - if (tr != null) - return tr; - else - return typeRef(((FunctionSignature)valueType).getFunction().getName().clone()); - } - if (valueType instanceof TargettedTypeRef) { - //TypeRef target = resolveTypeDef(((TargettedTypeRef) valueType).getTarget(), callerLibraryClass); - TypeRef target = ((TargettedTypeRef) valueType).getTarget(); - - boolean staticallySized = valueType instanceof ArrayRef && ((ArrayRef)valueType).hasStaticStorageSize(); - - TypeRef convArgType = null; - JavaPrim prim = getPrimitive(target, libraryClassName); - if (prim != null) { - if (prim == JavaPrim.Void) - return typeRef(result.config.runtime.pointerClass); - else - convArgType = primRef(prim); - } else { - Identifier name = null; - if (target instanceof SimpleTypeRef) - name = ((SimpleTypeRef) target).getName(); - else if (target instanceof Struct) { - Struct struct = (Struct)target; - if (struct == null) { - valueType = resolveTypeDef(original, libraryClassName, true, false); - struct = null; - } else { - name = result.declarationsConverter.getActualTaggedTypeName(struct); - } - } else if (target instanceof FunctionSignature) { - TypeRef tr = findCallbackRef((FunctionSignature)target, libraryClassName); - if (tr != null) { - if (valueType instanceof TypeRef.ArrayRef) { - return new TypeRef.ArrayRef(tr); - } else { - return tr; - } - } - //else - // return typeRef(((FunctionSignature)valueType).getFunction().getName()); - } else if (target instanceof Pointer) { - if (conversionMode == TypeConversionMode.NativeParameter) - return typeRef(PointerByReference.class); - - Pointer pt = ((Pointer)target); - TypeRef ptarget = pt.getTarget(); - if (ptarget instanceof SimpleTypeRef) { - SimpleTypeRef ptargett = (SimpleTypeRef) ptarget; - Identifier tname = ptargett.getName(); - if (result.structsFullNames.contains(tname)) { - if (conversionMode == TypeConversionMode.FieldType) - return typeRef(PointerByReference.class); - else - return new ArrayRef(typeRef(ident(ptargett.getName(), "ByReference"))); - } else if ((tname = result.findFakePointer(tname)) != null) - return new ArrayRef(typeRef(tname.clone())); - } - } - if (name != null) { - /// Pointer to Objective-C class ? - convArgType = findObjCClass(name); - boolean isQualStruct = result.structsFullNames.contains(name); - if (convArgType == null || isQualStruct) { - /// Pointer to C structure - SimpleTypeRef structRef = isQualStruct ? typeRef(name) : findStructRef(name, libraryClassName); - if (structRef != null) {//result.cStructNames.contains(name)) { - switch (conversionMode) { - case ExpressionType: - case FieldType: - convArgType = valueType instanceof TypeRef.ArrayRef ? - structRef : - subType(structRef, ident("ByReference")); - if (valueType instanceof Pointer) - return convArgType; - break; - default: - if (isQualStruct && - (valueType instanceof ArrayRef) && ( - conversionMode == TypeConversionMode.NativeParameterWithStructsPtrPtrs || - conversionMode == TypeConversionMode.PrimitiveOrBufferParameter - )) - return arrayRef(structRef); - convArgType = structRef; - if (valueType instanceof Pointer) - return convArgType; - break; - } - } else { - try { - TypeConversionMode targettedConversionMode; - switch (conversionMode) { - case NativeParameter: - case NativeParameterWithStructsPtrPtrs: - case PrimitiveOrBufferParameter: - case PrimitiveReturnType: - targettedConversionMode = TypeConversionMode.PointedValue; - break; - default: - targettedConversionMode = conversionMode; - break; - } - convArgType = convertTypeToJNA(target, targettedConversionMode, libraryClassName); - /*if (result.isUndefinedType(convArgType)) { - if (allowFakePointers && original instanceof SimpleTypeRef) - return typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); - else - convArgType = typeRef(result.config.runtime.pointerClass); - }*/ - - if (convArgType != null && result.callbacksFullNames.contains(ident(convArgType.toString())) && !(valueType instanceof ArrayRef)) { - TypeRef tr = typeRef(result.config.runtime.pointerClass); - if (!result.config.noComments) - tr.setCommentBefore("@see " + convArgType); - return tr; - } - prim = getPrimitive(convArgType, libraryClassName); - } catch (UnsupportedConversionException ex) { - //convArgType = null;//return typeRef(result.config.runtime.pointerClass); - if (valueType instanceof TypeRef.Pointer && - target instanceof TypeRef.SimpleTypeRef && - result.config.features.contains(JNAeratorConfig.GenFeatures.TypedPointersForForwardDeclarations) && - allowFakePointers - ) { - - if (isResolved((SimpleTypeRef) target)) { - return target; - } -// int i = name.lastIndexOf('.'); -// if (i >= 0) { -// name = name.substring(i + 1); -// } - return typeRef(result.getFakePointer(libraryClassName, name)); - } else { - return typeRef(result.config.runtime.pointerClass); - } - } - } - } - } else { - try { - convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); - prim = getPrimitive(convArgType, libraryClassName); - } catch (UnsupportedConversionException ex) { - //convArgType = null;// - return typeRef(result.config.runtime.pointerClass); - } - } - } - switch (conversionMode) { - case StaticallySizedArrayField: - return new ArrayRef(convArgType); - case PrimitiveOrBufferParameter: - if (!result.config.noPrimitiveArrays && (target.getModifiers().contains(ModifierType.Const) - || valueType.getModifiers().contains(ModifierType.Const))) { - return new ArrayRef(convArgType); - } - Class bc = primToBuffer.get(prim); - if (bc != null) { - return typeRef(bc); - } - case ReturnType: - case FieldType: - if (staticallySized) { - return arrayRef(convArgType); - } - default: - if (prim != null) { - if (prim == JavaPrim.Byte) { - return (TypeRef)typeRef(result.config.runtime.pointerClass).importComments(convArgType); - } - - Class byRefClass = primToByReference.get(prim); - if (byRefClass != null) { - return typeRef(byRefClass).importDetails(convArgType, false); - } - } - if (convArgType != null && !convArgType.toString().equals(result.config.runtime.pointerClass.getName()) && valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef) { - return convArgType; - } - - } - if (target instanceof Pointer) { - return typeRef(PointerByReference.class); - } - - if (allowUnknownPointers) { - return typeRef(result.config.runtime.pointerClass); - } - } - if (valueType instanceof SimpleTypeRef) { - Identifier name = ((SimpleTypeRef) valueType).getName(); - if (name == null) { - throw new UnsupportedConversionException(valueType, null); - } - - boolean isQualStruct = result.structsFullNames.contains(name); - //isQualCallback = result.callbacksFullNames.contains(name); - if (!isQualStruct && isResolved((SimpleTypeRef) valueType)) { - return valueType; - } - - if (name instanceof SimpleIdentifier) { - TypeRef tr = findObjCClass(name); - if (tr == null) { - tr = findObjCClass(new SimpleIdentifier(((SimpleIdentifier) name).getName())); - } - if (tr != null) { - return tr; - } - } - SimpleTypeRef structRef = isQualStruct ? typeRef(name) : findStructRef(name, libraryClassName); - if (structRef != null) { - switch (conversionMode) { - case PointedValue: - case FieldType: - return structRef; - default: - return subType(structRef, ident("ByValue")); - } - } - - TypeRef callbackRef = findCallbackRef(name, libraryClassName); - if (callbackRef != null) { - return callbackRef; - } - - SimpleTypeRef enumTypeRef = findEnum(name, libraryClassName); - //FieldRef enumQualifiedName = findEnum(name); - if (enumTypeRef != null) { - return enumTypeRef; - } - - TypeRef objCClassRef = findObjCClass(name); - if (objCClassRef != null) { - return objCClassRef; - } - } - - JavaPrim prim = getPrimitive(valueType, libraryClassName); - if (prim != null) { - return primRef(prim); - } - - if (valueType instanceof SimpleTypeRef && allowFakePointers) { - //return typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); - return typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); - } - unknownTypes.add(String.valueOf(valueType)); - throw new UnsupportedConversionException(valueType, null); - } - static Map> predefObjCClasses = new HashMap>(); - - static { - predefObjCClasses.put("id", ObjCObject.class);//org.rococoa.ID.class); - predefObjCClasses.put("SEL", org.rococoa.Selector.class); - predefObjCClasses.put("IMP", com.sun.jna.Pointer.class); - predefObjCClasses.put("Class", ObjCClass.class); - predefObjCClasses.put("Protocol", ObjCClass.class); - predefObjCClasses.put("NSObject", NSObject.class); - //predefObjCClasses.put("NSClass", NSClass.class); - } - - public Identifier findObjCClassIdent(Identifier name) { - if (name instanceof SimpleIdentifier) { - SimpleIdentifier sname = (SimpleIdentifier) name; - String n = sname.getName(); - if (n.equals("id") - && sname.getTemplateArguments().size() == 1/* && - conversionMode != TypeConversionMode.NativeParameter && - conversionMode != TypeConversionMode.NativeParameterWithStructsPtrPtrs*/) { - Expression x = sname.getTemplateArguments().get(0); - TypeRefExpression trx = x instanceof TypeRefExpression ? (TypeRefExpression) x : null; - SimpleTypeRef str = trx.getType() instanceof SimpleTypeRef ? (SimpleTypeRef) trx.getType() : null; - if (str != null) { - name = str.getName(); - } - } - } - - Class class1 = predefObjCClasses.get(name.toString()); - if (class1 != null) { - return ident(class1); - } - - Struct s = result.resolveObjCClass(name); - if (s != null) { - return result.objectiveCGenerator.getFullClassName(s); - } - return null; - } - - public TypeRef findObjCClass(Identifier name) { - return typeRef(findObjCClassIdent(name)); - } - - protected TypeRef arrayRef(TypeRef tr) { - ArrayRef arrayRef; - if (tr instanceof ArrayRef) { - arrayRef = (ArrayRef) tr; - arrayRef.addDimension(new Expression.EmptyArraySize()); - } else { - arrayRef = new ArrayRef(tr); - } - return arrayRef; - } - Set unknownTypes = new HashSet(); - - public static Pair pair(A a, B b) { - return new Pair(a, b); - } - - public static Pair typed(Expression a, TypeRef b) { - return new Pair(a, b); - } - - public boolean isString(Expression val) { - return val instanceof Constant && ((Constant)val).getType() == Constant.Type.String; // TODO use typer + type annotations ! - } - - public Constant.Type getConstantType(Expression expr) { - if (!(expr instanceof Constant)) - return null; - return ((Constant)expr).getType(); - } - - public abstract Expression getEnumItemValue(EnumItem enumItem); - - public TypeRef convertToJavaType(Constant.Type type) { - switch (type) { - case Bool: - return typeRef(Boolean.TYPE); - case IntegerString: - case UInt: - case Int: - return typeRef(Integer.TYPE); - case LongString: - case ULong: - case Long: - return typeRef(Long.TYPE); - case Short: - return typeRef(Short.TYPE); - case Byte: - return typeRef(Byte.TYPE); - case Float: - return typeRef(Float.TYPE); - case Double: - return typeRef(Double.TYPE); - case String: - return typeRef(String.class); - default: - return null; - } - } - - protected Expression sizeof(JavaPrim prim) { - return prim.size.sizeof(prim); - } - - protected Expression findEnumItem(EnumItem enumItem) { - String library = result.getLibrary(enumItem); - if (library == null) { - return null; - } - - Element parent = enumItem.getParentElement(); - if (parent == null || !(parent instanceof Enum)) { - return null; - } - - Enum e = (Enum) parent; - Identifier ident = ident(result.getLibraryClassFullName(library), result.declarationsConverter.getActualTaggedTypeName(e), ident(enumItem.getName())); - return expr(typeRef(ident).setMarkedAsResolved(true)); - } - /// @see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html - public static Set JAVA_KEYWORDS = new HashSet(Arrays.asList( - "null", - "true", - "false", - "abstract", - "continue", - "for", - "new", - "switch", - "assert", - "default", - "goto", - "package", - "synchronized", - "boolean", - "do", - "if", - "private", - "this", - "break", - "double", - "implements", - "protected", - "throw", - "byte", - "else", - "import", - "public", - "throws", - "case", - "enum", - "instanceof", - "return", - "transient", - "catch", - "extends", - "int", - "short", - "try", - "char", - "final", - "interface", - "static", - "void", - "class", - "finally", - "long", - "strictfp", - "volatile", - "const", - "float", - "native", - "super", - "while", - "wait" // not allowed for function names - )); - //static String keywords = " true false double float wait new null boolean return class public protected private "; - - public Identifier getValidJavaArgumentName(Identifier name) { - return getValidJavaIdentifier(name); - } - - public Identifier getValidJavaMethodName(Identifier name) { - String nameStr = name.toString(); - String newName = null; - if (nameStr.matches("operator[^\\w]+")) { - String op = nameStr.substring("operator".length()); - //int nArgs = method.getArgs().size(); - String suffix = null; - java.lang.Enum e = Expression.getAnyOperator(op); - if (e == null) { - if (op.equals("()")) { - suffix = "parenthesis"; - } else if (op.equals("[]")) { - suffix = "brackets"; - } else if (op.equals("->")) { - suffix = "arrow"; - } - } else { - suffix = e.name(); - } - - if (suffix != null) { - newName = "operator" + StringUtils.capitalize(suffix); - } - } else if (objectMethodNames.contains(nameStr)) { - newName = name + "$"; - }/* else if (nameStr.startsWith("~")) { - newName = getValidJavaIdentifierString(ident(nameStr.substring(1))) + "Destructor"; - }*/ - - if (newName == null) { - newName = getValidJavaIdentifierString(name); - } -// else if (result.config.beautifyNames) { -// newName = beautify(newName); -// } - - return ident(newName); - } - - String beautify(String name, boolean isType) { - String newName = StringUtils.underscoredToCamel(name); - if (!isType) - newName = StringUtils.uncapitalize(newName); - - if (name.endsWith("_")) { - newName += "$"; - } - return newName; - } - - public boolean isJavaKeyword(String name) { - return JAVA_KEYWORDS.contains(name); - } - - public Identifier getValidJavaIdentifier(Identifier name) { - return ident(getValidJavaIdentifierString(name)); - } - - public String getValidJavaIdentifierString(Identifier name) { - if (name == null) { - return null; - } - - if (isJavaKeyword(name.toString())) { - return name + "$"; - } else { - String newName = name.toString().replace('-', '_').replaceAll("[^\\w]", "\\$"); -// if (result.config.beautifyNames) { -// newName = beautify(newName); -// } - return newName; - } - } - - public static String toPrimString(JavaPrim prim) { - return prim.name; - } - - public Expression getJavaClassLitteralExpression(TypeRef tr) { - JavaPrim prim = result.typeConverter.getPrimitive(tr, null); - return prim != null ? classLiteral(prim.type) : typeLiteral(tr.clone()); - } - - public Expression getJavaClassLitteralExpression() { - throw new UnsupportedOperationException(getClass().getName() + "." + toString() + " not handled !"); - } - - - public Pair convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { - Pair res = null; - if (x instanceof Expression.AssignmentOp) { - Pair convTarget = convertExpressionToJava(((Expression.AssignmentOp) x).getTarget(), libraryClassName, promoteNativeLongToLong), - convValue = convertExpressionToJava(((Expression.AssignmentOp) x).getValue(), libraryClassName, promoteNativeLongToLong); - - res = typed(expr(convTarget.getFirst(), Expression.AssignmentOperator.Equal, convValue.getFirst()), convTarget.getSecond()); - } else if (x instanceof Expression.BinaryOp) { - Expression.BinaryOp bop = (Expression.BinaryOp) x; - Pair conv1 = convertExpressionToJava(bop.getFirstOperand(), libraryClassName, promoteNativeLongToLong), - conv2 = convertExpressionToJava(bop.getSecondOperand(), libraryClassName, promoteNativeLongToLong); - - if (conv1 != null && conv2 != null) { - TypeRef t1 = conv1.getSecond(), t2 = conv2.getSecond(); - Expression x1 = conv1.getFirst(), x2 = conv2.getFirst(); - - String s1 = String.valueOf(t1), s2 = String.valueOf(t2); - TypeRef tr = null; - if (bop.getOperator().givesBool) - tr = typeRef(boolean.class); - else { - if (s1.equals(s2)) { - tr = t1; - } else { - JavaPrim p1 = getPrimitive(t1, null), p2 = getPrimitive(t2, null); - if (p1 != null && p2 != null) { - switch (bop.getOperator()) { - case LeftShift: - case RightShift: - case SignedRightShift: - tr = t1; - break; - default: - for (JavaPrim p : new JavaPrim[]{ - JavaPrim.Double, JavaPrim.Float, - JavaPrim.Long, JavaPrim.NativeSize, JavaPrim.NativeLong, JavaPrim.Int, - JavaPrim.Short, JavaPrim.Byte - }) { - if (p1 == p || p2 == p) { - if (promoteNativeLongToLong && (p == JavaPrim.NativeLong || p == JavaPrim.NativeSize)) { - p = JavaPrim.Long; - } - tr = primRef(p); - break; - } - } - } - - } - } - } - res = typed(expr(x1, ((Expression.BinaryOp) x).getOperator(), x2), tr); - } - } else if (x instanceof Expression.UnaryOp) { - Expression.UnaryOperator op = ((Expression.UnaryOp) x).getOperator(); - if (op == Expression.UnaryOperator.Not) { - throw new UnsupportedConversionException(x, null); // TODO handle this properly ? - } - Pair conv = convertExpressionToJava(((Expression.UnaryOp) x).getOperand(), libraryClassName, promoteNativeLongToLong); - - res = typed(expr(op, conv.getFirst()), conv.getSecond()); - } else if (x instanceof Expression.Constant) { - Class c = null; - Expression.Constant jc = ((Expression.Constant) x).asJava(); - switch (jc.getType()) { - case Byte: - c = Byte.TYPE; - break; - case Char: - c = Character.TYPE; - break; - case Double: - c = Double.TYPE; - break; - case Float: - c = Float.TYPE; - break; - case Int: - case UInt: - case IntegerString: - c = Integer.TYPE; - break; - case ULong: - case Long: - case LongString: - c = Long.TYPE; - break; - case Short: - c = Short.TYPE; - break; - case String: - c = String.class; - break; - } - if (c != null) { - res = typed(((Expression.Constant) x).asJava(), typeRef(c)); - } - - } else if (x instanceof Expression.TypeRefExpression) { - - Expression.TypeRefExpression tre = (Expression.TypeRefExpression) x; - TypeRef tr = tre.getType(); - if (tr instanceof TypeRef.SimpleTypeRef) { - TypeRef.SimpleTypeRef str = (TypeRef.SimpleTypeRef) tr; - Identifier ident = str.getName(); - if (ident != null) { - if (result.enumItemsFullName.contains(ident)) { - res = typed(tre, typeRef(Integer.TYPE)); - } - } - } - if (res == null) { - if (tr.isMarkedAsResolved()) { - res = typed(tre, tr); - } else { - TypeRef conv = convertTypeToJNA(tr, TypeConversionMode.ExpressionType, libraryClassName); - res = typed(new Expression.TypeRefExpression(conv), conv); - } - } - } else if (x instanceof Expression.VariableRef) { - Expression.VariableRef fr = (Expression.VariableRef) x; - Identifier name = fr.getName(); - if (name != null) { - Define define = result.defines.get(name); - if (define != null && define.getValue() != null) { - if (x.toString().equals(define.getValue().toString())) { - res = null; // avoid some nasty loops - } else { - Expression defineValue = define.getValue(); - if (defineValue instanceof Expression.Constant) { - Expression.Constant constant = (Expression.Constant) defineValue; - res = typed(findDefine(name), convertToJavaType(constant.getType())); - } - - if (res == null) { - res = convertExpressionToJava(defineValue, libraryClassName, promoteNativeLongToLong); - } - } - } else { - String sname = name.toString(); - if (sname.equals("True") || sname.equals("true")) { - res = typed(expr(Expression.Constant.Type.Bool, true), primRef(JavaPrim.Boolean)); - } else if (sname.equals("False") || sname.equals("false")) { - res = typed(expr(Expression.Constant.Type.Bool, false), primRef(JavaPrim.Boolean)); - } else { - Enum.EnumItem enumItem = result.enumItems.get(name); - if (enumItem != null) { - res = typed(getEnumItemValue(enumItem), typeRef(Long.TYPE)); - } else { - VariablesDeclaration constant = result.globalVariablesByName.get(name); - if (constant != null) { - res = typed(varRef(findRef(name, constant, libraryClassName, true)), null); - } else { - res = typed(new Expression.VariableRef(name), null); - } - } - } - } - } - } - if (res == null) { -// return convertExpressionToJava(x); - throw new UnsupportedConversionException(x, null); - } - if (res.getFirst() == null) { - return null; - } - res.getFirst().setParenthesis(x.getParenthesis()); - return (Pair) res; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UniversalReconciliator.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UniversalReconciliator.java deleted file mode 100644 index fa3cdff9f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UniversalReconciliator.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ochafik.lang.jnaerator; - -import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.ochafik.lang.jnaerator.parser.Declarator; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.jnaerator.parser.Modifier; -import com.ochafik.lang.jnaerator.parser.ModifierType; -import com.ochafik.lang.jnaerator.parser.Scanner; -import com.ochafik.lang.jnaerator.parser.TypeRef; -import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; -import com.ochafik.util.listenable.Pair; - -public class UniversalReconciliator { - - - static class DefSeq { - List simpleTypeRefs = new ArrayList(); -// List identifiers = new ArrayList(); - List declarators = new ArrayList(); - boolean matches(DefSeq o) { - int n = declarators.size(); - if (n != declarators.size()) - return false; - if (simpleTypeRefs.size() != o.simpleTypeRefs.size()) - return false; - for (int i = 0; i < n; i++) { - Declarator id = declarators.get(i), oid = declarators.get(i); - if (!id.toString().equals(oid.toString())) - return false; - } - return true; - } - } - DefSeq extractDefSeq(Element tr) { - final DefSeq ret = new DefSeq(); - tr.accept(new Scanner() { - @Override - public void visitDeclarator(Declarator declarator) { - super.visitDeclarator(declarator); - ret.declarators.add(declarator); - } -// public void visitIdentifier(Identifier i) { -// super.visitIdentifier(i); -// ret.identifiers.add(i); -// } - @Override - public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { - super.visitSimpleTypeRef(simpleTypeRef); - ret.simpleTypeRefs.add(simpleTypeRef); - } - }); - return ret; - } - public static class ReconciliationException extends Exception { - private static final long serialVersionUID = -8197343041734256268L; - public ReconciliationException(Element t1, Element t2, Element reason1, Element reason2) { - this(t1, t2, "\"" + reason1 + "\" and \"" + reason2 + "\" cannot be matched"); - } - public ReconciliationException(Element t1, Element t2, String reason) { - super("Types \"" + t1 + "\" and \"" + t2 + "\" could not be reconciliated" + (reason == null ? "" : ". Reason = " + reason)); - } - } - public Element reconciliate32bitsAnd64bits(Element tr32, Element tr64) throws ReconciliationException { - if (tr32 == null && tr64 == null) - return null; - if ((tr32 == null) != (tr64 == null)) { - if (tr32 == null && tr64.toString().matches("id") || - tr64 == null && tr32.toString().equals("id")) - return typeRef("id"); - throw new ReconciliationException(tr32, tr64, null); - } - - tr32 = tr32.clone(); - DefSeq s32 = extractDefSeq(tr32), s64 = extractDefSeq(tr64); - if (!s32.matches(s64)) - throw new ReconciliationException(tr32, tr64, null); - - int n = s32.simpleTypeRefs.size(); - for (int i = 0; i < n; i++) { - TypeRef.SimpleTypeRef t32 = s32.simpleTypeRefs.get(i), t64 = s64.simpleTypeRefs.get(i); - if (t32.toString().equals(t64.toString())) - continue; - TypeRef tr = reconciliateSimple32bitsAnd64bits(t32, t64); - if (tr == null) - throw new ReconciliationException(tr32, tr64, t32, t64); - if (t32 == tr32) - tr32 = tr; - else - t32.replaceBy(tr); - } - // TODO Auto-generated method stub - return tr32; - } - - static Map, TypeRef> predefined32_64Reconciliations = new HashMap, TypeRef>(); - static { - defRecon("float", "double", typeRef("CGFloat")); - defRecon("long", "long long", typeRef("long")); - defRecon("int", "long long", typeRef("NSInteger")); - - defRecon("int", "unsigned long long", typeRef("NSInteger")); - defRecon("int", "signed long long", typeRef("NSInteger")); - defRecon("long", "unsigned long long", typeRef("NSInteger")); - defRecon("long", "signed long long", typeRef("NSInteger")); - defRecon("unsigned long", "unsigned long long", typeRef("long").addModifiers(ModifierType.Unsigned)); - defRecon("unsigned int", "unsigned long long", typeRef("NSUInteger"));//int").addModifiers(ModifierType.Unsigned)); - - defRecon("unsigned long", "unsigned int", typeRef("int").addModifiers(ModifierType.Unsigned)); - defRecon("signed long", "signed int", typeRef("int").addModifiers(ModifierType.Signed)); - defRecon("long", "int", typeRef("int")); - defRecon("int", "unsigned int", typeRef("int")); - - defRecon("signed long", "signed long long", typeRef("long").addModifiers(ModifierType.Signed)); - defRecon("signed int", "signed long long", typeRef("NSInteger"));//int").addModifiers(ModifierType.Signed)); - } - static void defRecon(String s32, String s64, TypeRef sRecon) { - predefined32_64Reconciliations.put(new Pair(s32, s64), sRecon); - } - /*static TypeRef cleanClone(TypeRef t) { - t = t.clone(); - List mods = new ArrayList(t.getModifiers()); - mods.remove(ModifierType.Signed); - mods.remove(ModifierType.Unsigned); - t.setModifiers(mods); - return t; - }*/ - public static TypeRef reconciliateSimple32bitsAnd64bits(TypeRef t32, TypeRef t64) { - TypeRef recon = predefined32_64Reconciliations.get(new Pair(t32.toString(), t64.toString())); - /*if (recon == null) { - TypeRef tt32 = cleanClone(t32), tt64 = cleanClone(t64); - if (tt32.toString().equals(t64)) - return tt32; - recon = predefined32_64Reconciliations.get(new Pair(tt32.toString(), tt64.toString())); - }*/ - - return recon == null ? null : recon.clone(); - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UnsupportedConversionException.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UnsupportedConversionException.java deleted file mode 100644 index d05e214c8..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/UnsupportedConversionException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import com.ochafik.lang.jnaerator.parser.Element; - -public class UnsupportedConversionException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; - Element element; - public UnsupportedConversionException(Element x, Object reason) { - super("Conversion Error : " + String.valueOf(x) + (reason == null ? "" : " (" + reason + ")")); - assert x != null; - this.element = x; - } - @Override - public String toString() { - return getMessage(); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/DllExport.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/DllExport.java deleted file mode 100644 index 7d30e5e2e..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/DllExport.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport; - -import static com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.IMAGE_DIRECTORY_ENTRY_EXPORT; -import static com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.IMAGE_DOS_SIGNATURE; -import static com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.IMAGE_NT_SIGNATURE; -import static com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.INSTANCE; -import static com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.UNDNAME_COMPLETE; - -import static com.ochafik.lang.jnaerator.nativesupport.NativeExportUtils.*; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_DOS_HEADER; -import com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_EXPORT_DIRECTORY; -import com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_NT_HEADERS; -import com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_SECTION_HEADER; -import com.ochafik.util.string.RegexUtils; -import com.sun.jna.Memory; -import com.sun.jna.Pointer; -import com.sun.jna.PointerUtils; - -public class DllExport { - private static final Pattern libraryFileNamePattern = Pattern.compile("^([^.]+)\\.dll"); - public static String createSourceFile(File sourceFile, List dllExports) { - if (dllExports == null) - return null; - - StringBuilder b = new StringBuilder(); - b.append("#line \"" + sourceFile + "\"\n"); - for (ParsedExport ex : dllExports) { - b.append("// @mangling " + ex.mangling + "\n"); - b.append(ex.demangled + ";\n"); - b.append("\n"); - } - return b.toString(); - } - public static List parseDllExports(File f) throws IOException { - List ret = new ArrayList(); - List list = OutputDllFunctions(f); - if (list == null) - return null; - - String library = RegexUtils.findFirst(f.getName(), libraryFileNamePattern, 1); - - int outSize = 8196; - byte[] bytes = new byte[outSize]; - Memory m = new Memory(outSize); - for (String symbol : list) { - INSTANCE.UnDecorateSymbolName(symbol, m.getByteBuffer(0, outSize), outSize, UNDNAME_COMPLETE); - m.read(0, bytes, 0, outSize); - int len = 0; - while (len < outSize && bytes[len] != 0) - len++; - ParsedExport ex = new ParsedExport(); - ex.mangling = symbol; - ex.demangled = new String(bytes, 0, len); - ex.library = library ; - ret.add(ex); - } - return ret; - } - private static List OutputDllFunctions(File f) throws IOException { - RandomAccessFile raf = new RandomAccessFile(f, "r"); - IMAGE_DOS_HEADER dosHeader = deserializeStruct(new IMAGE_DOS_HEADER(), raf, 0); - if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE) - return null; - - long ntHeaderBase = dosHeader.e_lfanew.longValue(); - IMAGE_NT_HEADERS ntHeader = deserializeStruct(new IMAGE_NT_HEADERS(), raf, ntHeaderBase); - if (ntHeader.Signature != IMAGE_NT_SIGNATURE) - return null; - - int exportsStartRVA = ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; - IMAGE_SECTION_HEADER header = GetExportsSectionHeader(raf, exportsStartRVA, ntHeaderBase, ntHeader ); - if (header == null) - return null; - - int delta = header.VirtualAddress - header.PointerToRawData; - IMAGE_EXPORT_DIRECTORY exportDir = deserializeStruct(new IMAGE_EXPORT_DIRECTORY(), raf, exportsStartRVA - delta); - - List ret = new ArrayList(exportDir.NumberOfNames); - //IntBuffer functions = ByteBuffer.wrap(GetFileBytes(raf, PointerUtils.getAddress(exportDir.AddressOfFunctions) - delta, exportDir.NumberOfFunctions * 4)).asIntBuffer(); - //ShortBuffer ordinals = ByteBuffer.wrap(GetFileBytes(raf, PointerUtils.getAddress(exportDir.AddressOfNameOrdinals) - delta, exportDir.NumberOfNames * 2)).asShortBuffer(); - for (int i = 0; i < exportDir.NumberOfNames; i++ ) { - int pstr = readLittleEndianInt(raf, PointerUtils.getAddress(exportDir.AddressOfNames) - delta + i * Pointer.SIZE); - String name = new String(GetFileBytes(raf, pstr - delta, -1)); - ret.add(name); - } - return ret; - } - private static IMAGE_SECTION_HEADER GetExportsSectionHeader(RandomAccessFile raf, int exportsStartRVA, long ntHeaderBase, IMAGE_NT_HEADERS ntHeader) throws IOException { - IMAGE_SECTION_HEADER firstSection = new IMAGE_SECTION_HEADER(); - byte[] bytes = GetFileBytes( - raf, - ntHeaderBase + - PointerUtils.getAddress(ntHeader.OptionalHeader.getPointer()) - - PointerUtils.getAddress(ntHeader.getPointer()) + - ntHeader.FileHeader.SizeOfOptionalHeader, - firstSection.size() * ntHeader.FileHeader.NumberOfSections - ); - IMAGE_SECTION_HEADER[] sections = firstSection.toArray(ntHeader.FileHeader.NumberOfSections); - sections[0].getPointer().write(0, bytes, 0, bytes.length); - for (IMAGE_SECTION_HEADER section : sections) { - section.read(); - if (exportsStartRVA >= section.VirtualAddress && exportsStartRVA < (section.VirtualAddress + section.Misc.VirtualSize)) - return section; - } - return null; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/FatMachOExport.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/FatMachOExport.java deleted file mode 100644 index bb8dde6f0..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/FatMachOExport.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport; - - -import static com.ochafik.lang.jnaerator.nativesupport.NativeExportUtils.*; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import static com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary.*; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.fat_arch; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.fat_header; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.load_command; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.mach_header; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.nlist; -import com.ochafik.lang.jnaerator.nativesupport.machoexport.symtab_command; -import com.ochafik.lang.reflect.DebugUtils; - - -public class FatMachOExport { - - public static char[] parseDllExports(File f) throws IOException { - RandomAccessFile raf = new RandomAccessFile(f, "r"); - byte[] b = GetFileBytes(raf, 0, 100); - - int i = readBigEndianInt(raf, 0); - String h = Integer.toHexString(i); - fat_header fat = deserializeBigEndianStruct(new fat_header(), raf, 0); - if (fat.magic == FAT_MAGIC) { - long archsBase = fat.size(); - long archSize = new fat_arch().size(); - for (int iFatArch = 0; iFatArch < fat.nfat_arch; iFatArch++) { - long archBase = archsBase + archSize * iFatArch; - fat_arch arch = deserializeBigEndianStruct(new fat_arch(), raf, archBase); - - if (arch.cputype == 0) - continue; - - mach_header mach = deserializeBigEndianStruct(new mach_header(), raf, arch.offset); - if (mach.cputype != arch.cputype || mach.cpusubtype != arch.cpusubtype) - throw new IOException("Failed to recognize Fat + MachO format !"); - - if (mach.magic == MH_MAGIC) { - OutputSymbols(raf, mach, arch.offset); - } - - - } - } - return null; - } - - private static void OutputSymbols(RandomAccessFile raf, mach_header mach, int machOffset) throws IOException { - int currentCommandOffset = machOffset + mach.size(); - boolean passedLastOk = false; - for (int iLoadCmd = 0; iLoadCmd < mach.ncmds; iLoadCmd++) { - load_command lc = deserializeBigEndianStruct(new load_command(), raf, currentCommandOffset); - switch (lc.cmd) { - case LC_SYMTAB: - symtab_command sc = deserializeBigEndianStruct(new symtab_command(), raf, currentCommandOffset); - //byte[] tbytes = GetFileBytes(raf, sc.symoff + machOffset, 100); - - int symtabsize = new nlist().size(), scsize = sc.size(); - for (int iSymTab = 0; iSymTab < sc.nsyms; iSymTab++) { - long nlOffset = machOffset + scsize + sc.symoff + iSymTab * symtabsize; -// if ((nlOffset % 8) != 0) -// nlOffset = ((nlOffset / 8) + 1) * 8; - nlist nl = deserializeBigEndianStruct(new nlist(), raf, nlOffset); - nl.n_un.setType(Integer.TYPE); -// nl.n_un.read(); -// if (nl.N_EXT != 1) -// continue; - if (nl.n_un.n_strx == 0) - continue; - - short desc = nl.n_desc; - if (nl.n_desc != -1) - continue; - - int stab = nl.n_type & N_STAB; - if ((stab) != 0) { - String h = Integer.toHexString(stab); - h = h.toString(); - continue; - } - - try { - long stroff = sc.stroff + machOffset + nl.n_un.n_strx; -// byte[] obytes = GetFileBytes(raf, stroff - 10, 20); -// char[] chars = new char[obytes.length]; -// for (int i = 0; i < obytes.length; i++) -// chars[i] = (char)(0xff & obytes[i]); - - byte[] sbytes = NativeExportUtils.GetFileBytes(raf, stroff, -1); - // char[] chars = new char[sbytes.length]; - // for (int i = 0; i < sbytes.length; i++) - // chars[i] = (char)(0xff & sbytes[i]); - // - // System.out.println(new String(chars)); - String symbol = new String(sbytes); - - int sector = nl.n_sect; - if (symbol.equals("_kCFUserNotificationSoundPathKey")) - passedLastOk = true; - // symbol = symbol.toString(); - System.out.println(symbol);// + ": sect = " + sector); -// if (passedLastOk) -// DebugUtils.println(nl); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - byte[] sbytes = GetFileBytes(raf, sc.stroff + machOffset, 100); - char[] chars = new char[sbytes.length]; - for (int i = 0; i < sbytes.length; i++) - chars[i] = (char)(0xff & sbytes[i]); - int nsyms = sc.nsyms; - break; - case LC_FVMFILE: - case LC_IDENT: - case LC_LOADFVMLIB: - case LC_SEGMENT: - case LC_SYMSEG: - case LC_THREAD: - case LC_UNIXTHREAD: - } - currentCommandOffset += lc.cmdsize; - } - } - -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/NativeExportUtils.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/NativeExportUtils.java deleted file mode 100644 index 802bf8337..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/NativeExportUtils.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.lang.reflect.Modifier; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.List; - -import com.sun.jna.Structure; -import com.sun.jna.Union; -public class NativeExportUtils { - public static byte[] GetFileBytes(RandomAccessFile raf, long offset, int size) throws IOException { - raf.seek(offset); - if (size < 0) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] b = new byte[1]; - while (raf.read(b) != 0 && b[0] != 0) - out.write(b); - return out.toByteArray(); - } - byte[] bytes = new byte[size]; - raf.readFully(bytes); - return bytes; - } - public static int fromBigEndian(int i) { - return ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN ? invertBytes(i) : i; - } - public static int fromLittleEndian(int i) { - return ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN ? invertBytes(i) : i; - } - - private static long fromBigEndian(Long i) { - return ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN ? invertBytes(i) : i; - } - public static int invertBytes(long i) { - return invertBytes((int)(i & 0xffffffff)) << 32 | invertBytes((int)(i >> 32)); - } - public static int invertBytes(int i) { -// String h = Integer.toHexString(i); - int j = (invertBytes((short)(i & 0xffff)) & 0xffff) << 16 | (invertBytes((short)(i >> 16)) & 0xffff); -// String h2 = Integer.toHexString(j); - return j; - } - public static short invertBytes(short i) { -// String h = Integer.toHexString(i).substring(4); -// int k = i & 0xff; -// h = Integer.toHexString(k); -// k <<= 8; -// h = Integer.toHexString(k); -// int l = i >> 8; -// h = Integer.toHexString(l); -// int m = k | l; -// h = Integer.toHexString(m); -// -// - short j = (short)(((i & 0xff) << 8) | (i >> 8) & 0xff); -// String h2 = Integer.toHexString(j).substring(4); - return j; - } - public static S deserializeBigEndianStruct(S struct, RandomAccessFile raf, long offset) throws IOException { - return fromBigEndianFields(deserializeStruct(struct, raf, offset)); - } - static T fromBigEndianFields(T o) { - - try { - for (java.lang.reflect.Field f : o.getClass().getFields()) - { - if ((f.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) - continue; - if ((f.getModifiers() & Modifier.PUBLIC) == 0) - continue; - - if (f.getType() == Integer.TYPE) - f.set(o, fromBigEndian((Integer)f.get(o))); - else if (f.getType() == Short.TYPE) - f.set(o, (short)fromBigEndian((Short)f.get(o))); - else if (f.getType() == Long.TYPE) - f.set(o, (long)fromBigEndian((Long)f.get(o))); - else if (Union.class.isAssignableFrom(f.getType())) { - Union u = (Union)f.get(o); - fromBigEndianFields(u); - } else if (Structure.class.isAssignableFrom(f.getType())) { - Structure u = (Structure)f.get(o); - fromBigEndianFields(u); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return o; - } - - public static S deserializeStruct(S struct, RandomAccessFile raf, long offset) throws IOException { - byte[] bytes = GetFileBytes(raf, offset, struct.size()); - struct.getPointer().write(0, bytes, 0, bytes.length); -// int i = struct.getPointer().getInt(0); -// byte[] rb = struct.getPointer().getByteArray(0, 4); - struct.read(); - return struct; - } - public static String createSourceFile(File sourceFile, List dllExports) { - if (dllExports == null) - return null; - - StringBuilder b = new StringBuilder(); - b.append("#line \"" + sourceFile + "\"\n"); - for (ParsedExport ex : dllExports) { - b.append("// @mangling " + ex.mangling + "\n"); - b.append(ex.demangled + ";\n"); - b.append("\n"); - } - return b.toString(); - } - public static void main(String[] args) { - try { -// File f = new File("C:\\Prog\\C++\\DllExportTest\\Release\\DllTest.dll"); -// System.out.println(DllExport.createSourceFile(f, DllExport.parseDllExports(f))); - - File f = new File("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"); - System.out.println(FatMachOExport.parseDllExports(f)); - } catch (Exception ex) { - ex.printStackTrace(); - } - - } - public static class ParsedExport { - public String mangling, demangled, library; - } - public static int readLittleEndianInt(RandomAccessFile raf, long l) throws IOException { - raf.seek(l); - byte[] bytes = new byte[4]; - raf.read(bytes); - return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(0); - } - public static int readBigEndianInt(RandomAccessFile raf, long l) throws IOException { - raf.seek(l); - byte[] bytes = new byte[4]; - raf.read(bytes); - return ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asIntBuffer().get(0); - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.h b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.h deleted file mode 100644 index 615c46612..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.h +++ /dev/null @@ -1,172 +0,0 @@ -// Directory Entries - -#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory -#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory -#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory -#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 // Exception Directory -#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 // Security Directory -#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 // Base Relocation Table -#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 // Debug Directory -// IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 // (X86 usage) -#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 // Architecture Specific Data -#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 // RVA of GP -#define IMAGE_DIRECTORY_ENTRY_TLS 9 // TLS Directory -#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 // Load Configuration Directory -#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 // Bound Import Directory in headers -#define IMAGE_DIRECTORY_ENTRY_IAT 12 // Import Address Table -#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 // Delay Load Import Descriptors -#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 // COM Runtime descriptor - - -#define IMAGE_SIZEOF_SHORT_NAME 8 -#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory -#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 -#define IMAGE_NT_SIGNATURE 0x00004550 // PE00 -#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ - -typedef struct _IMAGE_DATA_DIRECTORY { - DWORD VirtualAddress; - DWORD Size; -} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; - -typedef struct _IMAGE_FILE_HEADER { - WORD Machine; - WORD NumberOfSections; - DWORD TimeDateStamp; - DWORD PointerToSymbolTable; - DWORD NumberOfSymbols; - WORD SizeOfOptionalHeader; - WORD Characteristics; -} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; - -typedef struct _IMAGE_OPTIONAL_HEADER { - // - // Standard fields. - // - - WORD Magic; - BYTE MajorLinkerVersion; - BYTE MinorLinkerVersion; - DWORD SizeOfCode; - DWORD SizeOfInitializedData; - DWORD SizeOfUninitializedData; - DWORD AddressOfEntryPoint; - DWORD BaseOfCode; - DWORD BaseOfData; - - // - // NT additional fields. - // - - DWORD ImageBase; - DWORD SectionAlignment; - DWORD FileAlignment; - WORD MajorOperatingSystemVersion; - WORD MinorOperatingSystemVersion; - WORD MajorImageVersion; - WORD MinorImageVersion; - WORD MajorSubsystemVersion; - WORD MinorSubsystemVersion; - DWORD Reserved1; - DWORD SizeOfImage; - DWORD SizeOfHeaders; - DWORD CheckSum; - WORD Subsystem; - WORD DllCharacteristics; - DWORD SizeOfStackReserve; - DWORD SizeOfStackCommit; - DWORD SizeOfHeapReserve; - DWORD SizeOfHeapCommit; - DWORD LoaderFlags; - DWORD NumberOfRvaAndSizes; - IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; -} IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER; - - -typedef struct _IMAGE_NT_HEADERS { - DWORD Signature; - IMAGE_FILE_HEADER FileHeader; - IMAGE_OPTIONAL_HEADER OptionalHeader; -} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS; - -typedef struct _IMAGE_SECTION_HEADER { - BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; - union { - DWORD PhysicalAddress; - DWORD VirtualSize; - } Misc; - DWORD VirtualAddress; - DWORD SizeOfRawData; - DWORD PointerToRawData; - DWORD PointerToRelocations; - DWORD PointerToLinenumbers; - WORD NumberOfRelocations; - WORD NumberOfLinenumbers; - DWORD Characteristics; -} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; - -typedef struct _IMAGE_EXPORT_DIRECTORY { - DWORD Characteristics; - DWORD TimeDateStamp; - WORD MajorVersion; - WORD MinorVersion; - DWORD Name; - DWORD Base; - DWORD NumberOfFunctions; - DWORD NumberOfNames; - PDWORD *AddressOfFunctions; - PDWORD *AddressOfNames; - PWORD *AddressOfNameOrdinals; -} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; - -typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header - WORD e_magic; // Magic number - WORD e_cblp; // Bytes on last page of file - WORD e_cp; // Pages in file - WORD e_crlc; // Relocations - WORD e_cparhdr; // Size of header in paragraphs - WORD e_minalloc; // Minimum extra paragraphs needed - WORD e_maxalloc; // Maximum extra paragraphs needed - WORD e_ss; // Initial (relative) SS value - WORD e_sp; // Initial SP value - WORD e_csum; // Checksum - WORD e_ip; // Initial IP value - WORD e_cs; // Initial (relative) CS value - WORD e_lfarlc; // File address of relocation table - WORD e_ovno; // Overlay number - WORD e_res[4]; // Reserved words - WORD e_oemid; // OEM identifier (for e_oeminfo) - WORD e_oeminfo; // OEM information; e_oemid specific - WORD e_res2[10]; // Reserved words - LONG e_lfanew; // File address of new exe header - } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; - - -#define UNDNAME_COMPLETE (0x0000) // Enable full undecoration -#define UNDNAME_NO_LEADING_UNDERSCORES (0x0001) // Remove leading underscores from MS extended keywords -#define UNDNAME_NO_MS_KEYWORDS (0x0002) // Disable expansion of MS extended keywords -#define UNDNAME_NO_FUNCTION_RETURNS (0x0004) // Disable expansion of return type for primary declaration -#define UNDNAME_NO_ALLOCATION_MODEL (0x0008) // Disable expansion of the declaration model -#define UNDNAME_NO_ALLOCATION_LANGUAGE (0x0010) // Disable expansion of the declaration language specifier -#define UNDNAME_NO_MS_THISTYPE (0x0020) // NYI Disable expansion of MS keywords on the 'this' type for primary declaration -#define UNDNAME_NO_CV_THISTYPE (0x0040) // NYI Disable expansion of CV modifiers on the 'this' type for primary declaration -#define UNDNAME_NO_THISTYPE (0x0060) // Disable all modifiers on the 'this' type -#define UNDNAME_NO_ACCESS_SPECIFIERS (0x0080) // Disable expansion of access specifiers for members -#define UNDNAME_NO_THROW_SIGNATURES (0x0100) // Disable expansion of 'throw-signatures' for functions and pointers to functions -#define UNDNAME_NO_MEMBER_TYPE (0x0200) // Disable expansion of 'static' or 'virtual'ness of members -#define UNDNAME_NO_RETURN_UDT_MODEL (0x0400) // Disable expansion of MS model for UDT returns -#define UNDNAME_32_BIT_DECODE (0x0800) // Undecorate 32-bit decorated names -#define UNDNAME_NAME_ONLY (0x1000) // Crack only the name for primary declaration; - // return just [scope::]name. Does expand template params -#define UNDNAME_NO_ARGUMENTS (0x2000) // Don't undecorate arguments to function -#define UNDNAME_NO_SPECIAL_SYMS (0x4000) // Don't undecorate special names (v-table, vcall, vector xxx, metatype, etc) - - -DWORD -__declspec(dllimport) __stdcall -UnDecorateSymbolName( - PCSTR name, - PSTR outputString, - DWORD maxStringLength, - DWORD flags -); diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.jnaerator b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.jnaerator deleted file mode 100644 index 58a1c22b5..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport.jnaerator +++ /dev/null @@ -1,30 +0,0 @@ -//-v -//-preprocessingOut "$(DIR)/prepro.out.cpp" -//-nocpp -//-DUNICODE -//-DCONST=const -//-D_X86_ -//-D_M_IX86 -//-DHANDLE=void* -//-DSIZE_T=size_t -//"-DWINAPI=__declspec(dllexport)" - -//-DVOID=void -//-DPDWORD=int* -//-DPWORD=short* --DPWSTR=wchar_t* --noComp --library DbgHelp - //WinBase.h - //WinNT.h - //"-Ic:\Program Files\Microsoft SDKs\Windows\v6.0A\Include" - //"c:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinDef.h" - //"c:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinBase.h" - //"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\Windows.h" - //"c:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinNT.h" - "$(DIR)/dllexport.h" - --package com.ochafik.lang.jnaerator.nativesupport.dllexport - --o "$(DIR)/../../../../.." - diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/DbgHelpLibrary.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/DbgHelpLibrary.java deleted file mode 100644 index 5a2f3e9f8..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/DbgHelpLibrary.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * JNA Wrapper for library DbgHelp
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public interface DbgHelpLibrary extends com.sun.jna.Library { - public static final com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary INSTANCE = (com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary)com.sun.jna.Native.loadLibrary(com.ochafik.lang.jnaerator.runtime.LibraryExtractor.getLibraryPath("DbgHelp", true, com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.class), com.ochafik.lang.jnaerator.nativesupport.dllexport.DbgHelpLibrary.class, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_ACCESS_SPECIFIERS = (128); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_SPECIAL_SYMS = (16384); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_MS_THISTYPE = (32); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NAME_ONLY = (4096); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_IAT = 12; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_THISTYPE = (96); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_RESOURCE = 2; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_BASERELOC = 5; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_THROW_SIGNATURES = (256); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_ARGUMENTS = (8192); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_TLS = 9; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_32_BIT_DECODE = (2048); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_IMPORT = 1; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_ALLOCATION_MODEL = (8); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_RETURN_UDT_MODEL = (1024); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_LEADING_UNDERSCORES = (1); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_SIZEOF_SHORT_NAME = 8; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_COMPLETE = (0); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_DEBUG = 6; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_CV_THISTYPE = (64); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_MS_KEYWORDS = (2); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_EXPORT = 0; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DIRECTORY_ENTRY_SECURITY = 4; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_FUNCTION_RETURNS = (4); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_MEMBER_TYPE = (512); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int UNDNAME_NO_ALLOCATION_LANGUAGE = (16); - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_NT_SIGNATURE = 17744; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h - public static final int IMAGE_DOS_SIGNATURE = 23117; - /** - * Original signature : UnDecorateSymbolName(PCSTR, PSTR, DWORD, DWORD)
      - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h:166
      - * @deprecated use the safer methods {@link #UnDecorateSymbolName(java.lang.String, com.ochafik.lang.jnaerator.runtime.StringPointer.ByValue, int, int)} and {@link #UnDecorateSymbolName(java.lang.String, java.nio.ByteBuffer, int, int)} instead - */ - @com.ochafik.lang.jnaerator.runtime.Mangling({"_Z20UnDecorateSymbolName5PCSTR4PSTR5DWORD5DWORD", "?UnDecorateSymbolName@@YGX5PCSTR4PSTR5DWORD5DWORD@Z"}) - @java.lang.Deprecated - int UnDecorateSymbolName(com.sun.jna.ptr.ByteByReference name, com.sun.jna.ptr.ByteByReference outputString, int maxStringLength, int flags); - /** - * Original signature : UnDecorateSymbolName(PCSTR, PSTR, DWORD, DWORD)
      - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h:166 - */ - @com.ochafik.lang.jnaerator.runtime.Mangling({"_Z20UnDecorateSymbolName5PCSTR4PSTR5DWORD5DWORD", "?UnDecorateSymbolName@@YGX5PCSTR4PSTR5DWORD5DWORD@Z"}) - int UnDecorateSymbolName(java.lang.String name, java.nio.ByteBuffer outputString, int maxStringLength, int flags); -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DATA_DIRECTORY.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DATA_DIRECTORY.java deleted file mode 100644 index 07abe063f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DATA_DIRECTORY.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_DATA_DIRECTORY extends com.ochafik.lang.jnaerator.runtime.Structure { - public int VirtualAddress; - public int Size; - public IMAGE_DATA_DIRECTORY() { - super(); - } - public IMAGE_DATA_DIRECTORY(int VirtualAddress, int Size) { - super(); - this.VirtualAddress = VirtualAddress; - this.Size = Size; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_DATA_DIRECTORY newInstance() { return new IMAGE_DATA_DIRECTORY(); } - public static class ByReference extends IMAGE_DATA_DIRECTORY implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_DATA_DIRECTORY implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DOS_HEADER.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DOS_HEADER.java deleted file mode 100644 index dc41a7300..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_DOS_HEADER.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_DOS_HEADER extends com.ochafik.lang.jnaerator.runtime.Structure { - /// Magic number - public short e_magic; - /// Bytes on last page of file - public short e_cblp; - /// Pages in file - public short e_cp; - /// Relocations - public short e_crlc; - /// Size of header in paragraphs - public short e_cparhdr; - /// Minimum extra paragraphs needed - public short e_minalloc; - /// Maximum extra paragraphs needed - public short e_maxalloc; - /// Initial (relative) SS value - public short e_ss; - /// Initial SP value - public short e_sp; - /// Checksum - public short e_csum; - /// Initial IP value - public short e_ip; - /// Initial (relative) CS value - public short e_cs; - /// File address of relocation table - public short e_lfarlc; - /// Overlay number - public short e_ovno; - /// Reserved words - public short[] e_res = new short[(4)]; - /// OEM identifier (for e_oeminfo) - public short e_oemid; - /// OEM information; e_oemid specific - public short e_oeminfo; - /// Reserved words - public short[] e_res2 = new short[(10)]; - /// File address of new exe header - public com.sun.jna.NativeLong e_lfanew; - public IMAGE_DOS_HEADER() { - super(); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_DOS_HEADER newInstance() { return new IMAGE_DOS_HEADER(); } - public static class ByReference extends IMAGE_DOS_HEADER implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_DOS_HEADER implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_EXPORT_DIRECTORY.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_EXPORT_DIRECTORY.java deleted file mode 100644 index c849a30da..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_EXPORT_DIRECTORY.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_EXPORT_DIRECTORY extends com.ochafik.lang.jnaerator.runtime.Structure { - public int Characteristics; - public int TimeDateStamp; - public short MajorVersion; - public short MinorVersion; - public int Name; - public int Base; - public int NumberOfFunctions; - public int NumberOfNames; - public com.sun.jna.ptr.PointerByReference AddressOfFunctions; - public com.sun.jna.ptr.PointerByReference AddressOfNames; - public com.sun.jna.ptr.PointerByReference AddressOfNameOrdinals; - public IMAGE_EXPORT_DIRECTORY() { - super(); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_EXPORT_DIRECTORY newInstance() { return new IMAGE_EXPORT_DIRECTORY(); } - public static class ByReference extends IMAGE_EXPORT_DIRECTORY implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_EXPORT_DIRECTORY implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_FILE_HEADER.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_FILE_HEADER.java deleted file mode 100644 index 936518e7d..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_FILE_HEADER.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_FILE_HEADER extends com.ochafik.lang.jnaerator.runtime.Structure { - public short Machine; - public short NumberOfSections; - public int TimeDateStamp; - public int PointerToSymbolTable; - public int NumberOfSymbols; - public short SizeOfOptionalHeader; - public short Characteristics; - public IMAGE_FILE_HEADER() { - super(); - } - public IMAGE_FILE_HEADER(short Machine, short NumberOfSections, int TimeDateStamp, int PointerToSymbolTable, int NumberOfSymbols, short SizeOfOptionalHeader, short Characteristics) { - super(); - this.Machine = Machine; - this.NumberOfSections = NumberOfSections; - this.TimeDateStamp = TimeDateStamp; - this.PointerToSymbolTable = PointerToSymbolTable; - this.NumberOfSymbols = NumberOfSymbols; - this.SizeOfOptionalHeader = SizeOfOptionalHeader; - this.Characteristics = Characteristics; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_FILE_HEADER newInstance() { return new IMAGE_FILE_HEADER(); } - public static class ByReference extends IMAGE_FILE_HEADER implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_FILE_HEADER implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_NT_HEADERS.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_NT_HEADERS.java deleted file mode 100644 index fd66450d1..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_NT_HEADERS.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_NT_HEADERS extends com.ochafik.lang.jnaerator.runtime.Structure { - public int Signature; - public com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_FILE_HEADER FileHeader; - public com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_OPTIONAL_HEADER OptionalHeader; - public IMAGE_NT_HEADERS() { - super(); - } - public IMAGE_NT_HEADERS(int Signature, com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_FILE_HEADER FileHeader, com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_OPTIONAL_HEADER OptionalHeader) { - super(); - this.Signature = Signature; - this.FileHeader = FileHeader; - this.OptionalHeader = OptionalHeader; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_NT_HEADERS newInstance() { return new IMAGE_NT_HEADERS(); } - public static class ByReference extends IMAGE_NT_HEADERS implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_NT_HEADERS implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_OPTIONAL_HEADER.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_OPTIONAL_HEADER.java deleted file mode 100644 index c43c08053..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_OPTIONAL_HEADER.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_OPTIONAL_HEADER extends com.ochafik.lang.jnaerator.runtime.Structure { - public short Magic; - public byte MajorLinkerVersion; - public byte MinorLinkerVersion; - public int SizeOfCode; - public int SizeOfInitializedData; - public int SizeOfUninitializedData; - public int AddressOfEntryPoint; - public int BaseOfCode; - public int BaseOfData; - public int ImageBase; - public int SectionAlignment; - public int FileAlignment; - public short MajorOperatingSystemVersion; - public short MinorOperatingSystemVersion; - public short MajorImageVersion; - public short MinorImageVersion; - public short MajorSubsystemVersion; - public short MinorSubsystemVersion; - public int Reserved1; - public int SizeOfImage; - public int SizeOfHeaders; - public int CheckSum; - public short Subsystem; - public short DllCharacteristics; - public int SizeOfStackReserve; - public int SizeOfStackCommit; - public int SizeOfHeapReserve; - public int SizeOfHeapCommit; - public int LoaderFlags; - public int NumberOfRvaAndSizes; - public com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_DATA_DIRECTORY[] DataDirectory = new com.ochafik.lang.jnaerator.nativesupport.dllexport.IMAGE_DATA_DIRECTORY[(16)]; - public IMAGE_OPTIONAL_HEADER() { - super(); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_OPTIONAL_HEADER newInstance() { return new IMAGE_OPTIONAL_HEADER(); } - public static class ByReference extends IMAGE_OPTIONAL_HEADER implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_OPTIONAL_HEADER implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_SECTION_HEADER.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_SECTION_HEADER.java deleted file mode 100644 index 5b579fbb0..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/dllexport/IMAGE_SECTION_HEADER.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.dllexport; -/** - * native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class IMAGE_SECTION_HEADER extends com.ochafik.lang.jnaerator.runtime.Structure { - public byte[] Name = new byte[(8)]; - public Misc_union Misc; - public int VirtualAddress; - public int SizeOfRawData; - public int PointerToRawData; - public int PointerToRelocations; - public int PointerToLinenumbers; - public short NumberOfRelocations; - public short NumberOfLinenumbers; - public int Characteristics; - /// native declaration : C:\Prog\jnaerator\sources\com\ochafik\lang\jnaerator\nativesupport\dllexport.h:94 - public static class Misc_union extends com.ochafik.lang.jnaerator.runtime.Union { - public int PhysicalAddress; - public int VirtualSize; - public Misc_union() { - super(); - } - public Misc_union(int PhysicalAddress_or_VirtualSize) { - super(); - this.VirtualSize = this.PhysicalAddress = PhysicalAddress_or_VirtualSize; - setType(Integer.TYPE); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected Misc_union newInstance() { return new Misc_union(); } - public static class ByReference extends Misc_union implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends Misc_union implements com.sun.jna.Structure.ByValue {} - } - public IMAGE_SECTION_HEADER() { - super(); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected IMAGE_SECTION_HEADER newInstance() { return new IMAGE_SECTION_HEADER(); } - public static class ByReference extends IMAGE_SECTION_HEADER implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends IMAGE_SECTION_HEADER implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.h b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.h deleted file mode 100644 index e90426b3f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.h +++ /dev/null @@ -1,147 +0,0 @@ -//http://whine.fr/2009/un-format-pas-si-macho/ -//http://www.cilinder.be/docs/next/NeXTStep/3.3/nd/DevTools/14_MachO/MachO.htmld/index.html - -typedef int cpu_type_t; -typedef int cpu_subtype_t; - - -#define CPU_TYPE_MC680x0 ((cpu_type_t) 6) -#define CPU_SUBTYPE_MC68030 ((cpu_subtype_t) 1) -#define CPU_SUBTYPE_MC68040 ((cpu_subtype_t) 2) - - - -struct fat_header -{ - uint32_t magic; - uint32_t nfat_arch; -}; - -struct fat_arch -{ - cpu_type_t cputype; - cpu_subtype_t cpusubtype; - uint32_t offset; - uint32_t size; - uint32_t align; -}; - -#define MH_MAGIC 0xfeedface /* the Mach magic number */ - -#define MH_OBJECT 0x1 /* relocatable object file */ -#define MH_EXECUTE 0x2 /* executable object file */ -#define MH_FVMLIB 0x3 /* fixed vm shared library file */ -#define MH_CORE 0x4 /* core file */ -#define MH_PRELOAD 0x5 /* preloaded executable file */ - -#define MH_NOUNDEFS 0x1 /* object file has no undefined references; -can be executed */ -#define MH_INCRLINK 0x2 /* object file is the output of an -incremental link against a base file; -can't be link-edited again */ - -#define long int - -struct mach_header { - unsigned long magic; /* Mach magic number identifier */ - cpu_type_t cputype; /* cpu specifier */ - cpu_subtype_t cpusubtype; /* machine specifier */ - unsigned long filetype; /* type of file */ - unsigned long ncmds; /* number of load commands */ - unsigned long sizeofcmds; /* size of all load commands */ - unsigned long flags; /* flags */ -}; - - -#define LC_SEGMENT 0x1 /* file segment to be mapped */ -#define LC_SYMTAB 0x2 /* link-edit stab symbol table info -(obsolete) */ -#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info */ -#define LC_THREAD 0x4 /* thread */ -#define LC_UNIXTHREAD 0x5 /* UNIX thread (includes a stack) */ -#define LC_LOADFVMLIB 0x6 /* load a fixed VM shared library */ -#define LC_IDFVMLIB 0x7 /* fixed VM shared library id */ -#define LC_IDENT 0x8 /* object identification information -(obsolete) */ -#define LC_FVMFILE 0x9 /* fixed VM file inclusion */ - - -struct load_command { - unsigned long cmd; /* type of load command */ - unsigned long cmdsize; /* total size of command in bytes */ -}; - -struct symtab_command { - unsigned long cmd; /* LC_SYMTAB */ - unsigned long cmdsize; /* sizeof(struct symtab_command) */ - unsigned long symoff; /* symbol table offset */ - unsigned long nsyms; /* number of symbol table entries */ - unsigned long stroff; /* string table offset */ - unsigned long strsize; /* string table size in bytes */ -}; - -struct nlist { - union { - char *n_name; /* for use when in-core */ - long n_strx; /* index into file string table */ - } n_un; -#if 1 - unsigned char n_type; /* type flag; see below */ -#else - unsigned char N_STAB:3, - N_TYPE:4, - N_EXT:1; -#endif - unsigned char n_sect; /* section number or NO_SECT */ - short n_desc; /* see the header file stab.h */ - unsigned n_value; /* value of this symbol table entry - (or stab offset) */ -}; - -/* -* Simple values for n_type. -*/ - -#define N_UNDF 0x0 /* undefined */ -#define N_ABS 0x2 /* absolute */ -#define N_TEXT 0x4 /* text */ -#define N_DATA 0x6 /* data */ -#define N_BSS 0x8 /* bss */ - -#define N_EXT 01 /* external bit, orÕed in */ - -/* -* Other permanent symbol table entries have some of the N_STAB bits set. -* These are given in -*/ - -#define N_STAB 0xe0 /* if any of these bits set, donÕt discard */ - -#define N_GSYM 0x20 /* global symbol: name,,0,type,0 */ -#define N_FNAME 0x22 /* procedure name (f77 kludge): name,,0 */ -#define N_FUN 0x24 /* procedure: name,,0,linenumber,address */ -#define N_STSYM 0x26 /* static symbol: name,,0,type,address */ -#define N_LCSYM 0x28 /* .lcomm symbol: name,,0,type,address */ -#define N_RSYM 0x40 /* register sym: name,,0,type,register */ -#define N_SLINE 0x44 /* src line: 0,,0,linenumber,address */ -#define N_SSYM 0x60 /* structure elt: name,,0,type,struct_offset */ -#define N_SO 0x64 /* source file name: name,,0,0,address */ -#define N_LSYM 0x80 /* local sym: name,,0,type,offset */ -#define N_SOL 0x84 /* #included file name: name,,0,0,address */ -#define N_PSYM 0xa0 /* parameter: name,,0,type,offset */ -#define N_ENTRY 0xa4 /* alternate entry: name,linenumber,address */ -#define N_LBRAC 0xc0 /* left bracket: 0,,0,nesting level,address */ -#define N_RBRAC 0xe0 /* right bracket: 0,,0,nesting level,address */ -#define N_BCOMM 0xe2 /* begin common: name,, */ -#define N_ECOMM 0xe4 /* end common: name,, */ -#define N_ECOML 0xe8 /* end common (local name): ,,address */ -#define N_LENG 0xfe /* second stab entry with length information */ - - -#define N_UNDF 0x0 /* undefined; n_sect == NO_SECT */ -#define N_ABS 0x2 /* absolute; n_sect == NO_SECT */ -#define N_SECT 0xe /* defined in section number n_sect */ -#define N_INDR 0xa /* indirect */ - -#define FAT_MAGIC 0xCAFEBABE -#define FAT_CIGAM 0xEBABEFAC diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.jnaerator b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.jnaerator deleted file mode 100644 index 8729b7593..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport.jnaerator +++ /dev/null @@ -1,8 +0,0 @@ --DPWSTR=wchar_t* --library FatMachO - "$(DIR)/machoexport.h" - --package com.ochafik.lang.jnaerator.nativesupport.machoexport --noComp --o "$(DIR)/../../../../.." - diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/FatMachOLibrary.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/FatMachOLibrary.java deleted file mode 100644 index b4cddce11..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/FatMachOLibrary.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * JNA Wrapper for library FatMachO
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public interface FatMachOLibrary extends com.sun.jna.Library { - public static final com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary INSTANCE = (com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary)com.sun.jna.Native.loadLibrary(com.ochafik.lang.jnaerator.runtime.LibraryExtractor.getLibraryPath("FatMachO", true, com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary.class), com.ochafik.lang.jnaerator.nativesupport.machoexport.FatMachOLibrary.class, com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper.DEFAULT_OPTIONS); - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_SLINE = 68; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_PRELOAD = 5; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_INCRLINK = 2; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_RBRAC = 224; - /** - * define
      - * SKIPPED:
      - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h
      - * (cpu_subtype_t) - */ - /** - * define
      - * Conversion Error : int (The name 'long' is invalid for a Java field.)
      - * SKIPPED:
      - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h
      - * int - */ - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_SOL = 132; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_GSYM = 32; - /** - * define
      - * SKIPPED:
      - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h
      - * (cpu_type_t) - */ - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_IDENT = 8; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int FAT_CIGAM = -341053524; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int FAT_MAGIC = -889275714; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_ENTRY = 164; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_LBRAC = 192; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_SECT = 14; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_PSYM = 160; - /** - * define
      - * SKIPPED:
      - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h
      - * (cpu_subtype_t) - */ - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_STSYM = 38; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_MAGIC = -17958194; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_IDFVMLIB = 7; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_STAB = 224; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_FVMFILE = 9; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_OBJECT = 1; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_SEGMENT = 1; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_LSYM = 128; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_NOUNDEFS = 1; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_SYMTAB = 2; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_TEXT = 4; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_INDR = 10; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_ABS = 2; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_LENG = 254; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_ECOML = 232; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_FNAME = 34; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_SYMSEG = 3; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_CORE = 4; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_LOADFVMLIB = 6; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_UNDF = 0; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_BSS = 8; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_EXECUTE = 2; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_UNIXTHREAD = 5; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int LC_THREAD = 4; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int MH_FVMLIB = 3; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_FUN = 36; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_ECOMM = 228; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_SSYM = 96; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_LCSYM = 40; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_BCOMM = 226; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_SO = 100; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_RSYM = 64; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h - public static final int N_DATA = 6; -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_arch.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_arch.java deleted file mode 100644 index 9dd8d14ce..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_arch.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:20
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class fat_arch extends com.ochafik.lang.jnaerator.runtime.Structure { - public int cputype; - public int cpusubtype; - public int offset; - public int size; - public int align; - public fat_arch() { - super(); - } - public fat_arch(int cputype, int cpusubtype, int offset, int size, int align) { - super(); - this.cputype = cputype; - this.cpusubtype = cpusubtype; - this.offset = offset; - this.size = size; - this.align = align; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected fat_arch newInstance() { return new fat_arch(); } - public static class ByReference extends fat_arch implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends fat_arch implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_header.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_header.java deleted file mode 100644 index 1666b219f..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/fat_header.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:14
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class fat_header extends com.ochafik.lang.jnaerator.runtime.Structure { - public int magic; - public int nfat_arch; - public fat_header() { - super(); - } - public fat_header(int magic, int nfat_arch) { - super(); - this.magic = magic; - this.nfat_arch = nfat_arch; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected fat_header newInstance() { return new fat_header(); } - public static class ByReference extends fat_header implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends fat_header implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/load_command.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/load_command.java deleted file mode 100644 index 00dbd96c4..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/load_command.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:64
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class load_command extends com.ochafik.lang.jnaerator.runtime.Structure { - /// type of load command - public int cmd; - /// total size of command in bytes - public int cmdsize; - public load_command() { - super(); - } - /** - * @param cmd type of load command
      - * @param cmdsize total size of command in bytes - */ - public load_command(int cmd, int cmdsize) { - super(); - this.cmd = cmd; - this.cmdsize = cmdsize; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected load_command newInstance() { return new load_command(); } - public static class ByReference extends load_command implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends load_command implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/mach_header.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/mach_header.java deleted file mode 100644 index 8896fa8bc..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/mach_header.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:42
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class mach_header extends com.ochafik.lang.jnaerator.runtime.Structure { - /// Mach magic number identifier - public int magic; - /// cpu specifier - public int cputype; - /// machine specifier - public int cpusubtype; - /// type of file - public int filetype; - /// number of load commands - public int ncmds; - /// size of all load commands - public int sizeofcmds; - /// flags - public int flags; - public mach_header() { - super(); - } - /** - * @param magic Mach magic number identifier
      - * @param cputype cpu specifier
      - * @param cpusubtype machine specifier
      - * @param filetype type of file
      - * @param ncmds number of load commands
      - * @param sizeofcmds size of all load commands
      - * @param flags flags - */ - public mach_header(int magic, int cputype, int cpusubtype, int filetype, int ncmds, int sizeofcmds, int flags) { - super(); - this.magic = magic; - this.cputype = cputype; - this.cpusubtype = cpusubtype; - this.filetype = filetype; - this.ncmds = ncmds; - this.sizeofcmds = sizeofcmds; - this.flags = flags; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected mach_header newInstance() { return new mach_header(); } - public static class ByReference extends mach_header implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends mach_header implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/nlist.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/nlist.java deleted file mode 100644 index 121ae0cd2..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/nlist.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:78
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class nlist extends com.ochafik.lang.jnaerator.runtime.Structure { - public n_un_union n_un; - /// type flag; see below - public byte n_type; - /// section number or NO_SECT - public byte n_sect; - /// see the header file stab.h - public short n_desc; - /** - * value of this symbol table entry
      - * (or stab offset) - */ - public int n_value; - /// native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:79 - public static class n_un_union extends com.ochafik.lang.jnaerator.runtime.Union { - /// for use when in-core - public com.sun.jna.ptr.ByteByReference n_name; - /// index into file string table - public int n_strx; - public n_un_union() { - super(); - } - /// @param n_strx index into file string table - public n_un_union(int n_strx) { - super(); - this.n_strx = n_strx; - setType(Integer.TYPE); - } - /// @param n_name for use when in-core - public n_un_union(com.sun.jna.ptr.ByteByReference n_name) { - super(); - this.n_name = n_name; - setType(com.sun.jna.ptr.ByteByReference.class); - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected n_un_union newInstance() { return new n_un_union(); } - public static class ByReference extends n_un_union implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends n_un_union implements com.sun.jna.Structure.ByValue {} - } - public nlist() { - super(); - } - /** - * @param n_type type flag; see below
      - * @param n_sect section number or NO_SECT
      - * @param n_desc see the header file stab.h
      - * @param n_value value of this symbol table entry
      - * (or stab offset) - */ - public nlist(n_un_union n_un, byte n_type, byte n_sect, short n_desc, int n_value) { - super(); - this.n_un = n_un; - this.n_type = n_type; - this.n_sect = n_sect; - this.n_desc = n_desc; - this.n_value = n_value; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected nlist newInstance() { return new nlist(); } - public static class ByReference extends nlist implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends nlist implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/symtab_command.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/symtab_command.java deleted file mode 100644 index c5a6e00d3..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/nativesupport/machoexport/symtab_command.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ochafik.lang.jnaerator.nativesupport.machoexport; -/** - * native declaration : sources/com/ochafik/lang/jnaerator/nativesupport/machoexport.h:69
      - * This file was autogenerated by JNAerator,
      - * a tool written by Olivier Chafik that uses a few opensource projects..
      - * For help, please visit NativeLibs4Java, Rococoa, or JNA. - */ -public class symtab_command extends com.ochafik.lang.jnaerator.runtime.Structure { - /// LC_SYMTAB - public int cmd; - /// sizeof(struct symtab_command) - public int cmdsize; - /// symbol table offset - public int symoff; - /// number of symbol table entries - public int nsyms; - /// string table offset - public int stroff; - /// string table size in bytes - public int strsize; - public symtab_command() { - super(); - } - /** - * @param cmd LC_SYMTAB
      - * @param cmdsize sizeof(struct symtab_command)
      - * @param symoff symbol table offset
      - * @param nsyms number of symbol table entries
      - * @param stroff string table offset
      - * @param strsize string table size in bytes - */ - public symtab_command(int cmd, int cmdsize, int symoff, int nsyms, int stroff, int strsize) { - super(); - this.cmd = cmd; - this.cmdsize = cmdsize; - this.symoff = symoff; - this.nsyms = nsyms; - this.stroff = stroff; - this.strsize = strsize; - } - protected ByReference newByReference() { return new ByReference(); } - protected ByValue newByValue() { return new ByValue(); } - protected symtab_command newInstance() { return new symtab_command(); } - public static class ByReference extends symtab_command implements com.sun.jna.Structure.ByReference {} - public static class ByValue extends symtab_command implements com.sun.jna.Structure.ByValue {} -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/AbstractNode.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/AbstractNode.java deleted file mode 100644 index 1be0bca8a..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/AbstractNode.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.studio; - -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - -import com.ochafik.util.IteratorEnumeration; - -abstract class AbstractNode implements TreeNode { - - protected final String name; - protected final TreeNode parent; - protected List children; - - public AbstractNode(TreeNode parent, String name) { - this.name = name; - this.parent = parent; - } - - - @SuppressWarnings("unchecked") - @Override - public Enumeration children() { - buildChildren(); - return new IteratorEnumeration(children.iterator()); - } - @Override - public boolean getAllowsChildren() { - buildChildren(); - return !children.isEmpty(); - } - - @Override - public TreeNode getChildAt(int childIndex) { - buildChildren(); - return children.get(childIndex); - } - - @Override - public int getChildCount() { - buildChildren(); - return children.size(); - } - - @Override - public int getIndex(TreeNode node) { - buildChildren(); - return children.indexOf(node); - } - - @Override - public TreeNode getParent() { - return parent; - } - - @Override - public boolean isLeaf() { - buildChildren(); - return children.isEmpty(); - } - public abstract void buildChildren(); - - @Override - public String toString() { - return name; - } - - public abstract String getContent(); -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementListNode.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementListNode.java deleted file mode 100644 index 9cd3f19bf..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementListNode.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.studio; - -import java.util.ArrayList; -import java.util.Collection; -import javax.swing.tree.TreeNode; - -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.util.string.StringUtils; - -class ElementListNode extends AbstractNode { - - public ElementListNode(TreeNode parent, String name, Collection elements) { - super(parent, name); - this.elements = elements; - } - - final Collection elements; - - @Override - public void buildChildren() { - children = new ArrayList(); - for (Element e: elements) - if (e != null) - children.add(new ElementNode(this, null, e)); - } - - @Override - public String getContent() { - return StringUtils.implode(elements, "\n"); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementNode.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementNode.java deleted file mode 100644 index 3960d2049..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ElementNode.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.studio; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; - -import javax.swing.tree.TreeNode; - -import com.ochafik.beans.BeansUtils; -import com.ochafik.lang.jnaerator.parser.Element; -import com.ochafik.lang.reflect.GettersAndSettersHelper; - -class ElementNode extends AbstractNode { - public ElementNode(TreeNode parent, String name, Element element) { - super(parent, name); - this.element = element; - - } - final Element element; - - @SuppressWarnings("unchecked") - @Override - public void buildChildren() { - if (children != null) - return; - GettersAndSettersHelper helper = element.getGettersAndSetters(); - children = new ArrayList(); - for (String fieldName : helper.getFieldNames()) { - if (fieldName.equals("parentElement")) - continue; - if (fieldName.equals("previousSibling")) - continue; - if (fieldName.equals("nextSibling")) - continue; - - try { -// if (helper.getGetter(fieldName) == null || helper.getSetter(fieldName) == null) -// continue; - - Type c = helper.getFieldType(fieldName); - Object beanValue = BeansUtils.get(element, fieldName); - if (beanValue == null) - continue; - if (c instanceof Class && Element.class.isAssignableFrom((Class)c)) { - children.add(new ElementNode(this, fieldName, (Element)beanValue)); - } else if (c instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType)c; - if (pt.getRawType() instanceof Class && Collection.class.isAssignableFrom((Class)pt.getRawType())) { - if (pt.getActualTypeArguments().length == 1) { - Type ptt = pt.getActualTypeArguments()[0]; - if (ptt instanceof Class && Element.class.isAssignableFrom((Class)ptt)) { - Collection list = (Collection)beanValue; - if (!list.isEmpty()) - children.add(new ElementListNode(this, fieldName, list)); - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - @Override - public String getContent() { - return element.toString(); - } - - @Override - public String toString() { - String s = super.toString(); - if (s == null) { -// if (element instanceof Declaration) { -// s = ((Declaration)element).getName(); -// if (s == null) -// s = element.getClass().getSimpleName(); -// else -// s += " (" + element.getClass().getSimpleName() + ")"; -// } else - s = element.getClass().getSimpleName(); - } else - s += " (" + element.getClass().getSimpleName() + ")"; - - return s; - } - - public Element getElement() { - return element; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/JNAeratorStudio.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/JNAeratorStudio.java deleted file mode 100644 index 14bf35bf1..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/JNAeratorStudio.java +++ /dev/null @@ -1,794 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.studio; - -import com.ochafik.lang.jnaerator.JNAeratorConfig.Runtime; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.InputEvent; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.prefs.Preferences; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.JToolBar; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; - -import com.ochafik.io.JTextAreaOutputStream; -import com.ochafik.io.ReadText; -import com.ochafik.io.WriteText; -import com.ochafik.lang.SyntaxUtils; -import com.ochafik.lang.compiler.MemoryFileManager; -import com.ochafik.lang.jnaerator.ClassOutputter; -import com.ochafik.lang.jnaerator.JNAerator; -import com.ochafik.lang.jnaerator.JNAeratorCommandLineArgs; -import com.ochafik.lang.jnaerator.JNAeratorConfig; -import com.ochafik.lang.jnaerator.Result; -import com.ochafik.lang.jnaerator.SourceFiles; -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.JNAeratorConfig.OutputMode; -import com.ochafik.swing.SimpleDocumentAdapter; -import com.ochafik.swing.UndoRedoUtils; -import com.ochafik.swing.syntaxcoloring.CCTokenMarker; -import com.ochafik.swing.syntaxcoloring.JEditTextArea; -import com.ochafik.swing.syntaxcoloring.JavaTokenMarker; -import com.ochafik.swing.syntaxcoloring.TokenMarker; -import com.ochafik.util.SystemUtils; -import com.ochafik.util.listenable.ListenableCollections; -import com.ochafik.util.listenable.ListenableComboModel; -import com.ochafik.util.listenable.ListenableList; -import java.util.List; - -/* -include com/ochafik/lang/jnaerator/examples/*.h - */ -/// https://jna.dev.java.net/servlets/ReadMsg?list=users&msgNo=1988 -@SuppressWarnings("serial") -public class JNAeratorStudio extends JPanel { - private static final long serialVersionUID = -6061806156049213635L; - private static final String PREF_RADIX = "JNAeratorStudio."; - JEditTextArea sourceArea = textArea(new JavaTokenMarker()); - JEditTextArea resultArea = textArea(new CCTokenMarker()); - JTextField libraryName = new JTextField("test"); - JLabel classCountLabel = new JLabel("JNAerated class :"); -// JList resultsList = new JList(); - JComboBox resultsListCombo = new JComboBox(); - JCheckBox directCallingCb = new JCheckBox("Direct Calling", false), - structsAsTopLevelClassesCb = new JCheckBox("Structs as Top-Level classes", true), - charPtrAsString = new JCheckBox("char*/wchar_t* as (W)String", false), - reificationCb = new JCheckBox("Reification", false), - convertBodiesCb = new JCheckBox("Convert Statements (experimental, BridJ only)", false), - genRawBindingsCb = new JCheckBox("Generate raw bindings (BridJ only)", false), - //scalaSettersCb = new JCheckBox("Scala struct field setters", false), - beautifyNamesCb = new JCheckBox("Beautify names", false), - noCommentCb = new JCheckBox("No comments", false); - - JComboBox runtimeCombo; - JComboBox modeCombo; - - JTextArea errorsArea = new JTextArea(); - JSplitPane sp; - ListenableList results = ListenableCollections.listenableList(new ArrayList()); - MemoryFileManager memoryFileManager; - static MouseWheelListener mouseWheelListener = new MouseWheelListener() { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - JEditTextArea ta = SyntaxUtils.as(e.getSource(), JEditTextArea.class); - if (ta == null) - return; - - int line = ta.getFirstLine(); - if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { - int u = e.getUnitsToScroll(); - line += u > 0 ? 1 : -1; - if (line < 0) - line = 0; - else if (line >= ta.getLineCount()) - line = ta.getLineCount() - 1; - - ta.setFirstLine(line); - } - } - - }; - public void error(String title, String message, Throwable th) { - error(this, title, message, th); - } - public static void error(Component parent, String title, String message, Throwable th) { - StringWriter sw = new StringWriter(); - th.printStackTrace(new PrintWriter(sw)); - JScrollPane jsp = new JScrollPane(new JTextArea(sw.toString())) { - public Dimension getMaximumSize() { - return new Dimension(500, 500); - }; - }; -// jsp.setMaximumSize(new Dimension(500, 500)); - JOptionPane.showMessageDialog( - parent, - new Object[] { - message, - jsp - }, - title == null ? "JNAerator Error" : title, - -1 - ); - } - public File getDir(String name) { - File dir = new File(getDir(), name); - dir.mkdirs(); - return dir; - } - public File getDir() { - File dir = new File(System.getProperty("user.home")); - dir = new File(dir, ".jnaeratorStudio"); - dir = new File(dir, "pad"); - dir.mkdirs(); - return dir; - } - public File getInputFile() { - return new File(getDir(), "input.h"); - } - public File getOutputDir() { - return new File(getDir(), "out"); - } - public File getOutputJarFile() { - String lib = libraryName.getText().trim(); - if (lib.length() == 0) - lib = "out"; - return new File(getDir(), lib + ".jar"); - } - void save() throws IOException { - WriteText.writeText(sourceArea.getText(), getInputFile()); - } - static JEditTextArea textArea(TokenMarker marker) { - JEditTextArea ta = new JEditTextArea() { - private static final long serialVersionUID = 1L; -// int lastCode, lastLocation; -// char lastChar = 0; - - @Override - public void processKeyEvent(KeyEvent evt) { - if (SystemUtils.isMacOSX()) { - int m = evt.getModifiers(); - if ((m & InputEvent.META_MASK) != 0) { - m = (m & ~InputEvent.META_MASK) | InputEvent.CTRL_MASK; - evt = new KeyEvent(evt.getComponent(), evt.getID(), evt.getWhen(), m, evt.getKeyCode(), evt.getKeyChar(), evt.getKeyLocation()); - if (evt.getID() == KeyEvent.KEY_TYPED) - return; - } - } - - super.processKeyEvent(evt); - } - @Override - public Dimension getMinimumSize() { - return new Dimension(100, 100); - } - }; - ta.setBorder(BorderFactory.createLoweredBevelBorder()); - ta.setFocusTraversalKeysEnabled(false); - ta.addMouseWheelListener(mouseWheelListener); - ta.setPreferredSize(new Dimension(200, 300)); - ta.setTokenMarker(marker); - return ta; - } - //static final File FILE = new File(".jnaeratorStudio.cpp"); - - public void close(JFrame f) { - try { - save(); - setPref("window.width", f.getWidth()); - setPref("window.height", f.getHeight()); - setPref("window.extendedState", f.getExtendedState()); - setPref("options.libraryName", libraryName.getText()); - setPref("options.direct", directCallingCb.isSelected()); - setPref("options.topLevelStructs", structsAsTopLevelClassesCb.isSelected()); - setPref("options.reification", reificationCb.isSelected()); - setPref("options.convertBodies", convertBodiesCb.isSelected()); - setPref("options.genRawBindings", genRawBindingsCb.isSelected()); - //setPref("options.scalaSetters", scalaSettersCb.isSelected()); - setPref("options.beautifyNames", beautifyNamesCb.isSelected()); - setPref("options.charPtrAsString", charPtrAsString.isSelected()); - setPref("options.targetRuntime", ((JNAeratorConfig.Runtime)runtimeCombo.getSelectedItem()).name()); - setPref("options.outputMode", ((JNAeratorConfig.OutputMode)modeCombo.getSelectedItem()).name()); - setPref("options.noComments", noCommentCb.isSelected()); - setPref("splitPane.orientation", sp.getOrientation()); - setPref("splitPane.dividedLocation", getProportionalDividerLocation(sp)); - prefNode().flush(); - System.exit(0); - } catch (Throwable ex) { - error(null, "Error while closing", ex); - } - } - JTabbedPane sourceTabs = new JTabbedPane(JTabbedPane.TOP), resultTabs = new JTabbedPane(JTabbedPane.TOP); - //JButton actButton = new JButton("JNAerate !"); - - void switchOrientation() { - boolean hor = sp.getOrientation() == JSplitPane.HORIZONTAL_SPLIT; - int l = sp.getDividerLocation(), d = hor ? sp.getWidth() : sp.getHeight(); - sp.setOrientation(hor ? JSplitPane.VERTICAL_SPLIT : JSplitPane.HORIZONTAL_SPLIT); - if (d != 0) - sp.setDividerLocation(l / (double)d); - } - - Action - switchOrientationAction = new AbstractAction("Switch Orientation") { - @Override - public void actionPerformed(ActionEvent e) { - switchOrientation(); - } - }, - donateAction = new AbstractAction("Donate to the author") { - @Override - public void actionPerformed(ActionEvent e) { - try { - SystemUtils.runSystemOpenURL(new URL(JNAerator.DONATE_URL)); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - }, - generateAction = new AbstractAction("JNAerate !") { - @Override - public void actionPerformed(ActionEvent e) { - generate(); - generateButton.requestFocus(); - } - }, - aboutJNAeratorAction = aboutLink("About JNAerator", JNAerator.ABOUT_JNAERATOR_URL), - aboutRococoaAction = aboutLink("About Rococoa", JNAerator.ABOUT_ROCOCOA_URL), - aboutBridJAction = aboutLink("About BridJ", JNAerator.ABOUT_BRIDJ_URL), - aboutJNAAction = aboutLink("About JNA", JNAerator.ABOUT_JNA_URL), - showExampleAction = new AbstractAction("Open Example") { - @Override - public void actionPerformed(ActionEvent e) { - if (sourceArea.getText().trim().length() > 0) { - if (JOptionPane.showConfirmDialog(JNAeratorStudio.this, "This is going to overwrite the contents of your source text area.\nProceed ?", "Open Example", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) { - return; - } - doShowExample(true); - } - } - } - ; - - AbstractAction aboutLink(final String title, final String urlString) { - return new AbstractAction(title) { - @Override - public void actionPerformed(ActionEvent e) { - try { - URL url = new URL(urlString); - System.out.println(title + ": " + url); - SystemUtils.runSystemOpenURL(url); - } catch (Exception ex) { - error(null, "Error while opening page '" + title + "'", ex); - } - } - }; - } - Object lastJNAeratedArtifact; - //JLabel statusLabel = new JLabel("", JLabel.RIGHT); - JButton showJarButton; - JPanel errorsPane = new JPanel(new BorderLayout()); - JProgressBar statusBar = new JProgressBar(); - private JButton generateButton; - public JNAeratorStudio() { - super(new BorderLayout()); - - runtimeCombo = new JComboBox(JNAeratorConfig.Runtime.values()) {{ - setToolTipText("Target runtime library"); - setSelectedItem(JNAeratorConfig.Runtime.JNAerator); - }}; - - modeCombo = new JComboBox(OutputMode.values()) {{ - setToolTipText("Output mode"); - setSelectedItem(JNAeratorConfig.OutputMode.StandaloneJar); - }}; - - resultsListCombo.setModel(new ListenableComboModel(results)); - - //animator.setAcceleration(.2f); - //animator.setDeceleration(.2f); - - JToolBar tb = new JToolBar(); - generateButton = tb.add(generateAction); - tb.add(donateAction); - tb.add(showExampleAction); - tb.add(switchOrientationAction); - tb.addSeparator(); - tb.add(aboutJNAeratorAction); - tb.addSeparator(); - tb.add(aboutBridJAction); - tb.add(aboutJNAAction); - tb.add(aboutRococoaAction); - //tb.setOrientation(JToolBar.VERTICAL); - add("North", tb); - - sourceArea.getDocument().addDocumentListener(new SimpleDocumentAdapter() { - - @Override - public void updated(DocumentEvent e) { - setReadyToJNAerate(); - } - - }); - - add("South", statusBar); - - //statusBar.setBorder(BorderFactory.createLoweredBevelBorder()); - - JComponent sourcePane = new JPanel(new BorderLayout()), resultPane = new JPanel(new BorderLayout()); - Box libBox = Box.createHorizontalBox(); - showJarButton = new JButton("Show Output"); - showJarButton.setEnabled(false); - showJarButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (lastJNAeratedArtifact == null || !(lastJNAeratedArtifact instanceof File)) - return; - - File file = (File)lastJNAeratedArtifact; - try { - if (file.isDirectory()) - SystemUtils.runSystemOpenDirectory(file); - else - SystemUtils.runSystemOpenFileParent(file); - } catch (Exception e1) { - showJarButton.setEnabled(false); - showJarButton.setToolTipText(e1.toString()); - } - } - }); - statusBar.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (lastJNAeratedArtifact != null && lastJNAeratedArtifact instanceof Throwable) - error(null, null, (Throwable)lastJNAeratedArtifact); - else - generateAction.actionPerformed(null); - } - }); - libBox.add(new JLabel("Target Runtime")); - libBox.add(runtimeCombo); - - libBox.add(new JLabel("Library Name :", JLabel.RIGHT)); - libBox.add(libraryName); - - - Box modeBox = Box.createHorizontalBox(); - modeBox.add(new JLabel("Output Mode")); - modeBox.add(modeCombo); - - Box optBox = Box.createVerticalBox(); - optBox.add(libBox); - optBox.add(modeBox); - - - JPanel optPanel = new JPanel(new GridLayout(3, 3)); - optPanel.add(directCallingCb); - optPanel.add(noCommentCb); - optPanel.add(structsAsTopLevelClassesCb); - optPanel.add(charPtrAsString); - //optPanel.add(scalaSettersCb); - optPanel.add(reificationCb); - optPanel.add(convertBodiesCb); - optPanel.add(genRawBindingsCb); - optPanel.add(beautifyNamesCb); - optBox.add(optPanel); - for (Component c : optBox.getComponents()) - ((JComponent)c).setAlignmentX(0); - - sourcePane.add("North", optBox);//raryName); - sourcePane.add("Center", sourceArea); - sourceTabs.addTab("Source", sourcePane); - - - Box resChoiceBox = Box.createHorizontalBox(); - resChoiceBox.add(classCountLabel); - resChoiceBox.add(resultsListCombo); - resChoiceBox.add(showJarButton); - - resultPane.add("North", resChoiceBox); - resultPane.add("Center", resultArea); - sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sourceTabs, resultTabs); - sp.setOneTouchExpandable(true); - sp.setResizeWeight(0.5); - //sp.setDividerLocation(0.5); - - errorsPane.add("Center", new JScrollPane(errorsArea)); - - resultTabs.add("JNAeration Results", resultPane); - resultTabs.add("Logs", errorsPane); - add("Center", sp); - //add("Center", new JSplitPane(JSplitPane.VERTICAL_SPLIT, sp, new JScrollPane(errorsArea))); - - resultsListCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { - ResultContent c = (ResultContent)resultsListCombo.getSelectedItem(); - resultArea.setText(c == null ? "" : c.getContent()); - resultArea.scrollTo(0, 0); - }}); - - try { - sourceArea.setText(ReadText.readText(getInputFile())); - sourceArea.scrollTo(0, 0); - } catch (Exception ex) {} - - if (sourceArea.getText().trim().length() == 0) - doShowExample(false); - - UndoRedoUtils.registerNewUndoManager(sourceArea, sourceArea.getDocument()); - } - void setReadyToJNAerate() { - statusBar.setToolTipText("Click to JNAerate !"); - statusBar.setMaximum(1); - statusBar.setMinimum(0); - statusBar.setValue(0); - statusBar.setStringPainted(true); - statusBar.setString("Ready to JNAerate"); - statusBar.setIndeterminate(false); - } - - private void doShowExample(boolean generate) { - - try { - sourceArea.setText(ReadText.readText(getClass().getClassLoader().getResourceAsStream( - "com/ochafik/lang/jnaerator/examples/example.h" - ))); - sourceArea.scrollTo(0, 0); - if (generate) - generate(); - } catch (Exception e1) { - e1.printStackTrace(); - } - } - -// interface ProgressCallbacks { -// void sourcesParsed(SourceFiles sf); -// void log(String s); -// void filesGenerated(File outputDir); -// } - protected void generate() { - - try { - save(); - } catch (IOException e1) { - error(null, "Error while saving file", e1); - return; - } - JNAeratorStudio.this.setEnabled(false); - errorsArea.setText(""); - results.clear(); - resultArea.setText(""); - generateAction.setEnabled(false); - showJarButton.setEnabled(false); - showJarButton.setToolTipText(null); - statusBar.setIndeterminate(true); - statusBar.setToolTipText("JNAerating..."); - lastJNAeratedArtifact = null; - - new Thread() { - public void run() { - JNAeratorConfig config = new JNAeratorConfig(); - config.outputJar = getOutputJarFile(); - config.outputDir = getOutputDir(); - config.useJNADirectCalls = directCallingCb.isSelected(); - config.putTopStructsInSeparateFiles = structsAsTopLevelClassesCb.isSelected(); - config.reification = reificationCb.isSelected(); - config.convertBodies = convertBodiesCb.isSelected(); - config.genRawBindings = genRawBindingsCb.isSelected(); - config.beautifyNames = beautifyNamesCb.isSelected(); - //config.scalaStructSetters = scalaSettersCb.isSelected(); - config.stringifyConstCStringReturnValues = config.charPtrAsString = charPtrAsString.isSelected(); - config.runtime = (Runtime) runtimeCombo.getSelectedItem(); - config.outputMode = (OutputMode) modeCombo.getSelectedItem(); - config.noComments = noCommentCb.isSelected(); - config.defaultLibrary = libraryName.getText(); - config.libraryForElementsInNullFile = libraryName.getText(); -// config.addFile(getFile(), ""); - config.preprocessorConfig.includeStrings.add(sourceArea.getText()); - if (config.runtime == Runtime.BridJ) - config.genCPlusPlus = true; - else - config.genCPlusPlus = config.genCPlusPlus || sourceArea.getText().contains("//@" + JNAeratorCommandLineArgs.OptionDef.CPlusPlusGen.clSwitch); - config.cacheDir = getDir("cache"); - - final PrintStream out = System.out; - final PrintStream err = System.err; - JTextAreaOutputStream to = new JTextAreaOutputStream(errorsArea); - PrintStream pto = new PrintStream(to); - System.setOut(pto); - System.setErr(pto); - - Feedback feedback = new Feedback() { - - @Override - public void setStatus(final String string) { - SwingUtilities.invokeLater(new Runnable() { public void run() { - statusBar.setString(string); - statusBar.setToolTipText(string); - }}); - } - - @Override - public void setFinished(final File toOpen) { - lastJNAeratedArtifact = toOpen; - SwingUtilities.invokeLater(new Runnable() { public void run() { - statusBar.setToolTipText("Click to re-JNAerate !"); - statusBar.setString("JNAeration completed"); - showJarButton.setEnabled(true); - showJarButton.setToolTipText(toOpen.getAbsolutePath()); - statusBar.setValue(statusBar.getMaximum()); - statusBar.setIndeterminate(false); - }}); - } - - @Override - public void setFinished(Throwable e) { - statusBar.setToolTipText("Click to examine the JNAeration error report"); - lastJNAeratedArtifact = e; - setStatus("JNAeration failed : " + e.toString()); - statusBar.setValue(statusBar.getMinimum()); - statusBar.setIndeterminate(false); - //error(null, null, e); - } - @Override - public void wrappersGenerated(final Result result) { - SwingUtilities.invokeLater(new Runnable() { public void run() { - if (resultsListCombo.getItemCount() > 0) - resultsListCombo.setSelectedIndex(0); - }}); - } - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - final SourceFiles sourceFilesClone = sourceFiles;//.clone(); - SwingUtilities.invokeLater(new Runnable() { public void run() { - String title = "Parsing Tree"; - for (int i = sourceTabs.getTabCount(); i-- != 0;) { - if (title.equals(sourceTabs.getTitleAt(i))) { - sourceTabs.removeTabAt(i); - break; - } - } - - final JTree parsedTree = new JTree(new ElementNode(null, "ROOT", sourceFilesClone)); - final JEditTextArea selectionContent = textArea(new CCTokenMarker()); - - parsedTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { - TreePath selectionPath = parsedTree.getSelectionPath(); - AbstractNode c = selectionPath == null ? null : (AbstractNode)selectionPath.getLastPathComponent(); - selectionContent.setText(c == null ? "" : c.getContent()); - selectionContent.scrollTo(0, 0); - }}); - JPanel parsePane = new JPanel(new BorderLayout()); - parsePane.add("West", new JScrollPane(parsedTree)); - parsePane.add("Center", selectionContent); - - sourceTabs.addTab(title, parsePane); - }}); - } - }; - try { - new JNAerator(config) { - public PrintWriter getClassSourceWriter(final ClassOutputter outputter, final String className) throws IOException { - ResultContent c = new ResultContent(className) { - protected void closed() { - try { - PrintWriter w = outputter.getClassSourceWriter(className); - w.write(this.getContent()); - w.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }; - }; - results.add(c); - return c.getPrintWriter(); - }; - }.jnaerate(feedback); - } finally { - SwingUtilities.invokeLater(new Runnable() { public void run() { - generateAction.setEnabled(true); - sourceArea.scrollTo(0, 0); - JNAeratorStudio.this.setEnabled(true); - System.setOut(out); - System.setErr(err); - classCountLabel.setText("JNAerated classes (" + results.size() + ") :"); - setTabTitle(resultTabs, errorsPane, "Logs (" + (errorsArea.getLineCount() - 1) + " lines)"); - - }}); - } - } - }.start(); - } - - public static class SyntaxException extends Exception { - public SyntaxException(String message) { - super(message); - } - } - -// private void displayError(Exception e) { -// JOptionPane.showMessageDialog(this, e.toString(), "Error", JOptionPane.ERROR_MESSAGE); -// } - private static void setTabTitle(JTabbedPane tabs, Component c, String string) { - for (int i = tabs.getTabCount(); i-- != 0;) { - Component tc = tabs.getComponent(i);//tabs.getTabComponentAt(i); - if (tc == c) { - tabs.setTitleAt(i, string); - return; - } - - } - } - - static Preferences prefNode() { - return Preferences.userNodeForPackage(JNAeratorStudio.class); - } - public static String getPref(String name, String defaultValue) { - return prefNode().get(JNAeratorStudio.PREF_RADIX + name, defaultValue); - } - public static void setPref(String name, String value) { - prefNode().put(JNAeratorStudio.PREF_RADIX + name, value); - } - public static void setPref(String name, boolean value) { - prefNode().putBoolean(JNAeratorStudio.PREF_RADIX + name, value); - } - public static boolean getPref(String name, boolean defaultValue) { - return prefNode().getBoolean(JNAeratorStudio.PREF_RADIX + name, defaultValue); - } - public static void setPref(String name, double value) { - prefNode().putDouble(JNAeratorStudio.PREF_RADIX + name, value); - } - public static double getPref(String name, double defaultValue) { - return prefNode().getDouble(JNAeratorStudio.PREF_RADIX + name, defaultValue); - } - public static void setPref(String name, int value) { - prefNode().putInt(JNAeratorStudio.PREF_RADIX + name, value); - } - public static int getPref(String name, int defaultValue) { - return prefNode().getInt(JNAeratorStudio.PREF_RADIX + name, defaultValue); - } - - public static void main(String[] args) { - String[] prefArgs = JNAerator.getJNAeratorArgsFromPref(); - if (args.length > 0 || prefArgs != null) - { - String[] nargs = null; - if (prefArgs != null) - nargs = new String[0]; - else if (args.length == 1) { - nargs = new String[] {"@", args[0], "-gui"}; - } else if (args.length == 2 && args[0].equals("-open")) { - nargs = new String[] {"@", args[1], "-gui"}; - } - if (nargs != null) { - JNAerator.main(nargs); - return; - } - } - try { - System.setProperty("apple.laf.useScreenMenuBar", "true"); - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch(Exception e) { - System.out.println("Error setting native LAF: " + e); - } - - String ver = ""; - try { - ver = " " + ReadText.readText(JNAeratorStudio.class.getClassLoader().getResourceAsStream("VERSION")); - } catch (Exception ex) {} - - final JFrame f = new JFrame((JNAeratorStudio.class.getSimpleName() + ver).trim()); - final JNAeratorStudio js = new JNAeratorStudio(); - f.getContentPane().add("Center", js); - //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - try { - js.libraryName.setText(getPref("options.libraryName", "test")); - js.directCallingCb.setSelected(getPref("options.direct", false)); - js.structsAsTopLevelClassesCb.setSelected(getPref("options.topLevelStructs", true)); - js.reificationCb.setSelected(getPref("options.reification", false)); - js.convertBodiesCb.setSelected(getPref("options.convertBodies", false)); - js.genRawBindingsCb.setSelected(getPref("options.genRawBindings", false)); - js.beautifyNamesCb.setSelected(getPref("options.beautifyNames", false)); - js.charPtrAsString.setSelected(getPref("options.charPtrAsString", false)); - //js.scalaSettersCb.setSelected(getPref("options.scalaSetters", false)); - js.noCommentCb.setSelected(getPref("options.noComments", false)); - - js.sp.setOrientation(getPref("splitPane.orientation", JSplitPane.HORIZONTAL_SPLIT)); - js.sp.setDividerLocation(getPref("splitPane.dividedLocation", 0.5)); - f.setSize(getPref("window.width", 800), getPref("height", 600)); - f.setExtendedState(getPref("window.extendedState", JFrame.NORMAL)); - js.runtimeCombo.setSelectedItem(Runtime.valueOf(getPref("options.targetRuntime", Runtime.JNAerator.name()))); - - } catch (Exception ex) { - ex.printStackTrace(); - f.setExtendedState(JFrame.MAXIMIZED_BOTH); - f.setSize(800, 800); - } - - if (false) - java.lang.Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - try { - - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }); - f.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - js.close(f); - } - }); - - f.setVisible(true); - - } - protected static double getProportionalDividerLocation(JSplitPane sp) { - boolean hor = sp.getOrientation() == JSplitPane.HORIZONTAL_SPLIT; - int l = sp.getDividerLocation(), d = hor ? sp.getWidth() : sp.getHeight(); - sp.setOrientation(hor ? JSplitPane.VERTICAL_SPLIT : JSplitPane.HORIZONTAL_SPLIT); - return d != 0 ? l / (double)d : 0.5; - } -} diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ResultContent.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ResultContent.java deleted file mode 100644 index 3c08f95ad..000000000 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/studio/ResultContent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator.studio; - -import java.io.PrintWriter; -import java.io.StringWriter; - -class ResultContent { - StringWriter out = new StringWriter(); - final String path; - - public ResultContent(String path) { - this.path = path; - } - @Override - public String toString() { - return path; - } - public String getContent() { - return out.toString(); - } - public PrintWriter getPrintWriter() { - return new PrintWriter(out) { - @Override - public void close() { - super.close(); - closed(); - } - }; - } - protected void closed() { - - } -} \ No newline at end of file diff --git a/libraries/jnaerator/jnaerator/src/main/resources/bridj.jar.files b/libraries/jnaerator/jnaerator/src/main/resources/bridj.jar.files deleted file mode 100644 index f377a64d4..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/bridj.jar.files +++ /dev/null @@ -1,362 +0,0 @@ -org/bridj/AbstractBridJRuntime.class -org/bridj/AbstractIntegral.class -org/bridj/BridJ$1.class -org/bridj/BridJ$CastingType.class -org/bridj/BridJ$Switch.class -org/bridj/BridJ.class -org/bridj/BridJRuntime$TypeInfo.class -org/bridj/BridJRuntime.class -org/bridj/CLong.class -org/bridj/CRuntime$1.class -org/bridj/CRuntime$CTypeInfo.class -org/bridj/CRuntime$MethodCallInfoBuilder.class -org/bridj/CRuntime.class -org/bridj/CallIO$GenericPointerHandler.class -org/bridj/CallIO$NativeObjectHandler.class -org/bridj/CallIO$TypedPointerIO.class -org/bridj/CallIO$Utils$1.class -org/bridj/CallIO$Utils.class -org/bridj/CallIO.class -org/bridj/Callback.class -org/bridj/CallbackInterface.class -org/bridj/CallbackNativeImplementer$1.class -org/bridj/CallbackNativeImplementer.class -org/bridj/CommonPointerIOs$1.class -org/bridj/CommonPointerIOs$10.class -org/bridj/CommonPointerIOs$11.class -org/bridj/CommonPointerIOs$2.class -org/bridj/CommonPointerIOs$3.class -org/bridj/CommonPointerIOs$4.class -org/bridj/CommonPointerIOs$5.class -org/bridj/CommonPointerIOs$6.class -org/bridj/CommonPointerIOs$7.class -org/bridj/CommonPointerIOs$8.class -org/bridj/CommonPointerIOs$9.class -org/bridj/CommonPointerIOs$CallbackPointerIO.class -org/bridj/CommonPointerIOs$IntValuedEnumPointerIO.class -org/bridj/CommonPointerIOs$NativeObjectPointerIO.class -org/bridj/CommonPointerIOs$PointerArrayIO.class -org/bridj/CommonPointerIOs$PointerPointerIO.class -org/bridj/CommonPointerIOs$StructPointerIO.class -org/bridj/CommonPointerIOs$TypedPointerPointerIO.class -org/bridj/CommonPointerIOs.class -org/bridj/DefaultNativeList$1.class -org/bridj/DefaultNativeList.class -org/bridj/DefaultPointer.class -org/bridj/DynamicCallback.class -org/bridj/DynamicFunction.class -org/bridj/DynamicFunctionFactory.class -org/bridj/DyncallStructs$1.class -org/bridj/DyncallStructs.class -org/bridj/EllipsisHelper$1.class -org/bridj/EllipsisHelper.class -org/bridj/FlagSet$IntFlagSet.class -org/bridj/FlagSet.class -org/bridj/GenericCallback.class -org/bridj/HeadersReconstructor.class -org/bridj/Init.c -org/bridj/IntValuedEnum.class -org/bridj/JNI$1.class -org/bridj/JNI.class -org/bridj/LastError.class -org/bridj/MethodCallInfo$1.class -org/bridj/MethodCallInfo.class -org/bridj/NativeConstants$CallbackType.class -org/bridj/NativeConstants$ValueType.class -org/bridj/NativeConstants.class -org/bridj/NativeEntities$Builder.class -org/bridj/NativeEntities$CBInfo.class -org/bridj/NativeEntities.class -org/bridj/NativeError.class -org/bridj/NativeLibrary$SymbolAccepter.class -org/bridj/NativeLibrary.class -org/bridj/NativeList.class -org/bridj/NativeObject.class -org/bridj/NativeObjectInterface.class -org/bridj/Platform$1.class -org/bridj/Platform$2.class -org/bridj/Platform$DeleteFiles.class -org/bridj/Platform.class -org/bridj/PlatformSupport.class -org/bridj/Pointer$1.class -org/bridj/Pointer$2$1.class -org/bridj/Pointer$2.class -org/bridj/Pointer$3$1.class -org/bridj/Pointer$3.class -org/bridj/Pointer$4.class -org/bridj/Pointer$5.class -org/bridj/Pointer$6.class -org/bridj/Pointer$7.class -org/bridj/Pointer$DisorderedPointer.class -org/bridj/Pointer$FreeReleaser.class -org/bridj/Pointer$ListType.class -org/bridj/Pointer$OrderedPointer.class -org/bridj/Pointer$Releaser.class -org/bridj/Pointer$StringType.class -org/bridj/Pointer.class -org/bridj/PointerIO.class -org/bridj/SignalConstants.class -org/bridj/SignalError.class -org/bridj/SizeT.class -org/bridj/StringList.class -org/bridj/StructIO$1.class -org/bridj/StructIO$AggregatedFieldDesc.class -org/bridj/StructIO$Customizer.class -org/bridj/StructIO$DefaultCustomizer.class -org/bridj/StructIO$FieldDecl.class -org/bridj/StructIO$FieldDesc.class -org/bridj/StructIO$SolidRanges$Builder.class -org/bridj/StructIO$SolidRanges.class -org/bridj/StructIO.class -org/bridj/StructObject.class -org/bridj/TimeT$timeval.class -org/bridj/TimeT$timeval_customizer.class -org/bridj/TimeT.class -org/bridj/TypedPointer.class -org/bridj/ValuedEnum.class -org/bridj/Version.class -org/bridj/WinExceptionsConstants.class -org/bridj/WindowsError.class -org/bridj/ann/Alignment.class -org/bridj/ann/Array.class -org/bridj/ann/Bits.class -org/bridj/ann/CLong.class -org/bridj/ann/Constructor.class -org/bridj/ann/Convention$Style.class -org/bridj/ann/Convention.class -org/bridj/ann/DisableDirect.class -org/bridj/ann/Field.class -org/bridj/ann/Forwardable.class -org/bridj/ann/JNIBound.class -org/bridj/ann/Library.class -org/bridj/ann/Name.class -org/bridj/ann/Optional.class -org/bridj/ann/Ptr.class -org/bridj/ann/Runtime.class -org/bridj/ann/Struct.class -org/bridj/ann/Symbol.class -org/bridj/ann/Template.class -org/bridj/ann/Union.class -org/bridj/ann/Virtual.class -org/bridj/cpp/CPPObject.class -org/bridj/cpp/CPPRuntime$1.class -org/bridj/cpp/CPPRuntime$2.class -org/bridj/cpp/CPPRuntime$3.class -org/bridj/cpp/CPPRuntime$4.class -org/bridj/cpp/CPPRuntime$5.class -org/bridj/cpp/CPPRuntime$6.class -org/bridj/cpp/CPPRuntime$7.class -org/bridj/cpp/CPPRuntime$CPPDestructor.class -org/bridj/cpp/CPPRuntime$CPPTypeInfo.class -org/bridj/cpp/CPPRuntime$ClassTypeVariableExtractor.class -org/bridj/cpp/CPPRuntime$MemoryOperators.class -org/bridj/cpp/CPPRuntime$MethodTypeVariableExtractor.class -org/bridj/cpp/CPPRuntime$VTable.class -org/bridj/cpp/CPPRuntime$VirtMeth.class -org/bridj/cpp/CPPRuntime.class -org/bridj/cpp/CPPType.class -org/bridj/cpp/com/CLSID.class -org/bridj/cpp/com/COMCallableWrapper.class -org/bridj/cpp/com/COMRuntime$1$1.class -org/bridj/cpp/com/COMRuntime$1.class -org/bridj/cpp/com/COMRuntime$2.class -org/bridj/cpp/com/COMRuntime$COINIT.class -org/bridj/cpp/com/COMRuntime.class -org/bridj/cpp/com/CY.class -org/bridj/cpp/com/DECIMAL.class -org/bridj/cpp/com/GUID.class -org/bridj/cpp/com/IClassFactory.class -org/bridj/cpp/com/IDispatch$DISPPARAMS.class -org/bridj/cpp/com/IDispatch$EXCEPINFO.class -org/bridj/cpp/com/IDispatch.class -org/bridj/cpp/com/IID.class -org/bridj/cpp/com/IRecordInfo.class -org/bridj/cpp/com/ITypeInfo.class -org/bridj/cpp/com/IUnknown.class -org/bridj/cpp/com/OLEAutomationLibrary$CALLCONV.class -org/bridj/cpp/com/OLEAutomationLibrary$CUSTDATA.class -org/bridj/cpp/com/OLEAutomationLibrary$CUSTDATAITEM.class -org/bridj/cpp/com/OLEAutomationLibrary$DATE.class -org/bridj/cpp/com/OLEAutomationLibrary$DISPPARAMS.class -org/bridj/cpp/com/OLEAutomationLibrary$EXCEPINFO.class -org/bridj/cpp/com/OLEAutomationLibrary$ICreateErrorInfo.class -org/bridj/cpp/com/OLEAutomationLibrary$ICreateTypeLib.class -org/bridj/cpp/com/OLEAutomationLibrary$ICreateTypeLib2.class -org/bridj/cpp/com/OLEAutomationLibrary$IErrorInfo.class -org/bridj/cpp/com/OLEAutomationLibrary$INTERFACEDATA.class -org/bridj/cpp/com/OLEAutomationLibrary$ITypeLib.class -org/bridj/cpp/com/OLEAutomationLibrary$METHODDATA.class -org/bridj/cpp/com/OLEAutomationLibrary$NUMPARSE.class -org/bridj/cpp/com/OLEAutomationLibrary$PARAMDATA.class -org/bridj/cpp/com/OLEAutomationLibrary$REGKIND.class -org/bridj/cpp/com/OLEAutomationLibrary$SYSKIND.class -org/bridj/cpp/com/OLEAutomationLibrary$SYSTEMTIME.class -org/bridj/cpp/com/OLEAutomationLibrary$UDATE.class -org/bridj/cpp/com/OLEAutomationLibrary.class -org/bridj/cpp/com/RECT.class -org/bridj/cpp/com/SAFEARRAY.class -org/bridj/cpp/com/SAFEARRAYBOUND.class -org/bridj/cpp/com/VARENUM.class -org/bridj/cpp/com/VARIANT$__VARIANT_NAME_1_union$__tagVARIANT$__VARIANT_NAME_3_union$__tagBRECORD.class -org/bridj/cpp/com/VARIANT$__VARIANT_NAME_1_union$__tagVARIANT$__VARIANT_NAME_3_union.class -org/bridj/cpp/com/VARIANT$__VARIANT_NAME_1_union$__tagVARIANT.class -org/bridj/cpp/com/VARIANT$__VARIANT_NAME_1_union.class -org/bridj/cpp/com/VARIANT.class -org/bridj/cpp/com/shell/IShellFolder.class -org/bridj/cpp/com/shell/IShellWindows.class -org/bridj/cpp/com/shell/ITaskbarList.class -org/bridj/cpp/com/shell/ITaskbarList2.class -org/bridj/cpp/com/shell/ITaskbarList3$RECT.class -org/bridj/cpp/com/shell/ITaskbarList3$THUMBBUTTON.class -org/bridj/cpp/com/shell/ITaskbarList3$THUMBBUTTONFLAGS.class -org/bridj/cpp/com/shell/ITaskbarList3$THUMBBUTTONMASK.class -org/bridj/cpp/com/shell/ITaskbarList3$TbpFlag.class -org/bridj/cpp/com/shell/ITaskbarList3.class -org/bridj/cpp/mfc/AFXSignature.class -org/bridj/cpp/mfc/CArchive.class -org/bridj/cpp/mfc/CCmdUI.class -org/bridj/cpp/mfc/CObject.class -org/bridj/cpp/mfc/CPoint.class -org/bridj/cpp/mfc/CRuntimeClass.class -org/bridj/cpp/mfc/CString.class -org/bridj/cpp/mfc/CStringT.class -org/bridj/cpp/mfc/CWnd.class -org/bridj/cpp/mfc/MFCObject.class -org/bridj/cpp/mfc/MFCRuntime.class -org/bridj/cpp/mfc/MessageMapBuilder.class -org/bridj/cpp/mfc/OnCommand.class -org/bridj/cpp/mfc/OnCommandEx.class -org/bridj/cpp/mfc/OnMessage$Type.class -org/bridj/cpp/mfc/OnMessage.class -org/bridj/cpp/mfc/OnRegisteredMessage.class -org/bridj/cpp/mfc/OnUpdateCommand.class -org/bridj/cpp/mfc/StandardAfxCommands.class -org/bridj/cpp/mfc/TestMFC$1.class -org/bridj/cpp/mfc/TestMFC.class -org/bridj/cpp/std/STL.class -org/bridj/cpp/std/vector.class -org/bridj/cs/CSharpRuntime.class -org/bridj/cs/dotnet/DotNetRuntime.class -org/bridj/cs/mono/MonoRuntime.class -org/bridj/demangling/Demangler$1.class -org/bridj/demangling/Demangler$2.class -org/bridj/demangling/Demangler$3.class -org/bridj/demangling/Demangler$Annotations.class -org/bridj/demangling/Demangler$ClassRef.class -org/bridj/demangling/Demangler$Constant.class -org/bridj/demangling/Demangler$DemanglingException.class -org/bridj/demangling/Demangler$FunctionTypeRef.class -org/bridj/demangling/Demangler$Ident.class -org/bridj/demangling/Demangler$IdentLike.class -org/bridj/demangling/Demangler$JavaTypeRef.class -org/bridj/demangling/Demangler$MemberRef.class -org/bridj/demangling/Demangler$NamespaceRef.class -org/bridj/demangling/Demangler$PointerTypeRef.class -org/bridj/demangling/Demangler$SpecialName.class -org/bridj/demangling/Demangler$Symbol.class -org/bridj/demangling/Demangler$TemplateArg.class -org/bridj/demangling/Demangler$TypeRef.class -org/bridj/demangling/Demangler.class -org/bridj/demangling/GCC4Demangler$1.class -org/bridj/demangling/GCC4Demangler.class -org/bridj/demangling/VC9Demangler$1.class -org/bridj/demangling/VC9Demangler$AccessLevelAndStorageClass.class -org/bridj/demangling/VC9Demangler$AnonymousTemplateArg.class -org/bridj/demangling/VC9Demangler$CVClassModifier.class -org/bridj/demangling/VC9Demangler$DemanglingOp.class -org/bridj/demangling/VC9Demangler.class -org/bridj/dyncall/DyncallLibrary$DCCallVM.class -org/bridj/dyncall/DyncallLibrary$DCstruct.class -org/bridj/dyncall/DyncallLibrary.class -org/bridj/func/Fun0.class -org/bridj/func/Fun1.class -org/bridj/func/Fun2.class -org/bridj/jawt/JAWT$FreeDrawingSurface_callback.class -org/bridj/jawt/JAWT$GetComponent_callback.class -org/bridj/jawt/JAWT$GetDrawingSurface_callback.class -org/bridj/jawt/JAWT$Lock_callback.class -org/bridj/jawt/JAWT$Unlock_callback.class -org/bridj/jawt/JAWT.class -org/bridj/jawt/JAWTUtils$1.class -org/bridj/jawt/JAWTUtils$LockedComponentRunnable.class -org/bridj/jawt/JAWTUtils.class -org/bridj/jawt/JAWT_DrawingSurface$FreeDrawingSurfaceInfo_callback.class -org/bridj/jawt/JAWT_DrawingSurface$GetDrawingSurfaceInfo_callback.class -org/bridj/jawt/JAWT_DrawingSurface$Lock_callback.class -org/bridj/jawt/JAWT_DrawingSurface$Unlock_callback.class -org/bridj/jawt/JAWT_DrawingSurface.class -org/bridj/jawt/JAWT_DrawingSurfaceInfo.class -org/bridj/jawt/JAWT_Rectangle.class -org/bridj/jawt/JawtLibrary$JNIEnv.class -org/bridj/jawt/JawtLibrary.class -org/bridj/lib/darwin_universal/libbridj.dylib -org/bridj/lib/linux_arm32_arm/bridj.so -org/bridj/lib/linux_x64/bridj.so -org/bridj/lib/linux_x86/bridj.so -org/bridj/lib/sunos_x86/bridj.so -org/bridj/lib/win32/bridj.dll -org/bridj/lib/win64/bridj.dll -org/bridj/objc/FoundationLibrary.class -org/bridj/objc/IMP.class -org/bridj/objc/NSAutoreleasePool.class -org/bridj/objc/NSCalendar.class -org/bridj/objc/NSDictionary.class -org/bridj/objc/NSInvocation.class -org/bridj/objc/NSMethodSignature.class -org/bridj/objc/NSNumber.class -org/bridj/objc/NSObject.class -org/bridj/objc/NSString.class -org/bridj/objc/ObjCBlock.class -org/bridj/objc/ObjCClass.class -org/bridj/objc/ObjCDelegate.class -org/bridj/objc/ObjCJNI.class -org/bridj/objc/ObjCObject.class -org/bridj/objc/ObjCProxy.class -org/bridj/objc/ObjectiveCRuntime$1.class -org/bridj/objc/ObjectiveCRuntime$2$1.class -org/bridj/objc/ObjectiveCRuntime$2.class -org/bridj/objc/ObjectiveCRuntime.class -org/bridj/objc/SEL.class -org/bridj/objc/Selector.class -org/bridj/relocated/org/objectweb/asm/AnnotationVisitor.class -org/bridj/relocated/org/objectweb/asm/AnnotationWriter.class -org/bridj/relocated/org/objectweb/asm/Attribute.class -org/bridj/relocated/org/objectweb/asm/ByteVector.class -org/bridj/relocated/org/objectweb/asm/ClassReader.class -org/bridj/relocated/org/objectweb/asm/ClassVisitor.class -org/bridj/relocated/org/objectweb/asm/ClassWriter.class -org/bridj/relocated/org/objectweb/asm/Edge.class -org/bridj/relocated/org/objectweb/asm/FieldVisitor.class -org/bridj/relocated/org/objectweb/asm/FieldWriter.class -org/bridj/relocated/org/objectweb/asm/Frame.class -org/bridj/relocated/org/objectweb/asm/Handle.class -org/bridj/relocated/org/objectweb/asm/Handler.class -org/bridj/relocated/org/objectweb/asm/Item.class -org/bridj/relocated/org/objectweb/asm/Label.class -org/bridj/relocated/org/objectweb/asm/MethodVisitor.class -org/bridj/relocated/org/objectweb/asm/MethodWriter.class -org/bridj/relocated/org/objectweb/asm/Opcodes.class -org/bridj/relocated/org/objectweb/asm/Type.class -org/bridj/relocated/org/objectweb/asm/signature/SignatureReader.class -org/bridj/relocated/org/objectweb/asm/signature/SignatureVisitor.class -org/bridj/relocated/org/objectweb/asm/signature/SignatureWriter.class -org/bridj/util/ASMUtils$1.class -org/bridj/util/ASMUtils.class -org/bridj/util/AnnotationUtils.class -org/bridj/util/BytecodeAnalyzer$1.class -org/bridj/util/BytecodeAnalyzer$2.class -org/bridj/util/BytecodeAnalyzer$3.class -org/bridj/util/BytecodeAnalyzer$EmptyVisitor.class -org/bridj/util/BytecodeAnalyzer.class -org/bridj/util/ClassDefiner.class -org/bridj/util/ConcurrentCache.class -org/bridj/util/DefaultParameterizedType.class -org/bridj/util/JNIUtils$NativeMethodsCache.class -org/bridj/util/JNIUtils.class -org/bridj/util/Pair.class -org/bridj/util/ProcessUtils$Kernel32.class -org/bridj/util/ProcessUtils$LibC.class -org/bridj/util/ProcessUtils.class -org/bridj/util/StringUtils.class -org/bridj/util/Tuple.class -org/bridj/util/Utils.class diff --git a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCProtocolsForcedInheritanceList.data b/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCProtocolsForcedInheritanceList.data deleted file mode 100644 index 1412a598d..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCProtocolsForcedInheritanceList.data +++ /dev/null @@ -1,5 +0,0 @@ -// AppKit -NSOpenSavePanelDelegate:NSWindowDelegate -NSOutlineViewDelegate:NSTableViewDelegate -NSOutlineViewDataSource:NSTableViewDataSource -NSComboBoxDelegate:NSTextFieldDelegate diff --git a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data b/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data deleted file mode 100644 index 2937cfc19..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/ObjectiveCStaticForwardsExcludeList.data +++ /dev/null @@ -1,13 +0,0 @@ -// any -|+(BOOL)respondsToSelector:(SEL) -|+(Class)class - -// AppKit -NSControl|+(Class)cellClass -NSControl|+(void)setCellClass:(Class) - -// QuartzCore -CATransaction|+(id)valueForKey:(NSString*) -CATransaction|+(void)setValue:(id) forKey:(NSString*) - - diff --git a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/examples/example.h b/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/examples/example.h deleted file mode 100644 index 61780ee79..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/com/ochafik/lang/jnaerator/examples/example.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// This example file shows a few basic language -// features that are handled by JNAerator. -// -// Click on "JNAerate !" to see the JNAerated output. -// - -extern "C" { - -enum SimpleEnum { - First, // first comments - Second = 10, // comments on second - Last // not a real value -}; - -typedef int (__cdecl *DummyCallback)(void); - -struct TestStruct { - SimpleEnum enumValue; - char charValue; - short shortValue; // comment on shortValue - wchar_t wcharValue; - int intValue; - // comment on boolValue - bool boolValue; - long longValue; - size_t sizeValue; - long long longLongValue; - float floatValue; - double doubleValue; - char* cstringValue; - char charArrayValue[255]; - void* voidPointerValue; - // first comment on functionValue - int (*functionValue)(SimpleEnum e); // second comment on functionValue - struct { int first, second; } structValue; - TestStruct *structPointerValue; -}; - -void Test(const char* name, TestStruct& values, RandIntFunc func); -void TestByValue(TestStruct valuesByValue); - -void ComplexAnonymous(struct { union { enum { A, B } e; float f; } u; long v; void (*fptr)(); }*); - -} diff --git a/libraries/jnaerator/jnaerator/src/main/resources/jna-runtime.jar.files b/libraries/jnaerator/jnaerator/src/main/resources/jna-runtime.jar.files deleted file mode 100644 index f043a0afa..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/jna-runtime.jar.files +++ /dev/null @@ -1,119 +0,0 @@ -com/sun/jna/AltCallingConvention.class -com/sun/jna/Callback$UncaughtExceptionHandler.class -com/sun/jna/Callback.class -com/sun/jna/CallbackParameterContext.class -com/sun/jna/CallbackProxy.class -com/sun/jna/CallbackReference$AttachOptions.class -com/sun/jna/CallbackReference$DefaultCallbackProxy.class -com/sun/jna/CallbackReference$NativeFunctionHandler.class -com/sun/jna/CallbackReference.class -com/sun/jna/CallbackResultContext.class -com/sun/jna/CallbackThreadInitializer.class -com/sun/jna/DefaultTypeMapper$Entry.class -com/sun/jna/DefaultTypeMapper.class -com/sun/jna/FromNativeContext.class -com/sun/jna/FromNativeConverter.class -com/sun/jna/Function$NativeMappedArray.class -com/sun/jna/Function$PointerArray.class -com/sun/jna/Function$PostCallRead.class -com/sun/jna/Function.class -com/sun/jna/FunctionMapper.class -com/sun/jna/FunctionParameterContext.class -com/sun/jna/FunctionResultContext.class -com/sun/jna/IntegerType.class -com/sun/jna/InvocationMapper.class -com/sun/jna/LastErrorException.class -com/sun/jna/Library$1.class -com/sun/jna/Library$Handler$FunctionInfo.class -com/sun/jna/Library$Handler$FunctionNameMap.class -com/sun/jna/Library$Handler.class -com/sun/jna/Library.class -com/sun/jna/Memory$SharedMemory.class -com/sun/jna/Memory.class -com/sun/jna/MethodParameterContext.class -com/sun/jna/MethodResultContext.class -com/sun/jna/Native$1.class -com/sun/jna/Native$2.class -com/sun/jna/Native$3.class -com/sun/jna/Native$4.class -com/sun/jna/Native$5.class -com/sun/jna/Native$6.class -com/sun/jna/Native$7.class -com/sun/jna/Native$8.class -com/sun/jna/Native$AWT.class -com/sun/jna/Native$Buffers.class -com/sun/jna/Native$ffi_callback.class -com/sun/jna/Native.class -com/sun/jna/NativeLibrary$1.class -com/sun/jna/NativeLibrary$2.class -com/sun/jna/NativeLibrary.class -com/sun/jna/NativeLong.class -com/sun/jna/NativeMapped.class -com/sun/jna/NativeMappedConverter.class -com/sun/jna/NativeString.class -com/sun/jna/Platform.class -com/sun/jna/Pointer$1.class -com/sun/jna/Pointer$Opaque.class -com/sun/jna/Pointer.class -com/sun/jna/PointerType.class -com/sun/jna/StringArray.class -com/sun/jna/Structure$1.class -com/sun/jna/Structure$2$StructureSet.class -com/sun/jna/Structure$2.class -com/sun/jna/Structure$AutoAllocated.class -com/sun/jna/Structure$ByReference.class -com/sun/jna/Structure$ByValue.class -com/sun/jna/Structure$FFIType$FFITypes.class -com/sun/jna/Structure$FFIType$size_t.class -com/sun/jna/Structure$FFIType.class -com/sun/jna/Structure$LayoutInfo.class -com/sun/jna/Structure$MemberOrder.class -com/sun/jna/Structure$StructField.class -com/sun/jna/Structure.class -com/sun/jna/StructureReadContext.class -com/sun/jna/StructureWriteContext.class -com/sun/jna/ToNativeContext.class -com/sun/jna/ToNativeConverter.class -com/sun/jna/TypeConverter.class -com/sun/jna/TypeMapper.class -com/sun/jna/Union.class -com/sun/jna/WString.class -com/sun/jna/WeakIdentityHashMap$1.class -com/sun/jna/WeakIdentityHashMap$IdentityWeakReference.class -com/sun/jna/WeakIdentityHashMap.class -com/sun/jna/darwin/libjnidispatch.jnilib -com/sun/jna/freebsd-amd64/libjnidispatch.so -com/sun/jna/freebsd-i386/libjnidispatch.so -com/sun/jna/linux-amd64/libjnidispatch.so -com/sun/jna/linux-arm/libjnidispatch.so -com/sun/jna/linux-i386/libjnidispatch.so -com/sun/jna/linux-ia64/libjnidispatch.so -com/sun/jna/linux-ppc/libjnidispatch.so -com/sun/jna/linux-ppc64/libjnidispatch.so -com/sun/jna/ptr/ByReference.class -com/sun/jna/ptr/ByteByReference.class -com/sun/jna/ptr/DoubleByReference.class -com/sun/jna/ptr/FloatByReference.class -com/sun/jna/ptr/IntByReference.class -com/sun/jna/ptr/LongByReference.class -com/sun/jna/ptr/NativeLongByReference.class -com/sun/jna/ptr/PointerByReference.class -com/sun/jna/ptr/ShortByReference.class -com/sun/jna/sunos-amd64/libjnidispatch.so -com/sun/jna/sunos-sparc/libjnidispatch.so -com/sun/jna/sunos-sparcv9/libjnidispatch.so -com/sun/jna/sunos-x86/libjnidispatch.so -com/sun/jna/w32ce-arm/jnidispatch.dll -com/sun/jna/win32-amd64/jnidispatch.dll -com/sun/jna/win32-x86/jnidispatch.dll -com/sun/jna/win32/StdCall.class -com/sun/jna/win32/StdCallFunctionMapper.class -com/sun/jna/win32/StdCallLibrary$StdCallCallback.class -com/sun/jna/win32/StdCallLibrary.class -com/sun/jna/win32/W32APIFunctionMapper.class -com/sun/jna/win32/W32APIOptions$1.class -com/sun/jna/win32/W32APIOptions$2.class -com/sun/jna/win32/W32APIOptions.class -com/sun/jna/win32/W32APITypeMapper$1.class -com/sun/jna/win32/W32APITypeMapper$2.class -com/sun/jna/win32/W32APITypeMapper.class diff --git a/libraries/jnaerator/jnaerator/src/main/resources/jnaerator-runtime.jar.files b/libraries/jnaerator/jnaerator/src/main/resources/jnaerator-runtime.jar.files deleted file mode 100644 index b6606ef0a..000000000 --- a/libraries/jnaerator/jnaerator/src/main/resources/jnaerator-runtime.jar.files +++ /dev/null @@ -1,296 +0,0 @@ -com/ochafik/beans/BeansUtils$1.class -com/ochafik/beans/BeansUtils.class -com/ochafik/io/FileListUtils.class -com/ochafik/io/IOUtils.class -com/ochafik/io/JTextAreaOutputStream$Appender.class -com/ochafik/io/JTextAreaOutputStream.class -com/ochafik/io/ReadText.class -com/ochafik/io/StringBufferOutputStream.class -com/ochafik/io/WriteText.class -com/ochafik/junit/ParameterizedWithDescription.class -com/ochafik/lang/AssertUtils$1.class -com/ochafik/lang/AssertUtils$Test.class -com/ochafik/lang/AssertUtils.class -com/ochafik/lang/ClassUtils.class -com/ochafik/lang/SyntaxUtils$1.class -com/ochafik/lang/SyntaxUtils$10$1.class -com/ochafik/lang/SyntaxUtils$10.class -com/ochafik/lang/SyntaxUtils$2.class -com/ochafik/lang/SyntaxUtils$3.class -com/ochafik/lang/SyntaxUtils$4.class -com/ochafik/lang/SyntaxUtils$5.class -com/ochafik/lang/SyntaxUtils$6.class -com/ochafik/lang/SyntaxUtils$7.class -com/ochafik/lang/SyntaxUtils$8.class -com/ochafik/lang/SyntaxUtils$9.class -com/ochafik/lang/SyntaxUtils$Converter.class -com/ochafik/lang/SyntaxUtils$EasyMap.class -com/ochafik/lang/SyntaxUtils.class -com/ochafik/lang/Threads$Runner.class -com/ochafik/lang/Threads$State.class -com/ochafik/lang/Threads.class -com/ochafik/lang/jnaerator/runtime/Bits.class -com/ochafik/lang/jnaerator/runtime/CharByReference.class -com/ochafik/lang/jnaerator/runtime/FastCall.class -com/ochafik/lang/jnaerator/runtime/JNAeratorRuntime.class -com/ochafik/lang/jnaerator/runtime/LibraryExtractor$1.class -com/ochafik/lang/jnaerator/runtime/LibraryExtractor.class -com/ochafik/lang/jnaerator/runtime/MangledFunctionMapper.class -com/ochafik/lang/jnaerator/runtime/Mangling.class -com/ochafik/lang/jnaerator/runtime/NativeSize.class -com/ochafik/lang/jnaerator/runtime/NativeSizeByReference.class -com/ochafik/lang/jnaerator/runtime/ScalaRuntime.class -com/ochafik/lang/jnaerator/runtime/StringPointer$ByReference.class -com/ochafik/lang/jnaerator/runtime/StringPointer$ByValue.class -com/ochafik/lang/jnaerator/runtime/StringPointer.class -com/ochafik/lang/jnaerator/runtime/Structure$ByReference.class -com/ochafik/lang/jnaerator/runtime/Structure$ByValue.class -com/ochafik/lang/jnaerator/runtime/Structure.class -com/ochafik/lang/jnaerator/runtime/StructureType.class -com/ochafik/lang/jnaerator/runtime/StructureTypeDependent.class -com/ochafik/lang/jnaerator/runtime/This.class -com/ochafik/lang/jnaerator/runtime/ThisCall.class -com/ochafik/lang/jnaerator/runtime/Union$ByReference.class -com/ochafik/lang/jnaerator/runtime/Union$ByValue.class -com/ochafik/lang/jnaerator/runtime/Union.class -com/ochafik/lang/jnaerator/runtime/VirtualTablePointer.class -com/ochafik/lang/jnaerator/runtime/WStringPointer$ByReference.class -com/ochafik/lang/jnaerator/runtime/WStringPointer$ByValue.class -com/ochafik/lang/jnaerator/runtime/WStringPointer.class -com/ochafik/lang/jnaerator/runtime/globals/Global.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalByte.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalCallback.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalChar.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalDouble.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalFloat.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalInt.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalLong.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeLong.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeSize.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalPointer.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalPointerType.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalPrimitive.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalShort.class -com/ochafik/lang/jnaerator/runtime/globals/GlobalStruct.class -com/ochafik/lang/jnaerator/runtime/scala/ScalaJNA.scala.part -com/ochafik/lang/jnaerator/runtime/scala/ScalaRococoa.scala.part -com/ochafik/lang/reflect/DebugUtils$1.class -com/ochafik/lang/reflect/DebugUtils$2.class -com/ochafik/lang/reflect/DebugUtils$FieldAccessor.class -com/ochafik/lang/reflect/DebugUtils.class -com/ochafik/lang/reflect/GettersAndSettersHelper$FieldGetter.class -com/ochafik/lang/reflect/GettersAndSettersHelper$GetterAndSetterInfo.class -com/ochafik/lang/reflect/GettersAndSettersHelper.class -com/ochafik/net/URLUtils.class -com/ochafik/util/Adapter.class -com/ochafik/util/CollectionAdapter$IteratorAdapter.class -com/ochafik/util/CollectionAdapter.class -com/ochafik/util/CompoundCollection$1.class -com/ochafik/util/CompoundCollection.class -com/ochafik/util/DefaultAdapter.class -com/ochafik/util/IntArray$IntIterator.class -com/ochafik/util/IntArray.class -com/ochafik/util/IteratorEnumeration.class -com/ochafik/util/SortedIntArray.class -com/ochafik/util/SystemUtils$1.class -com/ochafik/util/SystemUtils$2.class -com/ochafik/util/SystemUtils$3.class -com/ochafik/util/SystemUtils$4.class -com/ochafik/util/SystemUtils$5.class -com/ochafik/util/SystemUtils$6.class -com/ochafik/util/SystemUtils.class -com/ochafik/util/listenable/AdaptedCollection$1.class -com/ochafik/util/listenable/AdaptedCollection$IteratorAdapter.class -com/ochafik/util/listenable/AdaptedCollection.class -com/ochafik/util/listenable/Adapter.class -com/ochafik/util/listenable/CollectionEvent$EventType.class -com/ochafik/util/listenable/CollectionEvent.class -com/ochafik/util/listenable/CollectionListener.class -com/ochafik/util/listenable/DefaultListenableCollection$ListenableIterator.class -com/ochafik/util/listenable/DefaultListenableCollection.class -com/ochafik/util/listenable/DefaultListenableList.class -com/ochafik/util/listenable/DefaultListenableMap$1$1.class -com/ochafik/util/listenable/DefaultListenableMap$1.class -com/ochafik/util/listenable/DefaultListenableMap$2.class -com/ochafik/util/listenable/DefaultListenableMap$3.class -com/ochafik/util/listenable/DefaultListenableMap$4$1.class -com/ochafik/util/listenable/DefaultListenableMap$4.class -com/ochafik/util/listenable/DefaultListenableMap.class -com/ochafik/util/listenable/DefaultListenableSet.class -com/ochafik/util/listenable/DefaultListenableSortedSet.class -com/ochafik/util/listenable/Filter.class -com/ochafik/util/listenable/FilteredListenableCollection$1.class -com/ochafik/util/listenable/FilteredListenableCollection$FilteredIterator.class -com/ochafik/util/listenable/FilteredListenableCollection.class -com/ochafik/util/listenable/FilteredListenableMap.class -com/ochafik/util/listenable/ListenableCollection.class -com/ochafik/util/listenable/ListenableCollections$1.class -com/ochafik/util/listenable/ListenableCollections$1RandomAccessListenableList.class -com/ochafik/util/listenable/ListenableCollections$2.class -com/ochafik/util/listenable/ListenableCollections$3.class -com/ochafik/util/listenable/ListenableCollections$MapResult.class -com/ochafik/util/listenable/ListenableCollections.class -com/ochafik/util/listenable/ListenableComboModel.class -com/ochafik/util/listenable/ListenableList.class -com/ochafik/util/listenable/ListenableListModel$1.class -com/ochafik/util/listenable/ListenableListModel$2.class -com/ochafik/util/listenable/ListenableListModel.class -com/ochafik/util/listenable/ListenableMap.class -com/ochafik/util/listenable/ListenableSet.class -com/ochafik/util/listenable/ListenableSortedSet.class -com/ochafik/util/listenable/ListenableSupport.class -com/ochafik/util/listenable/Pair.class -com/ochafik/util/listenable/SwingCollectionListener$1.class -com/ochafik/util/listenable/SwingCollectionListener.class -com/ochafik/util/listenable/SynchronizedListenableCollection$SynchronizedListenableIterator.class -com/ochafik/util/listenable/SynchronizedListenableCollection.class -com/ochafik/util/listenable/SynchronizedListenableList.class -com/ochafik/util/listenable/SynchronizedListenableMap.class -com/ochafik/util/listenable/SynchronizedListenableSet.class -com/ochafik/util/listenable/UnmodifiableEntry.class -com/ochafik/util/listenable/UnmodifiableListenableCollection$1.class -com/ochafik/util/listenable/UnmodifiableListenableCollection.class -com/ochafik/util/listenable/UnmodifiableListenableList.class -com/ochafik/util/listenable/UnmodifiableListenableMap.class -com/ochafik/util/listenable/UnmodifiableListenableSet.class -com/ochafik/util/progress/ProgressModel.class -com/ochafik/util/string/RegexUtils$1.class -com/ochafik/util/string/RegexUtils$Replacer.class -com/ochafik/util/string/RegexUtils.class -com/ochafik/util/string/StringUtils.class -com/ochafik/xml/XMLUtils.class -com/ochafik/xml/XPathUtils.class -com/sun/jna/AltCallingConvention.class -com/sun/jna/BitFields$1.class -com/sun/jna/BitFields$2.class -com/sun/jna/BitFields$3.class -com/sun/jna/BitFields$4.class -com/sun/jna/BitFields$5.class -com/sun/jna/BitFields$6.class -com/sun/jna/BitFields$7.class -com/sun/jna/BitFields$8.class -com/sun/jna/BitFields$9.class -com/sun/jna/BitFields$NonIntHandler.class -com/sun/jna/BitFields$PrimHandler.class -com/sun/jna/BitFields$StringHandler.class -com/sun/jna/BitFields.class -com/sun/jna/Callback$UncaughtExceptionHandler.class -com/sun/jna/Callback.class -com/sun/jna/CallbackParameterContext.class -com/sun/jna/CallbackProxy.class -com/sun/jna/CallbackReference$AttachOptions.class -com/sun/jna/CallbackReference$DefaultCallbackProxy.class -com/sun/jna/CallbackReference$NativeFunctionHandler.class -com/sun/jna/CallbackReference.class -com/sun/jna/CallbackReferenceHack.class -com/sun/jna/CallbackResultContext.class -com/sun/jna/CallbackThreadInitializer.class -com/sun/jna/DefaultTypeMapper$Entry.class -com/sun/jna/DefaultTypeMapper.class -com/sun/jna/FromNativeContext.class -com/sun/jna/FromNativeConverter.class -com/sun/jna/Function$NativeMappedArray.class -com/sun/jna/Function$PointerArray.class -com/sun/jna/Function$PostCallRead.class -com/sun/jna/Function.class -com/sun/jna/FunctionMapper.class -com/sun/jna/FunctionParameterContext.class -com/sun/jna/FunctionResultContext.class -com/sun/jna/IntegerType.class -com/sun/jna/InvocationMapper.class -com/sun/jna/LastErrorException.class -com/sun/jna/Library$1.class -com/sun/jna/Library$Handler$FunctionInfo.class -com/sun/jna/Library$Handler$FunctionNameMap.class -com/sun/jna/Library$Handler.class -com/sun/jna/Library.class -com/sun/jna/Memory$SharedMemory.class -com/sun/jna/Memory.class -com/sun/jna/MethodParameterContext.class -com/sun/jna/MethodResultContext.class -com/sun/jna/Native$1.class -com/sun/jna/Native$2.class -com/sun/jna/Native$3.class -com/sun/jna/Native$4.class -com/sun/jna/Native$5.class -com/sun/jna/Native$6.class -com/sun/jna/Native$7.class -com/sun/jna/Native$8.class -com/sun/jna/Native$AWT.class -com/sun/jna/Native$Buffers.class -com/sun/jna/Native$ffi_callback.class -com/sun/jna/Native.class -com/sun/jna/NativeLibrary$1.class -com/sun/jna/NativeLibrary$2.class -com/sun/jna/NativeLibrary.class -com/sun/jna/NativeLong.class -com/sun/jna/NativeMapped.class -com/sun/jna/NativeMappedConverter.class -com/sun/jna/NativeString.class -com/sun/jna/Platform.class -com/sun/jna/Pointer$1.class -com/sun/jna/Pointer$Opaque.class -com/sun/jna/Pointer.class -com/sun/jna/PointerType.class -com/sun/jna/PointerUtils.class -com/sun/jna/StringArray.class -com/sun/jna/Structure$1.class -com/sun/jna/Structure$2$StructureSet.class -com/sun/jna/Structure$2.class -com/sun/jna/Structure$AutoAllocated.class -com/sun/jna/Structure$ByReference.class -com/sun/jna/Structure$ByValue.class -com/sun/jna/Structure$FFIType$FFITypes.class -com/sun/jna/Structure$FFIType$size_t.class -com/sun/jna/Structure$FFIType.class -com/sun/jna/Structure$LayoutInfo.class -com/sun/jna/Structure$MemberOrder.class -com/sun/jna/Structure$StructField.class -com/sun/jna/Structure.class -com/sun/jna/StructureReadContext.class -com/sun/jna/StructureWriteContext.class -com/sun/jna/ToNativeContext.class -com/sun/jna/ToNativeConverter.class -com/sun/jna/TypeConverter.class -com/sun/jna/TypeMapper.class -com/sun/jna/Union.class -com/sun/jna/WString.class -com/sun/jna/WeakIdentityHashMap$1.class -com/sun/jna/WeakIdentityHashMap$IdentityWeakReference.class -com/sun/jna/WeakIdentityHashMap.class -com/sun/jna/darwin/libjnidispatch.jnilib -com/sun/jna/freebsd-amd64/libjnidispatch.so -com/sun/jna/freebsd-i386/libjnidispatch.so -com/sun/jna/linux-amd64/libjnidispatch.so -com/sun/jna/linux-arm/libjnidispatch.so -com/sun/jna/linux-i386/libjnidispatch.so -com/sun/jna/linux-ia64/libjnidispatch.so -com/sun/jna/linux-ppc/libjnidispatch.so -com/sun/jna/linux-ppc64/libjnidispatch.so -com/sun/jna/ptr/ByReference.class -com/sun/jna/ptr/ByteByReference.class -com/sun/jna/ptr/DoubleByReference.class -com/sun/jna/ptr/FloatByReference.class -com/sun/jna/ptr/IntByReference.class -com/sun/jna/ptr/LongByReference.class -com/sun/jna/ptr/NativeLongByReference.class -com/sun/jna/ptr/PointerByReference.class -com/sun/jna/ptr/ShortByReference.class -com/sun/jna/sunos-amd64/libjnidispatch.so -com/sun/jna/sunos-sparc/libjnidispatch.so -com/sun/jna/sunos-sparcv9/libjnidispatch.so -com/sun/jna/sunos-x86/libjnidispatch.so -com/sun/jna/w32ce-arm/jnidispatch.dll -com/sun/jna/win32-amd64/jnidispatch.dll -com/sun/jna/win32-x86/jnidispatch.dll -com/sun/jna/win32/StdCall.class -com/sun/jna/win32/StdCallFunctionMapper.class -com/sun/jna/win32/StdCallLibrary$StdCallCallback.class -com/sun/jna/win32/StdCallLibrary.class -com/sun/jna/win32/W32APIFunctionMapper.class -com/sun/jna/win32/W32APIOptions$1.class -com/sun/jna/win32/W32APIOptions$2.class -com/sun/jna/win32/W32APIOptions.class -com/sun/jna/win32/W32APITypeMapper$1.class -com/sun/jna/win32/W32APITypeMapper$2.class -com/sun/jna/win32/W32APITypeMapper.class diff --git a/libraries/jnaerator/jnaerator/src/main/resources/nl4j-runtime-structs-jna.jar.files b/libraries/jnaerator/jnaerator/src/main/resources/nl4j-runtime-structs-jna.jar.files deleted file mode 100644 index e69de29bb..000000000 diff --git a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/BridJ-pom.xml b/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/BridJ-pom.xml deleted file mode 100644 index 5cd461dcd..000000000 --- a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/BridJ-pom.xml +++ /dev/null @@ -1,10 +0,0 @@ -#parse("main/velocity/com/ochafik/lang/jnaerator/head.vm") - - - com.nativelibs4java - bridj - ${bridj_version} - - -#parse("main/velocity/com/ochafik/lang/jnaerator/tail.vm") - diff --git a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNA-pom.xml b/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNA-pom.xml deleted file mode 100644 index 2c8b79695..000000000 --- a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNA-pom.xml +++ /dev/null @@ -1,15 +0,0 @@ -#parse("main/velocity/com/ochafik/lang/jnaerator/head.vm") - - - net.java.dev.jna - jna - ${jna_version} - - - org.rococoa - rococoa - ${rococoa_version} - - -#parse("main/velocity/com/ochafik/lang/jnaerator/tail.vm") - diff --git a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNAerator-pom.xml b/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNAerator-pom.xml deleted file mode 100644 index 289e739f7..000000000 --- a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/JNAerator-pom.xml +++ /dev/null @@ -1,15 +0,0 @@ -#parse("main/velocity/com/ochafik/lang/jnaerator/head.vm") - - - com.nativelibs4java - jnaerator-runtime - ${jnaerator_version} - - - com.nativelibs4java - jnaerator-rococoa-runtime - ${jnaerator_version} - - -#parse("main/velocity/com/ochafik/lang/jnaerator/tail.vm") - diff --git a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/head.vm b/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/head.vm deleted file mode 100644 index 5c7f1494d..000000000 --- a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/head.vm +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - %groupId% - %artifactId% - %artifactId% - 1.0-SNAPSHOT - jar - - - UTF-8 - 1.5 - 1.5 - - - diff --git a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/tail.vm b/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/tail.vm deleted file mode 100644 index 0acd1398c..000000000 --- a/libraries/jnaerator/jnaerator/src/main/velocity/com/ochafik/lang/jnaerator/tail.vm +++ /dev/null @@ -1,87 +0,0 @@ - - - junit - junit - 4.10 - test - - - - - - - - - com.nativelibs4java - maven-jnaerator-plugin - ${jnaerator_version} - - - - generate - - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 1.4 - - - true - - - - org.scala-lang:scala-library - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - - - - sonatype - Sonatype OSS Snapshots Repository - http://oss.sonatype.org/content/groups/public - - - - - sonatype - Sonatype OSS Snapshots Repository - http://oss.sonatype.org/content/groups/public - - - - - - diff --git a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAerationTest.java b/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAerationTest.java deleted file mode 100644 index 6293145d9..000000000 --- a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAerationTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.Map.Entry; -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import org.junit.*; - -import org.anarres.cpp.LexerException; -import org.antlr.runtime.RecognitionException; - -import com.ochafik.io.ReadText; -import com.ochafik.lang.compiler.CompilerUtils; -import com.ochafik.lang.compiler.MemoryJavaFile; -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.JNAeratorConfig.OutputMode; -import com.ochafik.lang.jnaerator.studio.JNAeratorStudio.SyntaxException; -import com.ochafik.net.URLUtils; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Filter; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import com.ochafik.junit.ParameterizedWithDescription; - -@RunWith(Parameterized.class) -public class JNAerationTest { - String title; - TestDesc test; - - public JNAerationTest(String title, TestDesc test) { - this.title = title; - this.test = test; - } - - static class TestDesc { - String cSource; - String libraryName = "test"; - JNAeratorConfig.Runtime runtime; - Map extraJavaSourceFilesContents = new HashMap(); - public TestDesc(String cSource, JNAeratorConfig.Runtime runtime) { - this.cSource = cSource; - this.runtime = runtime; - } - public TestDesc addSource(String className, String javaContent) { - extraJavaSourceFilesContents.put(className, javaContent); - return this; - } - public TestDesc addMainContentSource(String className, String javaContent) { - Set imports = new TreeSet(); - List content = new ArrayList(); - //String lib = libraryName + "." + StringUtils.capitalize(libraryName) + "Library"; - //imports.add("import " + lib + ";"); - //imports.add("import static " + lib + ".*;"); - switch (runtime) { - - case JNAerator: - case JNA: - imports.add("import com.sun.jna.*;"); - imports.add("import com.sun.jna.ptr.*;"); - imports.add("import java.nio.*;"); - break; - case BridJ: - imports.add("import org.bridj.*;"); - imports.add("import static org.bridj.Pointer.*;"); - imports.add("import org.bridj.cpp.*;"); - imports.add("import java.nio.*;"); - break; - } - - for (String line : javaContent.split("\r?\n")) { - if (line.matches("^\\s*import[^\\w].*")) - imports.add(line); - else - content.add(line); - } - String simpleName = new File(className.replace('.', File.separatorChar)).getName(); - String transformedContent = StringUtils.implode(imports, "\n") + "\n" + - "public class " + simpleName + " {\n" + - "\tpublic static void main(String[] args) {\n\t\t" + - StringUtils.implode(content, "\n\t\t").trim() + "\n" + - "\t}\n}"; -// System.out.println(transformedContent); - extraJavaSourceFilesContents.put(className.replace('.', '/') + ".java", transformedContent); - return this; - } - } - - @Test - public void test() throws SyntaxException, IOException, LexerException, RecognitionException { - JNAeratorConfig config = new JNAeratorConfig(); - config.defaultLibrary = test.libraryName; - config.outputMode = OutputMode.StandaloneJar; - config.outputDir = new File("target/jnaeratorOut"); - config.runtime = test.runtime; - config.preferJavac = true; - config.extraJavaSourceFilesContents.putAll(test.extraJavaSourceFilesContents); - config.libraryForElementsInNullFile = test.libraryName;//test.classNameToJavaContent; -// config.addFile(getFile(), ""); - config.preprocessorConfig.includeStrings.add(test.cSource); - //config. - - new JNAerator(config).jnaerate(new Feedback() { - - @Override - public void sourcesParsed(SourceFiles sourceFiles) { - // TODO Auto-generated method stub - - } - - @Override - public void setStatus(String string) { - // TODO Auto-generated method stub - - } - - @Override - public void setFinished(Throwable ex) { - if (ex != null) { - ex.printStackTrace(System.out); - } - Collection> cc = test.extraJavaSourceFilesContents.entrySet();//new CompoundCollection>(test.extraJavaSourceFilesContents.entrySet(), Arrays.asList(new Pair("?.java", test.cSource))); - System.out.println("Finished with an error ! " + ex); - if (ex instanceof CompilerUtils.CompilationError) { - CompilerUtils.CompilationError cex = (CompilerUtils.CompilationError)ex; - for (Map.Entry e : cex.inputs.entrySet()) { - System.out.println("\n" + e.getKey() + ":"); - System.out.println(RegexUtils.regexReplace(Pattern.compile("\n"), "\n" + e.getValue().getCharContent(true), new Adapter() { - int line = 0; - - @Override - public String adapt(String[] value) { - return "\n" + (++line) + ":\t\t"; - } - })); - } - } - /* - for (final Map.Entry e : cc) { - System.out.println("\n" + e.getKey() + ":"); - System.out.println(RegexUtils.regexReplace(Pattern.compile("\n"), "\n" + e.getValue(), new Adapter() { - int line = 0; - - @Override - public String adapt(String[] value) { - return "\n" + (++line) + ":\t\t"; - } - })); - }*/ - Assert.assertTrue("Error : " + ex + " in :\n" + test.extraJavaSourceFilesContents, false); -// throw new RuntimeException(e); - } - - @Override - public void setFinished(File toOpen) { - // TODO Auto-generated method stub - - } - - @Override - public void wrappersGenerated(Result result) { - // TODO Auto-generated method stub - - } - }); - } - static Pattern runtimePattern = Pattern.compile("(?m)#runtime\\((-?(?:\\w+)(?:,\\w+)*)\\).*"); - @Parameters - public static List readParameters() throws IOException { - //List lines = ReadText.readLines(ObjCppParsingTests.class.getClassLoader().getResource(TEST_FILE)); - //List lines = ReadText.readLines(TEST_FILE); - //TestOption testOption = TestOption.ParseAndPrettyPrint; - //List list = URLUtils.listFiles(new URL("jar:file:/Users/ochafik/Prog/Java/bin/jnaerator.jar!/com/ochafik/lang/jnaerator"), null); - List data = new ArrayList(); - - URL dir = JNAerationTest.class.getClassLoader().getResource("com/ochafik/lang/jnaerator/tests"); - if(dir == null) - throw new FileNotFoundException("Could not find test files !"); - for (URL testURL : URLUtils.listFiles(dir, new Filter() { - @Override - public boolean accept(String path) { - return path.toLowerCase().endsWith(".test");// && path.contains("objective"); - } - })) { - String t = ReadText.readText(testURL); - String[] tt = t.split("\n\\s*--\\s*\n"); - String cSource = tt[0]; - String n = new File(URLDecoder.decode(testURL.toString(), "utf-8")).getName(); - - Map sourceByRuntime = new HashMap(); - sourceByRuntime.put(JNAeratorConfig.Runtime.BridJ, ""); - - //System.out.println("tt.length = " + tt.length); - for (int i = 1; i < tt.length; i++) { - String rawSource = tt[i]; - String runtimeString = JNAeratorConfig.Runtime.JNAerator.name(); - Matcher m = runtimePattern.matcher(rawSource); - if (m.find()) { - runtimeString = m.group(1); - } - boolean neg = runtimeString.startsWith("-"); - if (neg) - runtimeString = runtimeString.substring(1).trim(); - - for (String runtimeStr : runtimeString.split(",")) { - String rs = runtimeStr.trim(); - if (rs.isEmpty()) - continue; - - JNAeratorConfig.Runtime runtime; - try { - runtime = Enum.valueOf(JNAeratorConfig.Runtime.class, rs); - } catch (Throwable th) { - throw new RuntimeException("Failed to parse runtime '" + rs + "'", th); - } - - String javaSource = rawSource.replaceAll("^#", "//#"); - if (neg) - sourceByRuntime.remove(runtime); - else - sourceByRuntime.put(runtime, javaSource); - } - /* - for (String runtimeStr : runtimeString.split(",")) { - String rs = runtimeStr.trim(); - if (rs.isEmpty()) - continue; - JNAeratorConfig.Runtime runtime = Enum.valueOf(JNAeratorConfig.Runtime.class, rs); - - String javaSource = rawSource.replaceAll("^#", "//#"); - String testName = n + " / " + runtime.name(); - data.add(new Object[] { - testName, - new TestDesc(cSource, runtime).addMainContentSource( - "Test" + runtime.name(), - "// " + testName + "\n" + javaSource - ) - }); - }*/ - } - - for (Map.Entry e : sourceByRuntime.entrySet()) { - JNAeratorConfig.Runtime runtime = e.getKey(); - String javaSource = e.getValue(); - - String testName = n + " / " + runtime.name(); - - //System.out.println("Got runtime " + runtime + " " + testName); - - data.add(new Object[] { - testName, - new TestDesc(cSource, runtime).addMainContentSource( - "Test" + runtime.name(), - "// " + testName + "\n" + javaSource - ) - }); - } - } - return data; - } - -} diff --git a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorConfigTest.java b/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorConfigTest.java deleted file mode 100644 index fd3fbcb0e..000000000 --- a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorConfigTest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.ochafik.lang.jnaerator; - -import java.io.IOException; -import org.junit.Test; -import static org.junit.Assert.*; -/** - * - * @author ochafik - */ -public class JNAeratorConfigTest { - @Test - public void testPoms() throws Throwable { - try { - for (JNAeratorConfig.Runtime runtime : JNAeratorConfig.Runtime.values()) { - String pom = runtime.generateMavenProjectModel("com.mycompany", "myartifact", "1.0-SNAPSHOT"); - assertNotNull(pom); - } - } catch (Throwable th) { - th.printStackTrace(); - throw th; - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorTest.java b/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorTest.java deleted file mode 100644 index 955e4011d..000000000 --- a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/JNAeratorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.jnaerator; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.Map.Entry; -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import junit.framework.Assert; - -import org.anarres.cpp.LexerException; -import org.antlr.runtime.RecognitionException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized.Parameters; - -import com.ochafik.io.ReadText; -import com.ochafik.junit.ParameterizedWithDescription; -import com.ochafik.lang.compiler.CompilerUtils; -import com.ochafik.lang.compiler.MemoryJavaFile; -import com.ochafik.lang.jnaerator.JNAerator.Feedback; -import com.ochafik.lang.jnaerator.studio.JNAeratorStudio.SyntaxException; -import com.ochafik.net.URLUtils; -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Filter; -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; -import org.junit.runners.Parameterized; - -public class JNAeratorTest { - @Test - public void testFilesLists() throws IOException { - for (JNAeratorConfig.Runtime runtime : JNAeratorConfig.Runtime.values()) { - JNAerator.getRuntimeFiles(runtime, false); - } - } -} diff --git a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppParsingTest.java b/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppParsingTest.java deleted file mode 100644 index 3a020212d..000000000 --- a/libraries/jnaerator/jnaerator/src/test/java/com/ochafik/lang/jnaerator/parser/ObjCppParsingTest.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . - */ -package com.ochafik.lang.jnaerator.parser; - -import java.io.ByteArrayOutputStream; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.antlr.runtime.ANTLRReaderStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runner.notification.Failure; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import static org.junit.Assert.*; - -import com.ochafik.io.ReadText; -import com.ochafik.junit.ParameterizedWithDescription; -import com.ochafik.lang.SyntaxUtils; -import com.ochafik.lang.grammar.DummyDebugEventListener; -import com.ochafik.lang.jnaerator.JNAeratorConfig; -import com.ochafik.lang.jnaerator.Result; - -/* - include com/ochafik/lang/jnaerator/parser/ObjCppTest.mm - */ -@SuppressWarnings("unused") -@RunWith(Parameterized.class) -// @RunWith(Parameterized.class) -public class ObjCppParsingTest { - static final String TEST_FILE = "com/ochafik/lang/jnaerator/parser/ObjCppTest.mm"; - - enum TestOption { - ParseAndPrettyPrint, ParseOnly, ParseMustFail - }; - - String string; - TestOption testOption; - - public ObjCppParsingTest(String string, TestOption testOption) { - this.string = string; - this.testOption = testOption; - } - - @Test - public void test() throws RecognitionException, IOException { - PrintStream originalOut = System.out; - PrintStream originalErr = System.err; - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream pout = new PrintStream(bout); - System.setOut(pout); - System.setErr(pout); - - boolean ok = false; - SourceFile sourceFile = null; - - try { - - switch (testOption) { - case ParseMustFail: - try { - sourceFile = newParser(string).sourceFile();// .sourceFile; - assertTrue("Expression should not have been parsed : " - + string, false); - } catch (Throwable t) { - ok = true; - } - break; - case ParseOnly: - case ParseAndPrettyPrint: - sourceFile = newParser(string).sourceFile(); - assertNotNull(string, sourceFile); - if (testOption == TestOption.ParseAndPrettyPrint) { - if (!SyntaxUtils.equal(string, sourceFile == null ? null - : sourceFile.toString())) - sourceFile = newParser(string).sourceFile(); - - assertEqualsNewLineAware(string, string.trim(), - sourceFile == null ? null : sourceFile.toString() - .trim()); - } - ok = true; - break; - } - - for (Declaration decl : sourceFile.getDeclarations()) { - if (decl == null) - continue; - - String declStr = decl.toString(); - Declaration clo = decl.clone(); - assertNotNull("Null clone !", clo); - String cloStr = clo.toString(); - if (!SyntaxUtils.equal(declStr, cloStr)) { - // go here again to debug - clo = decl.clone(); - } - assertEquals("Clone failed !", declStr, cloStr); - } - } finally { - pout.flush(); - System.setOut(originalOut); - System.setErr(originalErr); - if (!ok) { - int i = string.trim().length(), j = String.valueOf(sourceFile).trim().length(); - System.out.println("IN: " + i + " OUT: " + j ); - System.out.println("IN:\n" + string.trim()); - try { - System.out.println("OUT:\n" + String.valueOf(sourceFile).trim()); - System.out.write(bout.toByteArray()); - System.out.println(); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - - } - static String lineAware(String s) { - return s.replaceAll("\n\r", "\n").replace("\r", "\n").replaceAll("\\s+", " "); - } - public static void assertEqualsNewLineAware(String message, String a, String b) { - assertEquals(message, lineAware(a), lineAware(b)); - } - - @Parameters - public static List readDataFromFile() throws IOException { - List lines = ReadText.readLines(ObjCppParsingTest.class.getClassLoader().getResource(TEST_FILE)); - TestOption testOption = TestOption.ParseAndPrettyPrint; - List data = new ArrayList(); - - StringBuilder b = new StringBuilder(); - for (String line : lines) { - String trl = line.trim().replaceAll("\\s+", " "); - if (trl.equals("#pragma reversible")) - testOption = TestOption.ParseAndPrettyPrint; - else if (trl.equals("#pragma parse")) - testOption = TestOption.ParseOnly; - else if (trl.equals("#pragma fail")) - testOption = TestOption.ParseMustFail; - else if (trl.startsWith("#pragma ")) - System.err.println("Unknown #pragma : " + line); - else if (trl.startsWith("#")) { - // skip - } else if (trl.equals("--")) { - if (b.length() > 0) { - data.add(new Object[] { b.toString(), testOption }); - b.delete(0, b.length()); - } - } else { - if (b.length() > 0) - b.append('\n'); - b.append(line); - } - } - if (b.length() > 0) - data.add(new Object[] { b.toString(), testOption }); - - return data; - } - - public static ObjCppParser newParser(String s) throws IOException { - Result result = new Result(new JNAeratorConfig(), null, null); - ObjCppParser parser = new ObjCppParser(new CommonTokenStream(new ObjCppLexer( - new ANTLRReaderStream(new StringReader(s)))) - // , new DummyDebugEventListener() - ); - parser.objCParserHelper = result.typeConverter; - return parser; - } -} diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/parser/ObjCppTest.mm b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/parser/ObjCppTest.mm deleted file mode 100644 index cfb6bb328..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/parser/ObjCppTest.mm +++ /dev/null @@ -1,502 +0,0 @@ -# -# Copyright (c) 2009 Olivier Chafik, All Rights Reserved -# -# This file is part of JNAerator (http://jnaerator.googlecode.com/). -# -# JNAerator is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# JNAerator is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with JNAerator.s If not, see . -# -#pragma reversible --- -void f() { - delete[] ptr; - delete ptr; -} --- -void f(int __in); --- -void meth(double*) throw(int, SomeEx*); --- -void f(void (*g)()); --- -void (*fptr)(); --- -int val = (1 << 16) - 2; --- -typedef void *__ptr64 PVOID64; --- -typedef char CHAR; -typedef CHAR *PCHAR, *LPCH, *PCH; --- -typedef char CHAR; -typedef const CHAR *LPCCH, *PCCH; --- -long value = (int)(__u.__u >> 31); --- -long long l = 0x8000000000000000; --- -void f(struct s i); --- -const char WINDOWS_ENDL_CH_CONST[3] = { 0x0d, 0x0a, '\0' }; --- -extern long long int i; --- -extern long int llrint(double); --- -extern long long int llrint(double); --- -typedef int I; -register I i; --- -char* initstate(unsigned, char*, size_t); /* no __DARWIN_ALIAS needed */ --- -register unsigned int g; --- -void srand(unsigned); --- -void f(int* pA, int* pB) { - int a = *pA, b = *pB; -} --- -void f(int* pA, int* pB) { - int a = *pA; - int b = *pB; - int c; - bool b; - c = a + b; - c = a - b; - c = a * b; - c = a / b; - c = a % b; - c = a ^ b; - c = a | b; - c = a & b; - c = a << b; - c = a >> b; - b = a > b; - b = a >= b; - b = a < b; - b = a <= b; - b = a == b; - b = a != b; - b = a && b; - b = a || b; - *pA = a + 1; -} -void test() { - int a = 10; - int *pA = &a; - f(pA); -} --- -/** - * Need to see public final ByteByReference[] data = new ByteByReference[3]; in results
      - * https://jna.dev.java.net/servlets/ReadMsg?list=users&msgNo=2335 - */ -typedef struct { - int width; - int height; - int rowBytes; - int columnBytes; - unsigned char *data[3]; -} ImageTransfer; --- -struct BitField { - float a; - int f1:1; - int f2:7; - unsigned f5:16; - double z; -}; --- -class string; -string name = "ok"; -string empty = ""; --- -class CPPClass { - static void f(); -}; --- -struct S { - friend long f(); -}; --- -extern void **const GC_objfreelist_ptr; --- -typedef struct _NSSize { - CGFloat width; /* width should never be negative */ - CGFloat height; /* height should never be negative */ -} NSSize; --- -void f() {} --- -free(void* _Memory); -malloc(int _Size); -int align(int); -int dllexport(int); --- -struct __declspec(uuid("9B")) __declspec(novtable) ID3D10DeviceChild : IUnknown -{ - void f(); -}; --- -template -struct S -{ - _A field; - S() : field() {} - S(const _A& __f) : field(__f) {} - template - S(const S<_B >& __s) : field(__s.field) {} - template - void f(S<_B >&); -}; --- -template -struct X { - void f(X&); -}; -template -inline bool operator==(const X&); --- -struct __attribute__((__unused__)) U { -}; --- -template , typename _Alloc = allocator<_CharT > > -class basic_string; -template < > struct char_traits; --- -/// Struct comment -struct ParamBlockRec { - int ok; // comment after ok -}; --- -class C { - C() : a(1), b() {} -}; --- -static inline int isascii(int _c) { - return (_c & ~0x7F) == 0; -} --- -/// these are comments... -void* CreateHandle(int size); --- -void** ResizeHandle(void** h, int size); --- -/// typedef bool BOOL; -class NSMapTable; -BOOL (*isEqual)(NSMapTable* table, const void*, const void*); --- -void operator()(signed&); --- -void operator+=(long long*, const signed&); --- -void A::~A(); --- -const void *x; --- -typedef void *GC_thread; -extern volatile GC_thread GC_threads[THREAD_TABLE_SZ]; --- -typedef bool GC_bool; -extern GC_bool GC_thr_initialized; --- -const void *x; --- -const void *const x; --- -int *const a = (int*)10; --- -int *const *aa = (int**)10; --- -const void x[]; --- -const void *const &volatile *register x[]; --- -#// Only comments here ! --- -char *(*(**foo[][8])())[]; --- -typedef struct { - unsigned char *data[3]; -} S; --- -int x[4]; --- -bool (*x)(const void* buffer, unsigned int length); --- -unsigned long long int d; --- -unsigned *pa[4]; --- -unsigned int a = a, *pa[4]; --- -unsigned short x, *px, **ppx, **&rppx = a, *pa[4]; --- -class pair; -class map; -class string; -pair > x; --- -class pair; -class map; -class string; -pair* > x; --- -enum { - a = 1, - b = 2 + 4, - c = 55, - rAliasType = 'alis' /* Aliases are stored as resources of this type */ -}; --- -@class NSAppleEventDescriptor; --- -typedef struct const __NSAppleEventManagerSuspension *NSAppleEventManagerSuspensionID; --- -extern const double NSAppleEventTimeOutNone; --- -class NSString; -extern NSString *NSAppleEventManagerWillProcessFirstEventNotification; --- -int i = 10; --- -int i = [NSObject createWithTest:"ok" encoding:[NSEncoding ascii] length:10]; --- -# see http://tigcc.ticalc.org/doc/keywords.html -typedef unsigned char byte; --- -typedef char str40[41]; --- -union short_or_long_NOVAR { - short i; - long l2; -}; --- -union short_or_long { - short i; - long l; -} a_number, *p_anumber = NULL; --- -struct IOParam; -struct FileParam; -struct VolumeParam; -struct CntrlParam; -struct SlotDevParam; -struct MultiDevParam; -/// Test of comments before -union ParamBlockRec { - IOParam ioParam; - FileParam fileParam; - VolumeParam volumeParam; - CntrlParam cntrlParam; - SlotDevParam slotDevParam; - MultiDevParam multiDevParam; -}; --- -typedef void *AVLTreePtr; -typedef void *AVLNodeType; -typedef SInt32 (__cdecl *AVLCompareItemsProcPtr)(AVLTreePtr tree, const void* i1, const void* i2, AVLNodeType nd_typ); --- -void ComplexArgFunction(struct { - union { - enum { - A, - B - } e; - float f; - } u; - long v; - void (*fptr)(); -}* pArg); --- -typedef struct { - float *re; - float im[4]; -} complex; --- -typedef char *byteptr; --- -int f(int* out, char byref, double in); --- -typedef int (*fncptr)(int); --- -__inline long f(); --- -struct GC_thread; -extern volatile GC_thread GC_threads[]; --- -#pragma parse - -struct Test {__ - int i, j, k; -}; --- -libvlc_instance_t* libvlc_new(char *const *); --- -void f(struct x * const); --- -typedef __success(return >= 0) long HRESULT; --- -static __inline__ int __inline_signbit( long double __x ){ - union { - long double __ld; - struct { - unsigned long long __m; - short __sexp; - } __p; - } __u = {__x}; - return (int) ((unsigned int) __u.__p.__sexp >> 15); -} --- -static __inline__ int __inline_isnormalf( float __x ) { - float fabsf = __builtin_fabsf(__x); - if( __x != __x ) - return 0; - return fabsf < __builtin_inff() && fabsf >= __FLT_MIN__; -} --- -@interface NSLock : NSObject { -@private - void *_priv; -} - -- (BOOL)tryLock; -- (BOOL)lockBeforeDate:(NSDate *)limit; - -//- (void)setName:(NSString *)n ; -- (void)setName:(NSString in*)n; -//- (NSString *)name ; -- (NSString *)name; - -@end --- -typedef struct { - NSUInteger (*hash)(NSMapTable *table, const void *); - BOOL (*isEqual)(NSMapTable *table, const void *, const void *); - void (*retain)(NSMapTable *table, const void *); - void (*release)(NSMapTable *table, void *); - NSString *(*describe)(NSMapTable *table, const void *); - const void *notAKeyMarker; -} NSMapTableKeyCallBacks; --- -@interface NSObject { - Class isa; -} - -+ (void)load; - -+ (void)initialize; -- (id)init; - -+ (id)new; -+ (id)allocWithZone:(NSZone *)zone; -+ (id)alloc; -- (void)dealloc; - -- (void)finalize ; - -- (id)copy; -- (id)mutableCopy; - -+ (id)copyWithZone:(NSZone *)zone; -+ (id)mutableCopyWithZone:(NSZone *)zone; - -+ (Class)superclass; -+ (Class)class; -+ (BOOL)instancesRespondToSelector:(SEL)aSelector; -+ (BOOL)conformsToProtocol:(Protocol *)protocol; -- (IMP)methodForSelector:(SEL)aSelector; -+ (IMP)instanceMethodForSelector:(SEL)aSelector; -- (void)doesNotRecognizeSelector:(SEL)aSelector; - -- (id)forwardingTargetForSelector:(SEL)aSelector; -- (void)forwardInvocation:(NSInvocation *)anInvocation; -- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector; - -+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector; - -+ (NSString *)description; - -+ (BOOL)isSubclassOfClass:(Class)aClass ; - -+ (BOOL)resolveClassMethod:(SEL)sel ; -+ (BOOL)resolveInstanceMethod:(SEL)sel ; - -@end --- -@interface NSObject (NSCoderMethods) - -+ (NSInteger)version; -+ (void)setVersion:(NSInteger)aVersion; -- (Class)classForCoder; -- (id)replacementObjectForCoder:(NSCoder *)aCoder; -- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder; - -@end --- -extern "C" void cvReleaseMat( CvMat** mat ); --- -/* Decrements CvMat data reference counter and deallocates the data if - it reaches 0 */ -inline void cvDecRefData( CvArr* arr ) -{ - if( (((arr) != 0 && (((const CvMat*)(arr))->type & 0xFFFF0000) == 0x42420000 && ((const CvMat*)(arr))->cols > 0 && ((const CvMat*)(arr))->rows > 0) && ((const CvMat*)(arr))->data.ptr != 0)) - { - CvMat* mat = (CvMat*)arr; - mat->data.ptr = 0; - if( mat->refcount != 0 && --*mat->refcount == 0 ) - (cvFree_(*(&mat->refcount)), *(&mat->refcount)=0); - mat->refcount = 0; - } - else if( (((arr) != 0 && (((const CvMatND*)(arr))->type & 0xFFFF0000) == 0x42430000) && ((const CvMatND*)(arr))->data.ptr != 0)) - { - CvMatND* mat = (CvMatND*)arr; - mat->data.ptr = 0; - if( mat->refcount != 0 && --*mat->refcount == 0 ) - (cvFree_(*(&mat->refcount)), *(&mat->refcount)=0); - mat->refcount = 0; - } -} --- -@class Categ; -@interface Base (Categ) - - (Base*)merge:(Base*)f; -@end --- -struct { - int i:13; - unsigned j:1, jj:2; - signed k:2; - long l:3; - short m:2; - float f; -} a; --- -namespace std { - using ::mbstate_t; -} --- -extern TestMe(); --- -#pragma fail -int[4] x; --- -bool (*test)(const void *buffer, unsigned int length) x; --- -class fpos; -class fpos -{ - fpos() {} -}; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/anonymous types.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/anonymous types.test deleted file mode 100644 index 9ac2248d4..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/anonymous types.test +++ /dev/null @@ -1,38 +0,0 @@ -void ComplexArgFunction( - struct { - union { - enum { A, B } e; - float f; - } u; - long v; - void (*fptr)(); - }* pArg -); - -void f(void (*arg)()); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -ComplexArgFunction_pArg_struct a = null; -a.v = (NativeLong)null; -a.fptr.apply(); -a.u = new ComplexArgFunction_pArg_struct.u_union.ByValue(); -a.u.e = ComplexArgFunction_pArg_struct.u_union.e_enum.A; -INSTANCE.ComplexArgFunction(a); - -INSTANCE.f((f_arg_callback)null); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -ComplexArgFunction_pArg_struct a = null; -a.v((long)0); -a.fptr().get().apply(); -//a.u(new ComplexArgFunction_pArg_struct.u_union()); -a.u().e(ComplexArgFunction_pArg_struct.u_union.e_enum.A); -ComplexArgFunction(Pointer.pointerTo(a)); - -f((Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/apple enums name inference.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/apple enums name inference.test deleted file mode 100644 index dc6495d26..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/apple enums name inference.test +++ /dev/null @@ -1,56 +0,0 @@ -enum _E1 -{ - E1A, E1B -}; -typedef uint32_t NothingToDoWithE; - -enum _E2 -{ - E2A, E2B -}; -typedef uint32_t E2; - -typedef uint32_t E3; -enum -{ - E3A, E3B -}; - - -enum -{ - E4A, E4B -}; - -typedef uint32_t E4; // too far away ! - -enum -{ - E5A, E5B -}; - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -int i; -i = _E1.E1A; -i = _E2.E2A; -i = E3.E3A; -i = E4.E4A; --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -_E1 e1 = _E1.E1A; -_E2 e2 = _E2.E2A; -E3 e3 = E3.E3A; -E4 e4 = E4.E4A; - -IntValuedEnum<_E1> v1 = e1; -IntValuedEnum<_E2> v2 = e2; -IntValuedEnum v3 = e3; -IntValuedEnum v4 = e4; -int i5 = E5A; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/array fields.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/array fields.test deleted file mode 100644 index 7fa42a331..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/array fields.test +++ /dev/null @@ -1,25 +0,0 @@ -struct S { - int iarr[4]; - char* csarr[3][4]; - char s[8]; - long* (*foo2[12][8])(); -}; - - -typedef unsigned char Str15[16]; -struct Months { - Str15 names[12]; -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -S s = new S(); -s.iarr[2] = 10; -s.csarr[10] = (Pointer)null; -s.s[10] = (byte)0; -NativeLongByReference lp = s.foo2[10].apply(); - -Months m = null; -m.names = (byte[])null; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/basic structs.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/basic structs.test deleted file mode 100644 index ca56b802a..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/basic structs.test +++ /dev/null @@ -1,31 +0,0 @@ -struct A { - int i; - short int s; - long int l; -}; -struct B { - A a; - A *pa; -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -B b = new B(); -b.a = new A.ByValue(); -b.pa = new A.ByReference(); -int i = b.pa.i = 10; -short s = b.pa.s; -b.pa.l = (NativeLong)null; --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -B b = new B(); -b.pa(allocate(A.class)); -int i = b.pa().get().i(); -short s = b.pa().get().s(); -b.pa().get().l((long)0); -long l = b.pa().get().l(); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/bit fields.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/bit fields.test deleted file mode 100644 index d8477746d..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/bit fields.test +++ /dev/null @@ -1,22 +0,0 @@ -struct BF { - int i:1; - int j:2; - int k:5; - int i8:8, i16:16, i32:32; - long long l32:32, l64:64; - float f; -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -BF b = new BF(); -b.i = b.j = b.k = 1; -b.f = 1f; -byte i8 = b.i8; -short i16 = b.i16; -int i32 = b.i32; -int l32 = b.l32; -b.l64 = (long)0; - diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/callback fields.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/callback fields.test deleted file mode 100644 index a04e2479b..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/callback fields.test +++ /dev/null @@ -1,17 +0,0 @@ -struct S { - long (__cdecl *const fptr)(); - void (*functions[8])(void*); - long (*foo[10])(union { long l; int i; }); -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -S s = new S(); -s.functions[0].apply((Pointer)null); -s.fptr.apply(); -S.foo_callback_arg1_union u = new S.foo_callback_arg1_union(); -u.l = (NativeLong)null; -u.i = 12; -s.foo[0].apply(u.byValue()); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/complex.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/complex.test deleted file mode 100644 index ee060b641..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/complex.test +++ /dev/null @@ -1,23 +0,0 @@ -struct VeryComplex { - double _Complex first; - _Complex double second; - - double _Complex *pThird; - _Complex double *pFourth; - - double control; -}; - --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -VeryComplex c = new VeryComplex(); -c.first().real(1.0); -double x = c.second().imag(); -c.control(2.0); - -Pointer p; -p = c.pThird(); -p = c.pFourth(); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/constants.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/constants.test deleted file mode 100644 index 0e56e07f7..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/constants.test +++ /dev/null @@ -1,30 +0,0 @@ -#define X 10 -#define Y (X + 1) -#define Z (Y * 2) -#define ZZ (Y - 2) -#define A (200) -#define B (-(A + 6)) - -const int Expression = X + (1 + 2) * 4; -const int unsignedValue = (UInt32)4294967288L; - -#if Z == 22 -#define DEF1 1 -#endif - -#if ZZ == 9 -#define DEF2 1 -#endif - -#if B == -206 -#define DEF3 1 -#endif --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -int v = X / 2 + Y + Z + ZZ; -int x = Expression; -int u = unsignedValue; -int s = A + B + DEF1 + DEF2 + DEF3; // are they all defined? (they should be) diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/cpp operators.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/cpp operators.test deleted file mode 100644 index 9a2032c03..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/cpp operators.test +++ /dev/null @@ -1,22 +0,0 @@ -extern bool operator/=(int&, float); - -class T { - T& operator+=(const T&); -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -INSTANCE.operatorDivideEqual((IntByReference)null, 0f); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -T t = new T(); -Pointer p = pointerTo(t); -p = t.operatorPlusEqual(p); - -Pointer pInt = allocateInt(); -boolean b = operatorDivideEqual(pInt, 10f); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enum name.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enum name.test deleted file mode 100644 index e633c2b81..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enum name.test +++ /dev/null @@ -1,21 +0,0 @@ -typedef enum _Choice { - A, - B, - C -} Choice; - -enum _OtherChoice { - A, - B, - C -}; -void f(Choice c); -void ff(_OtherChoice c); - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -INSTANCE.f(Choice.A); -INSTANCE.ff(_OtherChoice.B); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enums.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enums.test deleted file mode 100644 index 103e48092..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/enums.test +++ /dev/null @@ -1,38 +0,0 @@ - -enum { A, B = A * 2, C }; -enum { A2, B2, C2 = (UInt32)0xFCE00000 }; - -enum E { - Item1, - Item2 = Item1 + 10 -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -int i; -i = A; -i = B; -i = C; -i = A2; -i = B2; -i = C2; -i = E.Item1; -i = E.Item2; - --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -int i; -i = A; -i = B; -i = C; -i = A2; -i = B2; -i = C2; -E e; -e = E.Item1; -e = E.Item2; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/exthaustive struct fields.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/exthaustive struct fields.test deleted file mode 100644 index 3bde13be9..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/exthaustive struct fields.test +++ /dev/null @@ -1,40 +0,0 @@ -struct S { - char c; - short s; - int i; - long l; - size_t t; - long long L; - float f; - double d; - - char *pc; - short *ps; - int *pi; - long *pl; - size_t *pt; - long long *pL; - float *pf; - double *pd; - - S* next; - struct T { - int o; - } inner; - - enum E { - A, B, C - } e, *pE; -}; - - -void f(PyObject*); - - --- -#runtime(BridJ) - -import test.*; -import static test.TestLibrary.*; - - diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/fake pointers.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/fake pointers.test deleted file mode 100644 index 0969422cd..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/fake pointers.test +++ /dev/null @@ -1,8 +0,0 @@ -typedef struct _cl_event * cl_event; -void f(cl_event, cl_event*); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -f((cl_event)null, (Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function alternatives.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function alternatives.test deleted file mode 100644 index f61fec1cd..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function alternatives.test +++ /dev/null @@ -1,14 +0,0 @@ -void CopyBytes(char* dest, const char* source, const wchar_t* wsource, size_t n, const int* intArray); -int process(void* ptr); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; -import org.rococoa.cocoa.foundation.*; -import org.rococoa.cocoa.*; -import com.ochafik.lang.jnaerator.runtime.*; - -INSTANCE.CopyBytes((Pointer)null, (Pointer)null, (CharByReference)null, (NativeSize)null, (IntByReference)null); -INSTANCE.CopyBytes((ByteBuffer)null, (String)null, (WString)null, (NativeSize)null, (int[])null); - -INSTANCE.process((Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function pointers.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function pointers.test deleted file mode 100644 index 4968abf1e..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function pointers.test +++ /dev/null @@ -1,32 +0,0 @@ -typedef int (foo_cb_t)(void *); -extern void test_cb1(foo_cb_t func); -extern void test_cb2(foo_cb_t *func); -extern void test_cb3(int (func)(void*)); -extern void test_cb4(int (*func)(void*)); -extern void test_cb5(int (*)(void*)); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; -import org.rococoa.cocoa.foundation.*; -import org.rococoa.cocoa.*; -import com.ochafik.lang.jnaerator.runtime.*; - -INSTANCE.test_cb1((TestLibrary.foo_cb_t)null); -INSTANCE.test_cb2((Pointer)null); -INSTANCE.test_cb3((TestLibrary.test_cb3_func_callback)null); -INSTANCE.test_cb4((TestLibrary.test_cb4_func_callback)null); -INSTANCE.test_cb5((TestLibrary.test_cb5_arg1_callback)null); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; -import org.rococoa.cocoa.foundation.*; -import org.rococoa.cocoa.*; -import com.ochafik.lang.jnaerator.runtime.*; - -test_cb1((Pointer)null); -test_cb2((Pointer)null); -test_cb3((Pointer)null); -test_cb4((Pointer)null); -test_cb5((Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function varargs and reserved.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function varargs and reserved.test deleted file mode 100644 index fe4b6a67c..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/function varargs and reserved.test +++ /dev/null @@ -1,15 +0,0 @@ -void varargAndReserved(int transient, ...); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -INSTANCE.varargAndReserved(1); -INSTANCE.varargAndReserved(1,(Pointer)null); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -varargAndReserved(1); -varargAndReserved(1,(Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/integers.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/integers.test deleted file mode 100644 index 9d498bd0d..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/integers.test +++ /dev/null @@ -1,26 +0,0 @@ -struct S { - intptr_t pi; - uintptr_t pui; - long l; - int i; -}; --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -S s = null; -s.pi = (IntByReference)null; -s.pui = (IntByReference)null; -s.l = (NativeLong)null; -int i = s.i = 10; --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -S s = null; -s.pi((Pointer)null); -s.pui((Pointer)null); -s.l(10L); -int i = s.i(); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/modifiers as identifiers.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/modifiers as identifiers.test deleted file mode 100644 index 4e5162674..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/modifiers as identifiers.test +++ /dev/null @@ -1,15 +0,0 @@ -typedef struct _simplestruct { - int myfield; -} simplestruct; - - -typedef struct _outerstruct2 { - simplestruct *byref; -} outerstruct2; - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -outerstruct2 s = new outerstruct2(new simplestruct(1).byReference()); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c categories protocols.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c categories protocols.test deleted file mode 100644 index ee463cd6e..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c categories protocols.test +++ /dev/null @@ -1,28 +0,0 @@ -@protocol Printing --(void) print; -@end - -@interface Base: NSObject -{} -+baseWithName(); - -@end - -@interface Base (Categ) --(Base*) merge: (Base*) f; --test:(id)arg; -@end - --- -#runtime(JNAerator) -import test.*; -import test.protocols.*; - -Base base = Base.baseWithName(); -base = base.as_Base_Categ().merge(base); -base.print(); -base.as_Base_Categ().test((Printing)null); -//base.test((org.rococoa.NSObject)null); -//base.asCateg().test((org.rococoa.ObjCObject)null); --- -#runtime(-BridJ) diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c class.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c class.test deleted file mode 100644 index 22e7fd48d..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/objective-c class.test +++ /dev/null @@ -1,17 +0,0 @@ -@interface NSMutableArray: NSObject -{} - --(int) count; --(BOOL) empty; -+arrayWithCapacity: (int) c; - -@end --- -#runtime(JNAerator) -import test.*; - -NSMutableArray a = NSMutableArray.arrayWithCapacity(10); -int c = a.count(); -boolean e = a.empty(); --- -#runtime(-BridJ) diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/overloads.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/overloads.test deleted file mode 100644 index c0faececc..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/overloads.test +++ /dev/null @@ -1,20 +0,0 @@ -void f(int*); -void f(double*); - -class Foo { -public: - void f(int*); - void f(double*); -}; --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -f(pointerToInts(10)); -f$2(pointerToDoubles(10)); - -Foo o = new Foo(); -o.f(pointerToInts(10)); -o.f$2(pointerToDoubles(10)); - diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/raw bindings.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/raw bindings.test deleted file mode 100644 index fa67d03d2..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/raw bindings.test +++ /dev/null @@ -1,22 +0,0 @@ -enum E { A, B }; -typedef struct cl_event_ *cl_event; - -int* f1(cl_event, void*, E e); - -int f2(int); -int* f3(int); -int* f4(int*); -int f5(int*); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -Pointer p; -int i; - -p = f1((cl_event)null, (Pointer)null, (IntValuedEnum)null); -i = f2(0); -p = f3(0); -p = f4((Pointer)null); -i = f5((Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/simple globals.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/simple globals.test deleted file mode 100644 index d0bcc6ff0..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/simple globals.test +++ /dev/null @@ -1,36 +0,0 @@ -extern int *pInt; -extern void *pVoid; -extern int i; -extern void (*fptr)(int); - -extern NSInteger nsi; -extern CGFloat cgf; - --- -#runtime(JNAerator) -import test.*; -import org.rococoa.cocoa.*; -import com.ochafik.lang.jnaerator.runtime.*; -import static test.TestLibrary.*; - -IntByReference pInt = TestLibrary.pInt.get(); -TestLibrary.pInt.set(pInt); - -Pointer pVoid = TestLibrary.pVoid.get(); -TestLibrary.pVoid.set(pVoid); - -int i = TestLibrary.i.get(); -TestLibrary.i.set(i); - -NativeSize nsi = TestLibrary.nsi.get(); -TestLibrary.nsi.set(nsi); - -CGFloat cgf = TestLibrary.cgf.get(); -TestLibrary.cgf.set(cgf); - -TestLibrary.fptr.get().apply(10); -TestLibrary.fptr.set(new TestLibrary.fptr_callback() { - public void apply(int value) {} -}); --- -#runtime(-BridJ) diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/stdcall library.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/stdcall library.test deleted file mode 100644 index 5c82c9f44..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/stdcall library.test +++ /dev/null @@ -1,12 +0,0 @@ -void __stdcall hello(); -typedef void (__stdcall * someFun)(); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; -import com.sun.jna.win32.StdCallLibrary; - -StdCallLibrary lib = INSTANCE; -INSTANCE.hello(); - -StdCallLibrary.StdCallCallback cb = (someFun)null; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct and enum fields constructors.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct and enum fields constructors.test deleted file mode 100644 index 2e3d7a767..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct and enum fields constructors.test +++ /dev/null @@ -1,37 +0,0 @@ - -union U { - int a; // first - float b; // second - const char* str; -}; - -// test struct -struct S { -// first value - int a; - float b; // second one - double d; -}; - -struct S2 : S { - long long ll; - long l; -}; - --- -#runtime(JNAerator) - -import test.*; -import static test.TestLibrary.*; - -U c = new U(0).clone(); -U.ByValue bv = new U(0f).byValue(); -U.ByReference br = new U((Pointer)null).byReference(); - -S sc = new S(0, 0f, 0.0).clone(); -S.ByValue sbv = new S(0, 0f, 0.0).byValue(); -S.ByReference sbr = new S(0, 0f, 0.0).byReference(); - -S2 s2 = new S2(); -s2 = new S2(0, 0f, 0.0, 0L, (NativeLong)null); -sc = s2; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct arguments.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct arguments.test deleted file mode 100644 index 7c9480088..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct arguments.test +++ /dev/null @@ -1,21 +0,0 @@ -typedef struct _S { - int a; -} S; - -void fv(S); -void fv_(_S); - -void fp(S*); -void fp_(_S*); - --- -#runtime(JNAerator) - -import test.*; -import static test.TestLibrary.*; - -INSTANCE.fv(new S.ByValue()); -INSTANCE.fv_(new S.ByValue()); - -INSTANCE.fp(new S()); -INSTANCE.fp_(new S()); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct by value vs by reference.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct by value vs by reference.test deleted file mode 100644 index ca27ff390..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct by value vs by reference.test +++ /dev/null @@ -1,65 +0,0 @@ -// Taken directly from JNA's front page : https://jna.dev.java.net/ - -typedef struct _simplestruct { - int myfield; -} simplestruct; - -typedef struct _outerstruct { - simplestruct nested; // use Structure -} outerstruct; - -typedef struct _outerstruct2 { - simplestruct *byref; // use Structure.ByReference -} outerstruct2; - -typedef struct _outerstruct3 { - simplestruct array[4]; // use Structure[] -} outerstruct3; - -typedef struct _outerstruct4 { - simplestruct* ptr_array[4]; // use Structure.ByReference[] -} outerstruct4; - -// Field is a pointer to an array of struct -typedef struct _outerstruct5 { - simplestruct* ptr_to_array; // use Structure.ByReference, and use Structure.toArray() to allocate array -} outerstruct5; - -// struct pointers as return value or argument -// use Structure -outerstruct *myfunc(); - -// struct pointers as return value or argument -// use Structure -void myfunc(outerstruct* data); - -// struct (by value) as return value or argument -// use Structure.ByValue -simplestruct myfuncV(); - -// struct (by value) as return value or argument -// use Structure.ByValue -void myfuncV(simplestruct); - --- -#runtime(JNAerator) - -import test.*; -import org.rococoa.cocoa.*; -import static test.TestLibrary.*; - -outerstruct o1 = new outerstruct(new simplestruct(10)); -simplestruct s1 = o1.nested; - -outerstruct2 o2 = new outerstruct2(new simplestruct(10).byReference()); -simplestruct.ByReference s2 = o2.byref; - -outerstruct3 o3 = new outerstruct3(new simplestruct[0]); -simplestruct[] s3 = o3.array; - -outerstruct4 o4 = new outerstruct4((simplestruct.ByReference[])null); -simplestruct.ByReference[] s4 = o4.ptr_array; - -simplestruct.ByValue fv = INSTANCE.myfuncV(); - - diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct fields.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct fields.test deleted file mode 100644 index 09f1d51fd..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/struct fields.test +++ /dev/null @@ -1,22 +0,0 @@ -struct S { - S byVal; - S* byRef; -}; - -struct S2 { - struct I { - int i; - } v[10]; -}; - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -S s = new S(); -Structure.ByValue v = (S.ByValue)s.byVal; -Structure.ByReference r = (S.ByReference)s.byRef; - -S2 s2 = new S2(); -s2.v[1] = new S2.I(2).byValue(); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/tagged types name correction.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/tagged types name correction.test deleted file mode 100644 index 39cc883b3..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/tagged types name correction.test +++ /dev/null @@ -1,36 +0,0 @@ -typedef enum _E1 -{ - E1A, E1B -} F, E1; - -f1_(_E1); -f1(E1); - -typedef enum _E2 -{ - E2A, E2B -} G; - -typedef struct _S1 -{ - int a; -} S, S1; - - -typedef struct _S2 -{ - int a; -} K; - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -int i; -i = E1.E1A; -i = G.E2A; - -Structure s; -s = (S1)null; -s = (K)null; diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedef scope.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedef scope.test deleted file mode 100644 index 6bf5e9dd6..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedef scope.test +++ /dev/null @@ -1,36 +0,0 @@ -typedef void (*lfptr)(); -struct S { - int a; - lfptr p; - U u; - typedef void (*fp2)(); - fp2 p2; -}; -struct U { - int u; -}; -f(S, void (*fptr)(), T*, lfptr p2); - - --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -S s = new S(); -(s.p = (test.TestLibrary.lfptr)null).apply(); -(s.p2 = (S.fp2)null).apply(); -TestLibrary.INSTANCE.f((S.ByValue)null, (TestLibrary.f_fptr_callback)null, (TestLibrary.T)null, (test.TestLibrary.lfptr)null); - - --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -S s = new S(); -s.p((Pointer)null); -s.p().get().apply(); -s.p2((Pointer)null); -s.p2().get().apply(); -f((S)null, (Pointer)null, (Pointer)null, (Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedefs.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedefs.test deleted file mode 100644 index 2bf76a74e..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/typedefs.test +++ /dev/null @@ -1,28 +0,0 @@ -typedef unsigned int cl_uint; -typedef cl_uint cl_info; -f(cl_info); - -struct ReSampleContext; -typedef struct ReSampleContext ReSampleContext; -void f2(ReSampleContext*); - -typedef void FC(int); -void f3(FC a, FC* b); --- -#runtime(JNAerator) -import test.*; -import static test.TestLibrary.*; - -int i = INSTANCE.f(10); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; - -int i = f(10); - -f2((Pointer)null); - -Callback cb = (FC)null; -Pointer pfc = null; -f3(pfc, pfc); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/unknown pointers.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/unknown pointers.test deleted file mode 100644 index 26f716684..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/unknown pointers.test +++ /dev/null @@ -1,26 +0,0 @@ -struct OpaqueStruct; - -const OpaqueStruct* GetInterestingMessage(UnknownPtr*); - --- -#runtime(JNAerator) - -import test.*; -import static test.TestLibrary.*; - -//PointerType pt = null; -new OpaqueStruct() {}; -new UnknownPtr() {}; -//pt = new OpaqueStruct((Pointer)null); -//pt = new UnknownPtr((Pointer)null); - -OpaqueStruct s = INSTANCE.GetInterestingMessage(null); --- -#runtime(BridJ) - -import test.*; -import static test.TestLibrary.*; - -new OpaqueStruct() {}; -new UnknownPtr() {}; -Pointer s = GetInterestingMessage((Pointer)null); diff --git a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/weird functions.test b/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/weird functions.test deleted file mode 100644 index 822253d90..000000000 --- a/libraries/jnaerator/jnaerator/src/test/resources/com/ochafik/lang/jnaerator/tests/weird functions.test +++ /dev/null @@ -1,14 +0,0 @@ -long l(void); -short s(void); -i(void); --- -#runtime(BridJ) -import test.*; -import static test.TestLibrary.*; -import org.rococoa.cocoa.foundation.*; -import org.rococoa.cocoa.*; -import com.ochafik.lang.jnaerator.runtime.*; - -long l = l(); -short s = s(); -int i = i(); diff --git a/libraries/jnaerator/maven-jnaerator-plugin/.classpath b/libraries/jnaerator/maven-jnaerator-plugin/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/maven-jnaerator-plugin/.gitignore b/libraries/jnaerator/maven-jnaerator-plugin/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/maven-jnaerator-plugin/.project b/libraries/jnaerator/maven-jnaerator-plugin/.project deleted file mode 100644 index 52798d407..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - maven-jnaerator-plugin - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bf858f543..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:16 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/maven-jnaerator-plugin/pom.xml b/libraries/jnaerator/maven-jnaerator-plugin/pom.xml deleted file mode 100644 index e83c8e299..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - - com.nativelibs4java - maven-jnaerator-plugin - maven-plugin - JNAerator Maven Plugin - http://jnaerator.googlecode.com - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - com.nativelibs4java - jnaerator - shaded - - - org.apache.maven - maven-plugin-api - 3.0.3 - - - org.apache.maven - maven-project - 3.0-alpha-2 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - aggregator - t - - - description - t - - - execute - t - - - goal - t - - - phase - t - - - requiresDirectInvocation - t - - - requiresDependencyResolution - t - - - requiresProject - t - - - requiresReports - t - - - requiresOnline - t - - - parameter - t - - - component - t - - - required - t - - - readonly - t - - - - - - - - diff --git a/libraries/jnaerator/maven-jnaerator-plugin/src/main/java/com/jnaerator/JNAeratorMojo.java b/libraries/jnaerator/maven-jnaerator-plugin/src/main/java/com/jnaerator/JNAeratorMojo.java deleted file mode 100644 index 0b77076c5..000000000 --- a/libraries/jnaerator/maven-jnaerator-plugin/src/main/java/com/jnaerator/JNAeratorMojo.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.jnaerator; - -/* - * Copyright 2001-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; - -import com.ochafik.lang.jnaerator.*; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.*; - -/** - * Launch JNAerator to wrap native libraries in Java for use with JNA. - * @goal generate - * @phase generate-sources - * @description Launches JNAerator with the command-line arguments contained in src/main/jnaerator/config.jnaerator. To launch from command line, use "mvn jnaerator:generate" - */ -public class JNAeratorMojo - extends AbstractMojo -{ - /** - * Path to JNAerator configuration file. - * @parameter expression="${project.basedir}/src/main/jnaerator/config.jnaerator" - * @required - */ - private File config; - - - /** - * Whether JNAerator should output helper Scala classes (experimental) - * @parameter expression="false" - * @required - */ - private boolean generateScala; - - /** - * Output directory for JNAerated Java sources. - * @parameter expression="${project.build.directory}/generated-sources/java" - * @optional - */ - private File javaOutputDirectory; - - /** - * Output directory for JNAerated Scala sources. - * @parameter expression="${project.build.directory}/generated-sources/scala" - * @optional - */ - private File scalaOutputDirectory; - - /** - * @parameter expression="${project}" - * @required - * @readonly - * @since 1.0 - */ - private MavenProject project; - - static File canonizeDir(File f) throws IOException { - if (!f.exists()) - f.mkdirs(); - return f.getCanonicalFile(); - } - public void execute() - throws MojoExecutionException - { - if (!config.exists()) { - getLog().info("No JNAerator config file '" + config + "' found"); - return; - } - try - { - List args = new ArrayList(); - - args.add(config.getAbsolutePath()); - - // Override settings from config file : - args.add("-mode"); - args.add(JNAeratorConfig.OutputMode.Directory.name()); - args.add("-f"); - args.add("-o"); - - File javaDir = canonizeDir(javaOutputDirectory); - args.add(javaDir.toString()); - - project.addCompileSourceRoot(javaDir.toString()); - - if (generateScala) { - args.add("-scalaOut"); - args.add(canonizeDir(scalaOutputDirectory).toString()); - } - - com.ochafik.lang.jnaerator.JNAerator.main(args.toArray(new String[0])); - } - catch (Exception e ) - { - throw new MojoExecutionException( "Error running JNAerator on " + config, e ); - } - } -} diff --git a/libraries/jnaerator/ochafik-swing/.classpath b/libraries/jnaerator/ochafik-swing/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/ochafik-swing/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/ochafik-swing/.gitignore b/libraries/jnaerator/ochafik-swing/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/ochafik-swing/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/ochafik-swing/.project b/libraries/jnaerator/ochafik-swing/.project deleted file mode 100644 index 579f5a8bc..000000000 --- a/libraries/jnaerator/ochafik-swing/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - ochafik-swing - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/ochafik-swing/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/ochafik-swing/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9cf8f359f..000000000 --- a/libraries/jnaerator/ochafik-swing/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:13 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/ochafik-swing/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/ochafik-swing/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/ochafik-swing/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/ochafik-swing/pom.xml b/libraries/jnaerator/ochafik-swing/pom.xml deleted file mode 100644 index 7948037e0..000000000 --- a/libraries/jnaerator/ochafik-swing/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - 4.0.0 - com.nativelibs4java - ochafik-swing - OChafik's Swing Utilities - http://ochafik.free.fr/blog/ - jar - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - com.nativelibs4java - ochafik-util - - - - - - diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/beans/BeansController.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/beans/BeansController.java deleted file mode 100644 index fe80373bf..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/beans/BeansController.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.beans; -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.text.JTextComponent; - -import com.ochafik.swing.FormUtils; - - -@SuppressWarnings("unchecked") -public class BeansController { - M model; - Class modelClass; - - public BeansController(Class modelClass) { - this.modelClass=modelClass; - } - - Map> viewsByPropertyName=new HashMap>(); - Map propertiesTypes=new HashMap(); - Map oldValues=new HashMap(); - Map getterMethods=new HashMap(); - Map setterMethods=new HashMap(); - public PropertyChangeSupport getPropertyChangeSupport() { - return propertyChangeSupport; - } - PropertyChangeSupport propertyChangeSupport=new PropertyChangeSupport(this); - static final Class getterArgs[]=new Class[0]; - - public void addPropertyChangeListener(PropertyChangeListener listener) { - propertyChangeSupport.addPropertyChangeListener(listener); - } - public void addPropertyChangeListener(String propertyName,PropertyChangeListener listener) { - propertyChangeSupport.addPropertyChangeListener(propertyName,listener); - } - public JComponent createScrollableViewComponent( - final String propertyName, - String caption, - String title, - String tooltip, - boolean largeComponent - ) {//, IllegalAccessException { - JComponent c=createViewComponent(propertyName,caption,largeComponent); - if (c==null) return c; - if (title!=null) c.setBorder(BorderFactory.createTitledBorder(title)); - if (c instanceof JTextArea) { - JTextArea ta=(JTextArea)c; - ta.setLineWrap(true); - ta.setWrapStyleWord(true); - JScrollPane jsp=new JScrollPane(ta); - c=jsp; - } - if (title!=null) c.setBorder(BorderFactory.createTitledBorder(title)); - if (tooltip!=null) c.setToolTipText(tooltip); - return c; - } - public static final boolean booleanTrue=true;//, booleanFalse=false; - //private static Object booleanTrueObject,booleanFalseObject; - //public static Class BooleanPrimitiveClass; - /*static { - try { - Class clazz=BeansController.class; - BooleanPrimitiveClass=clazz.getField("booleanTrue").getType(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }*/ - public JComponent createViewComponent(final String propertyName,String caption, boolean largeComponent) {//throws NoSuchMethodException {//, IllegalAccessException { - try { - Class propertyType=getPropertyType(propertyName); - JComponent jc; - if (String.class.isAssignableFrom(propertyType)) { - jc=largeComponent ? new JTextArea() : new JTextField(); - final JTextComponent jtc=(JTextComponent )jc; - FormUtils.addUndoRedoSupport(jtc); - jtc.addFocusListener(new FocusAdapter() { - @Override - public void focusGained(FocusEvent arg0) { - jtc.selectAll(); - } - @Override - public void focusLost(FocusEvent arg0) { - // TODO Auto-generated method stub - jtc.setSelectionStart(0); - jtc.setSelectionEnd(0); - } - }); - - } else if (isBoolean(propertyType)) { - jc=caption==null ? new JCheckBox() : new JCheckBox(caption); - } else if (isInteger(propertyType)) { - jc=new JTextField(); - } else { - System.err.println("IMPLEMENTME! Don't know how to create a view component for model class "+propertyType.getName()); - jc=null; - } - attachViewComponent(jc,propertyName); - return jc; - } catch (NoSuchMethodException ex) { - throw new RuntimeException("No such field in "+modelClass.getName()+" : "+propertyName); - } - } - public void attachViewComponent(JComponent jc, final String propertyName) throws NoSuchMethodException {//, IllegalAccessException { - Class propertyType=getPropertyType(propertyName); - if (String.class.isAssignableFrom(propertyType)) { - final JTextComponent c=(JTextComponent)jc; - c.getDocument().addDocumentListener( new DocumentListener() { - public void changedUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - public void insertUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - public void removeUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - }); - } else if (isBoolean(propertyType)) { - final AbstractButton c=(AbstractButton)jc; - c.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - fireViewChange(c,propertyName,new Boolean(c.isSelected())); - }}); - } else if (isInteger(propertyType)){ - final JTextComponent c=(JTextComponent)jc; - c.getDocument().addDocumentListener(new DocumentListener() { - public void changedUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - public void insertUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - public void removeUpdate(DocumentEvent e) { fireViewChange(c,propertyName,c.getText()); } - }); - - } else { - System.err.println("IMPLEMENTME! Don't know how to create a view component for model class "+propertyType.getName()); - } - if (jc!=null) { - java.util.List views=viewsByPropertyName.get(propertyName); - if (views==null) { - views=new ArrayList(); - viewsByPropertyName.put(propertyName,views); - } - views.add(jc); - } - jc.setEnabled(model!=null); - } - Method getGetterMethod(String propertyName) throws NoSuchMethodException {//, IllegalAccessException { - Method getterMethod=getterMethods.get(propertyName); - if (getterMethod==null) { - try { - getterMethod=modelClass.getMethod(getGetterMethodName(propertyName),getterArgs); - } catch (NoSuchMethodException ex) { - getterMethod=modelClass.getMethod(getIsGetterMethodName(propertyName),getterArgs); - } - getterMethods.put(propertyName,getterMethod); - } - return getterMethod; - } - Class getPropertyType(String propertyName) throws NoSuchMethodException { //, IllegalAccessException { - Class propertyType=propertiesTypes.get(propertyName); - if (propertyType==null) { - propertyType=getGetterMethod(propertyName).getReturnType(); - propertiesTypes.put(propertyName,propertyType); - } - return propertyType; - } - Method getSetterMethod(String propertyName) throws NoSuchMethodException { //, IllegalAccessException { - Method setterMethod=setterMethods.get(propertyName); - if (setterMethod==null) { - Class propertyType=getPropertyType(propertyName); - Class setterArgs[]=new Class[] { propertyType }; - setterMethod=modelClass.getMethod(getSetterMethodName(propertyName),setterArgs); - setterMethods.put(propertyName,setterMethod); - } - return setterMethod; - } - boolean updatingModel=false; - public M getModel() { return model; } - public void setModel(M model) { - this.model=model; - if (model!=null) { - if (!modelClass.isAssignableFrom(model.getClass())) throw new ClassCastException(model.getClass().getName()+" not a subclass of "+modelClass.getName()); - - } - modelUpdated(); - } - boolean firingPropertyChange=false; - Set propertiesBeingFired=new TreeSet(); - public void fireViewChange(Component eventSource,String propertyName, Object newValue) { - //System.out.println("FireViewChange : propertyName="+propertyName+", firingPropertyChange="+firingPropertyChange+", model="+model); - - /// Do not fire change events if somebody is just setting the model - if (updatingModel) return; - - if (propertiesBeingFired.contains(propertyName)) { - return; - } else { - propertiesBeingFired.add(propertyName); - } - if (model!=null) { - try { - Class propertyType=getPropertyType(propertyName); - Object oldValue=oldValues.get(propertyName); - boolean validValue=true; - if (String.class.isAssignableFrom(propertyType)) { - getSetterMethod(propertyName).invoke(model,newValue); - oldValues.put(propertyName,newValue); - - for (JComponent view : viewsByPropertyName.get(propertyName)) { - if (view!=eventSource) { - JTextComponent tc=(JTextComponent)view; - //System.out.println("propertyName="+propertyName+" set at "+newValue - tc.setText((String)newValue); - } - } - } else if (isBoolean(propertyType)) { - getSetterMethod(propertyName).invoke(model,newValue); - oldValues.put(propertyName,newValue); - - for (JComponent view : viewsByPropertyName.get(propertyName)) { - if (view!=eventSource) { - AbstractButton cb=(AbstractButton)view; - cb.setSelected(((Boolean)newValue).booleanValue()); - } - } - } else if (isInteger(propertyType)) { - try { - int intValue=Integer.parseInt(((String)newValue).trim()); - getSetterMethod(propertyName).invoke(model,new Integer(intValue)); - oldValues.put(propertyName,newValue); - - for (JComponent view : viewsByPropertyName.get(propertyName)) { - view.setFont(view.getFont().deriveFont(Font.PLAIN)); - view.setForeground(Color.black); - if (view!=eventSource) { - JTextComponent tc=(JTextComponent)view; - tc.setText(intValue+""); - } - } - } catch (NumberFormatException ex) { - validValue=false; - if (eventSource instanceof Component) { - Component eventSourceComponent=(Component)eventSource; - eventSourceComponent.setFont(eventSourceComponent.getFont().deriveFont(Font.BOLD|Font.ITALIC)); - eventSourceComponent.setForeground(Color.red); - } - } - } - if (propertyChangeSupport!=null&&validValue) { - propertyChangeSupport.firePropertyChange( - propertyName, - oldValue, - newValue - ); - } - - } catch (Exception ex) { - ex.printStackTrace(); - } - } - //firingPropertyChange=false; - propertiesBeingFired.remove(propertyName); - } - private static boolean isBoolean(Class propertyType) { - return Boolean.class.isAssignableFrom(propertyType) || propertyType.getName().equals("boolean"); - } - public void modelUpdated() { - if (updatingModel) return; - updatingModel=true; - boolean nullModel=model==null; - //System.out.println("Model updated "+nullModel); - for (String propertyName : propertiesTypes.keySet()) { - try { - Class propertyType=getPropertyType(propertyName); - - Object value=model==null ? - null : - getGetterMethod(propertyName).invoke(model); - //System.out.println("\tValue("+propertyName+") = "+value); - for (JComponent view : viewsByPropertyName.get(propertyName)) { - if (String.class.isAssignableFrom(propertyType)) { - JTextComponent tc=(JTextComponent)view; - String svalue=(String)value; - tc.setText(svalue==null ? "" : svalue); - tc.setEnabled(!nullModel); - } else if (isBoolean(propertyType)) { - //TODO - AbstractButton cb=(AbstractButton)view; - Boolean bvalue=(Boolean)value; - cb.setEnabled(!nullModel); - cb.setSelected(bvalue!=null && bvalue.booleanValue()); - } else if (isInteger(propertyType)) { - JTextComponent tc=(JTextComponent)view; - Integer ivalue=(Integer)value; - tc.setText(ivalue==null ? "" : ivalue.toString()); - tc.setEnabled(!nullModel); - } - } - } catch (Exception ex) { - System.err.println("Error while updating views for property '"+propertyName+"' of model "+modelClass.getName()); - ex.printStackTrace(); - } - } - updatingModel=false; - } - private static final boolean isInteger(Class c) { - return Integer.class.isAssignableFrom(c); - } - final static String getGetterMethodName(String field) { - return "get"+capitalizeFirstLetter(field); - } - final static String getIsGetterMethodName(String field) { - return "is"+capitalizeFirstLetter(field); - } - final static String getSetterMethodName(String field) { - return "set"+capitalizeFirstLetter(field); - } - final static String capitalizeFirstLetter(String s) { - int sLength=s.length(); - if (sLength<=1) return s.toUpperCase(); - else { - return s.substring(0,1).toUpperCase()+s.substring(1); - } - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormElement.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormElement.java deleted file mode 100644 index cf6f4ce02..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormElement.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.swing; - -import java.awt.Component; - -public final class FormElement { - public String name, title, toolTip, propertyName; - public boolean largeComponent; - public Component editorComponent; - public FormElement(String name, Component editorComponent) { - this.name=name; - this.editorComponent=editorComponent; - } - public FormElement(String name, String propertyName) { - this(name,propertyName,false); - } - public FormElement(String name, String propertyName,boolean largeComponent) { - this(name,null,null,propertyName,largeComponent); - } - public FormElement(String name, String title, String toolTip, String propertyName,boolean largeComponent) { - this.name=name; - this.title=title; - this.toolTip=toolTip; - this.propertyName=propertyName; - this.largeComponent=largeComponent; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormUtils.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormUtils.java deleted file mode 100644 index 36264df5e..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/FormUtils.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ActionMap; -import javax.swing.Box; -import javax.swing.InputMap; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.KeyStroke; -import javax.swing.text.JTextComponent; -import javax.swing.undo.UndoManager; - -import com.ochafik.beans.BeansController; - - -public class FormUtils { - - @SuppressWarnings("serial") - public static Action createUndoAction(final UndoManager undoManager, String name) { - return new AbstractAction(name) { - public void actionPerformed(ActionEvent arg0) { - if (undoManager.canUndo()) { - undoManager.undo(); - } - } - }; - } - @SuppressWarnings("serial") - public static Action createRedoAction(final UndoManager undoManager, String name) { - return new AbstractAction(name) { - public void actionPerformed(ActionEvent arg0) { - if (undoManager.canRedo()) { - undoManager.redo(); - } - } - }; - } - public static void registerUndoRedoActions(JComponent jtc, Action undoAction, Action redoAction) { - InputMap inputMap = jtc.getInputMap(); - inputMap.put(KeyStroke.getKeyStroke("pressed UNDO"), "undo"); - inputMap.put(KeyStroke.getKeyStroke("ctrl pressed Z"), "undo"); - inputMap.put(KeyStroke.getKeyStroke("meta pressed Z"), "undo"); - - inputMap.put(KeyStroke.getKeyStroke("pressed REDO"), "redo"); - inputMap.put(KeyStroke.getKeyStroke("ctrl pressed Y"), "redo"); - inputMap.put(KeyStroke.getKeyStroke("meta pressed Y"), "redo"); - - ActionMap actionMap = jtc.getActionMap(); - actionMap.put("undo", undoAction); - actionMap.put("redo", redoAction); - } - - public final static void addUndoRedoSupport(final JTextComponent jtc) { - jtc.addPropertyChangeListener("document", new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - UndoRedoUtils.registerNewUndoManager(jtc); - } - - }); - UndoRedoUtils.registerNewUndoManager(jtc); - } - public final static JPanel makeEntriesPanel(BeansController beansController,int widthMin,FormElement[] formElements) { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - gbc.weighty=1; - - JPanel panel=new JPanel(gbl);//new GridLayout(captionsAndProperties.length,2)); - int space=5,pad=1; - Insets labelsInsets=new Insets(pad,space,pad,space); - Insets editorsInsets=new Insets(pad,pad,pad,pad); - for (int i=0;i. -*/ -package com.ochafik.swing; - -import javax.swing.JComponent; -import javax.swing.text.Document; -import javax.swing.text.JTextComponent; -import javax.swing.undo.UndoManager; - -public class UndoRedoUtils { - - public static void registerNewUndoManager(JTextComponent jtc) { - registerNewUndoManager(jtc, jtc.getDocument()); - } - public static void registerNewUndoManager(JComponent jtc, Document d) { - UndoManager undoManager = new UndoManager(); - d.addUndoableEditListener(undoManager); - FormUtils.registerUndoRedoActions(jtc, FormUtils.createUndoAction(undoManager, "undo"), FormUtils.createRedoAction(undoManager, "redo")); - } - -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/candy/JLinkLabel.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/candy/JLinkLabel.java deleted file mode 100644 index 190bc3368..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/candy/JLinkLabel.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.ochafik.swing.candy; - -import java.awt.Cursor; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.JLabel; - -import com.ochafik.xml.XMLUtils; - -public class JLinkLabel extends JLabel { - private static final long serialVersionUID = -2619802894792618038L; - Runnable linkAction; - boolean actInNewThread = false; - - public JLinkLabel(String text) { - super(text); - init(null); - } - - public JLinkLabel(String text, int orientation) { - super(text, orientation); - init(null); - } - - public JLinkLabel(String text, int orientation, Runnable linkAction) { - this(text, orientation, linkAction, false); - } - public JLinkLabel(String text, int orientation, Runnable linkAction, boolean actInNewThread) { - super(text, orientation); - init(linkAction); - setActInNewThread(actInNewThread); - } - public JLinkLabel(String text, Runnable linkAction) { - this(text, linkAction, false); - } - public JLinkLabel(String text, Runnable linkAction, boolean actInNewThread) { - super(text); - init(linkAction); - setActInNewThread(actInNewThread); - } - - public void setActInNewThread(boolean actInNewThread) { - this.actInNewThread = actInNewThread; - } - public boolean isActInNewThread() { - return actInNewThread; - } - - protected void enabledChanged() { - String text = actualText; - if (getLinkAction() == null) { - setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } else { - if (isEnabled()) { - setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - if (!actualText.startsWith("")) - text = "" + XMLUtils.escapeEntities(actualText) + ""; - - } else { - setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - if (!actualText.startsWith("")) - text = "" + XMLUtils.escapeEntities(actualText) + ""; - } - } - super.setText(text); - setMaximumSize(getMinimumSize()); - } - String actualText; - @Override - public void setText(String text) { - this.actualText = text; - enabledChanged(); - } - private void init(Runnable linkAction2) { - setLinkAction(linkAction2); - enabledChanged(); - addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent arg0) { - action(); - } - @Override - public void mouseEntered(MouseEvent arg0) { - if (isEnabled() && getLinkAction() != null) - setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - else - setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - }); - } - - public boolean action() { - Runnable linkAction = getLinkAction(); - if (!isEnabled() || linkAction == null) - return false; - - if (isActInNewThread()) - new Thread(linkAction).start(); - else - linkAction.run(); - return true; - } - - public void setLinkAction(Runnable linkAction) { - this.linkAction = linkAction; - enabledChanged(); - } - public Runnable getLinkAction() { - return linkAction; - } - -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/BatchFileTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/BatchFileTokenMarker.java deleted file mode 100644 index 36c51e12e..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/BatchFileTokenMarker.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Batch file token marker. - * - * @author Slava Pestov - * @version $Id: BatchFileTokenMarker.java,v 1.20 1999/12/13 03:40:29 sp Exp $ - */ -public class BatchFileTokenMarker extends TokenMarker -{ - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - int lastOffset = offset; - int length = line.count + offset; - - if(SyntaxUtilities.regionMatches(true,line,offset,"rem")) - { - addToken(line.count,Token.COMMENT1); - return Token.NULL; - } - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - switch(token) - { - case Token.NULL: - switch(array[i]) - { - case '%': - addToken(i - lastOffset,token); - lastOffset = i; - if(length - i <= 3 || array[i+2] == ' ') - { - addToken(2,Token.KEYWORD2); - i += 2; - lastOffset = i; - } - else - token = Token.KEYWORD2; - break; - case '"': - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lastOffset = i; - break; - case ':': - if(i == offset) - { - addToken(line.count,Token.LABEL); - lastOffset = length; - break loop; - } - break; - case ' ': - if(lastOffset == offset) - { - addToken(i - lastOffset,Token.KEYWORD1); - lastOffset = i; - } - break; - } - break; - case Token.KEYWORD2: - if(array[i] == '%') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = i1; - } - break; - case Token.LITERAL1: - if(array[i] == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = i1; - } - break; - default: - throw new InternalError("Invalid state: " + token); - } - } - - if(lastOffset != length) - { - if(token != Token.NULL) - token = Token.INVALID; - else if(lastOffset == offset) - token = Token.KEYWORD1; - addToken(length - lastOffset,token); - } - return Token.NULL; - } - - public boolean supportsMultilineTokens() - { - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CCTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CCTokenMarker.java deleted file mode 100644 index d8967ddc6..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CCTokenMarker.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; - -/** - * C++ token marker. - * - * @author Slava Pestov - * @version $Id: CCTokenMarker.java,v 1.6 1999/12/13 03:40:29 sp Exp $ - */ -public class CCTokenMarker extends CTokenMarker -{ - public CCTokenMarker() - { - super(true,getKeywords()); - } - - public static KeywordMap getKeywords() - { - if(ccKeywords == null) - { - ccKeywords = new KeywordMap(false); - - ccKeywords.add("and", Token.KEYWORD3); - ccKeywords.add("and_eq", Token.KEYWORD3); - ccKeywords.add("asm", Token.KEYWORD2); // - ccKeywords.add("auto", Token.KEYWORD1); // - ccKeywords.add("bitand", Token.KEYWORD3); - ccKeywords.add("bitor", Token.KEYWORD3); - ccKeywords.add("bool",Token.KEYWORD3); - ccKeywords.add("break", Token.KEYWORD1); // - ccKeywords.add("case", Token.KEYWORD1); // - ccKeywords.add("catch", Token.KEYWORD1); - ccKeywords.add("char", Token.KEYWORD3); // - ccKeywords.add("class", Token.KEYWORD3); - ccKeywords.add("compl", Token.KEYWORD3); - ccKeywords.add("const", Token.KEYWORD1); // - ccKeywords.add("const_cast", Token.KEYWORD3); - ccKeywords.add("continue", Token.KEYWORD1); // - ccKeywords.add("default", Token.KEYWORD1); // - ccKeywords.add("delete", Token.KEYWORD1); - ccKeywords.add("do",Token.KEYWORD1); // - ccKeywords.add("double" ,Token.KEYWORD3); // - ccKeywords.add("dynamic_cast", Token.KEYWORD3); - ccKeywords.add("else", Token.KEYWORD1); // - ccKeywords.add("enum", Token.KEYWORD3); // - ccKeywords.add("explicit", Token.KEYWORD1); - ccKeywords.add("export", Token.KEYWORD2); - ccKeywords.add("extern", Token.KEYWORD2); // - ccKeywords.add("false", Token.LITERAL2); - ccKeywords.add("float", Token.KEYWORD3); // - ccKeywords.add("for", Token.KEYWORD1); // - ccKeywords.add("friend", Token.KEYWORD1); - ccKeywords.add("goto", Token.KEYWORD1); // - ccKeywords.add("if", Token.KEYWORD1); // - ccKeywords.add("inline", Token.KEYWORD1); - ccKeywords.add("int", Token.KEYWORD3); // - ccKeywords.add("long", Token.KEYWORD3); // - ccKeywords.add("mutable", Token.KEYWORD3); - ccKeywords.add("namespace", Token.KEYWORD2); - ccKeywords.add("new", Token.KEYWORD1); - ccKeywords.add("not", Token.KEYWORD3); - ccKeywords.add("not_eq", Token.KEYWORD3); - ccKeywords.add("operator", Token.KEYWORD3); - ccKeywords.add("or", Token.KEYWORD3); - ccKeywords.add("or_eq", Token.KEYWORD3); - ccKeywords.add("private", Token.KEYWORD1); - ccKeywords.add("protected", Token.KEYWORD1); - ccKeywords.add("public", Token.KEYWORD1); - ccKeywords.add("register", Token.KEYWORD1); - ccKeywords.add("reinterpret_cast", Token.KEYWORD3); - ccKeywords.add("return", Token.KEYWORD1); // - ccKeywords.add("short", Token.KEYWORD3); // - ccKeywords.add("signed", Token.KEYWORD3); // - ccKeywords.add("sizeof", Token.KEYWORD1); // - ccKeywords.add("static", Token.KEYWORD1); // - ccKeywords.add("static_cast", Token.KEYWORD3); - ccKeywords.add("struct", Token.KEYWORD3); // - ccKeywords.add("switch", Token.KEYWORD1); // - ccKeywords.add("template", Token.KEYWORD3); - ccKeywords.add("this", Token.LITERAL2); - ccKeywords.add("throw", Token.KEYWORD1); - ccKeywords.add("true", Token.LITERAL2); - ccKeywords.add("try", Token.KEYWORD1); - ccKeywords.add("typedef", Token.KEYWORD3); // - ccKeywords.add("typeid", Token.KEYWORD3); - ccKeywords.add("typename", Token.KEYWORD3); - ccKeywords.add("union", Token.KEYWORD3); // - ccKeywords.add("unsigned", Token.KEYWORD3); // - ccKeywords.add("using", Token.KEYWORD2); - ccKeywords.add("virtual", Token.KEYWORD1); - ccKeywords.add("void", Token.KEYWORD1); // - ccKeywords.add("volatile", Token.KEYWORD1); // - ccKeywords.add("wchar_t", Token.KEYWORD3); - ccKeywords.add("while", Token.KEYWORD1); // - ccKeywords.add("xor", Token.KEYWORD3); - ccKeywords.add("xor_eq", Token.KEYWORD3); - - // non ANSI keywords - ccKeywords.add("NULL", Token.LITERAL2); - } - return ccKeywords; - } - - // private members - private static KeywordMap ccKeywords; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CTokenMarker.java deleted file mode 100644 index 5327da756..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/CTokenMarker.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * CTokenMarker.java - C token marker - * Copyright (C) 1998, 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * C token marker. - * - * @author Slava Pestov - * @version $Id: CTokenMarker.java,v 1.34 1999/12/13 03:40:29 sp Exp $ - */ -public class CTokenMarker extends TokenMarker -{ - public CTokenMarker() - { - this(true,getKeywords()); - } - - public CTokenMarker(boolean cpp, KeywordMap keywords) - { - this.cpp = cpp; - this.keywords = keywords; - } - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - lastOffset = offset; - lastKeyword = offset; - int length = line.count + offset; - boolean backslash = false; - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case '#': - if(backslash) - backslash = false; - else if(cpp) - { - if(doKeyword(line,i,c)) - break; - addToken(i - lastOffset,token); - addToken(length - i,Token.KEYWORD2); - lastOffset = lastKeyword = length; - break loop; - } - break; - case '"': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lastOffset = lastKeyword = i; - } - break; - case '\'': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL2; - lastOffset = lastKeyword = i; - } - break; - case ':': - if(lastKeyword == offset) - { - if(doKeyword(line,i,c)) - break; - backslash = false; - addToken(i1 - lastOffset,Token.LABEL); - lastOffset = lastKeyword = i1; - } - else if(doKeyword(line,i,c)) - break; - break; - case '/': - backslash = false; - doKeyword(line,i,c); - if(length - i > 1) - { - switch(array[i1]) - { - case '*': - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - if(length - i > 2 && array[i+2] == '*') - token = Token.COMMENT2; - else - token = Token.COMMENT1; - break; - case '/': - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = lastKeyword = length; - break loop; - } - } - break; - default: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - } - break; - case Token.COMMENT1: - case Token.COMMENT2: - backslash = false; - if(c == '*' && length - i > 1) - { - if(array[i1] == '/') - { - i++; - addToken((i+1) - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i+1; - } - } - break; - case Token.LITERAL1: - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - if(token == Token.NULL) - doKeyword(line,length,'\0'); - - switch(token) - { - case Token.LITERAL1: - case Token.LITERAL2: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - case Token.KEYWORD2: - addToken(length - lastOffset,token); - if(!backslash) - token = Token.NULL; - default: - addToken(length - lastOffset,token); - break; - } - - return token; - } - - public static KeywordMap getKeywords() - { - if(cKeywords == null) - { - cKeywords = new KeywordMap(false); - cKeywords.add("char",Token.KEYWORD3); - cKeywords.add("double",Token.KEYWORD3); - cKeywords.add("enum",Token.KEYWORD3); - cKeywords.add("float",Token.KEYWORD3); - cKeywords.add("int",Token.KEYWORD3); - cKeywords.add("long",Token.KEYWORD3); - cKeywords.add("short",Token.KEYWORD3); - cKeywords.add("signed",Token.KEYWORD3); - cKeywords.add("struct",Token.KEYWORD3); - cKeywords.add("typedef",Token.KEYWORD3); - cKeywords.add("union",Token.KEYWORD3); - cKeywords.add("unsigned",Token.KEYWORD3); - cKeywords.add("void",Token.KEYWORD3); - cKeywords.add("auto",Token.KEYWORD1); - cKeywords.add("const",Token.KEYWORD1); - cKeywords.add("extern",Token.KEYWORD1); - cKeywords.add("register",Token.KEYWORD1); - cKeywords.add("static",Token.KEYWORD1); - cKeywords.add("volatile",Token.KEYWORD1); - cKeywords.add("break",Token.KEYWORD1); - cKeywords.add("case",Token.KEYWORD1); - cKeywords.add("continue",Token.KEYWORD1); - cKeywords.add("default",Token.KEYWORD1); - cKeywords.add("do",Token.KEYWORD1); - cKeywords.add("else",Token.KEYWORD1); - cKeywords.add("for",Token.KEYWORD1); - cKeywords.add("goto",Token.KEYWORD1); - cKeywords.add("if",Token.KEYWORD1); - cKeywords.add("return",Token.KEYWORD1); - cKeywords.add("sizeof",Token.KEYWORD1); - cKeywords.add("switch",Token.KEYWORD1); - cKeywords.add("while",Token.KEYWORD1); - cKeywords.add("asm",Token.KEYWORD2); - cKeywords.add("asmlinkage",Token.KEYWORD2); - cKeywords.add("far",Token.KEYWORD2); - cKeywords.add("huge",Token.KEYWORD2); - cKeywords.add("inline",Token.KEYWORD2); - cKeywords.add("near",Token.KEYWORD2); - cKeywords.add("pascal",Token.KEYWORD2); - cKeywords.add("true",Token.LITERAL2); - cKeywords.add("false",Token.LITERAL2); - cKeywords.add("NULL",Token.LITERAL2); - } - return cKeywords; - } - - // private members - private static KeywordMap cKeywords; - - private boolean cpp; - private KeywordMap keywords; - private int lastOffset; - private int lastKeyword; - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/DefaultInputHandler.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/DefaultInputHandler.java deleted file mode 100644 index f913d7b84..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/DefaultInputHandler.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * DefaultInputHandler.java - Default implementation of an input handler - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import java.awt.Toolkit; -import java.awt.event.ActionListener; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.util.Hashtable; -import java.util.StringTokenizer; - -import javax.swing.KeyStroke; - -/** - * The default input handler. It maps sequences of keystrokes into actions - * and inserts key typed events into the text area. - * @author Slava Pestov - * @version $Id: DefaultInputHandler.java,v 1.18 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings({"unused", "unchecked"}) -public class DefaultInputHandler extends InputHandler -{ - /** - * Creates a new input handler with no key bindings defined. - */ - public DefaultInputHandler() - { - bindings = currentBindings = new Hashtable(); - } - - /** - * Sets up the default key bindings. - */ - public void addDefaultKeyBindings() - { - addKeyBinding("C+C",COPY); - addKeyBinding("C+X",CUT); - addKeyBinding("C+V",PASTE); - - addKeyBinding("BACK_SPACE",BACKSPACE); - addKeyBinding("C+BACK_SPACE",BACKSPACE_WORD); - addKeyBinding("DELETE",DELETE); - addKeyBinding("C+DELETE",DELETE_WORD); - - addKeyBinding("ENTER",INSERT_BREAK); - addKeyBinding("TAB",INSERT_TAB); - addKeyBinding("S+TAB",REMOVE_TAB); - addKeyBinding("C+A",SELECT_ALL); - - addKeyBinding("INSERT",OVERWRITE); - addKeyBinding("C+\\",TOGGLE_RECT); - - addKeyBinding("HOME",HOME); - addKeyBinding("END",END); - addKeyBinding("S+HOME",SELECT_HOME); - addKeyBinding("S+END",SELECT_END); - addKeyBinding("C+HOME",DOCUMENT_HOME); - addKeyBinding("C+END",DOCUMENT_END); - addKeyBinding("CS+HOME",SELECT_DOC_HOME); - addKeyBinding("CS+END",SELECT_DOC_END); - - addKeyBinding("PAGE_UP",PREV_PAGE); - addKeyBinding("PAGE_DOWN",NEXT_PAGE); - addKeyBinding("S+PAGE_UP",SELECT_PREV_PAGE); - addKeyBinding("S+PAGE_DOWN",SELECT_NEXT_PAGE); - - addKeyBinding("LEFT",PREV_CHAR); - addKeyBinding("S+LEFT",SELECT_PREV_CHAR); - addKeyBinding("C+LEFT",PREV_WORD); - addKeyBinding("CS+LEFT",SELECT_PREV_WORD); - addKeyBinding("RIGHT",NEXT_CHAR); - addKeyBinding("S+RIGHT",SELECT_NEXT_CHAR); - addKeyBinding("C+RIGHT",NEXT_WORD); - addKeyBinding("CS+RIGHT",SELECT_NEXT_WORD); - addKeyBinding("UP",PREV_LINE); - addKeyBinding("S+UP",SELECT_PREV_LINE); - addKeyBinding("DOWN",NEXT_LINE); - addKeyBinding("S+DOWN",SELECT_NEXT_LINE); - - addKeyBinding("C+ENTER",REPEAT); - } - - /** - * Adds a key binding to this input handler. The key binding is - * a list of white space separated key strokes of the form - * [modifiers+]key where modifier is C for Control, A for Alt, - * or S for Shift, and key is either a character (a-z) or a field - * name in the KeyEvent class prefixed with VK_ (e.g., BACK_SPACE) - * @param keyBinding The key binding - * @param action The action - */ - public void addKeyBinding(String keyBinding, ActionListener action) - { - Hashtable current = bindings; - - StringTokenizer st = new StringTokenizer(keyBinding); - while(st.hasMoreTokens()) - { - KeyStroke keyStroke = parseKeyStroke(st.nextToken()); - if(keyStroke == null) - return; - - if(st.hasMoreTokens()) - { - Object o = current.get(keyStroke); - if(o instanceof Hashtable) - current = (Hashtable)o; - else - { - o = new Hashtable(); - current.put(keyStroke,o); - current = (Hashtable)o; - } - } - else - current.put(keyStroke,action); - } - } - public void addKeyBinding(KeyStroke keyStroke, ActionListener action) { - Hashtable current = bindings; - current.put(keyStroke,action); - } - - /** - * Removes a key binding from this input handler. This is not yet - * implemented. - * @param keyBinding The key binding - */ - public void removeKeyBinding(String keyBinding) - { - throw new InternalError("Not yet implemented"); - } - - /** - * Removes all key bindings from this input handler. - */ - public void removeAllKeyBindings() - { - bindings.clear(); - } - - /** - * Returns a copy of this input handler that shares the same - * key bindings. Setting key bindings in the copy will also - * set them in the original. - */ - public InputHandler copy() - { - return new DefaultInputHandler(this); - } - - /** - * Handle a key pressed event. This will look up the binding for - * the key stroke and execute it. - */ - public void keyPressed(KeyEvent evt) - { - int keyCode = evt.getKeyCode(); - int modifiers = evt.getModifiers(); - - if(keyCode == KeyEvent.VK_CONTROL || - keyCode == KeyEvent.VK_SHIFT || - keyCode == KeyEvent.VK_ALT || - keyCode == KeyEvent.VK_META) - return; - - if((modifiers & ~KeyEvent.SHIFT_MASK) != 0 - || evt.isActionKey() - || keyCode == KeyEvent.VK_BACK_SPACE - || keyCode == KeyEvent.VK_DELETE - || keyCode == KeyEvent.VK_ENTER - || keyCode == KeyEvent.VK_TAB - || keyCode == KeyEvent.VK_ESCAPE) - { - if(grabAction != null) - { - handleGrabAction(evt); - return; - } - - KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, - modifiers); - Object o = currentBindings.get(keyStroke); - if(o == null) - { - // Don't beep if the user presses some - // key we don't know about unless a - // prefix is active. Otherwise it will - // beep when caps lock is pressed, etc. - if(currentBindings != bindings) - { - Toolkit.getDefaultToolkit().beep(); - // F10 should be passed on, but C+e F10 - // shouldn't - repeatCount = 0; - repeat = false; - evt.consume(); - } - currentBindings = bindings; - return; - } - else if(o instanceof ActionListener) - { - currentBindings = bindings; - - executeAction(((ActionListener)o), - evt.getSource(),null); - - evt.consume(); - return; - } - else if(o instanceof Hashtable) - { - currentBindings = (Hashtable)o; - evt.consume(); - return; - } - } - } - - /** - * Handle a key typed event. This inserts the key into the text area. - */ - public void keyTyped(KeyEvent evt) - { - int modifiers = evt.getModifiers(); - char c = evt.getKeyChar(); - if(c != KeyEvent.CHAR_UNDEFINED)// && -// (modifiers & KeyEvent.ALT_MASK) == 0) - { - if(c >= 0x20 && c != 0x7f) - { - KeyStroke keyStroke = KeyStroke.getKeyStroke( - Character.toUpperCase(c)); - Object o = currentBindings.get(keyStroke); - - if(o instanceof Hashtable) - { - currentBindings = (Hashtable)o; - return; - } - else if(o instanceof ActionListener) - { - currentBindings = bindings; - executeAction((ActionListener)o, - evt.getSource(), - String.valueOf(c)); - return; - } - - currentBindings = bindings; - - if(grabAction != null) - { - handleGrabAction(evt); - return; - } - - // 0-9 adds another 'digit' to the repeat number - if(repeat && Character.isDigit(c)) - { - repeatCount *= 10; - repeatCount += (c - '0'); - return; - } - - executeAction(INSERT_CHAR,evt.getSource(), - String.valueOf(evt.getKeyChar())); - - repeatCount = 0; - repeat = false; - } - } - } - - /** - * Converts a string to a keystroke. The string should be of the - * form modifiers+shortcut where modifiers - * is any combination of A for Alt, C for Control, S for Shift - * or M for Meta, and shortcut is either a single character, - * or a keycode name from the KeyEvent class, without - * the VK_ prefix. - * @param keyStroke A string description of the key stroke - */ - public static KeyStroke parseKeyStroke(String keyStroke) - { - if(keyStroke == null) - return null; - int modifiers = 0; - int index = keyStroke.indexOf('+'); - if(index != -1) - { - for(int i = 0; i < index; i++) - { - switch(Character.toUpperCase(keyStroke - .charAt(i))) - { - case 'A': - modifiers |= InputEvent.ALT_MASK; - break; - case 'C': - modifiers |= InputEvent.CTRL_MASK; - break; - case 'M': - modifiers |= InputEvent.META_MASK; - break; - case 'S': - modifiers |= InputEvent.SHIFT_MASK; - break; - } - } - } - String key = keyStroke.substring(index + 1); - if(key.length() == 1) - { - char ch = Character.toUpperCase(key.charAt(0)); - if(modifiers == 0) - return KeyStroke.getKeyStroke(ch); - else - return KeyStroke.getKeyStroke(ch,modifiers); - } - else if(key.length() == 0) - { - System.err.println("Invalid key stroke: " + keyStroke); - return null; - } - else - { - int ch; - - try - { - ch = KeyEvent.class.getField("VK_".concat(key)) - .getInt(null); - } - catch(Exception e) - { - System.err.println("Invalid key stroke: " - + keyStroke); - return null; - } - - return KeyStroke.getKeyStroke(ch,modifiers); - } - } - - // private members - private Hashtable bindings; - private Hashtable currentBindings; - - private DefaultInputHandler(DefaultInputHandler copy) - { - bindings = currentBindings = copy.bindings; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/EiffelTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/EiffelTokenMarker.java deleted file mode 100644 index afc0e432c..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/EiffelTokenMarker.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Eiffel token Marker. - * - * @author Artur Biesiadowski - */ -public class EiffelTokenMarker extends TokenMarker -{ - - public EiffelTokenMarker() - { - this.keywords = getKeywords(); - } - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - lastOffset = offset; - lastKeyword = offset; - int length = line.count + offset; - boolean backslash = false; - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '%') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case '"': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lastOffset = lastKeyword = i; - } - break; - case '\'': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL2; - lastOffset = lastKeyword = i; - } - break; - case ':': - if(lastKeyword == offset) - { - if(doKeyword(line,i,c)) - break; - backslash = false; - addToken(i1 - lastOffset,Token.LABEL); - lastOffset = lastKeyword = i1; - } - else if(doKeyword(line,i,c)) - break; - break; - case '-': - backslash = false; - doKeyword(line,i,c); - if(length - i > 1) - { - switch(array[i1]) - { - case '-': - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = lastKeyword = length; - break loop; - } - } - break; - default: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - } - break; - case Token.COMMENT1: - case Token.COMMENT2: - throw new RuntimeException("Wrong eiffel parser state"); - case Token.LITERAL1: - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - if(token == Token.NULL) - doKeyword(line,length,'\0'); - - switch(token) - { - case Token.LITERAL1: - case Token.LITERAL2: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - case Token.KEYWORD2: - addToken(length - lastOffset,token); - if(!backslash) - token = Token.NULL; - default: - addToken(length - lastOffset,token); - break; - } - - return token; - } - - public static KeywordMap getKeywords() - { - if(eiffelKeywords == null) - { - eiffelKeywords = new KeywordMap(true); - eiffelKeywords.add("alias", Token.KEYWORD1); - eiffelKeywords.add("all", Token.KEYWORD1); - eiffelKeywords.add("and", Token.KEYWORD1); - eiffelKeywords.add("as", Token.KEYWORD1); - eiffelKeywords.add("check", Token.KEYWORD1); - eiffelKeywords.add("class", Token.KEYWORD1); - eiffelKeywords.add("creation", Token.KEYWORD1); - eiffelKeywords.add("debug", Token.KEYWORD1); - eiffelKeywords.add("deferred", Token.KEYWORD1); - eiffelKeywords.add("do", Token.KEYWORD1); - eiffelKeywords.add("else",Token.KEYWORD1); - eiffelKeywords.add("elseif", Token.KEYWORD1); - eiffelKeywords.add("end", Token.KEYWORD1); - eiffelKeywords.add("ensure", Token.KEYWORD1); - eiffelKeywords.add("expanded", Token.KEYWORD1); - eiffelKeywords.add("export", Token.KEYWORD1); - eiffelKeywords.add("external", Token.KEYWORD1); - eiffelKeywords.add("feature", Token.KEYWORD1); - eiffelKeywords.add("from", Token.KEYWORD1); - eiffelKeywords.add("frozen", Token.KEYWORD1); - eiffelKeywords.add("if", Token.KEYWORD1); - eiffelKeywords.add("implies",Token.KEYWORD1); - eiffelKeywords.add("indexing", Token.KEYWORD1); - eiffelKeywords.add("infix", Token.KEYWORD1); - eiffelKeywords.add("inherit", Token.KEYWORD1); - eiffelKeywords.add("inspect", Token.KEYWORD1); - eiffelKeywords.add("invariant", Token.KEYWORD1); - eiffelKeywords.add("is", Token.KEYWORD1); - eiffelKeywords.add("like", Token.KEYWORD1); - eiffelKeywords.add("local", Token.KEYWORD1); - eiffelKeywords.add("loop", Token.KEYWORD1); - eiffelKeywords.add("not", Token.KEYWORD1); - eiffelKeywords.add("obsolete", Token.KEYWORD1); - eiffelKeywords.add("old",Token.KEYWORD1); - eiffelKeywords.add("once", Token.KEYWORD1); - eiffelKeywords.add("or", Token.KEYWORD1); - eiffelKeywords.add("prefix", Token.KEYWORD1); - eiffelKeywords.add("redefine", Token.KEYWORD1); - eiffelKeywords.add("rename", Token.KEYWORD1); - eiffelKeywords.add("require", Token.KEYWORD1); - eiffelKeywords.add("rescue", Token.KEYWORD1); - eiffelKeywords.add("retry", Token.KEYWORD1); - eiffelKeywords.add("select", Token.KEYWORD1); - eiffelKeywords.add("separate", Token.KEYWORD1); - eiffelKeywords.add("then",Token.KEYWORD1); - eiffelKeywords.add("undefine", Token.KEYWORD1); - eiffelKeywords.add("until", Token.KEYWORD1); - eiffelKeywords.add("variant", Token.KEYWORD1); - eiffelKeywords.add("when", Token.KEYWORD1); - eiffelKeywords.add("xor", Token.KEYWORD1); - - eiffelKeywords.add("current",Token.LITERAL2); - eiffelKeywords.add("false",Token.LITERAL2); - eiffelKeywords.add("precursor",Token.LITERAL2); - eiffelKeywords.add("result",Token.LITERAL2); - eiffelKeywords.add("strip",Token.LITERAL2); - eiffelKeywords.add("true",Token.LITERAL2); - eiffelKeywords.add("unique",Token.LITERAL2); - eiffelKeywords.add("void",Token.LITERAL2); - - } - return eiffelKeywords; - } - - // private members - private static KeywordMap eiffelKeywords; - - private KeywordMap keywords; - private int lastOffset; - private int lastKeyword; - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - boolean klassname = false; - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if ( id == Token.NULL ) - { - klassname = true; - for ( int at = lastKeyword; at < lastKeyword + len; at++ ) - { - char ch = line.array[at]; - if ( ch != '_' && !Character.isUpperCase(ch) ) - { - klassname = false; - break; - } - } - if ( klassname ) - id = Token.KEYWORD3; - } - - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/HTMLTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/HTMLTokenMarker.java deleted file mode 100644 index 792dfb032..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/HTMLTokenMarker.java +++ /dev/null @@ -1,251 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * HTML token marker. - * - * @author Slava Pestov - * @version $Id: HTMLTokenMarker.java,v 1.34 1999/12/13 03:40:29 sp Exp $ - */ -public class HTMLTokenMarker extends TokenMarker -{ - public static final byte JAVASCRIPT = Token.INTERNAL_FIRST; - - public HTMLTokenMarker() - { - this(true); - } - - public HTMLTokenMarker(boolean js) - { - this.js = js; - keywords = JavaScriptTokenMarker.getKeywords(); - } - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - lastOffset = offset; - lastKeyword = offset; - int length = line.count + offset; - boolean backslash = false; - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: // HTML text - backslash = false; - switch(c) - { - case '<': - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - if(SyntaxUtilities.regionMatches(false, - line,i1,"!--")) - { - i += 3; - token = Token.COMMENT1; - } - else if(js && SyntaxUtilities.regionMatches( - true,line,i1,"script>")) - { - addToken(8,Token.KEYWORD1); - lastOffset = lastKeyword = (i += 8); - token = JAVASCRIPT; - } - else - { - token = Token.KEYWORD1; - } - break; - case '&': - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - token = Token.KEYWORD2; - break; - } - break; - case Token.KEYWORD1: // Inside a tag - backslash = false; - if(c == '>') - { - addToken(i1 - lastOffset,token); - lastOffset = lastKeyword = i1; - token = Token.NULL; - } - break; - case Token.KEYWORD2: // Inside an entity - backslash = false; - if(c == ';') - { - addToken(i1 - lastOffset,token); - lastOffset = lastKeyword = i1; - token = Token.NULL; - break; - } - break; - case Token.COMMENT1: // Inside a comment - backslash = false; - if(SyntaxUtilities.regionMatches(false,line,i,"-->")) - { - addToken((i + 3) - lastOffset,token); - lastOffset = lastKeyword = i + 3; - token = Token.NULL; - } - break; - case JAVASCRIPT: // Inside a JavaScript - switch(c) - { - case '<': - backslash = false; - doKeyword(line,i,c); - if(SyntaxUtilities.regionMatches(true, - line,i1,"/script>")) - { - addToken(i - lastOffset, - Token.NULL); - addToken(9,Token.KEYWORD1); - lastOffset = lastKeyword = (i += 9); - token = Token.NULL; - } - break; - case '"': - if(backslash) - backslash = false; - else - { - doKeyword(line,i,c); - addToken(i - lastOffset,Token.NULL); - lastOffset = lastKeyword = i; - token = Token.LITERAL1; - } - break; - case '\'': - if(backslash) - backslash = false; - else - { - doKeyword(line,i,c); - addToken(i - lastOffset,Token.NULL); - lastOffset = lastKeyword = i; - token = Token.LITERAL2; - } - break; - case '/': - backslash = false; - doKeyword(line,i,c); - if(length - i > 1) - { - addToken(i - lastOffset,Token.NULL); - lastOffset = lastKeyword = i; - if(array[i1] == '/') - { - addToken(length - i,Token.COMMENT2); - lastOffset = lastKeyword = length; - break loop; - } - else if(array[i1] == '*') - { - token = Token.COMMENT2; - } - } - break; - default: backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - } - break; - case Token.LITERAL1: // JavaScript "..." - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,Token.LITERAL1); - lastOffset = lastKeyword = i1; - token = JAVASCRIPT; - } - break; - case Token.LITERAL2: // JavaScript '...' - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - lastOffset = lastKeyword = i1; - token = JAVASCRIPT; - } - break; - case Token.COMMENT2: // Inside a JavaScript comment - backslash = false; - if(c == '*' && length - i > 1 && array[i1] == '/') - { - addToken((i+=2) - lastOffset,Token.COMMENT2); - lastOffset = lastKeyword = i; - token = JAVASCRIPT; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - switch(token) - { - case Token.LITERAL1: - case Token.LITERAL2: - addToken(length - lastOffset,Token.INVALID); - token = JAVASCRIPT; - break; - case Token.KEYWORD2: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - case JAVASCRIPT: - doKeyword(line,length,'\0'); - addToken(length - lastOffset,Token.NULL); - break; - default: - addToken(length - lastOffset,token); - break; - } - - return token; - } - - // private members - private KeywordMap keywords; - private boolean js; - private int lastOffset; - private int lastKeyword; - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/IDLTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/IDLTokenMarker.java deleted file mode 100644 index 34476c002..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/IDLTokenMarker.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; - -/** - * IDL token marker. - * - * @author Slava Pestov - * @author Juha Lindfors - * @version $Id: IDLTokenMarker.java,v 1.2 1999/12/18 06:10:56 sp Exp $ - */ -public class IDLTokenMarker extends CTokenMarker -{ - public IDLTokenMarker() - { - super(true,getKeywords()); - } - - public static KeywordMap getKeywords() - { - if(idlKeywords == null) - { - idlKeywords = new KeywordMap(false); - - idlKeywords.add("any", Token.KEYWORD3); - idlKeywords.add("attribute",Token.KEYWORD1); - idlKeywords.add("boolean", Token.KEYWORD3); - idlKeywords.add("case", Token.KEYWORD1); - idlKeywords.add("char", Token.KEYWORD3); - idlKeywords.add("const", Token.KEYWORD1); - idlKeywords.add("context", Token.KEYWORD1); - idlKeywords.add("default", Token.KEYWORD1); - idlKeywords.add("double", Token.KEYWORD3); - idlKeywords.add("enum", Token.KEYWORD3); - idlKeywords.add("exception",Token.KEYWORD1); - idlKeywords.add("FALSE", Token.LITERAL2); - idlKeywords.add("fixed", Token.KEYWORD1); - idlKeywords.add("float", Token.KEYWORD3); - idlKeywords.add("in", Token.KEYWORD1); - idlKeywords.add("inout", Token.KEYWORD1); - idlKeywords.add("interface",Token.KEYWORD1); - idlKeywords.add("long", Token.KEYWORD3); - idlKeywords.add("module", Token.KEYWORD1); - idlKeywords.add("Object", Token.KEYWORD3); - idlKeywords.add("octet", Token.KEYWORD3); - idlKeywords.add("oneway", Token.KEYWORD1); - idlKeywords.add("out", Token.KEYWORD1); - idlKeywords.add("raises", Token.KEYWORD1); - idlKeywords.add("readonly", Token.KEYWORD1); - idlKeywords.add("sequence", Token.KEYWORD3); - idlKeywords.add("short", Token.KEYWORD3); - idlKeywords.add("string", Token.KEYWORD3); - idlKeywords.add("struct", Token.KEYWORD3); - idlKeywords.add("switch", Token.KEYWORD1); - idlKeywords.add("TRUE", Token.LITERAL2); - idlKeywords.add("typedef", Token.KEYWORD3); - idlKeywords.add("unsigned", Token.KEYWORD3); - idlKeywords.add("union", Token.KEYWORD3); - idlKeywords.add("void", Token.KEYWORD3); - idlKeywords.add("wchar", Token.KEYWORD3); - idlKeywords.add("wstring", Token.KEYWORD3); - } - return idlKeywords; - } - - // private members - private static KeywordMap idlKeywords; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/InputHandler.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/InputHandler.java deleted file mode 100644 index c6d3d4d6c..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/InputHandler.java +++ /dev/null @@ -1,1192 +0,0 @@ -/* - * InputHandler.java - Manages key bindings and executes actions - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.util.Enumeration; -import java.util.EventObject; -import java.util.Hashtable; - -import javax.swing.JPopupMenu; -import javax.swing.KeyStroke; -import javax.swing.text.BadLocationException; - -/** - * An input handler converts the user's key strokes into concrete actions. - * It also takes care of macro recording and action repetition.

      - * - * This class provides all the necessary support code for an input - * handler, but doesn't actually do any key binding logic. It is up - * to the implementations of this class to do so. - * - * @author Slava Pestov - * @version $Id: InputHandler.java,v 1.14 1999/12/13 03:40:30 sp Exp $ - * @see DefaultInputHandler - */ -@SuppressWarnings("unchecked") -public abstract class InputHandler extends KeyAdapter -{ - /** - * If this client property is set to Boolean.TRUE on the text area, - * the home/end keys will support 'smart' BRIEF-like behaviour - * (one press = start/end of line, two presses = start/end of - * viewscreen, three presses = start/end of document). By default, - * this property is not set. - */ - public static final String SMART_HOME_END_PROPERTY = "InputHandler.homeEnd"; - public static final ActionListener COPY=new TAction() { protected void doIt(JEditTextArea ta) { - ta.copy(); - }}, - CUT=new TAction() { protected void doIt(JEditTextArea ta) { - ta.cut(); - }}, - PASTE=new TAction() { protected void doIt(JEditTextArea ta) { - ta.paste(); - }}/*, - UNDO=new TAction() { protected void doIt(JEditTextArea ta) { - try { - ta.undo(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }}*/, - SELECT_ALL=new TAction() { protected void doIt(JEditTextArea ta) { - ta.selectAll(); - }}; - - public static final ActionListener INSERT_TAB=new TAction() { protected void doIt(JEditTextArea textArea) { - if(!textArea.isEditable()) { - textArea.getToolkit().beep(); - return; - } - int[] start=new int[]{textArea.getSelectionStart()}, end=new int[]{textArea.getSelectionEnd()}; - if (start[0]!=end[0]) { - textArea.setText(increaseIndentation(textArea.getText(),start,end)); - textArea.setSelectionStart(start[0]); - textArea.setSelectionEnd(end[0]); - } else textArea.overwriteSetSelectedText("\t"); - }}; - public static final ActionListener REMOVE_TAB=new TAction() { protected void doIt(JEditTextArea textArea) { - if(!textArea.isEditable()) { - textArea.getToolkit().beep(); - return; - } - int[] start=new int[]{textArea.getSelectionStart()}, end=new int[]{textArea.getSelectionEnd()}; - textArea.setText(decreaseIndentation(textArea.getText(),start,end)); - textArea.setSelectionStart(start[0]); - textArea.setSelectionEnd(end[0]); - }}; - - public static final ActionListener BACKSPACE = new backspace(); - public static final ActionListener BACKSPACE_WORD = new backspace_word(); - public static final ActionListener DELETE = new delete(); - public static final ActionListener DELETE_WORD = new delete_word(); - public static final ActionListener END = new end(false); - public static final ActionListener DOCUMENT_END = new document_end(false); - public static final ActionListener SELECT_END = new end(true); - public static final ActionListener SELECT_DOC_END = new document_end(true); - public static final ActionListener INSERT_BREAK = new insert_break(); - //public static final ActionListener INSERT_TAB = new insert_tab(); - public static final ActionListener HOME = new home(false); - public static final ActionListener DOCUMENT_HOME = new document_home(false); - public static final ActionListener SELECT_HOME = new home(true); - public static final ActionListener SELECT_DOC_HOME = new document_home(true); - public static final ActionListener NEXT_CHAR = new next_char(false); - public static final ActionListener NEXT_LINE = new next_line(false); - public static final ActionListener NEXT_PAGE = new next_page(false); - public static final ActionListener NEXT_WORD = new next_word(false); - public static final ActionListener SELECT_NEXT_CHAR = new next_char(true); - public static final ActionListener SELECT_NEXT_LINE = new next_line(true); - public static final ActionListener SELECT_NEXT_PAGE = new next_page(true); - public static final ActionListener SELECT_NEXT_WORD = new next_word(true); - public static final ActionListener OVERWRITE = new overwrite(); - public static final ActionListener PREV_CHAR = new prev_char(false); - public static final ActionListener PREV_LINE = new prev_line(false); - public static final ActionListener PREV_PAGE = new prev_page(false); - public static final ActionListener PREV_WORD = new prev_word(false); - public static final ActionListener SELECT_PREV_CHAR = new prev_char(true); - public static final ActionListener SELECT_PREV_LINE = new prev_line(true); - public static final ActionListener SELECT_PREV_PAGE = new prev_page(true); - public static final ActionListener SELECT_PREV_WORD = new prev_word(true); - public static final ActionListener REPEAT = new repeat(); - public static final ActionListener TOGGLE_RECT = new toggle_rect(); - - // Default action - public static final ActionListener INSERT_CHAR = new insert_char(); - - private static Hashtable actions; - - static - { - actions = new Hashtable(); - actions.put("copy",COPY); - actions.put("cut",CUT); - actions.put("paste",PASTE); - actions.put("select-all",SELECT_ALL); - //actions.put("",); - - actions.put("backspace",BACKSPACE); - actions.put("backspace-word",BACKSPACE_WORD); - actions.put("delete",DELETE); - actions.put("delete-word",DELETE_WORD); - actions.put("end",END); - actions.put("select-end",SELECT_END); - actions.put("document-end",DOCUMENT_END); - actions.put("select-doc-end",SELECT_DOC_END); - actions.put("insert-break",INSERT_BREAK); - actions.put("insert-tab",INSERT_TAB); - actions.put("remove-tab",REMOVE_TAB); - actions.put("home",HOME); - actions.put("select-home",SELECT_HOME); - actions.put("document-home",DOCUMENT_HOME); - actions.put("select-doc-home",SELECT_DOC_HOME); - actions.put("next-char",NEXT_CHAR); - actions.put("next-line",NEXT_LINE); - actions.put("next-page",NEXT_PAGE); - actions.put("next-word",NEXT_WORD); - actions.put("select-next-char",SELECT_NEXT_CHAR); - actions.put("select-next-line",SELECT_NEXT_LINE); - actions.put("select-next-page",SELECT_NEXT_PAGE); - actions.put("select-next-word",SELECT_NEXT_WORD); - actions.put("overwrite",OVERWRITE); - actions.put("prev-char",PREV_CHAR); - actions.put("prev-line",PREV_LINE); - actions.put("prev-page",PREV_PAGE); - actions.put("prev-word",PREV_WORD); - actions.put("select-prev-char",SELECT_PREV_CHAR); - actions.put("select-prev-line",SELECT_PREV_LINE); - actions.put("select-prev-page",SELECT_PREV_PAGE); - actions.put("select-prev-word",SELECT_PREV_WORD); - actions.put("repeat",REPEAT); - actions.put("toggle-rect",TOGGLE_RECT); - actions.put("insert-char",INSERT_CHAR); - } - - /** - * Returns a named text area action. - * @param name The action name - */ - public static ActionListener getAction(String name) - { - return (ActionListener)actions.get(name); - } - - /** - * Returns the name of the specified text area action. - * @param listener The action listener - */ - public static String getActionName(ActionListener listener) - { - Enumeration enu = getActions(); - while(enu.hasMoreElements()) - { - String name = (String)enu.nextElement(); - ActionListener _listener = getAction(name); - if(_listener == listener) - return name; - } - return null; - } - - /** - * Returns an enumeration of all available actions. - */ - public static Enumeration getActions() - { - return actions.keys(); - } - - /** - * Adds the default key bindings to this input handler. - * This should not be called in the constructor of this - * input handler, because applications might load the - * key bindings from a file, etc. - */ - public abstract void addDefaultKeyBindings(); - - /** - * Adds a key binding to this input handler. - * @param keyBinding The key binding (the format of this is - * input-handler specific) - * @param action The action - */ - public abstract void addKeyBinding(String keyBinding, ActionListener action); - public abstract void addKeyBinding(KeyStroke keyStroke, ActionListener action); - /** - * Removes a key binding from this input handler. - * @param keyBinding The key binding - */ - public abstract void removeKeyBinding(String keyBinding); - - /** - * Removes all key bindings from this input handler. - */ - public abstract void removeAllKeyBindings(); - - /** - * Grabs the next key typed event and invokes the specified - * action with the key as a the action command. - * @param listener The action listener - */ - public void grabNextKeyStroke(ActionListener listener) - { - grabAction = listener; - } - - /** - * Returns if repeating is enabled. When repeating is enabled, - * actions will be executed multiple times. This is usually - * invoked with a special key stroke in the input handler. - */ - public boolean isRepeatEnabled() - { - return repeat; - } - - /** - * Enables repeating. When repeating is enabled, actions will be - * executed multiple times. Once repeating is enabled, the input - * handler should read a number from the keyboard. - */ - public void setRepeatEnabled(boolean repeat) - { - this.repeat = repeat; - } - - /** - * Returns the number of times the next action will be repeated. - */ - public int getRepeatCount() - { - return (repeat ? Math.max(1,repeatCount) : 1); - } - - /** - * Sets the number of times the next action will be repeated. - * @param repeatCount The repeat count - */ - public void setRepeatCount(int repeatCount) - { - this.repeatCount = repeatCount; - } - - /** - * Returns the macro recorder. If this is non-null, all executed - * actions should be forwarded to the recorder. - */ - public InputHandler.MacroRecorder getMacroRecorder() - { - return recorder; - } - - /** - * Sets the macro recorder. If this is non-null, all executed - * actions should be forwarded to the recorder. - * @param recorder The macro recorder - */ - public void setMacroRecorder(InputHandler.MacroRecorder recorder) - { - this.recorder = recorder; - } - - /** - * Returns a copy of this input handler that shares the same - * key bindings. Setting key bindings in the copy will also - * set them in the original. - */ - public abstract InputHandler copy(); - - /** - * Executes the specified action, repeating and recording it as - * necessary. - * @param listener The action listener - * @param source The event source - * @param actionCommand The action command - */ - public void executeAction(ActionListener listener, Object source, - String actionCommand) - { - // create event - ActionEvent evt = new ActionEvent(source, - ActionEvent.ACTION_PERFORMED, - actionCommand); - - // don't do anything if the action is a wrapper - // (like EditAction.Wrapper) - if(listener instanceof Wrapper) - { - listener.actionPerformed(evt); - return; - } - - // remember old values, in case action changes them - boolean _repeat = repeat; - int _repeatCount = getRepeatCount(); - - // execute the action - if(listener instanceof InputHandler.NonRepeatable) - listener.actionPerformed(evt); - else - { - for(int i = 0; i < Math.max(1,repeatCount); i++) - listener.actionPerformed(evt); - } - - // do recording. Notice that we do no recording whatsoever - // for actions that grab keys - if(grabAction == null) - { - if(recorder != null) - { - if(!(listener instanceof InputHandler.NonRecordable)) - { - if(_repeatCount != 1) - recorder.actionPerformed(REPEAT,String.valueOf(_repeatCount)); - - recorder.actionPerformed(listener,actionCommand); - } - } - - // If repeat was true originally, clear it - // Otherwise it might have been set by the action, etc - if(_repeat) - { - repeat = false; - repeatCount = 0; - } - } - } - - /** - * Returns the text area that fired the specified event. - * @param evt The event - */ - public static JEditTextArea getTextArea(EventObject evt) - { - if(evt != null) - { - Object o = evt.getSource(); - if(o instanceof Component) - { - // find the parent text area - Component c = (Component)o; - for(;;) - { - if(c instanceof JEditTextArea) - return (JEditTextArea)c; - else if(c == null) - break; - if(c instanceof JPopupMenu) - c = ((JPopupMenu)c) - .getInvoker(); - else - c = c.getParent(); - } - } - } - - // this shouldn't happen - System.err.println("BUG: getTextArea() returning null"); - System.err.println("Report this to Slava Pestov "); - return null; - } - - // protected members - - /** - * If a key is being grabbed, this method should be called with - * the appropriate key event. It executes the grab action with - * the typed character as the parameter. - */ - protected void handleGrabAction(KeyEvent evt) - { - // Clear it *before* it is executed so that executeAction() - // resets the repeat count - ActionListener _grabAction = grabAction; - grabAction = null; - executeAction(_grabAction,evt.getSource(), - String.valueOf(evt.getKeyChar())); - } - - // protected members - protected ActionListener grabAction; - protected boolean repeat; - protected int repeatCount; - protected InputHandler.MacroRecorder recorder; - - /** - * If an action implements this interface, it should not be repeated. - * Instead, it will handle the repetition itself. - */ - public interface NonRepeatable {} - - /** - * If an action implements this interface, it should not be recorded - * by the macro recorder. Instead, it will do its own recording. - */ - public interface NonRecordable {} - - /** - * For use by EditAction.Wrapper only. - * @since jEdit 2.2final - */ - public interface Wrapper {} - - /** - * Macro recorder. - */ - public interface MacroRecorder - { - void actionPerformed(ActionListener listener, - String actionCommand); - } - static abstract class TAction implements ActionListener { - public void actionPerformed(ActionEvent evt) { - JEditTextArea textArea = getTextArea(evt); - doIt(textArea); - } - protected abstract void doIt(JEditTextArea ta); - } - public static class backspace implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - - if(!textArea.isEditable()) - { - textArea.getToolkit().beep(); - return; - } - - if(textArea.getSelectionStart() - != textArea.getSelectionEnd()) - { - textArea.setSelectedText(""); - } - else - { - int caret = textArea.getCaretPosition(); - if(caret == 0) - { - textArea.getToolkit().beep(); - return; - } - try - { - textArea.getDocument().remove(caret - 1,1); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - } - } - } - - public static class backspace_word implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int start = textArea.getSelectionStart(); - if(start != textArea.getSelectionEnd()) - { - textArea.setSelectedText(""); - } - - int line = textArea.getCaretLine(); - int lineStart = textArea.getLineStartOffset(line); - int caret = start - lineStart; - - String lineText = textArea.getLineText(textArea - .getCaretLine()); - - if(caret == 0) - { - if(lineStart == 0) - { - textArea.getToolkit().beep(); - return; - } - caret--; - } - else - { - String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); - caret = TextUtilities.findWordStart(lineText,caret,noWordSep); - } - - try - { - textArea.getDocument().remove( - caret + lineStart, - start - (caret + lineStart)); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - } - } - - public static class delete implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - - if(!textArea.isEditable()) - { - textArea.getToolkit().beep(); - return; - } - - if(textArea.getSelectionStart() - != textArea.getSelectionEnd()) - { - textArea.setSelectedText(""); - } - else - { - int caret = textArea.getCaretPosition(); - if(caret == textArea.getDocumentLength()) - { - textArea.getToolkit().beep(); - return; - } - try - { - textArea.getDocument().remove(caret,1); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - } - } - } - - public static class delete_word implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int start = textArea.getSelectionStart(); - if(start != textArea.getSelectionEnd()) - { - textArea.setSelectedText(""); - } - - int line = textArea.getCaretLine(); - int lineStart = textArea.getLineStartOffset(line); - int caret = start - lineStart; - - String lineText = textArea.getLineText(textArea - .getCaretLine()); - - if(caret == lineText.length()) - { - if(lineStart + caret == textArea.getDocumentLength()) - { - textArea.getToolkit().beep(); - return; - } - caret++; - } - else - { - String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); - caret = TextUtilities.findWordEnd(lineText,caret,noWordSep); - } - - try - { - textArea.getDocument().remove(start, - (caret + lineStart) - start); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - } - } - - public static class end implements ActionListener - { - private boolean select; - - public end(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - - int caret = textArea.getCaretPosition(); - - int lastOfLine = textArea.getLineEndOffset( - textArea.getCaretLine()) - 1; - int lastVisibleLine = textArea.getFirstLine() - + textArea.getVisibleLines(); - if(lastVisibleLine >= textArea.getLineCount()) - { - lastVisibleLine = Math.min(textArea.getLineCount() - 1, - lastVisibleLine); - } - else - lastVisibleLine -= (textArea.getElectricScroll() + 1); - - int lastVisible = textArea.getLineEndOffset(lastVisibleLine) - 1; - int lastDocument = textArea.getDocumentLength(); - - if(caret == lastDocument) - { - textArea.getToolkit().beep(); - return; - } - else if(!Boolean.TRUE.equals(textArea.getClientProperty( - SMART_HOME_END_PROPERTY))) - caret = lastOfLine; - else if(caret == lastVisible) - caret = lastDocument; - else if(caret == lastOfLine) - caret = lastVisible; - else - caret = lastOfLine; - - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - } - } - - public static class document_end implements ActionListener - { - private boolean select; - - public document_end(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - if(select) - textArea.select(textArea.getMarkPosition(), - textArea.getDocumentLength()); - else - textArea.setCaretPosition(textArea - .getDocumentLength()); - } - } - - public static class home implements ActionListener - { - private boolean select; - - public home(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - - int caret = textArea.getCaretPosition(); - - int firstLine = textArea.getFirstLine(); - - int firstOfLine = textArea.getLineStartOffset( - textArea.getCaretLine()); - int firstVisibleLine = (firstLine == 0 ? 0 : - firstLine + textArea.getElectricScroll()); - int firstVisible = textArea.getLineStartOffset( - firstVisibleLine); - - if(caret == 0) - { - textArea.getToolkit().beep(); - return; - } - else if(!Boolean.TRUE.equals(textArea.getClientProperty( - SMART_HOME_END_PROPERTY))) - caret = firstOfLine; - else if(caret == firstVisible) - caret = 0; - else if(caret == firstOfLine) - caret = firstVisible; - else - caret = firstOfLine; - - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - } - } - - public static class document_home implements ActionListener - { - private boolean select; - - public document_home(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - if(select) - textArea.select(textArea.getMarkPosition(),0); - else - textArea.setCaretPosition(0); - } - } - - public static class insert_break implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - - if(!textArea.isEditable()) - { - textArea.getToolkit().beep(); - return; - } - - textArea.setSelectedText("\n"); - } - } - - public static String increaseIndentation(String text, int selectionStart[], int selectionEnd[]) { - int start=selectionStart[0]; - int end=selectionEnd[0]; - start=text.lastIndexOf("\n",text.charAt(start)=='\n'&&!(start==0||text.charAt(start-1)=='\n') ? start-1 : start); - //start=text.lastIndexOf("\n",start); - if (start<0) start=0; else start=start+1; - end=text.indexOf("\n",end); - boolean endsWithLine=end>=0; - if (end<0) end=text.length(); else end++; - String middle=text.substring(start,end); - StringBuffer buf=new StringBuffer(text.substring(0,start)); - try { - BufferedReader in=new BufferedReader(new StringReader(middle)); - String line; - int lines=0; - boolean firstLine=true; - while ((line=in.readLine())!=null) { - lines++; - if (!firstLine) buf.append('\n'); - buf.append('\t'); - buf.append(line); - firstLine=false; - } - if (endsWithLine) buf.append('\n'); - buf.append(text.substring(end)); - selectionStart[0]++; - selectionEnd[0]+=lines; - return buf.toString(); - } catch (IOException ex) { - ex.printStackTrace(); - return null; - } - } - public static String decreaseIndentation(String text, int selectionStart[], int selectionEnd[]) { - int start=selectionStart[0]; - int end=selectionEnd[0]; - - start=text.lastIndexOf("\n",text.charAt(start)=='\n'&&!(start==0||text.charAt(start-1)=='\n') ? start-1 : start); - if (start<0) start=0; else start=start+1; - end=text.indexOf("\n",end); - boolean endsWithLine=end>=0; - if (end<0) end=text.length(); else end++; - String middle=text.substring(start,end); - StringBuffer buf=new StringBuffer(text.substring(0,start)); - try { - BufferedReader in=new BufferedReader(new StringReader(middle)); - String line; - int lines=0; - boolean firstLine=true; - boolean firstLineDecreased=false; - while ((line=in.readLine())!=null) { - if (!firstLine) buf.append('\n'); - if (!line.equals("")) { - char c=line.charAt(0); - if (c==' '||c=='\t') { - if (firstLine) firstLineDecreased=true; - line=line.substring(1); - lines++; - } - buf.append(line); - } - firstLine=false; - } - if (endsWithLine) buf.append('\n'); - buf.append(text.substring(end)); - if (firstLineDecreased) selectionStart[0]--; - selectionEnd[0]-=lines; - return buf.toString(); - } catch (IOException ex) { - ex.printStackTrace(); - return null; - } - } - public static class next_char implements ActionListener - { - private boolean select; - - public next_char(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - if(caret == textArea.getDocumentLength()) - { - textArea.getToolkit().beep(); - return; - } - - if(select) - textArea.select(textArea.getMarkPosition(), - caret + 1); - else - textArea.setCaretPosition(caret + 1); - } - } - - public static class next_line implements ActionListener - { - private boolean select; - - public next_line(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - int line = textArea.getCaretLine(); - - if(line == textArea.getLineCount() - 1) - { - textArea.getToolkit().beep(); - return; - } - - int magic = textArea.getMagicCaretPosition(); - if(magic == -1) - { - magic = textArea.offsetToX(line, - caret - textArea.getLineStartOffset(line)); - } - - caret = textArea.getLineStartOffset(line + 1) - + textArea.xToOffset(line + 1,magic); - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - textArea.setMagicCaretPosition(magic); - } - } - - public static class next_page implements ActionListener - { - private boolean select; - - public next_page(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int lineCount = textArea.getLineCount(); - int firstLine = textArea.getFirstLine(); - int visibleLines = textArea.getVisibleLines(); - int line = textArea.getCaretLine(); - - firstLine += visibleLines; - - if(firstLine + visibleLines >= lineCount - 1) - firstLine = lineCount - visibleLines; - - textArea.setFirstLine(firstLine); - - int caret = textArea.getLineStartOffset( - Math.min(textArea.getLineCount() - 1, - line + visibleLines)); - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - } - } - - public static class next_word implements ActionListener - { - private boolean select; - - public next_word(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - int line = textArea.getCaretLine(); - int lineStart = textArea.getLineStartOffset(line); - caret -= lineStart; - - String lineText = textArea.getLineText(textArea - .getCaretLine()); - - if(caret == lineText.length()) - { - if(lineStart + caret == textArea.getDocumentLength()) - { - textArea.getToolkit().beep(); - return; - } - caret++; - } - else - { - String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); - caret = TextUtilities.findWordEnd(lineText,caret,noWordSep); - } - - if(select) - textArea.select(textArea.getMarkPosition(), - lineStart + caret); - else - textArea.setCaretPosition(lineStart + caret); - } - } - - public static class overwrite implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - textArea.setOverwriteEnabled( - !textArea.isOverwriteEnabled()); - } - } - - public static class prev_char implements ActionListener - { - private boolean select; - - public prev_char(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - if(caret == 0) - { - textArea.getToolkit().beep(); - return; - } - - if(select) - textArea.select(textArea.getMarkPosition(), - caret - 1); - else - textArea.setCaretPosition(caret - 1); - } - } - - public static class prev_line implements ActionListener - { - private boolean select; - - public prev_line(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - int line = textArea.getCaretLine(); - - if(line == 0) - { - textArea.getToolkit().beep(); - return; - } - - int magic = textArea.getMagicCaretPosition(); - if(magic == -1) - { - magic = textArea.offsetToX(line, - caret - textArea.getLineStartOffset(line)); - } - - caret = textArea.getLineStartOffset(line - 1) - + textArea.xToOffset(line - 1,magic); - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - textArea.setMagicCaretPosition(magic); - } - } - - public static class prev_page implements ActionListener - { - private boolean select; - - public prev_page(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int firstLine = textArea.getFirstLine(); - int visibleLines = textArea.getVisibleLines(); - int line = textArea.getCaretLine(); - - if(firstLine < visibleLines) - firstLine = visibleLines; - - textArea.setFirstLine(firstLine - visibleLines); - - int caret = textArea.getLineStartOffset( - Math.max(0,line - visibleLines)); - if(select) - textArea.select(textArea.getMarkPosition(),caret); - else - textArea.setCaretPosition(caret); - } - } - - public static class prev_word implements ActionListener - { - private boolean select; - - public prev_word(boolean select) - { - this.select = select; - } - - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - int caret = textArea.getCaretPosition(); - int line = textArea.getCaretLine(); - int lineStart = textArea.getLineStartOffset(line); - caret -= lineStart; - - String lineText = textArea.getLineText(textArea - .getCaretLine()); - - if(caret == 0) - { - if(lineStart == 0) - { - textArea.getToolkit().beep(); - return; - } - caret--; - } - else - { - String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); - caret = TextUtilities.findWordStart(lineText,caret,noWordSep); - } - - if(select) - textArea.select(textArea.getMarkPosition(), - lineStart + caret); - else - textArea.setCaretPosition(lineStart + caret); - } - } - - public static class repeat implements ActionListener, - InputHandler.NonRecordable - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - textArea.getInputHandler().setRepeatEnabled(true); - String actionCommand = evt.getActionCommand(); - if(actionCommand != null) - { - textArea.getInputHandler().setRepeatCount( - Integer.parseInt(actionCommand)); - } - } - } - - public static class toggle_rect implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - textArea.setSelectionRectangular( - !textArea.isSelectionRectangular()); - } - } - - public static class insert_char implements ActionListener, - InputHandler.NonRepeatable - { - public void actionPerformed(ActionEvent evt) - { - JEditTextArea textArea = getTextArea(evt); - String str = evt.getActionCommand(); - int repeatCount = textArea.getInputHandler().getRepeatCount(); - - if(textArea.isEditable()) - { - StringBuffer buf = new StringBuffer(); - for(int i = 0; i < repeatCount; i++) - buf.append(str); - textArea.overwriteSetSelectedText(buf.toString()); - } - else - { - textArea.getToolkit().beep(); - } - } - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JEditTextArea.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JEditTextArea.java deleted file mode 100644 index d106ce843..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JEditTextArea.java +++ /dev/null @@ -1,2198 +0,0 @@ -/* - * JEditTextArea.java - jEdit's text component - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import java.awt.AWTEvent; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.StringSelection; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.AdjustmentEvent; -import java.awt.event.AdjustmentListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.util.Enumeration; -import java.util.Vector; - -import javax.swing.Action; -import javax.swing.ActionMap; -import javax.swing.InputMap; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.JScrollBar; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.EventListenerList; -import javax.swing.text.BadLocationException; -import javax.swing.text.Element; -import javax.swing.text.Segment; -import javax.swing.text.Utilities; -import javax.swing.undo.AbstractUndoableEdit; -import javax.swing.undo.CannotRedoException; -import javax.swing.undo.CannotUndoException; -import javax.swing.undo.UndoableEdit; - -/** - * jEdit's text area component. It is more suited for editing program - * source code than JEditorPane, because it drops the unnecessary features - * (images, variable-width lines, and so on) and adds a whole bunch of - * useful goodies such as: - *

        - *
      • More flexible key binding scheme - *
      • Supports macro recorders - *
      • Rectangular selection - *
      • Bracket highlighting - *
      • Syntax highlighting - *
      • Command repetition - *
      • Block caret can be enabled - *
      - * It is also faster and doesn't have as many problems. It can be used - * in other applications; the only other part of jEdit it depends on is - * the syntax package.

      - * - * To use it in your app, treat it like any other component, for example: - *

      JEditTextArea ta = new JEditTextArea();
      - * ta.setTokenMarker(new JavaTokenMarker());
      - * ta.setText("public class Test {\n"
      - *     + "    public static void main(String[] args) {\n"
      - *     + "        System.out.println(\"Hello World\");\n"
      - *     + "    }\n"
      - *     + "}");
      - * - * @author Slava Pestov - * @version $Id: JEditTextArea.java,v 1.36 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings("serial") -public class JEditTextArea extends JComponent -{ - /** - * Adding components with this name to the text area will place - * them left of the horizontal scroll bar. In jEdit, the status - * bar is added this way. - */ - public static String LEFT_OF_SCROLLBAR = "los"; - - /** - * Creates a new JEditTextArea with the default settings. - */ - public JEditTextArea() - { - this(TextAreaDefaults.getDefaults()); - } - - /** - * Creates a new JEditTextArea with the specified settings. - * @param defaults The default settings - */ - public JEditTextArea(TextAreaDefaults defaults) - { - propertyChangeSupport=new PropertyChangeSupport(this); - // Enable the necessary events - enableEvents(AWTEvent.KEY_EVENT_MASK); - - // Initialize some misc. stuff - painter = new TextAreaPainter(this,defaults); - documentHandler = new DocumentHandler(); - listenerList = new EventListenerList(); - caretEvent = new MutableCaretEvent(); - lineSegment = new Segment(); - bracketLine = bracketPosition = -1; - blink = true; - - // Initialize the GUI - setLayout(new ScrollLayout()); - add(CENTER,painter); - add(RIGHT,vertical = new JScrollBar(JScrollBar.VERTICAL)); - add(BOTTOM,horizontal = new JScrollBar(JScrollBar.HORIZONTAL)); - - // Add some event listeners - vertical.addAdjustmentListener(new AdjustHandler()); - horizontal.addAdjustmentListener(new AdjustHandler()); - painter.addComponentListener(new ComponentHandler()); - painter.addMouseListener(new MouseHandler()); - painter.addMouseMotionListener(new DragHandler()); - addFocusListener(new FocusHandler()); - - // Load the defaults - setInputHandler(defaults.inputHandler); - setDocument(defaults.document); - editable = defaults.editable; - caretVisible = defaults.caretVisible; - caretBlinks = defaults.caretBlinks; - electricScroll = defaults.electricScroll; - - popup = defaults.popup; - - // We don't seem to get the initial focus event? - focusedComponent = this; - } - - /** - * Returns if this component can be traversed by pressing - * the Tab key. This returns false. - */ - public final boolean isFocusable() - { - return true; - } - - /** - * Returns the object responsible for painting this text area. - */ - public final TextAreaPainter getPainter() - { - return painter; - } - - /** - * Returns the input handler. - */ - public final InputHandler getInputHandler() - { - return inputHandler; - } - - /** - * Sets the input handler. - * @param inputHandler The new input handler - */ - public void setInputHandler(InputHandler inputHandler) - { - this.inputHandler = inputHandler; - } - - /** - * Returns true if the caret is blinking, false otherwise. - */ - public final boolean isCaretBlinkEnabled() - { - return caretBlinks; - } - - /** - * Toggles caret blinking. - * @param caretBlinks True if the caret should blink, false otherwise - */ - public void setCaretBlinkEnabled(boolean caretBlinks) - { - this.caretBlinks = caretBlinks; - if(!caretBlinks) - blink = false; - - painter.invalidateSelectedLines(); - } - - /** - * Returns true if the caret is visible, false otherwise. - */ - public final boolean isCaretVisible() - { - return (!caretBlinks || blink) && caretVisible; - } - - /** - * Sets if the caret should be visible. - * @param caretVisible True if the caret should be visible, false - * otherwise - */ - public void setCaretVisible(boolean caretVisible) - { - this.caretVisible = caretVisible; - blink = true; - - painter.invalidateSelectedLines(); - } - - /** - * Blinks the caret. - */ - public final void blinkCaret() - { - if(caretBlinks) - { - blink = !blink; - painter.invalidateSelectedLines(); - } - else - blink = true; - } - - /** - * Returns the number of lines from the top and button of the - * text area that are always visible. - */ - public final int getElectricScroll() - { - return electricScroll; - } - - /** - * Sets the number of lines from the top and bottom of the text - * area that are always visible - * @param electricScroll The number of lines always visible from - * the top or bottom - */ - public final void setElectricScroll(int electricScroll) - { - this.electricScroll = electricScroll; - } - - /** - * Updates the state of the scroll bars. This should be called - * if the number of lines in the document changes, or when the - * size of the text are changes. - */ - public void updateScrollBars() - { - if(vertical != null && visibleLines != 0) - { - vertical.setValues(firstLine,visibleLines,0,getLineCount()); - vertical.setUnitIncrement(2); - vertical.setBlockIncrement(visibleLines); - } - - int width = painter.getWidth(); - if(horizontal != null && width != 0) - { - horizontal.setValues(-horizontalOffset,width,0,width * 5); - horizontal.setUnitIncrement(painter.getFontMetrics() - .charWidth('w')); - horizontal.setBlockIncrement(width / 2); - } - } - - /** - * Returns the line displayed at the text area's origin. - */ - public final int getFirstLine() - { - return firstLine; - } - - /** - * Sets the line displayed at the text area's origin without - * updating the scroll bars. - */ - public void setFirstLine(int firstLine) - { - if(firstLine == this.firstLine) - return; - this.firstLine = firstLine; - if(firstLine != vertical.getValue()) - updateScrollBars(); - painter.repaint(); - } - - /** - * Returns the number of lines visible in this text area. - */ - public final int getVisibleLines() - { - return visibleLines; - } - - /** - * Recalculates the number of visible lines. This should not - * be called directly. - */ - public final void recalculateVisibleLines() - { - if(painter == null) - return; - int height = painter.getHeight(); - int lineHeight = painter.getFontMetrics().getHeight(); - visibleLines = height / lineHeight; - updateScrollBars(); - } - - /** - * Returns the horizontal offset of drawn lines. - */ - public final int getHorizontalOffset() - { - return horizontalOffset; - } - - /** - * Sets the horizontal offset of drawn lines. This can be used to - * implement horizontal scrolling. - * @param horizontalOffset offset The new horizontal offset - */ - public void setHorizontalOffset(int horizontalOffset) - { - if(horizontalOffset == this.horizontalOffset) - return; - this.horizontalOffset = horizontalOffset; - if(horizontalOffset != horizontal.getValue()) - updateScrollBars(); - painter.repaint(); - } - - /** - * A fast way of changing both the first line and horizontal - * offset. - * @param firstLine The new first line - * @param horizontalOffset The new horizontal offset - * @return True if any of the values were changed, false otherwise - */ - public boolean setOrigin(int firstLine, int horizontalOffset) - { - boolean changed = false; - if(horizontalOffset != this.horizontalOffset) - { - this.horizontalOffset = horizontalOffset; - changed = true; - } - - if(firstLine != this.firstLine) - { - this.firstLine = firstLine; - changed = true; - } - - if(changed) - { - updateScrollBars(); - painter.repaint(); - } - - return changed; - } - - /** - * Ensures that the caret is visible by scrolling the text area if - * necessary. - * @return True if scrolling was actually performed, false if the - * caret was already visible - */ - public boolean scrollToCaret() - { - int line = getCaretLine(); - int lineStart = getLineStartOffset(line); - int offset = Math.max(0,Math.min(getLineLength(line) - 1, - getCaretPosition() - lineStart)); - - return scrollTo(line,offset); - } - - /** - * Ensures that the specified line and offset is visible by scrolling - * the text area if necessary. - * @param line The line to scroll to - * @param offset The offset in the line to scroll to - * @return True if scrolling was actually performed, false if the - * line and offset was already visible - */ - public boolean scrollTo(int line, int offset) - { - // visibleLines == 0 before the component is realized - // we can't do any proper scrolling then, so we have - // this hack... - if(visibleLines == 0) - { - setFirstLine(Math.max(0,line - electricScroll)); - return true; - } - - int newFirstLine = firstLine; - int newHorizontalOffset = horizontalOffset; - - if(line < firstLine + electricScroll) - { - newFirstLine = Math.max(0,line - electricScroll); - } - else if(line + electricScroll >= firstLine + visibleLines) - { - newFirstLine = (line - visibleLines) + electricScroll + 1; - if(newFirstLine + visibleLines >= getLineCount()) - newFirstLine = getLineCount() - visibleLines; - if(newFirstLine < 0) - newFirstLine = 0; - } - - int x = _offsetToX(line,offset); - int width = painter.getFontMetrics().charWidth('w'); - - if(x < 0) - { - newHorizontalOffset = Math.min(0,horizontalOffset - - x + width + 5); - } - else if(x + width >= painter.getWidth()) - { - newHorizontalOffset = horizontalOffset + - (painter.getWidth() - x) - width - 5; - } - - return setOrigin(newFirstLine,newHorizontalOffset); - } - - /** - * Converts a line index to a y co-ordinate. - * @param line The line - */ - public int lineToY(int line) - { - FontMetrics fm = painter.getFontMetrics(); - return (line - firstLine) * fm.getHeight() - - (fm.getLeading() + fm.getMaxDescent()); - } - public int lineToBottomY(int line) - { - FontMetrics fm = painter.getFontMetrics(); - return (line - firstLine) * fm.getHeight() - + (fm.getLeading()+ fm.getAscent()+ fm.getMaxDescent()); - } - - /** - * Converts a y co-ordinate to a line index. - * @param y The y co-ordinate - */ - public int yToLine(int y) - { - FontMetrics fm = painter.getFontMetrics(); - int height = fm.getHeight(); - return Math.max(0,Math.min(getLineCount() - 1, - y / height + firstLine)); - } - - /** - * Converts an offset in a line into an x co-ordinate. This is a - * slow version that can be used any time. - * @param line The line - * @param offset The offset, from the start of the line - */ - public final int offsetToX(int line, int offset) - { - // don't use cached tokens - painter.currentLineTokens = null; - return _offsetToX(line,offset); - } - - /** - * Converts an offset in a line into an x co-ordinate. This is a - * fast version that should only be used if no changes were made - * to the text since the last repaint. - * @param line The line - * @param offset The offset, from the start of the line - */ - public int _offsetToX(int line, int offset) - { - TokenMarker tokenMarker = getTokenMarker(); - - /* Use painter's cached info for speed */ - FontMetrics fm = painter.getFontMetrics(); - - getLineText(line,lineSegment); - - int segmentOffset = lineSegment.offset; - int x = horizontalOffset; - - /* If syntax coloring is disabled, do simple translation */ - if(tokenMarker == null) - { - lineSegment.count = offset; - return x + Utilities.getTabbedTextWidth(lineSegment, - fm,x,painter,0); - } - /* If syntax coloring is enabled, we have to do this because - * tokens can vary in width */ - else - { - Token tokens; - if(painter.currentLineIndex == line - && painter.currentLineTokens != null) - tokens = painter.currentLineTokens; - else - { - painter.currentLineIndex = line; - tokens = painter.currentLineTokens - = tokenMarker.markTokens(lineSegment,line); - } - -// Toolkit toolkit = - painter.getToolkit(); - Font defaultFont = painter.getFont(); - SyntaxStyle[] styles = painter.getStyles(); - - for(;;) - { - byte id = tokens.id; - if(id == Token.END) - { - return x; - } - - if(id == Token.NULL) - fm = painter.getFontMetrics(); - else - fm = styles[id].getFontMetrics(defaultFont); - - int length = tokens.length; - - if(offset + segmentOffset < lineSegment.offset + length) - { - lineSegment.count = offset - (lineSegment.offset - segmentOffset); - return x + Utilities.getTabbedTextWidth( - lineSegment,fm,x,painter,0); - } - else - { - lineSegment.count = length; - x += Utilities.getTabbedTextWidth( - lineSegment,fm,x,painter,0); - lineSegment.offset += length; - } - tokens = tokens.next; - } - } - } - - /** - * Converts an x co-ordinate to an offset within a line. - * @param line The line - * @param x The x co-ordinate - */ - public int xToOffset(int line, int x) - { - TokenMarker tokenMarker = getTokenMarker(); - - /* Use painter's cached info for speed */ - FontMetrics fm = painter.getFontMetrics(); - - getLineText(line,lineSegment); - - char[] segmentArray = lineSegment.array; - int segmentOffset = lineSegment.offset; - int segmentCount = lineSegment.count; - - int width = horizontalOffset; - - if(tokenMarker == null) - { - for(int i = 0; i < segmentCount; i++) - { - char c = segmentArray[i + segmentOffset]; - int charWidth; - if(c == '\t') - charWidth = (int)painter.nextTabStop(width,i) - - width; - else - charWidth = fm.charWidth(c); - - if(painter.isBlockCaretEnabled()) - { - if(x - charWidth <= width) - return i; - } - else - { - if(x - charWidth / 2 <= width) - return i; - } - - width += charWidth; - } - - return segmentCount; - } - else - { - Token tokens; - if(painter.currentLineIndex == line && painter - .currentLineTokens != null) - tokens = painter.currentLineTokens; - else - { - painter.currentLineIndex = line; - tokens = painter.currentLineTokens - = tokenMarker.markTokens(lineSegment,line); - } - - int offset = 0; -// Toolkit toolkit = - painter.getToolkit(); - Font defaultFont = painter.getFont(); - SyntaxStyle[] styles = painter.getStyles(); - - for(;;) - { - byte id = tokens.id; - if(id == Token.END) - return offset; - - if(id == Token.NULL) - fm = painter.getFontMetrics(); - else - fm = styles[id].getFontMetrics(defaultFont); - - int length = tokens.length; - - for(int i = 0; i < length; i++) - { - char c = segmentArray[segmentOffset + offset + i]; - int charWidth; - if(c == '\t') - charWidth = (int)painter.nextTabStop(width,offset + i) - - width; - else - charWidth = fm.charWidth(c); - - if(painter.isBlockCaretEnabled()) - { - if(x - charWidth <= width) - return offset + i; - } - else - { - if(x - charWidth / 2 <= width) - return offset + i; - } - - width += charWidth; - } - - offset += length; - tokens = tokens.next; - } - } - } - - /** - * Converts a point to an offset, from the start of the text. - * @param x The x co-ordinate of the point - * @param y The y co-ordinate of the point - */ - public int xyToOffset(int x, int y) - { - int line = yToLine(y); - int start = getLineStartOffset(line); - return start + xToOffset(line,x); - } - - /** - * Returns the document this text area is editing. - */ - public final SyntaxDocument getDocument() - { - return document; - } - - /** - * Sets the document this text area is editing. - * @param document The document - */ - public void setDocument(SyntaxDocument document) - { - if(this.document == document) - return; - if(this.document != null) - this.document.removeDocumentListener(documentHandler); - this.document = document; - - document.addDocumentListener(documentHandler); - - select(0,0); - updateScrollBars(); - painter.repaint(); - } - - /** - * Returns the document's token marker. Equivalent to calling - * getDocument().getTokenMarker(). - */ - public final TokenMarker getTokenMarker() - { - return document.getTokenMarker(); - } - - /** - * Sets the document's token marker. Equivalent to caling - * getDocument().setTokenMarker(). - * @param tokenMarker The token marker - */ - public final void setTokenMarker(TokenMarker tokenMarker) - { - document.setTokenMarker(tokenMarker); - } - - /** - * Returns the length of the document. Equivalent to calling - * getDocument().getLength(). - */ - public final int getDocumentLength() - { - return document.getLength(); - } - - /** - * Returns the number of lines in the document. - */ - public final int getLineCount() - { - return document.getDefaultRootElement().getElementCount(); - } - - /** - * Returns the line containing the specified offset. - * @param offset The offset - */ - public final int getLineOfOffset(int offset) - { - return document.getDefaultRootElement().getElementIndex(offset); - } - - /** - * Returns the start offset of the specified line. - * @param line The line - * @return The start offset of the specified line, or -1 if the line is - * invalid - */ - public int getLineStartOffset(int line) - { - Element lineElement = document.getDefaultRootElement() - .getElement(line); - if(lineElement == null) - return -1; - else - return lineElement.getStartOffset(); - } - - /** - * Returns the end offset of the specified line. - * @param line The line - * @return The end offset of the specified line, or -1 if the line is - * invalid. - */ - public int getLineEndOffset(int line) - { - Element lineElement = document.getDefaultRootElement() - .getElement(line); - if(lineElement == null) - return -1; - else - return lineElement.getEndOffset(); - } - - /** - * Returns the length of the specified line. - * @param line The line - */ - public int getLineLength(int line) - { - Element lineElement = document.getDefaultRootElement() - .getElement(line); - if(lineElement == null) - return -1; - else - return lineElement.getEndOffset() - - lineElement.getStartOffset() - 1; - } - - /** - * Returns the entire text of this text area. - */ - public String getText() - { - try - { - return document.getText(0,document.getLength()); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - return null; - } - } - - /** - * Sets the entire text of this text area. - */ - public void setText(String text) - { - try - { - document.beginCompoundEdit(); - document.remove(0,document.getLength()); - document.insertString(0,text,null); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - finally - { - document.endCompoundEdit(); - } - } - - /** - * Returns the specified substring of the document. - * @param start The start offset - * @param len The length of the substring - * @return The substring, or null if the offsets are invalid - */ - public final String getText(int start, int len) - { - try - { - return document.getText(start,len); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - return null; - } - } - - /** - * Copies the specified substring of the document into a segment. - * If the offsets are invalid, the segment will contain a null string. - * @param start The start offset - * @param len The length of the substring - * @param segment The segment - */ - public final void getText(int start, int len, Segment segment) - { - try - { - document.getText(start,len,segment); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - segment.offset = segment.count = 0; - } - } - - /** - * Returns the text on the specified line. - * @param lineIndex The line - * @return The text, or null if the line is invalid - */ - public final String getLineText(int lineIndex) - { - int start = getLineStartOffset(lineIndex); - return getText(start,getLineEndOffset(lineIndex) - start - 1); - } - - /** - * Copies the text on the specified line into a segment. If the line - * is invalid, the segment will contain a null string. - * @param lineIndex The line - */ - public final void getLineText(int lineIndex, Segment segment) - { - int start = getLineStartOffset(lineIndex); - getText(start,getLineEndOffset(lineIndex) - start - 1,segment); - } - - /** - * Returns the selection start offset. - */ - public final int getSelectionStart() - { - return selectionStart; - } - - /** - * Returns the offset where the selection starts on the specified - * line. - */ - public int getSelectionStart(int line) - { - if(line == selectionStartLine) - return selectionStart; - else if(rectSelect) - { - Element map = document.getDefaultRootElement(); - int start = selectionStart - map.getElement(selectionStartLine) - .getStartOffset(); - - Element lineElement = map.getElement(line); - int lineStart = lineElement.getStartOffset(); - int lineEnd = lineElement.getEndOffset() - 1; - return Math.min(lineEnd,lineStart + start); - } - else - return getLineStartOffset(line); - } - - /** - * Returns the selection start line. - */ - public final int getSelectionStartLine() - { - return selectionStartLine; - } - - /** - * Sets the selection start. The new selection will be the new - * selection start and the old selection end. - * @param selectionStart The selection start - * @see #select(int,int) - */ - public final void setSelectionStart(int selectionStart) - { - select(selectionStart,selectionEnd); - } - - /** - * Returns the selection end offset. - */ - public final int getSelectionEnd() - { - return selectionEnd; - } - - /** - * Returns the offset where the selection ends on the specified - * line. - */ - public int getSelectionEnd(int line) - { - if(line == selectionEndLine) - return selectionEnd; - else if(rectSelect) - { - Element map = document.getDefaultRootElement(); - int end = selectionEnd - map.getElement(selectionEndLine) - .getStartOffset(); - - Element lineElement = map.getElement(line); - int lineStart = lineElement.getStartOffset(); - int lineEnd = lineElement.getEndOffset() - 1; - return Math.min(lineEnd,lineStart + end); - } - else - return getLineEndOffset(line) - 1; - } - - /** - * Returns the selection end line. - */ - public final int getSelectionEndLine() - { - return selectionEndLine; - } - - /** - * Sets the selection end. The new selection will be the old - * selection start and the bew selection end. - * @param selectionEnd The selection end - * @see #select(int,int) - */ - public final void setSelectionEnd(int selectionEnd) - { - select(selectionStart,selectionEnd); - } - - /** - * Returns the caret position. This will either be the selection - * start or the selection end, depending on which direction the - * selection was made in. - */ - public final int getCaretPosition() - { - return (biasLeft ? selectionStart : selectionEnd); - } - - /** - * Returns the caret line. - */ - public final int getCaretLine() - { - return (biasLeft ? selectionStartLine : selectionEndLine); - } - - /** - * Returns the mark position. This will be the opposite selection - * bound to the caret position. - * @see #getCaretPosition() - */ - public final int getMarkPosition() - { - return (biasLeft ? selectionEnd : selectionStart); - } - - /** - * Returns the mark line. - */ - public final int getMarkLine() - { - return (biasLeft ? selectionEndLine : selectionStartLine); - } - - /** - * Sets the caret position. The new selection will consist of the - * caret position only (hence no text will be selected) - * @param caret The caret position - * @see #select(int,int) - */ - public final void setCaretPosition(int caret) - { - select(caret,caret); - } - - /** - * Selects all text in the document. - */ - public final void selectAll() - { - select(0,getDocumentLength()); - } - - /** - * Moves the mark to the caret position. - */ - public final void selectNone() - { - select(getCaretPosition(),getCaretPosition()); - } - - /** - * Selects from the start offset to the end offset. This is the - * general selection method used by all other selecting methods. - * The caret position will be start if start < end, and end - * if end > start. - * @param start The start offset - * @param end The end offset - */ - public void select(int start, int end) - { - int newStart, newEnd; - boolean newBias; - if(start <= end) - { - newStart = start; - newEnd = end; - newBias = false; - } - else - { - newStart = end; - newEnd = start; - newBias = true; - } - - if(newStart < 0 || newEnd > getDocumentLength()) - { - throw new IllegalArgumentException("Bounds out of" - + " range: " + newStart + "," + - newEnd); - } - - // If the new position is the same as the old, we don't - // do all this crap, however we still do the stuff at - // the end (clearing magic position, scrolling) - if(newStart != selectionStart || newEnd != selectionEnd - || newBias != biasLeft) - { - int newStartLine = getLineOfOffset(newStart); - int newEndLine = getLineOfOffset(newEnd); - - if(painter.isBracketHighlightEnabled()) - { - if(bracketLine != -1) - painter.invalidateLine(bracketLine); - updateBracketHighlight(end); - if(bracketLine != -1) - painter.invalidateLine(bracketLine); - } - - painter.invalidateLineRange(selectionStartLine,selectionEndLine); - painter.invalidateLineRange(newStartLine,newEndLine); - - document.addUndoableEdit(new CaretUndo( - selectionStart,selectionEnd)); - - selectionStart = newStart; - selectionEnd = newEnd; - selectionStartLine = newStartLine; - selectionEndLine = newEndLine; - biasLeft = newBias; - - fireCaretEvent(); - } - - // When the user is typing, etc, we don't want the caret - // to blink - blink = true; - caretTimer.restart(); - - // Disable rectangle select if selection start = selection end - if(selectionStart == selectionEnd) - rectSelect = false; - - // Clear the `magic' caret position used by up/down - magicCaret = -1; - - scrollToCaret(); - } - - /** - * Returns the selected text, or null if no selection is active. - */ - public final String getSelectedText() - { - if(selectionStart == selectionEnd) - return null; - - if(rectSelect) - { - // Return each row of the selection on a new line - - Element map = document.getDefaultRootElement(); - - int start = selectionStart - map.getElement(selectionStartLine) - .getStartOffset(); - int end = selectionEnd - map.getElement(selectionEndLine) - .getStartOffset(); - - // Certain rectangles satisfy this condition... - if(end < start) - { - int tmp = end; - end = start; - start = tmp; - } - - StringBuffer buf = new StringBuffer(); - Segment seg = new Segment(); - - for(int i = selectionStartLine; i <= selectionEndLine; i++) - { - Element lineElement = map.getElement(i); - int lineStart = lineElement.getStartOffset(); - int lineEnd = lineElement.getEndOffset() - 1; - int lineLen = lineEnd - lineStart; - - lineStart = Math.min(lineStart + start,lineEnd); - lineLen = Math.min(end - start,lineEnd - lineStart); - - getText(lineStart,lineLen,seg); - buf.append(seg.array,seg.offset,seg.count); - - if(i != selectionEndLine) - buf.append('\n'); - } - - return buf.toString(); - } - else - { - return getText(selectionStart, - selectionEnd - selectionStart); - } - } - - /** - * Replaces the selection with the specified text. - * @param selectedText The replacement text for the selection - */ - public void setSelectedText(String selectedText) - { - if(!editable) - { - throw new InternalError("Text component" - + " read only"); - } - - document.beginCompoundEdit(); - - try - { - if(rectSelect) - { - Element map = document.getDefaultRootElement(); - - int start = selectionStart - map.getElement(selectionStartLine) - .getStartOffset(); - int end = selectionEnd - map.getElement(selectionEndLine) - .getStartOffset(); - - // Certain rectangles satisfy this condition... - if(end < start) - { - int tmp = end; - end = start; - start = tmp; - } - - int lastNewline = 0; - int currNewline = 0; - - for(int i = selectionStartLine; i <= selectionEndLine; i++) - { - Element lineElement = map.getElement(i); - int lineStart = lineElement.getStartOffset(); - int lineEnd = lineElement.getEndOffset() - 1; - int rectStart = Math.min(lineEnd,lineStart + start); - - document.remove(rectStart,Math.min(lineEnd - rectStart, - end - start)); - - if(selectedText == null) - continue; - - currNewline = selectedText.indexOf('\n',lastNewline); - if(currNewline == -1) - currNewline = selectedText.length(); - - document.insertString(rectStart,selectedText - .substring(lastNewline,currNewline),null); - - lastNewline = Math.min(selectedText.length(), - currNewline + 1); - } - - if(selectedText != null && - currNewline != selectedText.length()) - { - int offset = map.getElement(selectionEndLine) - .getEndOffset() - 1; - document.insertString(offset,"\n",null); - document.insertString(offset + 1,selectedText - .substring(currNewline + 1),null); - } - } - else - { - document.remove(selectionStart, - selectionEnd - selectionStart); - if(selectedText != null) - { - document.insertString(selectionStart, - selectedText,null); - } - } - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - throw new InternalError("Cannot replace" - + " selection"); - } - // No matter what happends... stops us from leaving document - // in a bad state - finally - { - document.endCompoundEdit(); - } - - setCaretPosition(selectionEnd); - } - - /** - * Returns true if this text area is editable, false otherwise. - */ - public final boolean isEditable() - { - return editable; - } - - /** - * Sets if this component is editable. - * @param editable True if this text area should be editable, - * false otherwise - */ - public final void setEditable(boolean editable) - { - this.editable = editable; - } - - /** - * Returns the right click popup menu. - */ - public final JPopupMenu getRightClickPopup() - { - return popup; - } - - /** - * Sets the right click popup menu. - * @param popup The popup - */ - public final void setRightClickPopup(JPopupMenu popup) - { - this.popup = popup; - } - - /** - * Returns the `magic' caret position. This can be used to preserve - * the column position when moving up and down lines. - */ - public final int getMagicCaretPosition() - { - return magicCaret; - } - - /** - * Sets the `magic' caret position. This can be used to preserve - * the column position when moving up and down lines. - * @param magicCaret The magic caret position - */ - public final void setMagicCaretPosition(int magicCaret) - { - this.magicCaret = magicCaret; - } - - /** - * Similar to setSelectedText(), but overstrikes the - * appropriate number of characters if overwrite mode is enabled. - * @param str The string - * @see #setSelectedText(String) - * @see #isOverwriteEnabled() - */ - public void overwriteSetSelectedText(String str) - { - // Don't overstrike if there is a selection - if(!overwrite || selectionStart != selectionEnd) - { - setSelectedText(str); - return; - } - - // Don't overstrike if we're on the end of - // the line - int caret = getCaretPosition(); - int caretLineEnd = getLineEndOffset(getCaretLine()); - if(caretLineEnd - caret <= str.length()) - { - setSelectedText(str); - return; - } - - document.beginCompoundEdit(); - - try - { - document.remove(caret,str.length()); - document.insertString(caret,str,null); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - finally - { - document.endCompoundEdit(); - } - } - - /** - * Returns true if overwrite mode is enabled, false otherwise. - */ - public final boolean isOverwriteEnabled() - { - return overwrite; - } - - /** - * Sets if overwrite mode should be enabled. - * @param overwrite True if overwrite mode should be enabled, - * false otherwise. - */ - public final void setOverwriteEnabled(boolean overwrite) - { - this.overwrite = overwrite; - painter.invalidateSelectedLines(); - } - - /** - * Returns true if the selection is rectangular, false otherwise. - */ - public final boolean isSelectionRectangular() - { - return rectSelect; - } - - /** - * Sets if the selection should be rectangular. - * @param rectSelect True if the selection should be rectangular, - * false otherwise. - */ - public final void setSelectionRectangular(boolean rectSelect) - { - this.rectSelect = rectSelect; - painter.invalidateSelectedLines(); - } - - /** - * Returns the position of the highlighted bracket (the bracket - * matching the one before the caret) - */ - public final int getBracketPosition() - { - return bracketPosition; - } - - /** - * Returns the line of the highlighted bracket (the bracket - * matching the one before the caret) - */ - public final int getBracketLine() - { - return bracketLine; - } - - /** - * Adds a caret change listener to this text area. - * @param listener The listener - */ - public final void addCaretListener(CaretListener listener) - { - listenerList.add(CaretListener.class,listener); - } - - /** - * Removes a caret change listener from this text area. - * @param listener The listener - */ - public final void removeCaretListener(CaretListener listener) - { - listenerList.remove(CaretListener.class,listener); - } - - /** - * Deletes the selected text from the text area and places it - * into the clipboard. - */ - public void cut() - { - if(editable) - { - copy(); - setSelectedText(""); - } - } - - /** - * Places the selected text into the clipboard. - */ - public void copy() - { - if(selectionStart != selectionEnd) - { - Clipboard clipboard = getToolkit().getSystemClipboard(); - - String selection = getSelectedText(); - - int repeatCount = inputHandler.getRepeatCount(); - StringBuffer buf = new StringBuffer(); - for(int i = 0; i < repeatCount; i++) - buf.append(selection); - - clipboard.setContents(new StringSelection(buf.toString()),null); - } - } - - /** - * Inserts the clipboard contents into the text. - */ - public void paste() - { - if(editable) - { - Clipboard clipboard = getToolkit().getSystemClipboard(); - try - { - // The MacOS MRJ doesn't convert \r to \n, - // so do it here - String selection = ((String)clipboard - .getContents(this).getTransferData( - DataFlavor.stringFlavor)) - .replace('\r','\n'); - - int repeatCount = inputHandler.getRepeatCount(); - StringBuffer buf = new StringBuffer(); - for(int i = 0; i < repeatCount; i++) - buf.append(selection); - selection = buf.toString(); - setSelectedText(selection); - } - catch(Exception e) - { - getToolkit().beep(); - System.err.println("Clipboard does not" - + " contain a string"); - } - } - } - - /** - * Called by the AWT when this component is removed from it's parent. - * This stops clears the currently focused component. - */ - public void removeNotify() - { - super.removeNotify(); - if(focusedComponent == this) - focusedComponent = null; - } - - /** - * Forwards key events directly to the input handler. - * This is slightly faster than using a KeyListener - * because some Swing overhead is avoided. - */ - public void processKeyEvent(KeyEvent evt) - { - if(inputHandler == null) - return; - switch(evt.getID()) - { - case KeyEvent.KEY_TYPED: - inputHandler.keyTyped(evt); - break; - case KeyEvent.KEY_PRESSED: - inputHandler.keyPressed(evt); - break; - case KeyEvent.KEY_RELEASED: - inputHandler.keyReleased(evt); - break; - } - if (inputMap==null) inputMap=getInputMap(); - Object o=inputMap.get(KeyStroke.getKeyStrokeForEvent(evt)); - if (o!=null) { - if (actionMap==null) actionMap=getActionMap(); - Object a=actionMap.get(o); - //System.out.println(o+" => "+a); - if (a!=null) ((Action)a).actionPerformed(new ActionEvent(this,ActionEvent.ACTION_PERFORMED,o.toString(),evt.getModifiers())); - } - - } - InputMap inputMap; - ActionMap actionMap; - /*public void setActionMap2(ActionMap am) { - actionMap=am; - } - public void setInputMap2(InputMap im) { - inputMap=im; - }*/ - // protected members - protected static String CENTER = "center"; - protected static String RIGHT = "right"; - protected static String BOTTOM = "bottom"; - - protected static JEditTextArea focusedComponent; - protected static Timer caretTimer; - - protected TextAreaPainter painter; - - protected JPopupMenu popup; - - protected EventListenerList listenerList; - protected MutableCaretEvent caretEvent; - - protected boolean caretBlinks; - protected boolean caretVisible; - protected boolean blink; - - protected boolean editable; - - protected int firstLine; - protected int visibleLines; - protected int electricScroll; - - protected int horizontalOffset; - - protected JScrollBar vertical; - protected JScrollBar horizontal; - protected boolean scrollBarsInitialized; - - protected InputHandler inputHandler; - protected SyntaxDocument document; - protected DocumentHandler documentHandler; - - protected Segment lineSegment; - - protected int selectionStart; - protected int selectionStartLine; - protected int selectionEnd; - protected int selectionEndLine; - protected boolean biasLeft; - - protected int bracketPosition; - protected int bracketLine; - - protected int magicCaret; - protected boolean overwrite; - protected boolean rectSelect; - - protected void fireCaretEvent() - { - Object[] listeners = listenerList.getListenerList(); - for(int i = listeners.length - 2; i >= 0; i--) - { - if(listeners[i] == CaretListener.class) - { - ((CaretListener)listeners[i+1]).caretUpdate(caretEvent); - } - } - } - - protected void updateBracketHighlight(int newCaretPosition) - { - if(newCaretPosition == 0) - { - bracketPosition = bracketLine = -1; - return; - } - - try - { - int offset = TextUtilities.findMatchingBracket( - document,newCaretPosition - 1); - if(offset != -1) - { - bracketLine = getLineOfOffset(offset); - bracketPosition = offset - getLineStartOffset(bracketLine); - return; - } - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - - bracketLine = bracketPosition = -1; - } - - protected void documentChanged(DocumentEvent evt) - { - DocumentEvent.ElementChange ch = evt.getChange( - document.getDefaultRootElement()); - - int count; - if(ch == null) - count = 0; - else - count = ch.getChildrenAdded().length - - ch.getChildrenRemoved().length; - - int line = getLineOfOffset(evt.getOffset()); - if(count == 0) - { - painter.invalidateLine(line); - } - // do magic stuff - else if(line < firstLine) - { - setFirstLine(firstLine + count); - } - // end of magic stuff - else - { - painter.invalidateLineRange(line,firstLine + visibleLines); - updateScrollBars(); - } - propertyChangeSupport.firePropertyChange(DOCUMENT_PROPERTY,null,null); - } - public static final String DOCUMENT_PROPERTY="doc"; - PropertyChangeSupport propertyChangeSupport; - public void addDocumentChangeListener(PropertyChangeListener l) { - propertyChangeSupport.addPropertyChangeListener(DOCUMENT_PROPERTY,l); - } - class ScrollLayout implements LayoutManager - { - public void addLayoutComponent(String name, Component comp) - { - if(name.equals(CENTER)) - center = comp; - else if(name.equals(RIGHT)) - right = comp; - else if(name.equals(BOTTOM)) - bottom = comp; - else if(name.equals(LEFT_OF_SCROLLBAR)) - leftOfScrollBar.addElement(comp); - } - - public void removeLayoutComponent(Component comp) - { - if(center == comp) - center = null; - if(right == comp) - right = null; - if(bottom == comp) - bottom = null; - else - leftOfScrollBar.removeElement(comp); - } - - public Dimension preferredLayoutSize(Container parent) - { - Dimension dim = new Dimension(); - Insets insets = getInsets(); - dim.width = insets.left + insets.right; - dim.height = insets.top + insets.bottom; - - Dimension centerPref = center.getPreferredSize(); - dim.width += centerPref.width; - dim.height += centerPref.height; - Dimension rightPref = right.getPreferredSize(); - dim.width += rightPref.width; - Dimension bottomPref = bottom.getPreferredSize(); - dim.height += bottomPref.height; - - return dim; - } - - public Dimension minimumLayoutSize(Container parent) - { - Dimension dim = new Dimension(); - Insets insets = getInsets(); - dim.width = insets.left + insets.right; - dim.height = insets.top + insets.bottom; - - Dimension centerPref = center.getMinimumSize(); - dim.width += centerPref.width; - dim.height += centerPref.height; - Dimension rightPref = right.getMinimumSize(); - dim.width += rightPref.width; - Dimension bottomPref = bottom.getMinimumSize(); - dim.height += bottomPref.height; - - return dim; - } - - public void layoutContainer(Container parent) - { - Dimension size = parent.getSize(); - Insets insets = parent.getInsets(); - int itop = insets.top; - int ileft = insets.left; - int ibottom = insets.bottom; - int iright = insets.right; - - int rightWidth = right.getPreferredSize().width; - int bottomHeight = bottom.getPreferredSize().height; - int centerWidth = size.width - rightWidth - ileft - iright; - int centerHeight = size.height - bottomHeight - itop - ibottom; - - center.setBounds( - ileft, - itop, - centerWidth, - centerHeight); - - right.setBounds( - ileft + centerWidth, - itop, - rightWidth, - centerHeight); - - // Lay out all status components, in order - Enumeration status = leftOfScrollBar.elements(); - while(status.hasMoreElements()) - { - Component comp = (Component)status.nextElement(); - Dimension dim = comp.getPreferredSize(); - comp.setBounds(ileft, - itop + centerHeight, - dim.width, - bottomHeight); - ileft += dim.width; - } - - bottom.setBounds( - ileft, - itop + centerHeight, - size.width - rightWidth - ileft - iright, - bottomHeight); - } - - // private members - private Component center; - private Component right; - private Component bottom; - private Vector leftOfScrollBar = new Vector(); - } - - static class CaretBlinker implements ActionListener - { - public void actionPerformed(ActionEvent evt) - { - if(focusedComponent != null - && focusedComponent.hasFocus()) - focusedComponent.blinkCaret(); - } - } - - class MutableCaretEvent extends CaretEvent - { - MutableCaretEvent() - { - super(JEditTextArea.this); - } - - public int getDot() - { - return getCaretPosition(); - } - - public int getMark() - { - return getMarkPosition(); - } - } - - class AdjustHandler implements AdjustmentListener - { - public void adjustmentValueChanged(final AdjustmentEvent evt) - { - if(!scrollBarsInitialized) - return; - - // If this is not done, mousePressed events accumilate - // and the result is that scrolling doesn't stop after - // the mouse is released - SwingUtilities.invokeLater(new Runnable() { - public void run() - { - if(evt.getAdjustable() == vertical) - setFirstLine(vertical.getValue()); - else - setHorizontalOffset(-horizontal.getValue()); - } - }); - } - } - - class ComponentHandler extends ComponentAdapter - { - public void componentResized(ComponentEvent evt) - { - recalculateVisibleLines(); - scrollBarsInitialized = true; - } - } - - class DocumentHandler implements DocumentListener - { - public void insertUpdate(DocumentEvent evt) - { - documentChanged(evt); - - int offset = evt.getOffset(); - int length = evt.getLength(); - - int newStart; - int newEnd; - - if(selectionStart > offset || (selectionStart - == selectionEnd && selectionStart == offset)) - newStart = selectionStart + length; - else - newStart = selectionStart; - - if(selectionEnd >= offset) - newEnd = selectionEnd + length; - else - newEnd = selectionEnd; - - select(newStart,newEnd); - } - - public void removeUpdate(DocumentEvent evt) - { - documentChanged(evt); - - int offset = evt.getOffset(); - int length = evt.getLength(); - - int newStart; - int newEnd; - - if(selectionStart > offset) - { - if(selectionStart > offset + length) - newStart = selectionStart - length; - else - newStart = offset; - } - else - newStart = selectionStart; - - if(selectionEnd > offset) - { - if(selectionEnd > offset + length) - newEnd = selectionEnd - length; - else - newEnd = offset; - } - else - newEnd = selectionEnd; - - select(newStart,newEnd); - } - - public void changedUpdate(DocumentEvent evt) - { - JOptionPane.showMessageDialog(null, evt.getType()+ ""); - } - } - - class DragHandler implements MouseMotionListener - { - public void mouseDragged(MouseEvent evt) - { - if(popup != null && popup.isVisible()) - return; - - setSelectionRectangular((evt.getModifiers() - & InputEvent.CTRL_MASK) != 0); - select(getMarkPosition(),xyToOffset(evt.getX(),evt.getY())); - } - - public void mouseMoved(MouseEvent evt) {} - } - - class FocusHandler implements FocusListener - { - public void focusGained(FocusEvent evt) - { - setCaretVisible(true); - focusedComponent = JEditTextArea.this; - } - - public void focusLost(FocusEvent evt) - { - setCaretVisible(false); - focusedComponent = null; - } - } - - class MouseHandler extends MouseAdapter - { - public void mousePressed(MouseEvent evt) - { - requestFocus(); - - // Focus events not fired sometimes? - setCaretVisible(true); - focusedComponent = JEditTextArea.this; - - if((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 - && popup != null) - { - popup.show(painter,evt.getX(),evt.getY()); - return; - } - - int line = yToLine(evt.getY()); - int offset = xToOffset(line,evt.getX()); - int dot = getLineStartOffset(line) + offset; - - switch(evt.getClickCount()) - { - case 1: - doSingleClick(evt,line,offset,dot); - break; - case 2: - // It uses the bracket matching stuff, so - // it can throw a BLE - try - { - doDoubleClick(evt,line,offset,dot); - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - break; - case 3: - doTripleClick(evt,line,offset,dot); - break; - } - } - - private void doSingleClick(MouseEvent evt, int line, - int offset, int dot) - { - if((evt.getModifiers() & InputEvent.SHIFT_MASK) != 0) - { - rectSelect = (evt.getModifiers() & InputEvent.CTRL_MASK) != 0; - select(getMarkPosition(),dot); - } - else - setCaretPosition(dot); - } - - private void doDoubleClick(MouseEvent evt, int line, - int offset, int dot) throws BadLocationException - { - // Ignore empty lines - if(getLineLength(line) == 0) - return; - - try - { - int bracket = TextUtilities.findMatchingBracket( - document,Math.max(0,dot - 1)); - if(bracket != -1) - { - int mark = getMarkPosition(); - // Hack - if(bracket > mark) - { - bracket++; - mark--; - } - select(mark,bracket); - return; - } - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - - // Ok, it's not a bracket... select the word - String lineText = getLineText(line); - char ch = lineText.charAt(Math.max(0,offset - 1)); - - String noWordSep = (String)document.getProperty("noWordSep"); - if(noWordSep == null) - noWordSep = ""; - - // If the user clicked on a non-letter char, - // we select the surrounding non-letters - boolean selectNoLetter = (!Character - .isLetterOrDigit(ch) - && noWordSep.indexOf(ch) == -1); - - int wordStart = 0; - - for(int i = offset - 1; i >= 0; i--) - { - ch = lineText.charAt(i); - if(selectNoLetter ^ (!Character - .isLetterOrDigit(ch) && - noWordSep.indexOf(ch) == -1)) - { - wordStart = i + 1; - break; - } - } - - int wordEnd = lineText.length(); - for(int i = offset; i < lineText.length(); i++) - { - ch = lineText.charAt(i); - if(selectNoLetter ^ (!Character - .isLetterOrDigit(ch) && - noWordSep.indexOf(ch) == -1)) - { - wordEnd = i; - break; - } - } - - int lineStart = getLineStartOffset(line); - select(lineStart + wordStart,lineStart + wordEnd); - - /* - String lineText = getLineText(line); - String noWordSep = (String)document.getProperty("noWordSep"); - int wordStart = TextUtilities.findWordStart(lineText,offset,noWordSep); - int wordEnd = TextUtilities.findWordEnd(lineText,offset,noWordSep); - - int lineStart = getLineStartOffset(line); - select(lineStart + wordStart,lineStart + wordEnd); - */ - } - - private void doTripleClick(MouseEvent evt, int line, - int offset, int dot) - { - select(getLineStartOffset(line),getLineEndOffset(line)-1); - } - } - - class CaretUndo extends AbstractUndoableEdit - { - private int start; - private int end; - - CaretUndo(int start, int end) - { - this.start = start; - this.end = end; - } - - public boolean isSignificant() - { - return false; - } - - public String getPresentationName() - { - return "caret move"; - } - - public void undo() throws CannotUndoException - { - super.undo(); - - select(start,end); - } - - public void redo() throws CannotRedoException - { - super.redo(); - - select(start,end); - } - - public boolean addEdit(UndoableEdit edit) - { - if(edit instanceof CaretUndo) - { - CaretUndo cedit = (CaretUndo)edit; - start = cedit.start; - end = cedit.end; - cedit.die(); - - return true; - } - else - return false; - } - } - - static - { - caretTimer = new Timer(500,new CaretBlinker()); - caretTimer.setInitialDelay(500); - caretTimer.start(); - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaScriptTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaScriptTokenMarker.java deleted file mode 100644 index 2d9f8fc5f..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaScriptTokenMarker.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; - -/** - * JavaScript token marker. - * - * @author Slava Pestov - * @version $Id: JavaScriptTokenMarker.java,v 1.3 1999/12/13 03:40:29 sp Exp $ - */ -public class JavaScriptTokenMarker extends CTokenMarker -{ - public JavaScriptTokenMarker() - { - super(false,getKeywords()); - } - - public static KeywordMap getKeywords() - { - if(javaScriptKeywords == null) - { - javaScriptKeywords = new KeywordMap(false); - javaScriptKeywords.add("function",Token.KEYWORD3); - javaScriptKeywords.add("var",Token.KEYWORD3); - javaScriptKeywords.add("else",Token.KEYWORD1); - javaScriptKeywords.add("for",Token.KEYWORD1); - javaScriptKeywords.add("if",Token.KEYWORD1); - javaScriptKeywords.add("in",Token.KEYWORD1); - javaScriptKeywords.add("new",Token.KEYWORD1); - javaScriptKeywords.add("return",Token.KEYWORD1); - javaScriptKeywords.add("while",Token.KEYWORD1); - javaScriptKeywords.add("with",Token.KEYWORD1); - javaScriptKeywords.add("break",Token.KEYWORD1); - javaScriptKeywords.add("case",Token.KEYWORD1); - javaScriptKeywords.add("continue",Token.KEYWORD1); - javaScriptKeywords.add("default",Token.KEYWORD1); - javaScriptKeywords.add("false",Token.LABEL); - javaScriptKeywords.add("this",Token.LABEL); - javaScriptKeywords.add("true",Token.LABEL); - } - return javaScriptKeywords; - } - - // private members - private static KeywordMap javaScriptKeywords; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaTokenMarker.java deleted file mode 100644 index 516caccfa..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/JavaTokenMarker.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * JavaTokenMarker.java - Java token marker - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -/** - * Java token marker. - * - * @author Slava Pestov - * @version $Id: JavaTokenMarker.java,v 1.5 1999/12/13 03:40:30 sp Exp $ - */ -public class JavaTokenMarker extends CTokenMarker -{ - public JavaTokenMarker() - { - super(false,getKeywords()); - } - - public static KeywordMap getKeywords() - { - if(javaKeywords == null) - { - javaKeywords = new KeywordMap(false); - javaKeywords.add("package",Token.KEYWORD2); - javaKeywords.add("import",Token.KEYWORD2); - javaKeywords.add("byte",Token.KEYWORD3); - javaKeywords.add("char",Token.KEYWORD3); - javaKeywords.add("short",Token.KEYWORD3); - javaKeywords.add("int",Token.KEYWORD3); - javaKeywords.add("long",Token.KEYWORD3); - javaKeywords.add("float",Token.KEYWORD3); - javaKeywords.add("double",Token.KEYWORD3); - javaKeywords.add("boolean",Token.KEYWORD3); - javaKeywords.add("void",Token.KEYWORD3); - javaKeywords.add("class",Token.KEYWORD3); - javaKeywords.add("interface",Token.KEYWORD3); - javaKeywords.add("abstract",Token.KEYWORD1); - javaKeywords.add("final",Token.KEYWORD1); - javaKeywords.add("private",Token.KEYWORD1); - javaKeywords.add("protected",Token.KEYWORD1); - javaKeywords.add("public",Token.KEYWORD1); - javaKeywords.add("static",Token.KEYWORD1); - javaKeywords.add("synchronized",Token.KEYWORD1); - javaKeywords.add("native",Token.KEYWORD1); - javaKeywords.add("volatile",Token.KEYWORD1); - javaKeywords.add("transient",Token.KEYWORD1); - javaKeywords.add("break",Token.KEYWORD1); - javaKeywords.add("case",Token.KEYWORD1); - javaKeywords.add("continue",Token.KEYWORD1); - javaKeywords.add("default",Token.KEYWORD1); - javaKeywords.add("do",Token.KEYWORD1); - javaKeywords.add("else",Token.KEYWORD1); - javaKeywords.add("for",Token.KEYWORD1); - javaKeywords.add("if",Token.KEYWORD1); - javaKeywords.add("instanceof",Token.KEYWORD1); - javaKeywords.add("new",Token.KEYWORD1); - javaKeywords.add("return",Token.KEYWORD1); - javaKeywords.add("switch",Token.KEYWORD1); - javaKeywords.add("while",Token.KEYWORD1); - javaKeywords.add("throw",Token.KEYWORD1); - javaKeywords.add("try",Token.KEYWORD1); - javaKeywords.add("catch",Token.KEYWORD1); - javaKeywords.add("extends",Token.KEYWORD1); - javaKeywords.add("finally",Token.KEYWORD1); - javaKeywords.add("implements",Token.KEYWORD1); - javaKeywords.add("throws",Token.KEYWORD1); - javaKeywords.add("this",Token.LITERAL2); - javaKeywords.add("null",Token.LITERAL2); - javaKeywords.add("super",Token.LITERAL2); - javaKeywords.add("true",Token.LITERAL2); - javaKeywords.add("false",Token.LITERAL2); - } - return javaKeywords; - } - - // private members - private static KeywordMap javaKeywords; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/KeywordMap.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/KeywordMap.java deleted file mode 100644 index 57e026d67..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/KeywordMap.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * KeywordMap.java - Fast keyword->id map - * Copyright (C) 1998, 1999 Slava Pestov - * Copyright (C) 1999 Mike Dillon - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * A KeywordMap is similar to a hashtable in that it maps keys - * to values. However, the `keys' are Swing segments. This allows lookups of - * text substrings without the overhead of creating a new string object. - *

      - * This class is used by CTokenMarker to map keywords to ids. - * - * @author Slava Pestov, Mike Dillon - * @version $Id: KeywordMap.java,v 1.16 1999/12/13 03:40:30 sp Exp $ - */ -public class KeywordMap -{ - /** - * Creates a new KeywordMap. - * @param ignoreCase True if keys are case insensitive - */ - public KeywordMap(boolean ignoreCase) - { - this(ignoreCase, 52); - this.ignoreCase = ignoreCase; - } - - /** - * Creates a new KeywordMap. - * @param ignoreCase True if the keys are case insensitive - * @param mapLength The number of `buckets' to create. - * A value of 52 will give good performance for most maps. - */ - public KeywordMap(boolean ignoreCase, int mapLength) - { - this.mapLength = mapLength; - this.ignoreCase = ignoreCase; - map = new Keyword[mapLength]; - } - - /** - * Looks up a key. - * @param text The text segment - * @param offset The offset of the substring within the text segment - * @param length The length of the substring - */ - public byte lookup(Segment text, int offset, int length) - { - if(length == 0) - return Token.NULL; - Keyword k = map[getSegmentMapKey(text, offset, length)]; - while(k != null) - { - if(length != k.keyword.length) - { - k = k.next; - continue; - } - if(SyntaxUtilities.regionMatches(ignoreCase,text,offset, - k.keyword)) - return k.id; - k = k.next; - } - return Token.NULL; - } - - /** - * Adds a key-value mapping. - * @param keyword The key - * @param id The value - */ - public void add(String keyword, byte id) - { - int key = getStringMapKey(keyword); - map[key] = new Keyword(keyword.toCharArray(),id,map[key]); - } - - /** - * Returns true if the keyword map is set to be case insensitive, - * false otherwise. - */ - public boolean getIgnoreCase() - { - return ignoreCase; - } - - /** - * Sets if the keyword map should be case insensitive. - * @param ignoreCase True if the keyword map should be case - * insensitive, false otherwise - */ - public void setIgnoreCase(boolean ignoreCase) - { - this.ignoreCase = ignoreCase; - } - - // protected members - protected int mapLength; - - protected int getStringMapKey(String s) - { - return (Character.toUpperCase(s.charAt(0)) + - Character.toUpperCase(s.charAt(s.length()-1))) - % mapLength; - } - - protected int getSegmentMapKey(Segment s, int off, int len) - { - return (Character.toUpperCase(s.array[off]) + - Character.toUpperCase(s.array[off + len - 1])) - % mapLength; - } - - // private members - class Keyword - { - public Keyword(char[] keyword, byte id, Keyword next) - { - this.keyword = keyword; - this.id = id; - this.next = next; - } - - public char[] keyword; - public byte id; - public Keyword next; - } - - private Keyword[] map; - private boolean ignoreCase; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/MakefileTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/MakefileTokenMarker.java deleted file mode 100644 index b90df7e20..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/MakefileTokenMarker.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Makefile token marker. - * - * @author Slava Pestov - * @version $Id: MakefileTokenMarker.java,v 1.18 1999/12/13 03:40:30 sp Exp $ - */ -public class MakefileTokenMarker extends TokenMarker -{ - // public members - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - int lastOffset = offset; - int length = line.count + offset; - boolean backslash = false; -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case ':': case '=': case ' ': case '\t': - backslash = false; - if(lastOffset == offset) - { - addToken(i1 - lastOffset,Token.KEYWORD1); - lastOffset = i1; - } - break; - case '#': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = length; - break loop; - } - break; - case '$': - if(backslash) - backslash = false; - else if(lastOffset != offset) - { - addToken(i - lastOffset,token); - lastOffset = i; - if(length - i > 1) - { - char c1 = array[i1]; - if(c1 == '(' || c1 == '{') - token = Token.KEYWORD2; - else - { - addToken(2,Token.KEYWORD2); - lastOffset += 2; - i++; - } - } - } - break; - case '"': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lastOffset = i; - } - break; - case '\'': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL2; - lastOffset = i; - } - break; - default: - backslash = false; - break; - } - case Token.KEYWORD2: - backslash = false; - if(c == ')' || c == '}') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = i1; - } - break; - case Token.LITERAL1: - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = i1; - } - else - backslash = false; - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - token = Token.NULL; - lastOffset = i1; - } - else - backslash = false; - break; - } - } - switch(token) - { - case Token.KEYWORD2: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - case Token.LITERAL2: - addToken(length - lastOffset,Token.LITERAL1); - break; - default: - addToken(length - lastOffset,token); - break; - } - return token; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PHPTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PHPTokenMarker.java deleted file mode 100644 index 313dc9b6e..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PHPTokenMarker.java +++ /dev/null @@ -1,348 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * PHP token marker. - * - * @author Clancy Malcolm - * @version $Id: PHPTokenMarker.java,v 1.1 1999/12/14 04:20:35 sp Exp $ - */ -public class PHPTokenMarker extends TokenMarker -{ - public static final byte SCRIPT = Token.INTERNAL_FIRST; - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - lastOffset = offset; - lastKeyword = offset; - int length = line.count + offset; - boolean backslash = false; - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: // HTML text - backslash = false; - switch(c) - { - case '<': - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - if(SyntaxUtilities.regionMatches(false, - line,i1,"!--")) - { - i += 3; - token = Token.COMMENT1; - } - else if(SyntaxUtilities.regionMatches( - true,line,i1,"?php")) - { - addToken(5,Token.LABEL); - lastOffset = lastKeyword = (i += 4) + 1; - token = SCRIPT; - } - else if(SyntaxUtilities.regionMatches( - true,line,i1,"?")) - { - addToken(2,Token.LABEL); - lastOffset = lastKeyword = (i += 1) + 1; - token = SCRIPT; - } - else if(SyntaxUtilities.regionMatches( - true,line,i1,"script>")) - { - addToken(8,Token.LABEL); - lastOffset = lastKeyword = (i += 7) + 1; - token = SCRIPT; - } - else - { - token = Token.KEYWORD1; - } - break; - case '&': - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - token = Token.KEYWORD2; - break; - } - break; - case Token.KEYWORD1: // Inside a tag - backslash = false; - if(c == '>') - { - addToken(i1 - lastOffset,token); - lastOffset = lastKeyword = i1; - token = Token.NULL; - } - break; - case Token.KEYWORD2: // Inside an entity - backslash = false; - if(c == ';') - { - addToken(i1 - lastOffset,token); - lastOffset = lastKeyword = i1; - token = Token.NULL; - break; - } - break; - case Token.COMMENT1: // Inside a comment - backslash = false; - if(SyntaxUtilities.regionMatches(false,line,i,"-->")) - { - addToken(i + 3 - lastOffset,token); - i += 2; - lastOffset = lastKeyword = i + 1; - token = Token.NULL; - } - break; - case SCRIPT: // Inside a JavaScript or PHP - switch(c) - { - case '<': - backslash = false; - doKeyword(line,i,c); - if(SyntaxUtilities.regionMatches(true, - line,i1,"/script>")) - { - //Ending the script - addToken(i - lastOffset, - Token.KEYWORD3); - addToken(9,Token.LABEL); - lastOffset = lastKeyword = (i += 8) + 1; - token = Token.NULL; - } - else - { - // < operator - addToken(i - lastOffset, - Token.KEYWORD3); - addToken(1,Token.OPERATOR); - lastOffset = lastKeyword = i1; - } - break; - case '?': - backslash = false; - doKeyword(line, i, c); - if (array[i1] == '>') - { - //Ending the script - addToken(i - lastOffset, - Token.KEYWORD3); - addToken(2,Token.LABEL); - lastOffset = lastKeyword = (i += 1) + 1; - token = Token.NULL; - } - else - { - //? operator - addToken(i - lastOffset, Token.KEYWORD3); - addToken(1,Token.OPERATOR); - lastOffset = lastKeyword = i1; - } - break; - case '"': - if(backslash) - backslash = false; - else - { - doKeyword(line,i,c); - addToken(i - lastOffset,Token.KEYWORD3); - lastOffset = lastKeyword = i; - token = Token.LITERAL1; - } - break; - case '\'': - if(backslash) - backslash = false; - else - { - doKeyword(line,i,c); - addToken(i - lastOffset,Token.KEYWORD3); - lastOffset = lastKeyword = i; - token = Token.LITERAL2; - } - break; - case '#': - doKeyword(line,i,c); - addToken(i - lastOffset,Token.KEYWORD3); - addToken(length - i,Token.COMMENT2); - lastOffset = lastKeyword = length; - break loop; - case '/': - backslash = false; - doKeyword(line,i,c); - if(length - i > 1) /*This is the same as if(length > i + 1) */ - { - addToken(i - lastOffset,Token.KEYWORD3); - lastOffset = lastKeyword = i; - if(array[i1] == '/') - { - addToken(length - i,Token.COMMENT2); - lastOffset = lastKeyword = length; - break loop; - } - else if(array[i1] == '*') - { - token = Token.COMMENT2; - } - else - { - // / operator - addToken(i - lastOffset, Token.KEYWORD3); - addToken(1,Token.OPERATOR); - lastOffset = lastKeyword = i1; - } - } - else - { - // / operator - addToken(i - lastOffset, Token.KEYWORD3); - addToken(1,Token.OPERATOR); - lastOffset = lastKeyword = i1; - } - break; - default: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_' && c != '$') - { - doKeyword(line,i,c); - if (c != ' ') - { - //assume non alphanumeric characters are operators - addToken(i - lastOffset, Token.KEYWORD3); - addToken(1,Token.OPERATOR); - lastOffset = lastKeyword = i1; - } - } - break; - } - break; - case Token.LITERAL1: // Script "..." - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,Token.LITERAL1); - lastOffset = lastKeyword = i1; - token = SCRIPT; - } - break; - case Token.LITERAL2: // Script '...' - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - lastOffset = lastKeyword = i1; - token = SCRIPT; - } - break; - case Token.COMMENT2: // Inside a Script comment - backslash = false; - if(c == '*' && length - i > 1 && array[i1] == '/') - { - addToken(i + 2 - lastOffset,Token.COMMENT2); - i += 1; - lastOffset = lastKeyword = i + 1; - token = SCRIPT; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - switch(token) - { - case Token.LITERAL1: - addToken(length - lastOffset,Token.LITERAL1); - break; - case Token.LITERAL2: - addToken(length - lastOffset,Token.LITERAL2); - break; - case Token.KEYWORD2: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - case SCRIPT: - doKeyword(line,length,'\0'); - addToken(length - lastOffset,Token.KEYWORD3); - break; - default: - addToken(length - lastOffset,token); - break; - } - - return token; - } - - // private members - private static KeywordMap keywords; - private int lastOffset; - private int lastKeyword; - - static - { - keywords = new KeywordMap(false); - keywords.add("function",Token.KEYWORD2); - keywords.add("class",Token.KEYWORD2); - keywords.add("var",Token.KEYWORD2); - keywords.add("require",Token.KEYWORD2); - keywords.add("include",Token.KEYWORD2); - keywords.add("else",Token.KEYWORD1); - keywords.add("elseif",Token.KEYWORD1); - keywords.add("do",Token.KEYWORD1); - keywords.add("for",Token.KEYWORD1); - keywords.add("if",Token.KEYWORD1); - keywords.add("endif",Token.KEYWORD1); - keywords.add("in",Token.KEYWORD1); - keywords.add("new",Token.KEYWORD1); - keywords.add("return",Token.KEYWORD1); - keywords.add("while",Token.KEYWORD1); - keywords.add("endwhile",Token.KEYWORD1); - keywords.add("with",Token.KEYWORD1); - keywords.add("break",Token.KEYWORD1); - keywords.add("switch",Token.KEYWORD1); - keywords.add("case",Token.KEYWORD1); - keywords.add("continue",Token.KEYWORD1); - keywords.add("default",Token.KEYWORD1); - keywords.add("echo",Token.KEYWORD1); - keywords.add("false",Token.KEYWORD1); - keywords.add("this",Token.KEYWORD1); - keywords.add("true",Token.KEYWORD1); - keywords.add("array",Token.KEYWORD1); - keywords.add("extends",Token.KEYWORD1); - } - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.KEYWORD3); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PatchTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PatchTokenMarker.java deleted file mode 100644 index aadf289fe..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PatchTokenMarker.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Patch/diff token marker. - * - * @author Slava Pestov - * @version $Id: PatchTokenMarker.java,v 1.7 1999/12/13 03:40:30 sp Exp $ - */ -public class PatchTokenMarker extends TokenMarker -{ - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - if(line.count == 0) - return Token.NULL; - switch(line.array[line.offset]) - { - case '+': case '>': - addToken(line.count,Token.KEYWORD1); - break; - case '-': case '<': - addToken(line.count,Token.KEYWORD2); - break; - case '@': case '*': - addToken(line.count,Token.KEYWORD3); - break; - default: - addToken(line.count,Token.NULL); - break; - } - return Token.NULL; - } - - public boolean supportsMultilineTokens() - { - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PerlTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PerlTokenMarker.java deleted file mode 100644 index e3ac9c334..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PerlTokenMarker.java +++ /dev/null @@ -1,704 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Perl token marker. - * - * @author Slava Pestov - * @version $Id: PerlTokenMarker.java,v 1.11 1999/12/13 03:40:30 sp Exp $ - */ -public class PerlTokenMarker extends TokenMarker -{ - // public members - public static final byte S_ONE = Token.INTERNAL_FIRST; - public static final byte S_TWO = (byte)(Token.INTERNAL_FIRST + 1); - public static final byte S_END = (byte)(Token.INTERNAL_FIRST + 2); - - public PerlTokenMarker() - { - this(getKeywords()); - } - - public PerlTokenMarker(KeywordMap keywords) - { - this.keywords = keywords; - } - - public byte markTokensImpl(byte _token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - token = _token; - lastOffset = offset; - lastKeyword = offset; - matchChar = '\0'; - matchCharBracket = false; - matchSpacesAllowed = false; - int length = line.count + offset; - - if(token == Token.LITERAL1 && lineIndex != 0 - && lineInfo[lineIndex - 1].obj != null) - { - String str = (String)lineInfo[lineIndex - 1].obj; - if(str != null && str.length() == line.count - && SyntaxUtilities.regionMatches(false,line, - offset,str)) - { - addToken(line.count,token); - return Token.NULL; - } - else - { - addToken(line.count,token); - lineInfo[lineIndex].obj = str; - return token; - } - } - - boolean backslash = false; -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case '#': - if(doKeyword(line,i,c)) - break; - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = lastKeyword = length; - break loop; - } - break; - case '=': - backslash = false; - if(i == offset) - { - token = Token.COMMENT2; - addToken(length - i,token); - lastOffset = lastKeyword = length; - break loop; - } - else - doKeyword(line,i,c); - break; - case '$': case '&': case '%': case '@': - backslash = false; - if(doKeyword(line,i,c)) - break; - if(length - i > 1) - { - if(c == '&' && (array[i1] == '&' - || Character.isWhitespace( - array[i1]))) - i++; - else - { - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - token = Token.KEYWORD2; - } - } - break; - case '"': - if(doKeyword(line,i,c)) - break; - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lineInfo[lineIndex].obj = null; - lastOffset = lastKeyword = i; - } - break; - case '\'': - if(backslash) - backslash = false; - else - { - int oldLastKeyword = lastKeyword; - if(doKeyword(line,i,c)) - break; - if(i != oldLastKeyword) - break; - addToken(i - lastOffset,token); - token = Token.LITERAL2; - lastOffset = lastKeyword = i; - } - break; - case '`': - if(doKeyword(line,i,c)) - break; - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.OPERATOR; - lastOffset = lastKeyword = i; - } - break; - case '<': - if(doKeyword(line,i,c)) - break; - if(backslash) - backslash = false; - else - { - if(length - i > 2 && array[i1] == '<' - && !Character.isWhitespace(array[i+2])) - { - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - token = Token.LITERAL1; - int len = length - (i+2); - if(array[length - 1] == ';') - len--; - lineInfo[lineIndex].obj = - createReadinString(array,i + 2,len); - } - } - break; - case ':': - backslash = false; - if(doKeyword(line,i,c)) - break; - // Doesn't pick up all labels, - // but at least doesn't mess up - // XXX::YYY - if(lastKeyword != 0) - break; - addToken(i1 - lastOffset,Token.LABEL); - lastOffset = lastKeyword = i1; - break; - case '-': - backslash = false; - if(doKeyword(line,i,c)) - break; - if(i != lastKeyword || length - i <= 1) - break; - switch(array[i1]) - { - case 'r': case 'w': case 'x': - case 'o': case 'R': case 'W': - case 'X': case 'O': case 'e': - case 'z': case 's': case 'f': - case 'd': case 'l': case 'p': - case 'S': case 'b': case 'c': - case 't': case 'u': case 'g': - case 'k': case 'T': case 'B': - case 'M': case 'A': case 'C': - addToken(i - lastOffset,token); - addToken(2,Token.KEYWORD3); - lastOffset = lastKeyword = i+2; - i++; - } - break; - case '/': case '?': - if(doKeyword(line,i,c)) - break; - if(length - i > 1) - { - backslash = false; - char ch = array[i1]; - if(Character.isWhitespace(ch)) - break; - matchChar = c; - matchSpacesAllowed = false; - addToken(i - lastOffset,token); - token = S_ONE; - lastOffset = lastKeyword = i; - } - break; - default: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - } - break; - case Token.KEYWORD2: - backslash = false; - // This test checks for an end-of-variable - // condition - if(!Character.isLetterOrDigit(c) && c != '_' - && c != '#' && c != '\'' && c != ':' - && c != '&') - { - // If this is the first character - // of the variable name ($'aaa) - // ignore it - if(i != offset && array[i-1] == '$') - { - addToken(i1 - lastOffset,token); - lastOffset = lastKeyword = i1; - } - // Otherwise, end of variable... - else - { - addToken(i - lastOffset,token); - lastOffset = lastKeyword = i; - // Wind back so that stuff - // like $hello$fred is picked - // up - i--; - token = Token.NULL; - } - } - break; - case S_ONE: case S_TWO: - if(backslash) - backslash = false; - else - { - if(matchChar == '\0') - { - if(Character.isWhitespace(matchChar) - && !matchSpacesAllowed) - break; - else - matchChar = c; - } - else - { - switch(matchChar) - { - case '(': - matchChar = ')'; - matchCharBracket = true; - break; - case '[': - matchChar = ']'; - matchCharBracket = true; - break; - case '{': - matchChar = '}'; - matchCharBracket = true; - break; - case '<': - matchChar = '>'; - matchCharBracket = true; - break; - default: - matchCharBracket = false; - break; - } - if(c != matchChar) - break; - if(token == S_TWO) - { - token = S_ONE; - if(matchCharBracket) - matchChar = '\0'; - } - else - { - token = S_END; - addToken(i1 - lastOffset, - Token.LITERAL2); - lastOffset = lastKeyword = i1; - } - } - } - break; - case S_END: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - case Token.COMMENT2: - backslash = false; - if(i == offset) - { - addToken(line.count,token); - if(length - i > 3 && SyntaxUtilities - .regionMatches(false,line,offset,"=cut")) - token = Token.NULL; - lastOffset = lastKeyword = length; - break loop; - } - break; - case Token.LITERAL1: - if(backslash) - backslash = false; - /* else if(c == '$') - backslash = true; */ - else if(c == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - /* else if(c == '$') - backslash = true; */ - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case Token.OPERATOR: - if(backslash) - backslash = false; - else if(c == '`') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - if(token == Token.NULL) - doKeyword(line,length,'\0'); - - switch(token) - { - case Token.KEYWORD2: - addToken(length - lastOffset,token); - token = Token.NULL; - break; - case Token.LITERAL2: - addToken(length - lastOffset,Token.LITERAL1); - break; - case S_END: - addToken(length - lastOffset,Token.LITERAL2); - token = Token.NULL; - break; - case S_ONE: case S_TWO: - addToken(length - lastOffset,Token.INVALID); // XXX - token = Token.NULL; - break; - default: - addToken(length - lastOffset,token); - break; - } - return token; - } - - // private members - private KeywordMap keywords; - private byte token; - private int lastOffset; - private int lastKeyword; - private char matchChar; - private boolean matchCharBracket; - private boolean matchSpacesAllowed; - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - - if(token == S_END) - { - addToken(i - lastOffset,Token.LITERAL2); - token = Token.NULL; - lastOffset = i; - lastKeyword = i1; - return false; - } - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id == S_ONE || id == S_TWO) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,Token.LITERAL2); - lastOffset = i; - lastKeyword = i1; - if(Character.isWhitespace(c)) - matchChar = '\0'; - else - matchChar = c; - matchSpacesAllowed = true; - token = id; - return true; - } - else if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } - - // Converts < EOF >, < 'EOF' >, etc to - private String createReadinString(char[] array, int start, int len) - { - int idx1 = start; - int idx2 = start + len - 1; - - while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx1]))) - idx1++; - - while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx2]))) - idx2--; - - return new String(array, idx1, idx2 - idx1 + 1); - } - - private static KeywordMap perlKeywords; - - private static KeywordMap getKeywords() - { - if(perlKeywords == null) - { - perlKeywords = new KeywordMap(false); - perlKeywords.add("my",Token.KEYWORD1); - perlKeywords.add("local",Token.KEYWORD1); - perlKeywords.add("new",Token.KEYWORD1); - perlKeywords.add("if",Token.KEYWORD1); - perlKeywords.add("until",Token.KEYWORD1); - perlKeywords.add("while",Token.KEYWORD1); - perlKeywords.add("elsif",Token.KEYWORD1); - perlKeywords.add("else",Token.KEYWORD1); - perlKeywords.add("eval",Token.KEYWORD1); - perlKeywords.add("unless",Token.KEYWORD1); - perlKeywords.add("foreach",Token.KEYWORD1); - perlKeywords.add("continue",Token.KEYWORD1); - perlKeywords.add("exit",Token.KEYWORD1); - perlKeywords.add("die",Token.KEYWORD1); - perlKeywords.add("last",Token.KEYWORD1); - perlKeywords.add("goto",Token.KEYWORD1); - perlKeywords.add("next",Token.KEYWORD1); - perlKeywords.add("redo",Token.KEYWORD1); - perlKeywords.add("goto",Token.KEYWORD1); - perlKeywords.add("return",Token.KEYWORD1); - perlKeywords.add("do",Token.KEYWORD1); - perlKeywords.add("sub",Token.KEYWORD1); - perlKeywords.add("use",Token.KEYWORD1); - perlKeywords.add("require",Token.KEYWORD1); - perlKeywords.add("package",Token.KEYWORD1); - perlKeywords.add("BEGIN",Token.KEYWORD1); - perlKeywords.add("END",Token.KEYWORD1); - perlKeywords.add("eq",Token.OPERATOR); - perlKeywords.add("ne",Token.OPERATOR); - perlKeywords.add("not",Token.OPERATOR); - perlKeywords.add("and",Token.OPERATOR); - perlKeywords.add("or",Token.OPERATOR); - - perlKeywords.add("abs",Token.KEYWORD3); - perlKeywords.add("accept",Token.KEYWORD3); - perlKeywords.add("alarm",Token.KEYWORD3); - perlKeywords.add("atan2",Token.KEYWORD3); - perlKeywords.add("bind",Token.KEYWORD3); - perlKeywords.add("binmode",Token.KEYWORD3); - perlKeywords.add("bless",Token.KEYWORD3); - perlKeywords.add("caller",Token.KEYWORD3); - perlKeywords.add("chdir",Token.KEYWORD3); - perlKeywords.add("chmod",Token.KEYWORD3); - perlKeywords.add("chomp",Token.KEYWORD3); - perlKeywords.add("chr",Token.KEYWORD3); - perlKeywords.add("chroot",Token.KEYWORD3); - perlKeywords.add("chown",Token.KEYWORD3); - perlKeywords.add("closedir",Token.KEYWORD3); - perlKeywords.add("close",Token.KEYWORD3); - perlKeywords.add("connect",Token.KEYWORD3); - perlKeywords.add("cos",Token.KEYWORD3); - perlKeywords.add("crypt",Token.KEYWORD3); - perlKeywords.add("dbmclose",Token.KEYWORD3); - perlKeywords.add("dbmopen",Token.KEYWORD3); - perlKeywords.add("defined",Token.KEYWORD3); - perlKeywords.add("delete",Token.KEYWORD3); - perlKeywords.add("die",Token.KEYWORD3); - perlKeywords.add("dump",Token.KEYWORD3); - perlKeywords.add("each",Token.KEYWORD3); - perlKeywords.add("endgrent",Token.KEYWORD3); - perlKeywords.add("endhostent",Token.KEYWORD3); - perlKeywords.add("endnetent",Token.KEYWORD3); - perlKeywords.add("endprotoent",Token.KEYWORD3); - perlKeywords.add("endpwent",Token.KEYWORD3); - perlKeywords.add("endservent",Token.KEYWORD3); - perlKeywords.add("eof",Token.KEYWORD3); - perlKeywords.add("exec",Token.KEYWORD3); - perlKeywords.add("exists",Token.KEYWORD3); - perlKeywords.add("exp",Token.KEYWORD3); - perlKeywords.add("fctnl",Token.KEYWORD3); - perlKeywords.add("fileno",Token.KEYWORD3); - perlKeywords.add("flock",Token.KEYWORD3); - perlKeywords.add("fork",Token.KEYWORD3); - perlKeywords.add("format",Token.KEYWORD3); - perlKeywords.add("formline",Token.KEYWORD3); - perlKeywords.add("getc",Token.KEYWORD3); - perlKeywords.add("getgrent",Token.KEYWORD3); - perlKeywords.add("getgrgid",Token.KEYWORD3); - perlKeywords.add("getgrnam",Token.KEYWORD3); - perlKeywords.add("gethostbyaddr",Token.KEYWORD3); - perlKeywords.add("gethostbyname",Token.KEYWORD3); - perlKeywords.add("gethostent",Token.KEYWORD3); - perlKeywords.add("getlogin",Token.KEYWORD3); - perlKeywords.add("getnetbyaddr",Token.KEYWORD3); - perlKeywords.add("getnetbyname",Token.KEYWORD3); - perlKeywords.add("getnetent",Token.KEYWORD3); - perlKeywords.add("getpeername",Token.KEYWORD3); - perlKeywords.add("getpgrp",Token.KEYWORD3); - perlKeywords.add("getppid",Token.KEYWORD3); - perlKeywords.add("getpriority",Token.KEYWORD3); - perlKeywords.add("getprotobyname",Token.KEYWORD3); - perlKeywords.add("getprotobynumber",Token.KEYWORD3); - perlKeywords.add("getprotoent",Token.KEYWORD3); - perlKeywords.add("getpwent",Token.KEYWORD3); - perlKeywords.add("getpwnam",Token.KEYWORD3); - perlKeywords.add("getpwuid",Token.KEYWORD3); - perlKeywords.add("getservbyname",Token.KEYWORD3); - perlKeywords.add("getservbyport",Token.KEYWORD3); - perlKeywords.add("getservent",Token.KEYWORD3); - perlKeywords.add("getsockname",Token.KEYWORD3); - perlKeywords.add("getsockopt",Token.KEYWORD3); - perlKeywords.add("glob",Token.KEYWORD3); - perlKeywords.add("gmtime",Token.KEYWORD3); - perlKeywords.add("grep",Token.KEYWORD3); - perlKeywords.add("hex",Token.KEYWORD3); - perlKeywords.add("import",Token.KEYWORD3); - perlKeywords.add("index",Token.KEYWORD3); - perlKeywords.add("int",Token.KEYWORD3); - perlKeywords.add("ioctl",Token.KEYWORD3); - perlKeywords.add("join",Token.KEYWORD3); - perlKeywords.add("keys",Token.KEYWORD3); - perlKeywords.add("kill",Token.KEYWORD3); - perlKeywords.add("lcfirst",Token.KEYWORD3); - perlKeywords.add("lc",Token.KEYWORD3); - perlKeywords.add("length",Token.KEYWORD3); - perlKeywords.add("link",Token.KEYWORD3); - perlKeywords.add("listen",Token.KEYWORD3); - perlKeywords.add("log",Token.KEYWORD3); - perlKeywords.add("localtime",Token.KEYWORD3); - perlKeywords.add("lstat",Token.KEYWORD3); - perlKeywords.add("map",Token.KEYWORD3); - perlKeywords.add("mkdir",Token.KEYWORD3); - perlKeywords.add("msgctl",Token.KEYWORD3); - perlKeywords.add("msgget",Token.KEYWORD3); - perlKeywords.add("msgrcv",Token.KEYWORD3); - perlKeywords.add("no",Token.KEYWORD3); - perlKeywords.add("oct",Token.KEYWORD3); - perlKeywords.add("opendir",Token.KEYWORD3); - perlKeywords.add("open",Token.KEYWORD3); - perlKeywords.add("ord",Token.KEYWORD3); - perlKeywords.add("pack",Token.KEYWORD3); - perlKeywords.add("pipe",Token.KEYWORD3); - perlKeywords.add("pop",Token.KEYWORD3); - perlKeywords.add("pos",Token.KEYWORD3); - perlKeywords.add("printf",Token.KEYWORD3); - perlKeywords.add("print",Token.KEYWORD3); - perlKeywords.add("push",Token.KEYWORD3); - perlKeywords.add("quotemeta",Token.KEYWORD3); - perlKeywords.add("rand",Token.KEYWORD3); - perlKeywords.add("readdir",Token.KEYWORD3); - perlKeywords.add("read",Token.KEYWORD3); - perlKeywords.add("readlink",Token.KEYWORD3); - perlKeywords.add("recv",Token.KEYWORD3); - perlKeywords.add("ref",Token.KEYWORD3); - perlKeywords.add("rename",Token.KEYWORD3); - perlKeywords.add("reset",Token.KEYWORD3); - perlKeywords.add("reverse",Token.KEYWORD3); - perlKeywords.add("rewinddir",Token.KEYWORD3); - perlKeywords.add("rindex",Token.KEYWORD3); - perlKeywords.add("rmdir",Token.KEYWORD3); - perlKeywords.add("scalar",Token.KEYWORD3); - perlKeywords.add("seekdir",Token.KEYWORD3); - perlKeywords.add("seek",Token.KEYWORD3); - perlKeywords.add("select",Token.KEYWORD3); - perlKeywords.add("semctl",Token.KEYWORD3); - perlKeywords.add("semget",Token.KEYWORD3); - perlKeywords.add("semop",Token.KEYWORD3); - perlKeywords.add("send",Token.KEYWORD3); - perlKeywords.add("setgrent",Token.KEYWORD3); - perlKeywords.add("sethostent",Token.KEYWORD3); - perlKeywords.add("setnetent",Token.KEYWORD3); - perlKeywords.add("setpgrp",Token.KEYWORD3); - perlKeywords.add("setpriority",Token.KEYWORD3); - perlKeywords.add("setprotoent",Token.KEYWORD3); - perlKeywords.add("setpwent",Token.KEYWORD3); - perlKeywords.add("setsockopt",Token.KEYWORD3); - perlKeywords.add("shift",Token.KEYWORD3); - perlKeywords.add("shmctl",Token.KEYWORD3); - perlKeywords.add("shmget",Token.KEYWORD3); - perlKeywords.add("shmread",Token.KEYWORD3); - perlKeywords.add("shmwrite",Token.KEYWORD3); - perlKeywords.add("shutdown",Token.KEYWORD3); - perlKeywords.add("sin",Token.KEYWORD3); - perlKeywords.add("sleep",Token.KEYWORD3); - perlKeywords.add("socket",Token.KEYWORD3); - perlKeywords.add("socketpair",Token.KEYWORD3); - perlKeywords.add("sort",Token.KEYWORD3); - perlKeywords.add("splice",Token.KEYWORD3); - perlKeywords.add("split",Token.KEYWORD3); - perlKeywords.add("sprintf",Token.KEYWORD3); - perlKeywords.add("sqrt",Token.KEYWORD3); - perlKeywords.add("srand",Token.KEYWORD3); - perlKeywords.add("stat",Token.KEYWORD3); - perlKeywords.add("study",Token.KEYWORD3); - perlKeywords.add("substr",Token.KEYWORD3); - perlKeywords.add("symlink",Token.KEYWORD3); - perlKeywords.add("syscall",Token.KEYWORD3); - perlKeywords.add("sysopen",Token.KEYWORD3); - perlKeywords.add("sysread",Token.KEYWORD3); - perlKeywords.add("syswrite",Token.KEYWORD3); - perlKeywords.add("telldir",Token.KEYWORD3); - perlKeywords.add("tell",Token.KEYWORD3); - perlKeywords.add("tie",Token.KEYWORD3); - perlKeywords.add("tied",Token.KEYWORD3); - perlKeywords.add("time",Token.KEYWORD3); - perlKeywords.add("times",Token.KEYWORD3); - perlKeywords.add("truncate",Token.KEYWORD3); - perlKeywords.add("uc",Token.KEYWORD3); - perlKeywords.add("ucfirst",Token.KEYWORD3); - perlKeywords.add("umask",Token.KEYWORD3); - perlKeywords.add("undef",Token.KEYWORD3); - perlKeywords.add("unlink",Token.KEYWORD3); - perlKeywords.add("unpack",Token.KEYWORD3); - perlKeywords.add("unshift",Token.KEYWORD3); - perlKeywords.add("untie",Token.KEYWORD3); - perlKeywords.add("utime",Token.KEYWORD3); - perlKeywords.add("values",Token.KEYWORD3); - perlKeywords.add("vec",Token.KEYWORD3); - perlKeywords.add("wait",Token.KEYWORD3); - perlKeywords.add("waitpid",Token.KEYWORD3); - perlKeywords.add("wantarray",Token.KEYWORD3); - perlKeywords.add("warn",Token.KEYWORD3); - perlKeywords.add("write",Token.KEYWORD3); - - perlKeywords.add("m",S_ONE); - perlKeywords.add("q",S_ONE); - perlKeywords.add("qq",S_ONE); - perlKeywords.add("qw",S_ONE); - perlKeywords.add("qx",S_ONE); - perlKeywords.add("s",S_TWO); - perlKeywords.add("tr",S_TWO); - perlKeywords.add("y",S_TWO); - } - return perlKeywords; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PropsTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PropsTokenMarker.java deleted file mode 100644 index e4b4e3782..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PropsTokenMarker.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Java properties/DOS INI token marker. - * - * @author Slava Pestov - * @version $Id: PropsTokenMarker.java,v 1.9 1999/12/13 03:40:30 sp Exp $ - */ -public class PropsTokenMarker extends TokenMarker -{ - public static final byte VALUE = Token.INTERNAL_FIRST; - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - int lastOffset = offset; - int length = line.count + offset; -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - switch(token) - { - case Token.NULL: - switch(array[i]) - { - case '#': case ';': - if(i == offset) - { - addToken(line.count,Token.COMMENT1); - lastOffset = length; - break loop; - } - break; - case '[': - if(i == offset) - { - addToken(i - lastOffset,token); - token = Token.KEYWORD2; - lastOffset = i; - } - break; - case '=': - addToken(i - lastOffset,Token.KEYWORD1); - token = VALUE; - lastOffset = i; - break; - } - break; - case Token.KEYWORD2: - if(array[i] == ']') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = i1; - } - break; - case VALUE: - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - if(lastOffset != length) - addToken(length - lastOffset,Token.NULL); - return Token.NULL; - } - - public boolean supportsMultilineTokens() - { - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PythonTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PythonTokenMarker.java deleted file mode 100644 index 074be82cc..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PythonTokenMarker.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Python token marker. - * - * @author Jonathan Revusky - * @version $Id: PythonTokenMarker.java,v 1.3 1999/12/14 04:20:35 sp Exp $ - */ -public class PythonTokenMarker extends TokenMarker -{ - private static final byte TRIPLEQUOTE1 = Token.INTERNAL_FIRST; - private static final byte TRIPLEQUOTE2 = Token.INTERNAL_LAST; - - public PythonTokenMarker() - { - this.keywords = getKeywords(); - } - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - lastOffset = offset; - lastKeyword = offset; - int length = line.count + offset; - boolean backslash = false; - -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case '#': - if(backslash) - backslash = false; - else - { - doKeyword(line,i,c); - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = lastKeyword = length; - break loop; - } - break; - case '"': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - if(SyntaxUtilities.regionMatches(false, - line,i1,"\"\"")) - { - token = TRIPLEQUOTE1; - } - else - { - token = Token.LITERAL1; - } - lastOffset = lastKeyword = i; - } - break; - case '\'': - doKeyword(line,i,c); - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - if(SyntaxUtilities.regionMatches(false, - line,i1,"''")) - { - token = TRIPLEQUOTE2; - } - else - { - token = Token.LITERAL2; - } - lastOffset = lastKeyword = i; - } - break; - default: - backslash = false; - if(!Character.isLetterOrDigit(c) - && c != '_') - doKeyword(line,i,c); - break; - } - break; - case Token.LITERAL1: - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,token); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i1; - } - break; - case TRIPLEQUOTE1: - if(backslash) - backslash = false; - else if(SyntaxUtilities.regionMatches(false, - line,i,"\"\"\"")) - { - addToken((i+=4) - lastOffset, - Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i; - } - break; - case TRIPLEQUOTE2: - if(backslash) - backslash = false; - else if(SyntaxUtilities.regionMatches(false, - line,i,"'''")) - { - addToken((i+=4) - lastOffset, - Token.LITERAL1); - token = Token.NULL; - lastOffset = lastKeyword = i; - } - break; - default: - throw new InternalError("Invalid state: " - + token); - } - } - - switch(token) - { - case TRIPLEQUOTE1: - case TRIPLEQUOTE2: - addToken(length - lastOffset,Token.LITERAL1); - break; - case Token.NULL: - doKeyword(line,length,'\0'); - default: - addToken(length - lastOffset,token); - break; - } - - return token; - } - - public static KeywordMap getKeywords() - { - if (pyKeywords == null) - { - pyKeywords = new KeywordMap(false); - pyKeywords.add("and",Token.KEYWORD3); - pyKeywords.add("not",Token.KEYWORD3); - pyKeywords.add("or",Token.KEYWORD3); - pyKeywords.add("if",Token.KEYWORD1); - pyKeywords.add("for",Token.KEYWORD1); - pyKeywords.add("assert",Token.KEYWORD1); - pyKeywords.add("break",Token.KEYWORD1); - pyKeywords.add("continue",Token.KEYWORD1); - pyKeywords.add("elif",Token.KEYWORD1); - pyKeywords.add("else",Token.KEYWORD1); - pyKeywords.add("except",Token.KEYWORD1); - pyKeywords.add("exec",Token.KEYWORD1); - pyKeywords.add("finally",Token.KEYWORD1); - pyKeywords.add("raise",Token.KEYWORD1); - pyKeywords.add("return",Token.KEYWORD1); - pyKeywords.add("try",Token.KEYWORD1); - pyKeywords.add("while",Token.KEYWORD1); - pyKeywords.add("def",Token.KEYWORD2); - pyKeywords.add("class",Token.KEYWORD2); - pyKeywords.add("del",Token.KEYWORD2); - pyKeywords.add("from",Token.KEYWORD2); - pyKeywords.add("global",Token.KEYWORD2); - pyKeywords.add("import",Token.KEYWORD2); - pyKeywords.add("in",Token.KEYWORD2); - pyKeywords.add("is",Token.KEYWORD2); - pyKeywords.add("lambda",Token.KEYWORD2); - pyKeywords.add("pass",Token.KEYWORD2); - pyKeywords.add("print",Token.KEYWORD2); - } - return pyKeywords; - } - - // private members - private static KeywordMap pyKeywords; - - private KeywordMap keywords; - private int lastOffset; - private int lastKeyword; - - private boolean doKeyword(Segment line, int i, char c) - { - int i1 = i+1; - - int len = i - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = i; - } - lastKeyword = i1; - return false; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/README.txt b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/README.txt deleted file mode 100755 index 07a825cd7..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/README.txt +++ /dev/null @@ -1,46 +0,0 @@ -OLDSYNTAX PACKAGE README - -I am placing the jEdit 2.2.1 syntax highlighting package in the public -domain. This means it can be integrated into commercial programs, etc. - -This package requires at least Java 1.1 and Swing 1.1. Syntax -highlighting for the following file types is supported: - -- C++, C -- CORBA IDL -- Eiffel -- HTML -- Java -- Java properties -- JavaScript -- MS-DOS INI -- MS-DOS batch files -- Makefile -- PHP -- Perl -- Python -- TeX -- Transact-SQL -- Unix patch/diff -- Unix shell script -- XML - -This package is undocumented; read the source (start by taking a look at -JEditTextArea.java) to find out how to use it; it's really simple. Feel -free to e-mail questions, queries, etc. to me, but keep in mind that -this code is very old and I no longer maintain it. So if you find a bug, -don't bother me about it; fix it yourself. - -* Copyright - -The jEdit 2.2.1 syntax highlighting package contains code that is -Copyright 1998-1999 Slava Pestov, Artur Biesiadowski, Clancy Malcolm, -Jonathan Revusky, Juha Lindfors and Mike Dillon. - -You may use and modify this package for any purpose. Redistribution is -permitted, in both source and binary form, provided that this notice -remains intact in all source distributions of this package. - --- Slava Pestov -25 September 2000 - diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SQLTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SQLTokenMarker.java deleted file mode 100644 index ac4bf01e7..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SQLTokenMarker.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * SQL token marker. - * - * @author mike dillon - * @version $Id: SQLTokenMarker.java,v 1.6 1999/04/19 05:38:20 sp Exp $ - */ -public class SQLTokenMarker extends TokenMarker -{ - private int offset, lastOffset, lastKeyword, length; - - // public members - public SQLTokenMarker(KeywordMap k) - { - this(k, false); - } - - public SQLTokenMarker(KeywordMap k, boolean tsql) - { - keywords = k; - isTSQL = tsql; - } - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - offset = lastOffset = lastKeyword = line.offset; - length = line.count + offset; - -loop: - for(int i = offset; i < length; i++) - { - switch(line.array[i]) - { - case '*': - if(token == Token.COMMENT1 && length - i >= 1 && line.array[i+1] == '/') - { - token = Token.NULL; - i++; - addToken((i + 1) - lastOffset,Token.COMMENT1); - lastOffset = i + 1; - } - else if (token == Token.NULL) - { - searchBack(line, i); - addToken(1,Token.OPERATOR); - lastOffset = i + 1; - } - break; - case '[': - if(token == Token.NULL) - { - searchBack(line, i); - token = Token.LITERAL1; - literalChar = '['; - lastOffset = i; - } - break; - case ']': - if(token == Token.LITERAL1 && literalChar == '[') - { - token = Token.NULL; - literalChar = 0; - addToken((i + 1) - lastOffset,Token.LITERAL1); - lastOffset = i + 1; - } - break; - case '.': case ',': case '(': case ')': - if (token == Token.NULL) { - searchBack(line, i); - addToken(1, Token.NULL); - lastOffset = i + 1; - } - break; - case '+': case '%': case '&': case '|': case '^': - case '~': case '<': case '>': case '=': - if (token == Token.NULL) { - searchBack(line, i); - addToken(1,Token.OPERATOR); - lastOffset = i + 1; - } - break; - case ' ': case '\t': - if (token == Token.NULL) { - searchBack(line, i, false); - } - break; - case ':': - if(token == Token.NULL) - { - addToken((i+1) - lastOffset,Token.LABEL); - lastOffset = i + 1; - } - break; - case '/': - if(token == Token.NULL) - { - if (length - i >= 2 && line.array[i + 1] == '*') - { - searchBack(line, i); - token = Token.COMMENT1; - lastOffset = i; - i++; - } - else - { - searchBack(line, i); - addToken(1,Token.OPERATOR); - lastOffset = i + 1; - } - } - break; - case '-': - if(token == Token.NULL) - { - if (length - i >= 2 && line.array[i+1] == '-') - { - searchBack(line, i); - addToken(length - i,Token.COMMENT1); - lastOffset = length; - break loop; - } - else - { - searchBack(line, i); - addToken(1,Token.OPERATOR); - lastOffset = i + 1; - } - } - break; - case '!': - if(isTSQL && token == Token.NULL && length - i >= 2 && - (line.array[i+1] == '=' || line.array[i+1] == '<' || line.array[i+1] == '>')) - { - searchBack(line, i); - addToken(1,Token.OPERATOR); - lastOffset = i + 1; - } - break; - case '"': case '\'': - if(token == Token.NULL) - { - token = Token.LITERAL1; - literalChar = line.array[i]; - addToken(i - lastOffset,Token.NULL); - lastOffset = i; - } - else if(token == Token.LITERAL1 && literalChar == line.array[i]) - { - token = Token.NULL; - literalChar = 0; - addToken((i + 1) - lastOffset,Token.LITERAL1); - lastOffset = i + 1; - } - break; - default: - break; - } - } - if(token == Token.NULL) - searchBack(line, length, false); - if(lastOffset != length) - addToken(length - lastOffset,token); - return token; - } - - // protected members - protected boolean isTSQL = false; - - // private members - private KeywordMap keywords; - private char literalChar = 0; - - private void searchBack(Segment line, int pos) - { - searchBack(line, pos, true); - } - - private void searchBack(Segment line, int pos, boolean padNull) - { - int len = pos - lastKeyword; - byte id = keywords.lookup(line,lastKeyword,len); - if(id != Token.NULL) - { - if(lastKeyword != lastOffset) - addToken(lastKeyword - lastOffset,Token.NULL); - addToken(len,id); - lastOffset = pos; - } - lastKeyword = pos + 1; - if (padNull && lastOffset < pos) - addToken(pos - lastOffset, Token.NULL); - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/ShellScriptTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/ShellScriptTokenMarker.java deleted file mode 100644 index 5b3388d40..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/ShellScriptTokenMarker.java +++ /dev/null @@ -1,260 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * Shell script token marker. - * - * @author Slava Pestov - * @version $Id: ShellScriptTokenMarker.java,v 1.18 1999/12/13 03:40:30 sp Exp $ - */ -public class ShellScriptTokenMarker extends TokenMarker -{ - // public members - public static final byte LVARIABLE = Token.INTERNAL_FIRST; - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - byte cmdState = 0; // 0 = space before command, 1 = inside - // command, 2 = after command - int offset = line.offset; - int lastOffset = offset; - int length = line.count + offset; - - if(token == Token.LITERAL1 && lineIndex != 0 - && lineInfo[lineIndex - 1].obj != null) - { - String str = (String)lineInfo[lineIndex - 1].obj; - if(str != null && str.length() == line.count - && SyntaxUtilities.regionMatches(false,line, - offset,str)) - { - addToken(line.count,Token.LITERAL1); - return Token.NULL; - } - else - { - addToken(line.count,Token.LITERAL1); - lineInfo[lineIndex].obj = str; - return Token.LITERAL1; - } - } - - boolean backslash = false; -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - - if(c == '\\') - { - backslash = !backslash; - continue; - } - - switch(token) - { - case Token.NULL: - switch(c) - { - case ' ': case '\t': case '(': case ')': - backslash = false; - if(cmdState == 1/*insideCmd*/) - { - addToken(i - lastOffset,Token.KEYWORD1); - lastOffset = i; - cmdState = 2; /*afterCmd*/ - } - break; - case '=': - backslash = false; - if(cmdState == 1/*insideCmd*/) - { - addToken(i - lastOffset,token); - lastOffset = i; - cmdState = 2; /*afterCmd*/ - } - break; - case '&': case '|': case ';': - if(backslash) - backslash = false; - else - cmdState = 0; /*beforeCmd*/ - break; - case '#': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = length; - break loop; - } - break; - case '$': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - cmdState = 2; /*afterCmd*/ - lastOffset = i; - if(length - i >= 2) - { - switch(array[i1]) - { - case '(': - continue; - case '{': - token = LVARIABLE; - break; - default: - token = Token.KEYWORD2; - break; - } - } - else - token = Token.KEYWORD2; - } - break; - case '"': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL1; - lineInfo[lineIndex].obj = null; - cmdState = 2; /*afterCmd*/ - lastOffset = i; - } - break; - case '\'': - if(backslash) - backslash = false; - else - { - addToken(i - lastOffset,token); - token = Token.LITERAL2; - cmdState = 2; /*afterCmd*/ - lastOffset = i; - } - break; - case '<': - if(backslash) - backslash = false; - else - { - if(length - i > 1 && array[i1] == '<') - { - addToken(i - lastOffset, - token); - token = Token.LITERAL1; - lastOffset = i; - lineInfo[lineIndex].obj = - new String(array,i + 2, - length - (i+2)); - } - } - break; - default: - backslash = false; - if(Character.isLetter(c)) - { - if(cmdState == 0 /*beforeCmd*/) - { - addToken(i - lastOffset,token); - lastOffset = i; - cmdState++; /*insideCmd*/ - } - } - break; - } - break; - case Token.KEYWORD2: - backslash = false; - if(!Character.isLetterOrDigit(c) && c != '_') - { - if(i != offset && array[i-1] == '$') - { - addToken(i1 - lastOffset,token); - lastOffset = i1; - token = Token.NULL; - continue; - } - else - { - addToken(i - lastOffset,token); - lastOffset = i; - token = Token.NULL; - } - } - break; - case Token.LITERAL1: - if(backslash) - backslash = false; - else if(c == '"') - { - addToken(i1 - lastOffset,token); - cmdState = 2; /*afterCmd*/ - lastOffset = i1; - token = Token.NULL; - } - else - backslash = false; - break; - case Token.LITERAL2: - if(backslash) - backslash = false; - else if(c == '\'') - { - addToken(i1 - lastOffset,Token.LITERAL1); - cmdState = 2; /*afterCmd*/ - lastOffset = i1; - token = Token.NULL; - } - else - backslash = false; - break; - case LVARIABLE: - backslash = false; - if(c == '}') - { - addToken(i1 - lastOffset,Token.KEYWORD2); - lastOffset = i1; - token = Token.NULL; - } - break; - default: - throw new InternalError("Invalid state: " + token); - } - } - - switch(token) - { - case Token.NULL: - if(cmdState == 1) - addToken(length - lastOffset,Token.KEYWORD1); - else - addToken(length - lastOffset,token); - break; - case Token.LITERAL2: - addToken(length - lastOffset,Token.LITERAL1); - break; - case Token.KEYWORD2: - addToken(length - lastOffset,token); - token = Token.NULL; - break; - case LVARIABLE: - addToken(length - lastOffset,Token.INVALID); - token = Token.NULL; - break; - default: - addToken(length - lastOffset,token); - break; - } - return token; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxDocument.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxDocument.java deleted file mode 100644 index 2e725a1f8..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxDocument.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * SyntaxDocument.java - Document that can be tokenized - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import javax.swing.event.DocumentEvent; -import javax.swing.text.BadLocationException; -import javax.swing.text.Element; -import javax.swing.text.PlainDocument; -import javax.swing.text.Segment; -import javax.swing.undo.UndoableEdit; - -/** - * A document implementation that can be tokenized by the syntax highlighting - * system. - * - * @author Slava Pestov - * @version $Id: SyntaxDocument.java,v 1.14 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings("serial") -public class SyntaxDocument extends PlainDocument -{ - /** - * Returns the token marker that is to be used to split lines - * of this document up into tokens. May return null if this - * document is not to be colorized. - */ - public TokenMarker getTokenMarker() - { - return tokenMarker; - } - - /** - * Sets the token marker that is to be used to split lines of - * this document up into tokens. May throw an exception if - * this is not supported for this type of document. - * @param tm The new token marker - */ - public void setTokenMarker(TokenMarker tm) - { - tokenMarker = tm; - if(tm == null) - return; - tokenMarker.insertLines(0,getDefaultRootElement() - .getElementCount()); - tokenizeLines(); - } - - /** - * Reparses the document, by passing all lines to the token - * marker. This should be called after the document is first - * loaded. - */ - public void tokenizeLines() - { - tokenizeLines(0,getDefaultRootElement().getElementCount()); - } - - /** - * Reparses the document, by passing the specified lines to the - * token marker. This should be called after a large quantity of - * text is first inserted. - * @param start The first line to parse - * @param len The number of lines, after the first one to parse - */ - public void tokenizeLines(int start, int len) - { - if(tokenMarker == null || !tokenMarker.supportsMultilineTokens()) - return; - - Segment lineSegment = new Segment(); - Element map = getDefaultRootElement(); - - len += start; - - try - { - for(int i = start; i < len; i++) - { - Element lineElement = map.getElement(i); - int lineStart = lineElement.getStartOffset(); - getText(lineStart,lineElement.getEndOffset() - - lineStart - 1,lineSegment); - tokenMarker.markTokens(lineSegment,i); - } - } - catch(BadLocationException bl) - { - bl.printStackTrace(); - } - } - - /** - * Starts a compound edit that can be undone in one operation. - * Subclasses that implement undo should override this method; - * this class has no undo functionality so this method is - * empty. - */ - public void beginCompoundEdit() {} - - /** - * Ends a compound edit that can be undone in one operation. - * Subclasses that implement undo should override this method; - * this class has no undo functionality so this method is - * empty. - */ - public void endCompoundEdit() {} - - /** - * Adds an undoable edit to this document's undo list. The edit - * should be ignored if something is currently being undone. - * @param edit The undoable edit - * - * @since jEdit 2.2pre1 - */ - public void addUndoableEdit(UndoableEdit edit) {} - - // protected members - protected TokenMarker tokenMarker; - - /** - * We overwrite this method to update the token marker - * state immediately so that any event listeners get a - * consistent token marker. - */ - protected void fireInsertUpdate(DocumentEvent evt) - { - if(tokenMarker != null) - { - DocumentEvent.ElementChange ch = evt.getChange( - getDefaultRootElement()); - if(ch != null) - { - tokenMarker.insertLines(ch.getIndex() + 1, - ch.getChildrenAdded().length - - ch.getChildrenRemoved().length); - } - } - - super.fireInsertUpdate(evt); - } - - /** - * We overwrite this method to update the token marker - * state immediately so that any event listeners get a - * consistent token marker. - */ - protected void fireRemoveUpdate(DocumentEvent evt) - { - if(tokenMarker != null) - { - DocumentEvent.ElementChange ch = evt.getChange( - getDefaultRootElement()); - if(ch != null) - { - tokenMarker.deleteLines(ch.getIndex() + 1, - ch.getChildrenRemoved().length - - ch.getChildrenAdded().length); - } - } - - super.fireRemoveUpdate(evt); - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxStyle.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxStyle.java deleted file mode 100644 index ad91ab95e..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxStyle.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * SyntaxStyle.java - A simple text style class - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Toolkit; - -/** - * A simple text style class. It can specify the color, italic flag, - * and bold flag of a run of text. - * @author Slava Pestov - * @version $Id: SyntaxStyle.java,v 1.6 1999/12/13 03:40:30 sp Exp $ - */ -public class SyntaxStyle -{ - /** - * Creates a new SyntaxStyle. - * @param color The text color - * @param italic True if the text should be italics - * @param bold True if the text should be bold - */ - public SyntaxStyle(Color color, boolean italic, boolean bold) - { - this.color = color; - this.italic = italic; - this.bold = bold; - } - - /** - * Returns the color specified in this style. - */ - public Color getColor() - { - return color; - } - - /** - * Returns true if no font styles are enabled. - */ - public boolean isPlain() - { - return !(bold || italic); - } - - /** - * Returns true if italics is enabled for this style. - */ - public boolean isItalic() - { - return italic; - } - - /** - * Returns true if boldface is enabled for this style. - */ - public boolean isBold() - { - return bold; - } - - /** - * Returns the specified font, but with the style's bold and - * italic flags applied. - */ - public Font getStyledFont(Font font) - { - if(font == null) - throw new NullPointerException("font param must not" - + " be null"); - if(font.equals(lastFont)) - return lastStyledFont; - lastFont = font; - lastStyledFont = new Font(font.getFamily(), - (bold ? Font.BOLD : 0) - | (italic ? Font.ITALIC : 0), - font.getSize()); - return lastStyledFont; - } - - /** - * Returns the font metrics for the styled font. - */ - @SuppressWarnings("deprecation") - public FontMetrics getFontMetrics(Font font) - { - if(font == null) - throw new NullPointerException("font param must not" - + " be null"); - if(font.equals(lastFont) && fontMetrics != null) - return fontMetrics; - lastFont = font; - lastStyledFont = new Font(font.getFamily(), - (bold ? Font.BOLD : 0) - | (italic ? Font.ITALIC : 0), - font.getSize()); - fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics( - lastStyledFont); - return fontMetrics; - } - - /** - * Sets the foreground color and font of the specified graphics - * context to that specified in this style. - * @param gfx The graphics context - * @param font The font to add the styles to - */ - public void setGraphicsFlags(Graphics gfx, Font font) - { - Font _font = getStyledFont(font); - gfx.setFont(_font); - gfx.setColor(color); - } - - /** - * Returns a string representation of this object. - */ - public String toString() - { - return getClass().getName() + "[color=" + color + - (italic ? ",italic" : "") + - (bold ? ",bold" : "") + "]"; - } - - // private members - private Color color; - private boolean italic; - private boolean bold; - private Font lastFont; - private Font lastStyledFont; - private FontMetrics fontMetrics; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxUtilities.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxUtilities.java deleted file mode 100644 index 23bd9936f..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/SyntaxUtilities.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * SyntaxUtilities.java - Utility functions used by syntax colorizing - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; - -import javax.swing.text.Segment; -import javax.swing.text.TabExpander; -import javax.swing.text.Utilities; - -/** - * Class with several utility functions used by jEdit's syntax colorizing - * subsystem. - * - * @author Slava Pestov - * @version $Id: SyntaxUtilities.java,v 1.9 1999/12/13 03:40:30 sp Exp $ - */ -public class SyntaxUtilities -{ - /** - * Checks if a subregion of a Segment is equal to a - * string. - * @param ignoreCase True if case should be ignored, false otherwise - * @param text The segment - * @param offset The offset into the segment - * @param match The string to match - */ - public static boolean regionMatches(boolean ignoreCase, Segment text, - int offset, String match) - { - int length = offset + match.length(); - char[] textArray = text.array; - if(length > text.offset + text.count) - return false; - for(int i = offset, j = 0; i < length; i++, j++) - { - char c1 = textArray[i]; - char c2 = match.charAt(j); - if(ignoreCase) - { - c1 = Character.toUpperCase(c1); - c2 = Character.toUpperCase(c2); - } - if(c1 != c2) - return false; - } - return true; - } - - /** - * Checks if a subregion of a Segment is equal to a - * character array. - * @param ignoreCase True if case should be ignored, false otherwise - * @param text The segment - * @param offset The offset into the segment - * @param match The character array to match - */ - public static boolean regionMatches(boolean ignoreCase, Segment text, - int offset, char[] match) - { - int length = offset + match.length; - char[] textArray = text.array; - if(length > text.offset + text.count) - return false; - for(int i = offset, j = 0; i < length; i++, j++) - { - char c1 = textArray[i]; - char c2 = match[j]; - if(ignoreCase) - { - c1 = Character.toUpperCase(c1); - c2 = Character.toUpperCase(c2); - } - if(c1 != c2) - return false; - } - return true; - } - - /** - * Returns the default style table. This can be passed to the - * setStyles() method of SyntaxDocument - * to use the default syntax styles. - */ - public static SyntaxStyle[] getDefaultSyntaxStyles() - { - SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT]; - - styles[Token.COMMENT1] = new SyntaxStyle(Color.green,true,false);//Color.black,true,false); - styles[Token.COMMENT2] = new SyntaxStyle(Color.blue,true,false);//new Color(0x990033),true,false); - styles[Token.KEYWORD1] = new SyntaxStyle(Color.black,false,true); - styles[Token.KEYWORD2] = new SyntaxStyle(Color.magenta,false,false); - styles[Token.KEYWORD3] = new SyntaxStyle(new Color(0x009600),false,false); - styles[Token.LITERAL1] = new SyntaxStyle(new Color(0x650099),false,false); - styles[Token.LITERAL2] = new SyntaxStyle(Color.blue,false,false);//new Color(0x650099),false,true); - //styles[Token.LITERAL3] = new SyntaxStyle(new Color(0x650099),false,false); - styles[Token.LABEL] = new SyntaxStyle(new Color(0x990033),false,true); - styles[Token.OPERATOR] = new SyntaxStyle(Color.black,false,true); - styles[Token.INVALID] = new SyntaxStyle(Color.red,false,true); - - return styles; - } - - /** - * Paints the specified line onto the graphics context. Note that this - * method munges the offset and count values of the segment. - * @param line The line segment - * @param tokens The token list for the line - * @param styles The syntax style list - * @param expander The tab expander used to determine tab stops. May - * be null - * @param gfx The graphics context - * @param x The x co-ordinate - * @param y The y co-ordinate - * @return The x co-ordinate, plus the width of the painted string - */ - public static int paintSyntaxLine(Segment line, Token tokens, - SyntaxStyle[] styles, TabExpander expander, Graphics gfx, - int x, int y) - { - Font defaultFont = gfx.getFont(); - Color defaultColor = gfx.getColor(); - - int offset = 0; - for(;;) - { - byte id = tokens.id; - if(id == Token.END) - break; - - int length = tokens.length; - if(id == Token.NULL) - { - if(!defaultColor.equals(gfx.getColor())) - gfx.setColor(defaultColor); - if(!defaultFont.equals(gfx.getFont())) - gfx.setFont(defaultFont); - } - else - styles[id].setGraphicsFlags(gfx,defaultFont); - - line.count = length; - x = Utilities.drawTabbedText(line,x,y,gfx,expander,0); - line.offset += length; - offset += length; - - tokens = tokens.next; - } - - return x; - } - - // private members - private SyntaxUtilities() {} -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TSQLTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TSQLTokenMarker.java deleted file mode 100644 index 0e83df5e0..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TSQLTokenMarker.java +++ /dev/null @@ -1,960 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; - -/** - * Transact-SQL token marker. - * - * @author mike dillon - * @version $Id: TSQLTokenMarker.java,v 1.9 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings({}) -public class TSQLTokenMarker extends SQLTokenMarker -{ - // public members - public TSQLTokenMarker() - { - super(getKeywordMap(), true); - } - - public static KeywordMap getKeywordMap() - { - if (tsqlKeywords == null) { - tsqlKeywords = new KeywordMap(true); - addKeywords(); - addDataTypes(); - addSystemFunctions(); - addOperators(); - addSystemStoredProcedures(); - addSystemTables(); - } - return tsqlKeywords; - } - - private static void addKeywords() - { - tsqlKeywords.add("ADD",Token.KEYWORD1); - tsqlKeywords.add("ALTER",Token.KEYWORD1); - tsqlKeywords.add("ANSI_NULLS",Token.KEYWORD1); - tsqlKeywords.add("AS",Token.KEYWORD1); - tsqlKeywords.add("ASC",Token.KEYWORD1); - tsqlKeywords.add("AUTHORIZATION",Token.KEYWORD1); - tsqlKeywords.add("BACKUP",Token.KEYWORD1); - tsqlKeywords.add("BEGIN",Token.KEYWORD1); - tsqlKeywords.add("BREAK",Token.KEYWORD1); - tsqlKeywords.add("BROWSE",Token.KEYWORD1); - tsqlKeywords.add("BULK",Token.KEYWORD1); - tsqlKeywords.add("BY",Token.KEYWORD1); - tsqlKeywords.add("CASCADE",Token.KEYWORD1); - tsqlKeywords.add("CHECK",Token.KEYWORD1); - tsqlKeywords.add("CHECKPOINT",Token.KEYWORD1); - tsqlKeywords.add("CLOSE",Token.KEYWORD1); - tsqlKeywords.add("CLUSTERED",Token.KEYWORD1); - tsqlKeywords.add("COLUMN",Token.KEYWORD1); - tsqlKeywords.add("COMMIT",Token.KEYWORD1); - tsqlKeywords.add("COMMITTED",Token.KEYWORD1); - tsqlKeywords.add("COMPUTE",Token.KEYWORD1); - tsqlKeywords.add("CONFIRM",Token.KEYWORD1); - tsqlKeywords.add("CONSTRAINT",Token.KEYWORD1); - tsqlKeywords.add("CONTAINS",Token.KEYWORD1); - tsqlKeywords.add("CONTAINSTABLE",Token.KEYWORD1); - tsqlKeywords.add("CONTINUE",Token.KEYWORD1); - tsqlKeywords.add("CONTROLROW",Token.KEYWORD1); - tsqlKeywords.add("CREATE",Token.KEYWORD1); - tsqlKeywords.add("CURRENT",Token.KEYWORD1); - tsqlKeywords.add("CURRENT_DATE",Token.KEYWORD1); - tsqlKeywords.add("CURRENT_TIME",Token.KEYWORD1); - tsqlKeywords.add("CURSOR",Token.KEYWORD1); - tsqlKeywords.add("DATABASE",Token.KEYWORD1); - tsqlKeywords.add("DBCC",Token.KEYWORD1); - tsqlKeywords.add("DEALLOCATE",Token.KEYWORD1); - tsqlKeywords.add("DECLARE",Token.KEYWORD1); - tsqlKeywords.add("DEFAULT",Token.KEYWORD1); - tsqlKeywords.add("DELETE",Token.KEYWORD1); - tsqlKeywords.add("DENY",Token.KEYWORD1); - tsqlKeywords.add("DESC",Token.KEYWORD1); - tsqlKeywords.add("DISK",Token.KEYWORD1); - tsqlKeywords.add("DISTINCT",Token.KEYWORD1); - tsqlKeywords.add("DISTRIBUTED",Token.KEYWORD1); - tsqlKeywords.add("DOUBLE",Token.KEYWORD1); - tsqlKeywords.add("DROP",Token.KEYWORD1); - tsqlKeywords.add("DUMMY",Token.KEYWORD1); - tsqlKeywords.add("DUMP",Token.KEYWORD1); - tsqlKeywords.add("ELSE",Token.KEYWORD1); - tsqlKeywords.add("END",Token.KEYWORD1); - tsqlKeywords.add("ERRLVL",Token.KEYWORD1); - tsqlKeywords.add("ERROREXIT",Token.KEYWORD1); - tsqlKeywords.add("ESCAPE",Token.KEYWORD1); - tsqlKeywords.add("EXCEPT",Token.KEYWORD1); - tsqlKeywords.add("EXEC",Token.KEYWORD1); - tsqlKeywords.add("EXECUTE",Token.KEYWORD1); - tsqlKeywords.add("EXIT",Token.KEYWORD1); - tsqlKeywords.add("FETCH",Token.KEYWORD1); - tsqlKeywords.add("FILE",Token.KEYWORD1); - tsqlKeywords.add("FILLFACTOR",Token.KEYWORD1); - tsqlKeywords.add("FLOPPY",Token.KEYWORD1); - tsqlKeywords.add("FOR",Token.KEYWORD1); - tsqlKeywords.add("FOREIGN",Token.KEYWORD1); - tsqlKeywords.add("FREETEXT",Token.KEYWORD1); - tsqlKeywords.add("FREETEXTTABLE",Token.KEYWORD1); - tsqlKeywords.add("FROM",Token.KEYWORD1); - tsqlKeywords.add("FULL",Token.KEYWORD1); - tsqlKeywords.add("GOTO",Token.KEYWORD1); - tsqlKeywords.add("GRANT",Token.KEYWORD1); - tsqlKeywords.add("GROUP",Token.KEYWORD1); - tsqlKeywords.add("HAVING",Token.KEYWORD1); - tsqlKeywords.add("HOLDLOCK",Token.KEYWORD1); - tsqlKeywords.add("IDENTITY_INSERT",Token.KEYWORD1); - tsqlKeywords.add("IDENTITYCOL",Token.KEYWORD1); - tsqlKeywords.add("ID",Token.KEYWORD1); - tsqlKeywords.add("IF",Token.KEYWORD1); - tsqlKeywords.add("INDEX",Token.KEYWORD1); - tsqlKeywords.add("INNER",Token.KEYWORD1); - tsqlKeywords.add("INSERT",Token.KEYWORD1); - tsqlKeywords.add("INTO",Token.KEYWORD1); - tsqlKeywords.add("IS",Token.KEYWORD1); - tsqlKeywords.add("ISOLATION",Token.KEYWORD1); - tsqlKeywords.add("KEY",Token.KEYWORD1); - tsqlKeywords.add("KILL",Token.KEYWORD1); - tsqlKeywords.add("LEVEL",Token.KEYWORD1); - tsqlKeywords.add("LINENO",Token.KEYWORD1); - tsqlKeywords.add("LOAD",Token.KEYWORD1); - tsqlKeywords.add("MAX",Token.KEYWORD1); - tsqlKeywords.add("MIN",Token.KEYWORD1); - tsqlKeywords.add("MIRROREXIT",Token.KEYWORD1); - tsqlKeywords.add("NATIONAL",Token.KEYWORD1); - tsqlKeywords.add("NOCHECK",Token.KEYWORD1); - tsqlKeywords.add("NONCLUSTERED",Token.KEYWORD1); - tsqlKeywords.add("OF",Token.KEYWORD1); - tsqlKeywords.add("OFF",Token.KEYWORD1); - tsqlKeywords.add("OFFSETS",Token.KEYWORD1); - tsqlKeywords.add("ON",Token.KEYWORD1); - tsqlKeywords.add("ONCE",Token.KEYWORD1); - tsqlKeywords.add("ONLY",Token.KEYWORD1); - tsqlKeywords.add("OPEN",Token.KEYWORD1); - tsqlKeywords.add("OPENDATASOURCE",Token.KEYWORD1); - tsqlKeywords.add("OPENQUERY",Token.KEYWORD1); - tsqlKeywords.add("OPENROWSET",Token.KEYWORD1); - tsqlKeywords.add("OPTION",Token.KEYWORD1); - tsqlKeywords.add("ORDER",Token.KEYWORD1); - tsqlKeywords.add("OVER",Token.KEYWORD1); - tsqlKeywords.add("PERCENT",Token.KEYWORD1); - tsqlKeywords.add("PERM",Token.KEYWORD1); - tsqlKeywords.add("PERMANENT",Token.KEYWORD1); - tsqlKeywords.add("PIPE",Token.KEYWORD1); - tsqlKeywords.add("PLAN",Token.KEYWORD1); - tsqlKeywords.add("PRECISION",Token.KEYWORD1); - tsqlKeywords.add("PREPARE",Token.KEYWORD1); - tsqlKeywords.add("PRIMARY",Token.KEYWORD1); - tsqlKeywords.add("PRINT",Token.KEYWORD1); - tsqlKeywords.add("PRIVILEGES",Token.KEYWORD1); - tsqlKeywords.add("PROC",Token.KEYWORD1); - tsqlKeywords.add("PROCEDURE",Token.KEYWORD1); - tsqlKeywords.add("PROCESSEXIT",Token.KEYWORD1); - tsqlKeywords.add("PUBLIC",Token.KEYWORD1); - tsqlKeywords.add("QUOTED_IDENTIFIER",Token.KEYWORD1); - tsqlKeywords.add("RAISERROR",Token.KEYWORD1); - tsqlKeywords.add("READ",Token.KEYWORD1); - tsqlKeywords.add("READTEXT",Token.KEYWORD1); - tsqlKeywords.add("RECONFIGURE",Token.KEYWORD1); - tsqlKeywords.add("REFERENCES",Token.KEYWORD1); - tsqlKeywords.add("REPEATABLE",Token.KEYWORD1); - tsqlKeywords.add("REPLICATION",Token.KEYWORD1); - tsqlKeywords.add("RESTORE",Token.KEYWORD1); - tsqlKeywords.add("RESTRICT",Token.KEYWORD1); - tsqlKeywords.add("RETURN",Token.KEYWORD1); - tsqlKeywords.add("REVOKE",Token.KEYWORD1); - tsqlKeywords.add("ROLLBACK",Token.KEYWORD1); - tsqlKeywords.add("ROWGUIDCOL",Token.KEYWORD1); - tsqlKeywords.add("RULE",Token.KEYWORD1); - tsqlKeywords.add("SAVE",Token.KEYWORD1); - tsqlKeywords.add("SCHEMA",Token.KEYWORD1); - tsqlKeywords.add("SELECT",Token.KEYWORD1); - tsqlKeywords.add("SERIALIZABLE",Token.KEYWORD1); - tsqlKeywords.add("SET",Token.KEYWORD1); - tsqlKeywords.add("SETUSER",Token.KEYWORD1); - tsqlKeywords.add("SHUTDOWN",Token.KEYWORD1); - tsqlKeywords.add("STATISTICS",Token.KEYWORD1); - tsqlKeywords.add("TABLE",Token.KEYWORD1); - tsqlKeywords.add("TAPE",Token.KEYWORD1); - tsqlKeywords.add("TEMP",Token.KEYWORD1); - tsqlKeywords.add("TEMPORARY",Token.KEYWORD1); - tsqlKeywords.add("TEXTIMAGE_ON",Token.KEYWORD1); - tsqlKeywords.add("THEN",Token.KEYWORD1); - tsqlKeywords.add("TO",Token.KEYWORD1); - tsqlKeywords.add("TOP",Token.KEYWORD1); - tsqlKeywords.add("TRAN",Token.KEYWORD1); - tsqlKeywords.add("TRANSACTION",Token.KEYWORD1); - tsqlKeywords.add("TRIGGER",Token.KEYWORD1); - tsqlKeywords.add("TRUNCATE",Token.KEYWORD1); - tsqlKeywords.add("TSEQUAL",Token.KEYWORD1); - tsqlKeywords.add("UNCOMMITTED",Token.KEYWORD1); - tsqlKeywords.add("UNION",Token.KEYWORD1); - tsqlKeywords.add("UNIQUE",Token.KEYWORD1); - tsqlKeywords.add("UPDATE",Token.KEYWORD1); - tsqlKeywords.add("UPDATETEXT",Token.KEYWORD1); - tsqlKeywords.add("USE",Token.KEYWORD1); - tsqlKeywords.add("VALUES",Token.KEYWORD1); - tsqlKeywords.add("VARYING",Token.KEYWORD1); - tsqlKeywords.add("VIEW",Token.KEYWORD1); - tsqlKeywords.add("WAITFOR",Token.KEYWORD1); - tsqlKeywords.add("WHEN",Token.KEYWORD1); - tsqlKeywords.add("WHERE",Token.KEYWORD1); - tsqlKeywords.add("WHILE",Token.KEYWORD1); - tsqlKeywords.add("WITH",Token.KEYWORD1); - tsqlKeywords.add("WORK",Token.KEYWORD1); - tsqlKeywords.add("WRITETEXT",Token.KEYWORD1); - } - - private static void addDataTypes() - { - tsqlKeywords.add("binary",Token.KEYWORD1); - tsqlKeywords.add("bit",Token.KEYWORD1); - tsqlKeywords.add("char",Token.KEYWORD1); - tsqlKeywords.add("character",Token.KEYWORD1); - tsqlKeywords.add("datetime",Token.KEYWORD1); - tsqlKeywords.add("decimal",Token.KEYWORD1); - tsqlKeywords.add("float",Token.KEYWORD1); - tsqlKeywords.add("image",Token.KEYWORD1); - tsqlKeywords.add("int",Token.KEYWORD1); - tsqlKeywords.add("integer",Token.KEYWORD1); - tsqlKeywords.add("money",Token.KEYWORD1); - tsqlKeywords.add("name",Token.KEYWORD1); - tsqlKeywords.add("numeric",Token.KEYWORD1); - tsqlKeywords.add("nchar",Token.KEYWORD1); - tsqlKeywords.add("nvarchar",Token.KEYWORD1); - tsqlKeywords.add("ntext",Token.KEYWORD1); - tsqlKeywords.add("real",Token.KEYWORD1); - tsqlKeywords.add("smalldatetime",Token.KEYWORD1); - tsqlKeywords.add("smallint",Token.KEYWORD1); - tsqlKeywords.add("smallmoney",Token.KEYWORD1); - tsqlKeywords.add("text",Token.KEYWORD1); - tsqlKeywords.add("timestamp",Token.KEYWORD1); - tsqlKeywords.add("tinyint",Token.KEYWORD1); - tsqlKeywords.add("uniqueidentifier",Token.KEYWORD1); - tsqlKeywords.add("varbinary",Token.KEYWORD1); - tsqlKeywords.add("varchar",Token.KEYWORD1); - } - - private static void addSystemFunctions() - { - tsqlKeywords.add("@@CONNECTIONS",Token.KEYWORD2); - tsqlKeywords.add("@@CPU_BUSY",Token.KEYWORD2); - tsqlKeywords.add("@@CURSOR_ROWS",Token.KEYWORD2); - tsqlKeywords.add("@@DATEFIRST",Token.KEYWORD2); - tsqlKeywords.add("@@DBTS",Token.KEYWORD2); - tsqlKeywords.add("@@ERROR",Token.KEYWORD2); - tsqlKeywords.add("@@FETCH_STATUS",Token.KEYWORD2); - tsqlKeywords.add("@@IDENTITY",Token.KEYWORD2); - tsqlKeywords.add("@@IDLE",Token.KEYWORD2); - tsqlKeywords.add("@@IO_BUSY",Token.KEYWORD2); - tsqlKeywords.add("@@LANGID",Token.KEYWORD2); - tsqlKeywords.add("@@LANGUAGE",Token.KEYWORD2); - tsqlKeywords.add("@@LOCK_TIMEOUT",Token.KEYWORD2); - tsqlKeywords.add("@@MAX_CONNECTIONS",Token.KEYWORD2); - tsqlKeywords.add("@@MAX_PRECISION",Token.KEYWORD2); - tsqlKeywords.add("@@NESTLEVEL",Token.KEYWORD2); - tsqlKeywords.add("@@OPTIONS",Token.KEYWORD2); - tsqlKeywords.add("@@PACK_RECEIVED",Token.KEYWORD2); - tsqlKeywords.add("@@PACK_SENT",Token.KEYWORD2); - tsqlKeywords.add("@@PACKET_ERRORS",Token.KEYWORD2); - tsqlKeywords.add("@@PROCID",Token.KEYWORD2); - tsqlKeywords.add("@@REMSERVER",Token.KEYWORD2); - tsqlKeywords.add("@@ROWCOUNT",Token.KEYWORD2); - tsqlKeywords.add("@@SERVERNAME",Token.KEYWORD2); - tsqlKeywords.add("@@SERVICENAME",Token.KEYWORD2); - tsqlKeywords.add("@@SPID",Token.KEYWORD2); - tsqlKeywords.add("@@TEXTSIZE",Token.KEYWORD2); - tsqlKeywords.add("@@TIMETICKS",Token.KEYWORD2); - tsqlKeywords.add("@@TOTAL_ERRORS",Token.KEYWORD2); - tsqlKeywords.add("@@TOTAL_READ",Token.KEYWORD2); - tsqlKeywords.add("@@TOTAL_WRITE",Token.KEYWORD2); - tsqlKeywords.add("@@TRANCOUNT",Token.KEYWORD2); - tsqlKeywords.add("@@VERSION",Token.KEYWORD2); - tsqlKeywords.add("ABS",Token.KEYWORD2); - tsqlKeywords.add("ACOS",Token.KEYWORD2); - tsqlKeywords.add("APP_NAME",Token.KEYWORD2); - tsqlKeywords.add("ASCII",Token.KEYWORD2); - tsqlKeywords.add("ASIN",Token.KEYWORD2); - tsqlKeywords.add("ATAN",Token.KEYWORD2); - tsqlKeywords.add("ATN2",Token.KEYWORD2); - tsqlKeywords.add("CASE",Token.KEYWORD2); - tsqlKeywords.add("CAST",Token.KEYWORD2); - tsqlKeywords.add("CEILING",Token.KEYWORD2); -// tsqlKeywords.add("CHAR",Token.KEYWORD2); - tsqlKeywords.add("CHARINDEX",Token.KEYWORD2); - tsqlKeywords.add("COALESCE",Token.KEYWORD2); - tsqlKeywords.add("COL_LENGTH",Token.KEYWORD2); - tsqlKeywords.add("COL_NAME",Token.KEYWORD2); - tsqlKeywords.add("COLUMNPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("CONVERT",Token.KEYWORD2); - tsqlKeywords.add("COS",Token.KEYWORD2); - tsqlKeywords.add("COT",Token.KEYWORD2); - tsqlKeywords.add("CURRENT_TIME",Token.KEYWORD2); - tsqlKeywords.add("CURRENT_DATE",Token.KEYWORD2); - tsqlKeywords.add("CURRENT_TIMESTAMP",Token.KEYWORD2); - tsqlKeywords.add("CURRENT_USER",Token.KEYWORD2); - tsqlKeywords.add("CURSOR_STATUS",Token.KEYWORD2); - tsqlKeywords.add("DATABASEPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("DATALENGTH",Token.KEYWORD2); - tsqlKeywords.add("DATEADD",Token.KEYWORD2); - tsqlKeywords.add("DATEDIFF",Token.KEYWORD2); - tsqlKeywords.add("DATENAME",Token.KEYWORD2); - tsqlKeywords.add("DATEPART",Token.KEYWORD2); - tsqlKeywords.add("DAY",Token.KEYWORD2); - tsqlKeywords.add("DB_ID",Token.KEYWORD2); - tsqlKeywords.add("DB_NAME",Token.KEYWORD2); - tsqlKeywords.add("DEGREES",Token.KEYWORD2); - tsqlKeywords.add("DIFFERENCE",Token.KEYWORD2); - tsqlKeywords.add("EXP",Token.KEYWORD2); - tsqlKeywords.add("FILE_ID",Token.KEYWORD2); - tsqlKeywords.add("FILE_NAME",Token.KEYWORD2); - tsqlKeywords.add("FILEGROUP_ID",Token.KEYWORD2); - tsqlKeywords.add("FILEGROUP_NAME",Token.KEYWORD2); - tsqlKeywords.add("FILEGROUPPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("FILEPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("FLOOR",Token.KEYWORD2); - tsqlKeywords.add("FORMATMESSAGE",Token.KEYWORD2); - tsqlKeywords.add("FULLTEXTCATALOGPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("FULLTEXTSERVICEPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("GETANSINULL",Token.KEYWORD2); - tsqlKeywords.add("GETDATE",Token.KEYWORD2); - tsqlKeywords.add("HOST_ID",Token.KEYWORD2); - tsqlKeywords.add("HOST_NAME",Token.KEYWORD2); - tsqlKeywords.add("IDENT_INCR",Token.KEYWORD2); - tsqlKeywords.add("IDENT_SEED",Token.KEYWORD2); -// tsqlKeywords.add("IDENTITY",Token.KEYWORD2); - tsqlKeywords.add("IDENTITY_INSERT",Token.KEYWORD2); - tsqlKeywords.add("INDEX_COL",Token.KEYWORD2); - tsqlKeywords.add("INDEXPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("IS_MEMBER",Token.KEYWORD2); - tsqlKeywords.add("IS_SRVROLEMEMBER",Token.KEYWORD2); - tsqlKeywords.add("ISDATE",Token.KEYWORD2); - tsqlKeywords.add("ISNULL",Token.KEYWORD2); - tsqlKeywords.add("ISNUMERIC",Token.KEYWORD2); - tsqlKeywords.add("LEFT",Token.KEYWORD2); - tsqlKeywords.add("LEN",Token.KEYWORD2); - tsqlKeywords.add("LOG",Token.KEYWORD2); - tsqlKeywords.add("LOG10",Token.KEYWORD2); - tsqlKeywords.add("LOWER",Token.KEYWORD2); - tsqlKeywords.add("LTRIM",Token.KEYWORD2); - tsqlKeywords.add("MONTH",Token.KEYWORD2); -// tsqlKeywords.add("NCHAR",Token.KEYWORD2); - tsqlKeywords.add("NEWID",Token.KEYWORD2); - tsqlKeywords.add("NULLIF",Token.KEYWORD2); - tsqlKeywords.add("OBJECT_ID",Token.KEYWORD2); - tsqlKeywords.add("OBJECT_NAME",Token.KEYWORD2); - tsqlKeywords.add("OBJECTPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("PARSENAME",Token.KEYWORD2); - tsqlKeywords.add("PATINDEX",Token.KEYWORD2); - tsqlKeywords.add("PERMISSIONS",Token.KEYWORD2); - tsqlKeywords.add("PI",Token.KEYWORD2); - tsqlKeywords.add("POWER",Token.KEYWORD2); - tsqlKeywords.add("QUOTENAME",Token.KEYWORD2); - tsqlKeywords.add("RADIANS",Token.KEYWORD2); - tsqlKeywords.add("RAND",Token.KEYWORD2); - tsqlKeywords.add("REPLACE",Token.KEYWORD2); - tsqlKeywords.add("REPLICATE",Token.KEYWORD2); - tsqlKeywords.add("REVERSE",Token.KEYWORD2); - tsqlKeywords.add("RIGHT",Token.KEYWORD2); - tsqlKeywords.add("ROUND",Token.KEYWORD2); - tsqlKeywords.add("RTRIM",Token.KEYWORD2); - tsqlKeywords.add("SESSION_USER",Token.KEYWORD2); - tsqlKeywords.add("SIGN",Token.KEYWORD2); - tsqlKeywords.add("SIN",Token.KEYWORD2); - tsqlKeywords.add("SOUNDEX",Token.KEYWORD2); - tsqlKeywords.add("SPACE",Token.KEYWORD2); - tsqlKeywords.add("SQRT",Token.KEYWORD2); - tsqlKeywords.add("SQUARE",Token.KEYWORD2); - tsqlKeywords.add("STATS_DATE",Token.KEYWORD2); - tsqlKeywords.add("STR",Token.KEYWORD2); - tsqlKeywords.add("STUFF",Token.KEYWORD2); - tsqlKeywords.add("SUBSTRING",Token.KEYWORD2); - tsqlKeywords.add("SUSER_ID",Token.KEYWORD2); - tsqlKeywords.add("SUSER_NAME",Token.KEYWORD2); - tsqlKeywords.add("SUSER_SID",Token.KEYWORD2); - tsqlKeywords.add("SUSER_SNAME",Token.KEYWORD2); - tsqlKeywords.add("SYSTEM_USER",Token.KEYWORD2); - tsqlKeywords.add("TAN",Token.KEYWORD2); - tsqlKeywords.add("TEXTPTR",Token.KEYWORD2); - tsqlKeywords.add("TEXTVALID",Token.KEYWORD2); - tsqlKeywords.add("TYPEPROPERTY",Token.KEYWORD2); - tsqlKeywords.add("UNICODE",Token.KEYWORD2); - tsqlKeywords.add("UPPER",Token.KEYWORD2); - tsqlKeywords.add("USER_ID",Token.KEYWORD2); - tsqlKeywords.add("USER_NAME",Token.KEYWORD2); - tsqlKeywords.add("USER",Token.KEYWORD2); - tsqlKeywords.add("YEAR",Token.KEYWORD2); - } - - private static void addOperators() - { - tsqlKeywords.add("ALL",Token.KEYWORD1); - tsqlKeywords.add("AND",Token.KEYWORD1); - tsqlKeywords.add("ANY",Token.KEYWORD1); - tsqlKeywords.add("BETWEEN",Token.KEYWORD1); - tsqlKeywords.add("CROSS",Token.KEYWORD1); - tsqlKeywords.add("EXISTS",Token.KEYWORD1); - tsqlKeywords.add("IN",Token.KEYWORD1); - tsqlKeywords.add("INTERSECT",Token.KEYWORD1); - tsqlKeywords.add("JOIN",Token.KEYWORD1); - tsqlKeywords.add("LIKE",Token.KEYWORD1); - tsqlKeywords.add("NOT",Token.KEYWORD1); - tsqlKeywords.add("NULL",Token.KEYWORD1); - tsqlKeywords.add("OR",Token.KEYWORD1); - tsqlKeywords.add("OUTER",Token.KEYWORD1); - tsqlKeywords.add("SOME",Token.KEYWORD1); - } - - private static void addSystemStoredProcedures() - { - tsqlKeywords.add("sp_add_agent_parameter",Token.KEYWORD3); - tsqlKeywords.add("sp_add_agent_profile",Token.KEYWORD3); - tsqlKeywords.add("sp_add_alert",Token.KEYWORD3); - tsqlKeywords.add("sp_add_category",Token.KEYWORD3); - tsqlKeywords.add("sp_add_data_file_recover_suspect_db",Token.KEYWORD3); - tsqlKeywords.add("sp_add_job",Token.KEYWORD3); - tsqlKeywords.add("sp_add_jobschedule",Token.KEYWORD3); - tsqlKeywords.add("sp_add_jobserver",Token.KEYWORD3); - tsqlKeywords.add("sp_add_jobstep",Token.KEYWORD3); - tsqlKeywords.add("sp_add_log_file_recover_suspect_db",Token.KEYWORD3); - tsqlKeywords.add("sp_add_notification",Token.KEYWORD3); - tsqlKeywords.add("sp_add_operator",Token.KEYWORD3); - tsqlKeywords.add("sp_add_targetservergroup",Token.KEYWORD3); - tsqlKeywords.add("sp_add_targetsvrgrp_member",Token.KEYWORD3); - tsqlKeywords.add("sp_addalias",Token.KEYWORD3); - tsqlKeywords.add("sp_addapprole",Token.KEYWORD3); - tsqlKeywords.add("sp_addarticle",Token.KEYWORD3); - tsqlKeywords.add("sp_adddistpublisher",Token.KEYWORD3); - tsqlKeywords.add("sp_adddistributiondb",Token.KEYWORD3); - tsqlKeywords.add("sp_adddistributor",Token.KEYWORD3); - tsqlKeywords.add("sp_addextendedproc",Token.KEYWORD3); - tsqlKeywords.add("sp_addgroup",Token.KEYWORD3); - tsqlKeywords.add("sp_addlinkedserver",Token.KEYWORD3); - tsqlKeywords.add("sp_addlinkedsrvlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_addlinkedsrvlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_addlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergearticle",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergefilter",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergepublication",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergepullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergepullsubscription_agent",Token.KEYWORD3); - tsqlKeywords.add("sp_addmergesubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_addmessage",Token.KEYWORD3); - tsqlKeywords.add("sp_addpublication",Token.KEYWORD3); - tsqlKeywords.add("sp_addpublication_snapshot",Token.KEYWORD3); - tsqlKeywords.add("sp_addpublisher70",Token.KEYWORD3); - tsqlKeywords.add("sp_addpullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_addpullsubscription_agent",Token.KEYWORD3); - tsqlKeywords.add("sp_addremotelogin",Token.KEYWORD3); - tsqlKeywords.add("sp_addrole",Token.KEYWORD3); - tsqlKeywords.add("sp_addrolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_addserver",Token.KEYWORD3); - tsqlKeywords.add("sp_addsrvrolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_addsubscriber",Token.KEYWORD3); - tsqlKeywords.add("sp_addsubscriber_schedule",Token.KEYWORD3); - tsqlKeywords.add("sp_addsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_addsynctriggers",Token.KEYWORD3); - tsqlKeywords.add("sp_addtabletocontents",Token.KEYWORD3); - tsqlKeywords.add("sp_addtask",Token.KEYWORD3); - tsqlKeywords.add("sp_addtype",Token.KEYWORD3); - tsqlKeywords.add("sp_addumpdevice",Token.KEYWORD3); - tsqlKeywords.add("sp_adduser",Token.KEYWORD3); - tsqlKeywords.add("sp_altermessage",Token.KEYWORD3); - tsqlKeywords.add("sp_apply_job_to_targets",Token.KEYWORD3); - tsqlKeywords.add("sp_approlepassword",Token.KEYWORD3); - tsqlKeywords.add("sp_article_validation",Token.KEYWORD3); - tsqlKeywords.add("sp_articlecolumn",Token.KEYWORD3); - tsqlKeywords.add("sp_articlefilter",Token.KEYWORD3); - tsqlKeywords.add("sp_articlesynctranprocs",Token.KEYWORD3); - tsqlKeywords.add("sp_articleview",Token.KEYWORD3); - tsqlKeywords.add("sp_attach_db",Token.KEYWORD3); - tsqlKeywords.add("sp_attach_single_file_db",Token.KEYWORD3); - tsqlKeywords.add("sp_autostats",Token.KEYWORD3); - tsqlKeywords.add("sp_bindefault",Token.KEYWORD3); - tsqlKeywords.add("sp_bindrule",Token.KEYWORD3); - tsqlKeywords.add("sp_bindsession",Token.KEYWORD3); - tsqlKeywords.add("sp_browsereplcmds",Token.KEYWORD3); - tsqlKeywords.add("sp_catalogs",Token.KEYWORD3); - tsqlKeywords.add("sp_certify_removable",Token.KEYWORD3); - tsqlKeywords.add("sp_change_agent_parameter",Token.KEYWORD3); - tsqlKeywords.add("sp_change_agent_profile",Token.KEYWORD3); - tsqlKeywords.add("sp_change_subscription_properties",Token.KEYWORD3); - tsqlKeywords.add("sp_change_users_login",Token.KEYWORD3); - tsqlKeywords.add("sp_changearticle",Token.KEYWORD3); - tsqlKeywords.add("sp_changedbowner",Token.KEYWORD3); - tsqlKeywords.add("sp_changedistpublisher",Token.KEYWORD3); - tsqlKeywords.add("sp_changedistributiondb",Token.KEYWORD3); - tsqlKeywords.add("sp_changedistributor_password",Token.KEYWORD3); - tsqlKeywords.add("sp_changedistributor_property",Token.KEYWORD3); - tsqlKeywords.add("sp_changegroup",Token.KEYWORD3); - tsqlKeywords.add("sp_changemergearticle",Token.KEYWORD3); - tsqlKeywords.add("sp_changemergefilter",Token.KEYWORD3); - tsqlKeywords.add("sp_changemergepublication",Token.KEYWORD3); - tsqlKeywords.add("sp_changemergepullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_changemergesubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_changeobjectowner",Token.KEYWORD3); - tsqlKeywords.add("sp_changepublication",Token.KEYWORD3); - tsqlKeywords.add("sp_changesubscriber",Token.KEYWORD3); - tsqlKeywords.add("sp_changesubscriber_schedule",Token.KEYWORD3); - tsqlKeywords.add("sp_changesubstatus",Token.KEYWORD3); - tsqlKeywords.add("sp_check_for_sync_trigger",Token.KEYWORD3); - tsqlKeywords.add("sp_column_privileges",Token.KEYWORD3); - tsqlKeywords.add("sp_column_privileges_ex",Token.KEYWORD3); - tsqlKeywords.add("sp_columns",Token.KEYWORD3); - tsqlKeywords.add("sp_columns_ex",Token.KEYWORD3); - tsqlKeywords.add("sp_configure",Token.KEYWORD3); - tsqlKeywords.add("sp_create_removable",Token.KEYWORD3); - tsqlKeywords.add("sp_createorphan",Token.KEYWORD3); - tsqlKeywords.add("sp_createstats",Token.KEYWORD3); - tsqlKeywords.add("sp_cursor",Token.KEYWORD3); - tsqlKeywords.add("sp_cursor_list",Token.KEYWORD3); - tsqlKeywords.add("sp_cursorclose",Token.KEYWORD3); - tsqlKeywords.add("sp_cursorexecute",Token.KEYWORD3); - tsqlKeywords.add("sp_cursorfetch",Token.KEYWORD3); - tsqlKeywords.add("sp_cursoropen",Token.KEYWORD3); - tsqlKeywords.add("sp_cursoroption",Token.KEYWORD3); - tsqlKeywords.add("sp_cursorprepare",Token.KEYWORD3); - tsqlKeywords.add("sp_cursorunprepare",Token.KEYWORD3); - tsqlKeywords.add("sp_cycle_errorlog",Token.KEYWORD3); - tsqlKeywords.add("sp_databases",Token.KEYWORD3); - tsqlKeywords.add("sp_datatype_info",Token.KEYWORD3); - tsqlKeywords.add("sp_dbcmptlevel",Token.KEYWORD3); - tsqlKeywords.add("sp_dbfixedrolepermission",Token.KEYWORD3); - tsqlKeywords.add("sp_dboption",Token.KEYWORD3); - tsqlKeywords.add("sp_defaultdb",Token.KEYWORD3); - tsqlKeywords.add("sp_defaultlanguage",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_alert",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_backuphistory",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_category",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_job",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_jobschedule",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_jobserver",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_jobstep",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_notification",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_operator",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_targetserver",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_targetservergroup",Token.KEYWORD3); - tsqlKeywords.add("sp_delete_targetsvrgrp_member",Token.KEYWORD3); - tsqlKeywords.add("sp_deletemergeconflictrow",Token.KEYWORD3); - tsqlKeywords.add("sp_denylogin",Token.KEYWORD3); - tsqlKeywords.add("sp_depends",Token.KEYWORD3); - tsqlKeywords.add("sp_describe_cursor",Token.KEYWORD3); - tsqlKeywords.add("sp_describe_cursor_columns",Token.KEYWORD3); - tsqlKeywords.add("sp_describe_cursor_tables",Token.KEYWORD3); - tsqlKeywords.add("sp_detach_db",Token.KEYWORD3); - tsqlKeywords.add("sp_drop_agent_parameter",Token.KEYWORD3); - tsqlKeywords.add("sp_drop_agent_profile",Token.KEYWORD3); - tsqlKeywords.add("sp_dropalias",Token.KEYWORD3); - tsqlKeywords.add("sp_dropapprole",Token.KEYWORD3); - tsqlKeywords.add("sp_droparticle",Token.KEYWORD3); - tsqlKeywords.add("sp_dropdevice",Token.KEYWORD3); - tsqlKeywords.add("sp_dropdistpublisher",Token.KEYWORD3); - tsqlKeywords.add("sp_dropdistributiondb",Token.KEYWORD3); - tsqlKeywords.add("sp_dropdistributor",Token.KEYWORD3); - tsqlKeywords.add("sp_dropextendedproc",Token.KEYWORD3); - tsqlKeywords.add("sp_dropgroup",Token.KEYWORD3); - tsqlKeywords.add("sp_droplinkedsrvlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_droplinkedsrvlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_droplogin",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmergearticle",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmergefilter",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmergepublication",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmergepullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmergesubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_dropmessage",Token.KEYWORD3); - tsqlKeywords.add("sp_droporphans",Token.KEYWORD3); - tsqlKeywords.add("sp_droppublication",Token.KEYWORD3); - tsqlKeywords.add("sp_droppullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_dropremotelogin",Token.KEYWORD3); - tsqlKeywords.add("sp_droprole",Token.KEYWORD3); - tsqlKeywords.add("sp_droprolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_dropserver",Token.KEYWORD3); - tsqlKeywords.add("sp_dropsrvrolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_dropsubscriber",Token.KEYWORD3); - tsqlKeywords.add("sp_dropsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_droptask",Token.KEYWORD3); - tsqlKeywords.add("sp_droptype",Token.KEYWORD3); - tsqlKeywords.add("sp_dropuser",Token.KEYWORD3); - tsqlKeywords.add("sp_dropwebtask",Token.KEYWORD3); - tsqlKeywords.add("sp_dsninfo",Token.KEYWORD3); - tsqlKeywords.add("sp_dumpparamcmd",Token.KEYWORD3); - tsqlKeywords.add("sp_enumcodepages",Token.KEYWORD3); - tsqlKeywords.add("sp_enumcustomresolvers",Token.KEYWORD3); - tsqlKeywords.add("sp_enumdsn",Token.KEYWORD3); - tsqlKeywords.add("sp_enumfullsubscribers",Token.KEYWORD3); - tsqlKeywords.add("sp_execute",Token.KEYWORD3); - tsqlKeywords.add("sp_executesql",Token.KEYWORD3); - tsqlKeywords.add("sp_expired_subscription_cleanup",Token.KEYWORD3); - tsqlKeywords.add("sp_fkeys",Token.KEYWORD3); - tsqlKeywords.add("sp_foreignkeys",Token.KEYWORD3); - tsqlKeywords.add("sp_fulltext_catalog",Token.KEYWORD3); - tsqlKeywords.add("sp_fulltext_column",Token.KEYWORD3); - tsqlKeywords.add("sp_fulltext_database",Token.KEYWORD3); - tsqlKeywords.add("sp_fulltext_service",Token.KEYWORD3); - tsqlKeywords.add("sp_fulltext_table",Token.KEYWORD3); - tsqlKeywords.add("sp_generatefilters",Token.KEYWORD3); - tsqlKeywords.add("sp_get_distributor",Token.KEYWORD3); - tsqlKeywords.add("sp_getbindtoken",Token.KEYWORD3); - tsqlKeywords.add("sp_getmergedeletetype",Token.KEYWORD3); - tsqlKeywords.add("sp_grant_publication_access",Token.KEYWORD3); - tsqlKeywords.add("sp_grantdbaccess",Token.KEYWORD3); - tsqlKeywords.add("sp_grantlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_help",Token.KEYWORD3); - tsqlKeywords.add("sp_help_agent_default",Token.KEYWORD3); - tsqlKeywords.add("sp_help_agent_parameter",Token.KEYWORD3); - tsqlKeywords.add("sp_help_agent_profile",Token.KEYWORD3); - tsqlKeywords.add("sp_help_alert",Token.KEYWORD3); - tsqlKeywords.add("sp_help_category",Token.KEYWORD3); - tsqlKeywords.add("sp_help_downloadlist",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_catalogs",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_catalogs_cursor",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_columns",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_columns_cursor",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_tables",Token.KEYWORD3); - tsqlKeywords.add("sp_help_fulltext_tables_cursor",Token.KEYWORD3); - tsqlKeywords.add("sp_help_job",Token.KEYWORD3); - tsqlKeywords.add("sp_help_jobhistory",Token.KEYWORD3); - tsqlKeywords.add("sp_help_jobschedule",Token.KEYWORD3); - tsqlKeywords.add("sp_help_jobserver",Token.KEYWORD3); - tsqlKeywords.add("sp_help_jobstep",Token.KEYWORD3); - tsqlKeywords.add("sp_help_notification",Token.KEYWORD3); - tsqlKeywords.add("sp_help_operator",Token.KEYWORD3); - tsqlKeywords.add("sp_help_publication_access",Token.KEYWORD3); - tsqlKeywords.add("sp_help_targetserver",Token.KEYWORD3); - tsqlKeywords.add("sp_help_targetservergroup",Token.KEYWORD3); - tsqlKeywords.add("sp_helparticle",Token.KEYWORD3); - tsqlKeywords.add("sp_helparticlecolumns",Token.KEYWORD3); - tsqlKeywords.add("sp_helpconstraint",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdb",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdbfixedrole",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdevice",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdistpublisher",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdistributiondb",Token.KEYWORD3); - tsqlKeywords.add("sp_helpdistributor",Token.KEYWORD3); - tsqlKeywords.add("sp_helpextendedproc",Token.KEYWORD3); - tsqlKeywords.add("sp_helpfile",Token.KEYWORD3); - tsqlKeywords.add("sp_helpfilegroup",Token.KEYWORD3); - tsqlKeywords.add("sp_helpgroup",Token.KEYWORD3); - tsqlKeywords.add("sp_helphistory",Token.KEYWORD3); - tsqlKeywords.add("sp_helpindex",Token.KEYWORD3); - tsqlKeywords.add("sp_helplanguage",Token.KEYWORD3); - tsqlKeywords.add("sp_helplinkedsrvlogin",Token.KEYWORD3); - tsqlKeywords.add("sp_helplogins",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergearticle",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergearticleconflicts",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergeconflictrows",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergedeleteconflictrows",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergefilter",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergepublication",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergepullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_helpmergesubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_helpntgroup",Token.KEYWORD3); - tsqlKeywords.add("sp_helppublication",Token.KEYWORD3); - tsqlKeywords.add("sp_helppullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_helpremotelogin",Token.KEYWORD3); - tsqlKeywords.add("sp_helpreplicationdboption",Token.KEYWORD3); - tsqlKeywords.add("sp_helprole",Token.KEYWORD3); - tsqlKeywords.add("sp_helprolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_helprotect",Token.KEYWORD3); - tsqlKeywords.add("sp_helpserver",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsort",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsrvrole",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsrvrolemember",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsubscriberinfo",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_helpsubscription_properties",Token.KEYWORD3); - tsqlKeywords.add("sp_helptask",Token.KEYWORD3); - tsqlKeywords.add("sp_helptext",Token.KEYWORD3); - tsqlKeywords.add("sp_helptrigger",Token.KEYWORD3); - tsqlKeywords.add("sp_helpuser",Token.KEYWORD3); - tsqlKeywords.add("sp_indexes",Token.KEYWORD3); - tsqlKeywords.add("sp_indexoption",Token.KEYWORD3); - tsqlKeywords.add("sp_link_publication",Token.KEYWORD3); - tsqlKeywords.add("sp_linkedservers",Token.KEYWORD3); - tsqlKeywords.add("sp_lock",Token.KEYWORD3); - tsqlKeywords.add("sp_makewebtask",Token.KEYWORD3); - tsqlKeywords.add("sp_manage_jobs_by_login",Token.KEYWORD3); - tsqlKeywords.add("sp_mergedummyupdate",Token.KEYWORD3); - tsqlKeywords.add("sp_mergesubscription_cleanup",Token.KEYWORD3); - tsqlKeywords.add("sp_monitor",Token.KEYWORD3); - tsqlKeywords.add("sp_msx_defect",Token.KEYWORD3); - tsqlKeywords.add("sp_msx_enlist",Token.KEYWORD3); - tsqlKeywords.add("sp_OACreate",Token.KEYWORD3); - tsqlKeywords.add("sp_OADestroy",Token.KEYWORD3); - tsqlKeywords.add("sp_OAGetErrorInfo",Token.KEYWORD3); - tsqlKeywords.add("sp_OAGetProperty",Token.KEYWORD3); - tsqlKeywords.add("sp_OAMethod",Token.KEYWORD3); - tsqlKeywords.add("sp_OASetProperty",Token.KEYWORD3); - tsqlKeywords.add("sp_OAStop",Token.KEYWORD3); - tsqlKeywords.add("sp_password",Token.KEYWORD3); - tsqlKeywords.add("sp_pkeys",Token.KEYWORD3); - tsqlKeywords.add("sp_post_msx_operation",Token.KEYWORD3); - tsqlKeywords.add("sp_prepare",Token.KEYWORD3); - tsqlKeywords.add("sp_primarykeys",Token.KEYWORD3); - tsqlKeywords.add("sp_processmail",Token.KEYWORD3); - tsqlKeywords.add("sp_procoption",Token.KEYWORD3); - tsqlKeywords.add("sp_publication_validation",Token.KEYWORD3); - tsqlKeywords.add("sp_purge_jobhistory",Token.KEYWORD3); - tsqlKeywords.add("sp_purgehistory",Token.KEYWORD3); - tsqlKeywords.add("sp_reassigntask",Token.KEYWORD3); - tsqlKeywords.add("sp_recompile",Token.KEYWORD3); - tsqlKeywords.add("sp_refreshsubscriptions",Token.KEYWORD3); - tsqlKeywords.add("sp_refreshview",Token.KEYWORD3); - tsqlKeywords.add("sp_reinitmergepullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_reinitmergesubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_reinitpullsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_reinitsubscription",Token.KEYWORD3); - tsqlKeywords.add("sp_remoteoption",Token.KEYWORD3); - tsqlKeywords.add("sp_remove_job_from_targets",Token.KEYWORD3); - tsqlKeywords.add("sp_removedbreplication",Token.KEYWORD3); - tsqlKeywords.add("sp_rename",Token.KEYWORD3); - tsqlKeywords.add("sp_renamedb",Token.KEYWORD3); - tsqlKeywords.add("sp_replcmds",Token.KEYWORD3); - tsqlKeywords.add("sp_replcounters",Token.KEYWORD3); - tsqlKeywords.add("sp_repldone",Token.KEYWORD3); - tsqlKeywords.add("sp_replflush",Token.KEYWORD3); - tsqlKeywords.add("sp_replication_agent_checkup",Token.KEYWORD3); - tsqlKeywords.add("sp_replicationdboption",Token.KEYWORD3); - tsqlKeywords.add("sp_replsetoriginator",Token.KEYWORD3); - tsqlKeywords.add("sp_replshowcmds",Token.KEYWORD3); - tsqlKeywords.add("sp_repltrans",Token.KEYWORD3); - tsqlKeywords.add("sp_reset_connection",Token.KEYWORD3); - tsqlKeywords.add("sp_resync_targetserver",Token.KEYWORD3); - tsqlKeywords.add("sp_revoke_publication_access",Token.KEYWORD3); - tsqlKeywords.add("sp_revokedbaccess",Token.KEYWORD3); - tsqlKeywords.add("sp_revokelogin",Token.KEYWORD3); - tsqlKeywords.add("sp_runwebtask",Token.KEYWORD3); - tsqlKeywords.add("sp_script_synctran_commands",Token.KEYWORD3); - tsqlKeywords.add("sp_scriptdelproc",Token.KEYWORD3); - tsqlKeywords.add("sp_scriptinsproc",Token.KEYWORD3); - tsqlKeywords.add("sp_scriptmappedupdproc",Token.KEYWORD3); - tsqlKeywords.add("sp_scriptupdproc",Token.KEYWORD3); - tsqlKeywords.add("sp_sdidebug",Token.KEYWORD3); - tsqlKeywords.add("sp_server_info",Token.KEYWORD3); - tsqlKeywords.add("sp_serveroption",Token.KEYWORD3); - tsqlKeywords.add("sp_serveroption",Token.KEYWORD3); - tsqlKeywords.add("sp_setapprole",Token.KEYWORD3); - tsqlKeywords.add("sp_setnetname",Token.KEYWORD3); - tsqlKeywords.add("sp_spaceused",Token.KEYWORD3); - tsqlKeywords.add("sp_special_columns",Token.KEYWORD3); - tsqlKeywords.add("sp_sproc_columns",Token.KEYWORD3); - tsqlKeywords.add("sp_srvrolepermission",Token.KEYWORD3); - tsqlKeywords.add("sp_start_job",Token.KEYWORD3); - tsqlKeywords.add("sp_statistics",Token.KEYWORD3); - tsqlKeywords.add("sp_stop_job",Token.KEYWORD3); - tsqlKeywords.add("sp_stored_procedures",Token.KEYWORD3); - tsqlKeywords.add("sp_subscription_cleanup",Token.KEYWORD3); - tsqlKeywords.add("sp_table_privileges",Token.KEYWORD3); - tsqlKeywords.add("sp_table_privileges_ex",Token.KEYWORD3); - tsqlKeywords.add("sp_table_validation",Token.KEYWORD3); - tsqlKeywords.add("sp_tableoption",Token.KEYWORD3); - tsqlKeywords.add("sp_tables",Token.KEYWORD3); - tsqlKeywords.add("sp_tables_ex",Token.KEYWORD3); - tsqlKeywords.add("sp_unbindefault",Token.KEYWORD3); - tsqlKeywords.add("sp_unbindrule",Token.KEYWORD3); - tsqlKeywords.add("sp_unprepare",Token.KEYWORD3); - tsqlKeywords.add("sp_update_agent_profile",Token.KEYWORD3); - tsqlKeywords.add("sp_update_alert",Token.KEYWORD3); - tsqlKeywords.add("sp_update_category",Token.KEYWORD3); - tsqlKeywords.add("sp_update_job",Token.KEYWORD3); - tsqlKeywords.add("sp_update_jobschedule",Token.KEYWORD3); - tsqlKeywords.add("sp_update_jobstep",Token.KEYWORD3); - tsqlKeywords.add("sp_update_notification",Token.KEYWORD3); - tsqlKeywords.add("sp_update_operator",Token.KEYWORD3); - tsqlKeywords.add("sp_update_targetservergroup",Token.KEYWORD3); - tsqlKeywords.add("sp_updatestats",Token.KEYWORD3); - tsqlKeywords.add("sp_updatetask",Token.KEYWORD3); - tsqlKeywords.add("sp_validatelogins",Token.KEYWORD3); - tsqlKeywords.add("sp_validname",Token.KEYWORD3); - tsqlKeywords.add("sp_who",Token.KEYWORD3); - tsqlKeywords.add("xp_cmdshell",Token.KEYWORD3); - tsqlKeywords.add("xp_deletemail",Token.KEYWORD3); - tsqlKeywords.add("xp_enumgroups",Token.KEYWORD3); - tsqlKeywords.add("xp_findnextmsg",Token.KEYWORD3); - tsqlKeywords.add("xp_findnextmsg",Token.KEYWORD3); - tsqlKeywords.add("xp_grantlogin",Token.KEYWORD3); - tsqlKeywords.add("xp_logevent",Token.KEYWORD3); - tsqlKeywords.add("xp_loginconfig",Token.KEYWORD3); - tsqlKeywords.add("xp_logininfo",Token.KEYWORD3); - tsqlKeywords.add("xp_msver",Token.KEYWORD3); - tsqlKeywords.add("xp_readmail",Token.KEYWORD3); - tsqlKeywords.add("xp_revokelogin",Token.KEYWORD3); - tsqlKeywords.add("xp_sendmail",Token.KEYWORD3); - tsqlKeywords.add("xp_sprintf",Token.KEYWORD3); - tsqlKeywords.add("xp_sqlinventory",Token.KEYWORD3); - tsqlKeywords.add("xp_sqlmaint",Token.KEYWORD3); - tsqlKeywords.add("xp_sqltrace",Token.KEYWORD3); - tsqlKeywords.add("xp_sscanf",Token.KEYWORD3); - tsqlKeywords.add("xp_startmail",Token.KEYWORD3); - tsqlKeywords.add("xp_stopmail",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_addnewqueue",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_deletequeuedefinition",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_destroyqueue",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_enumqueuedefname",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_enumqueuehandles",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_eventclassrequired",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_flushqueryhistory",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_generate_event",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getappfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getconnectionidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getcpufilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getdbidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getdurationfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_geteventfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_geteventnames",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getevents",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_gethostfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_gethpidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getindidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getntdmfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getntnmfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getobjidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getqueueautostart",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getqueuedestination",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getqueueproperties",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getreadfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getserverfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getseverityfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getspidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getsysobjectsfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_gettextfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getuserfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_getwritefilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_loadqueuedefinition",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_pausequeue",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_restartqueue",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_savequeuedefinition",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setappfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setconnectionidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setcpufilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setdbidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setdurationfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_seteventclassrequired",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_seteventfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_sethostfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_sethpidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setindidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setntdmfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setntnmfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setobjidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setqueryhistory",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setqueueautostart",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setqueuecreateinfo",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setqueuedestination",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setreadfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setserverfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setseverityfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setspidfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setsysobjectsfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_settextfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setuserfilter",Token.KEYWORD3); - tsqlKeywords.add("xp_trace_setwritefilter",Token.KEYWORD3); - } - - private static void addSystemTables() - { - tsqlKeywords.add("backupfile",Token.KEYWORD3); - tsqlKeywords.add("backupmediafamily",Token.KEYWORD3); - tsqlKeywords.add("backupmediaset",Token.KEYWORD3); - tsqlKeywords.add("backupset",Token.KEYWORD3); - tsqlKeywords.add("MSagent_parameters",Token.KEYWORD3); - tsqlKeywords.add("MSagent_profiles",Token.KEYWORD3); - tsqlKeywords.add("MSarticles",Token.KEYWORD3); - tsqlKeywords.add("MSdistpublishers",Token.KEYWORD3); - tsqlKeywords.add("MSdistribution_agents",Token.KEYWORD3); - tsqlKeywords.add("MSdistribution_history",Token.KEYWORD3); - tsqlKeywords.add("MSdistributiondbs",Token.KEYWORD3); - tsqlKeywords.add("MSdistributor",Token.KEYWORD3); - tsqlKeywords.add("MSlogreader_agents",Token.KEYWORD3); - tsqlKeywords.add("MSlogreader_history",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_agents",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_contents",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_delete_conflicts",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_genhistory",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_history",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_replinfo",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_subscriptions",Token.KEYWORD3); - tsqlKeywords.add("MSmerge_tombstone",Token.KEYWORD3); - tsqlKeywords.add("MSpublication_access",Token.KEYWORD3); - tsqlKeywords.add("Mspublications",Token.KEYWORD3); - tsqlKeywords.add("Mspublisher_databases",Token.KEYWORD3); - tsqlKeywords.add("MSrepl_commands",Token.KEYWORD3); - tsqlKeywords.add("MSrepl_errors",Token.KEYWORD3); - tsqlKeywords.add("Msrepl_originators",Token.KEYWORD3); - tsqlKeywords.add("MSrepl_transactions",Token.KEYWORD3); - tsqlKeywords.add("MSrepl_version",Token.KEYWORD3); - tsqlKeywords.add("MSreplication_objects",Token.KEYWORD3); - tsqlKeywords.add("MSreplication_subscriptions",Token.KEYWORD3); - tsqlKeywords.add("MSsnapshot_agents",Token.KEYWORD3); - tsqlKeywords.add("MSsnapshot_history",Token.KEYWORD3); - tsqlKeywords.add("MSsubscriber_info",Token.KEYWORD3); - tsqlKeywords.add("MSsubscriber_schedule",Token.KEYWORD3); - tsqlKeywords.add("MSsubscription_properties",Token.KEYWORD3); - tsqlKeywords.add("MSsubscriptions",Token.KEYWORD3); - tsqlKeywords.add("restorefile",Token.KEYWORD3); - tsqlKeywords.add("restorefilegroup",Token.KEYWORD3); - tsqlKeywords.add("restorehistory",Token.KEYWORD3); - tsqlKeywords.add("sysalerts",Token.KEYWORD3); - tsqlKeywords.add("sysallocations",Token.KEYWORD3); - tsqlKeywords.add("sysaltfiles",Token.KEYWORD3); - tsqlKeywords.add("sysarticles",Token.KEYWORD3); - tsqlKeywords.add("sysarticleupdates",Token.KEYWORD3); - tsqlKeywords.add("syscacheobjects",Token.KEYWORD3); - tsqlKeywords.add("syscategories",Token.KEYWORD3); - tsqlKeywords.add("syscharsets",Token.KEYWORD3); - tsqlKeywords.add("syscolumns",Token.KEYWORD3); - tsqlKeywords.add("syscomments",Token.KEYWORD3); - tsqlKeywords.add("sysconfigures",Token.KEYWORD3); - tsqlKeywords.add("sysconstraints",Token.KEYWORD3); - tsqlKeywords.add("syscurconfigs",Token.KEYWORD3); - tsqlKeywords.add("sysdatabases",Token.KEYWORD3); - tsqlKeywords.add("sysdatabases",Token.KEYWORD3); - tsqlKeywords.add("sysdepends",Token.KEYWORD3); - tsqlKeywords.add("sysdevices",Token.KEYWORD3); - tsqlKeywords.add("sysdownloadlist",Token.KEYWORD3); - tsqlKeywords.add("sysfilegroups",Token.KEYWORD3); - tsqlKeywords.add("sysfiles",Token.KEYWORD3); - tsqlKeywords.add("sysforeignkeys",Token.KEYWORD3); - tsqlKeywords.add("sysfulltextcatalogs",Token.KEYWORD3); - tsqlKeywords.add("sysindexes",Token.KEYWORD3); - tsqlKeywords.add("sysindexkeys",Token.KEYWORD3); - tsqlKeywords.add("sysjobhistory",Token.KEYWORD3); - tsqlKeywords.add("sysjobs",Token.KEYWORD3); - tsqlKeywords.add("sysjobschedules",Token.KEYWORD3); - tsqlKeywords.add("sysjobservers",Token.KEYWORD3); - tsqlKeywords.add("sysjobsteps",Token.KEYWORD3); - tsqlKeywords.add("syslanguages",Token.KEYWORD3); - tsqlKeywords.add("syslockinfo",Token.KEYWORD3); - tsqlKeywords.add("syslogins",Token.KEYWORD3); - tsqlKeywords.add("sysmembers",Token.KEYWORD3); - tsqlKeywords.add("sysmergearticles",Token.KEYWORD3); - tsqlKeywords.add("sysmergepublications",Token.KEYWORD3); - tsqlKeywords.add("sysmergeschemachange",Token.KEYWORD3); - tsqlKeywords.add("sysmergesubscriptions",Token.KEYWORD3); - tsqlKeywords.add("sysmergesubsetfilters",Token.KEYWORD3); - tsqlKeywords.add("sysmessages",Token.KEYWORD3); - tsqlKeywords.add("sysnotifications",Token.KEYWORD3); - tsqlKeywords.add("sysobjects",Token.KEYWORD3); - tsqlKeywords.add("sysobjects",Token.KEYWORD3); - tsqlKeywords.add("sysoledbusers",Token.KEYWORD3); - tsqlKeywords.add("sysoperators",Token.KEYWORD3); - tsqlKeywords.add("sysperfinfo",Token.KEYWORD3); - tsqlKeywords.add("syspermissions",Token.KEYWORD3); - tsqlKeywords.add("sysprocesses",Token.KEYWORD3); - tsqlKeywords.add("sysprotects",Token.KEYWORD3); - tsqlKeywords.add("syspublications",Token.KEYWORD3); - tsqlKeywords.add("sysreferences",Token.KEYWORD3); - tsqlKeywords.add("sysremotelogins",Token.KEYWORD3); - tsqlKeywords.add("sysreplicationalerts",Token.KEYWORD3); - tsqlKeywords.add("sysservers",Token.KEYWORD3); - tsqlKeywords.add("sysservers",Token.KEYWORD3); - tsqlKeywords.add("syssubscriptions",Token.KEYWORD3); - tsqlKeywords.add("systargetservergroupmembers",Token.KEYWORD3); - tsqlKeywords.add("systargetservergroups",Token.KEYWORD3); - tsqlKeywords.add("systargetservers",Token.KEYWORD3); - tsqlKeywords.add("systaskids",Token.KEYWORD3); - tsqlKeywords.add("systypes",Token.KEYWORD3); - tsqlKeywords.add("sysusers",Token.KEYWORD3); - } - - private static KeywordMap tsqlKeywords; -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TeXTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TeXTokenMarker.java deleted file mode 100644 index cd2fc38ed..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TeXTokenMarker.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * TeXTokenMarker.java - TeX/LaTeX/AMS-TeX token marker - * Copyright (C) 1998 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * TeX token marker. - * - * @author Slava Pestov - * @version $Id: TeXTokenMarker.java,v 1.16 1999/12/13 03:40:30 sp Exp $ - */ -public class TeXTokenMarker extends TokenMarker -{ - // public members - public static final byte BDFORMULA = Token.INTERNAL_FIRST; - public static final byte EDFORMULA = (byte)(Token.INTERNAL_FIRST + 1); - - public byte markTokensImpl(byte token, Segment line, int lineIndex) - { - char[] array = line.array; - int offset = line.offset; - int lastOffset = offset; - int length = line.count + offset; - boolean backslash = false; -loop: for(int i = offset; i < length; i++) - { - int i1 = (i+1); - - char c = array[i]; - // if a backslash is followed immediately - // by a non-alpha character, the command at - // the non-alpha char. If we have a backslash, - // some text, and then a non-alpha char, - // the command ends before the non-alpha char. - if(Character.isLetter(c)) - { - backslash = false; - } - else - { - if(backslash) - { - // \ - // we skip over this character, - // hence the `continue' - backslash = false; - if(token == Token.KEYWORD2 || token == EDFORMULA) - token = Token.KEYWORD2; - addToken(i1 - lastOffset,token); - lastOffset = i1; - if(token == Token.KEYWORD1) - token = Token.NULL; - continue; - } - else - { - //\blah - // we leave the character in - // the stream, and it's not - // part of the command token - if(token == BDFORMULA || token == EDFORMULA) - token = Token.KEYWORD2; - addToken(i - lastOffset,token); - if(token == Token.KEYWORD1) - token = Token.NULL; - lastOffset = i; - } - } - switch(c) - { - case '%': - if(backslash) - { - backslash = false; - break; - } - addToken(i - lastOffset,token); - addToken(length - i,Token.COMMENT1); - lastOffset = length; - break loop; - case '\\': - backslash = true; - if(token == Token.NULL) - { - token = Token.KEYWORD1; - addToken(i - lastOffset,Token.NULL); - lastOffset = i; - } - break; - case '$': - backslash = false; - if(token == Token.NULL) // singe $ - { - token = Token.KEYWORD2; - addToken(i - lastOffset,Token.NULL); - lastOffset = i; - } - else if(token == Token.KEYWORD1) // \...$ - { - token = Token.KEYWORD2; - addToken(i - lastOffset,Token.KEYWORD1); - lastOffset = i; - } - else if(token == Token.KEYWORD2) // $$aaa - { - if(i - lastOffset == 1 && array[i-1] == '$') - { - token = BDFORMULA; - break; - } - token = Token.NULL; - addToken(i1 - lastOffset,Token.KEYWORD2); - lastOffset = i1; - } - else if(token == BDFORMULA) // $$aaa$ - { - token = EDFORMULA; - } - else if(token == EDFORMULA) // $$aaa$$ - { - token = Token.NULL; - addToken(i1 - lastOffset,Token.KEYWORD2); - lastOffset = i1; - } - break; - } - } - if(lastOffset != length) - addToken(length - lastOffset,token == BDFORMULA - || token == EDFORMULA ? Token.KEYWORD2 : - token); - return (token != Token.KEYWORD1 ? token : Token.NULL); - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Test.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Test.java deleted file mode 100644 index fcfed19ba..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Test.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -import java.io.File; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; - -import com.ochafik.io.ReadText; - -public class Test { - @SuppressWarnings("deprecation") - public static void main(String args[]) { - JFrame f=new JFrame("Test"); - String text=args.length==0 ? "" : ReadText.readText(new File(args[0])); - JEditTextArea ta=new JEditTextArea(); - ta.setText(text); - f.getContentPane().add("Center",new JScrollPane(ta)); - f.pack(); - f.show(); - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaDefaults.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaDefaults.java deleted file mode 100644 index c793e6ff1..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaDefaults.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * TextAreaDefaults.java - Encapsulates default values for various settings - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import java.awt.Color; - -import javax.swing.JPopupMenu; - -/** - * Encapsulates default settings for a text area. This can be passed - * to the constructor once the necessary fields have been filled out. - * The advantage of doing this over calling lots of set() methods after - * creating the text area is that this method is faster. - */ -public class TextAreaDefaults -{ - //private static TextAreaDefaults DEFAULTS; - - public InputHandler inputHandler; - public SyntaxDocument document; - public boolean editable; - - public boolean caretVisible; - public boolean caretBlinks; - public boolean blockCaret; - public int electricScroll; - - public int cols; - public int rows; - public SyntaxStyle[] styles; - public Color caretColor; - public Color selectionColor; - public Color lineHighlightColor; - public boolean lineHighlight; - public Color bracketHighlightColor; - public boolean bracketHighlight; - public Color eolMarkerColor; - public boolean eolMarkers; - public boolean paintInvalid; - - public JPopupMenu popup; - - /** - * Returns a new TextAreaDefaults object with the default values filled - * in. - */ - public static TextAreaDefaults getDefaults() - { - /*if(DEFAULTS == null) - {*/ // we have to create a new object each time - TextAreaDefaults DEFAULTS; - DEFAULTS = new TextAreaDefaults(); - - DEFAULTS.inputHandler = new DefaultInputHandler(); - DEFAULTS.inputHandler.addDefaultKeyBindings(); - DEFAULTS.document = new SyntaxDocument(); - DEFAULTS.editable = true; - - DEFAULTS.caretVisible = true; - DEFAULTS.caretBlinks = true; - DEFAULTS.electricScroll = 3; - - DEFAULTS.cols = 80; - DEFAULTS.rows = 25; - DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles(); - DEFAULTS.caretColor = Color.red; - DEFAULTS.selectionColor = new Color(0xccccff); - DEFAULTS.lineHighlightColor = new Color(0xe0e0e0); - DEFAULTS.lineHighlight = true; - DEFAULTS.bracketHighlightColor = Color.black; - DEFAULTS.bracketHighlight = true; - DEFAULTS.eolMarkerColor = new Color(0x009999); - DEFAULTS.eolMarkers = true; - DEFAULTS.paintInvalid = true; - //} - - return DEFAULTS; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaPainter.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaPainter.java deleted file mode 100644 index d20d5ad97..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextAreaPainter.java +++ /dev/null @@ -1,716 +0,0 @@ - -/* - * TextAreaPainter.java - Paints the text area - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; - -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.Toolkit; -import java.awt.event.MouseEvent; - -import javax.swing.JComponent; -import javax.swing.ToolTipManager; -import javax.swing.text.PlainDocument; -import javax.swing.text.Segment; -import javax.swing.text.TabExpander; -import javax.swing.text.Utilities; - -/** - * The text area repaint manager. It performs double buffering and paints - * lines of text. - * @author Slava Pestov - * @version $Id: TextAreaPainter.java,v 1.24 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings({"serial"}) -public class TextAreaPainter extends JComponent implements TabExpander -{ - /** - * Creates a new repaint manager. This should be not be called - * directly. - */ - /*static BufferedImage backgroundImage; - static { - try { - backgroundImage=javax.imageio.ImageIO.read(new FileInputStream("olive.jpg")); - } catch (IOException ex) { - ex.printStackTrace(); - } - }*/ - public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults) - { - this.textArea = textArea; - - setAutoscrolls(true); - setDoubleBuffered(true); - setOpaque(true); - - ToolTipManager.sharedInstance().registerComponent(this); - - currentLine = new Segment(); - currentLineIndex = -1; - - setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); - - setFont(new Font("Monospaced",Font.PLAIN,14)); - setForeground(Color.black); - setBackground(Color.white); - - blockCaret = defaults.blockCaret; - styles = defaults.styles; - cols = defaults.cols; - rows = defaults.rows; - caretColor = defaults.caretColor; - selectionColor = defaults.selectionColor; - lineHighlightColor = defaults.lineHighlightColor; - lineHighlight = defaults.lineHighlight; - bracketHighlightColor = defaults.bracketHighlightColor; - bracketHighlight = defaults.bracketHighlight; - paintInvalid = defaults.paintInvalid; - eolMarkerColor = defaults.eolMarkerColor; - eolMarkers = defaults.eolMarkers; - } - - /** - * Returns if this component can be traversed by pressing the - * Tab key. This returns false. - */ - public final boolean isManagingFocus() - { - return false; - } - - /** - * Returns the syntax styles used to paint colorized text. Entry n - * will be used to paint tokens with id = n. - * @see Token - */ - public final SyntaxStyle[] getStyles() - { - return styles; - } - - /** - * Sets the syntax styles used to paint colorized text. Entry n - * will be used to paint tokens with id = n. - * @param styles The syntax styles - * @see Token - */ - public final void setStyles(SyntaxStyle[] styles) - { - this.styles = styles; - repaint(); - } - - /** - * Returns the caret color. - */ - public final Color getCaretColor() - { - return caretColor; - } - - /** - * Sets the caret color. - * @param caretColor The caret color - */ - public final void setCaretColor(Color caretColor) - { - this.caretColor = caretColor; - invalidateSelectedLines(); - } - - /** - * Returns the selection color. - */ - public final Color getSelectionColor() - { - return selectionColor; - } - - /** - * Sets the selection color. - * @param selectionColor The selection color - */ - public final void setSelectionColor(Color selectionColor) - { - this.selectionColor = selectionColor; - invalidateSelectedLines(); - } - - /** - * Returns the line highlight color. - */ - public final Color getLineHighlightColor() - { - return lineHighlightColor; - } - - /** - * Sets the line highlight color. - * @param lineHighlightColor The line highlight color - */ - public final void setLineHighlightColor(Color lineHighlightColor) - { - this.lineHighlightColor = lineHighlightColor; - invalidateSelectedLines(); - } - - /** - * Returns true if line highlight is enabled, false otherwise. - */ - public final boolean isLineHighlightEnabled() - { - return lineHighlight; - } - - /** - * Enables or disables current line highlighting. - * @param lineHighlight True if current line highlight should be enabled, - * false otherwise - */ - public final void setLineHighlightEnabled(boolean lineHighlight) - { - this.lineHighlight = lineHighlight; - invalidateSelectedLines(); - } - - /** - * Returns the bracket highlight color. - */ - public final Color getBracketHighlightColor() - { - return bracketHighlightColor; - } - - /** - * Sets the bracket highlight color. - * @param bracketHighlightColor The bracket highlight color - */ - public final void setBracketHighlightColor(Color bracketHighlightColor) - { - this.bracketHighlightColor = bracketHighlightColor; - invalidateLine(textArea.getBracketLine()); - } - - /** - * Returns true if bracket highlighting is enabled, false otherwise. - * When bracket highlighting is enabled, the bracket matching the - * one before the caret (if any) is highlighted. - */ - public final boolean isBracketHighlightEnabled() - { - return bracketHighlight; - } - - /** - * Enables or disables bracket highlighting. - * When bracket highlighting is enabled, the bracket matching the - * one before the caret (if any) is highlighted. - * @param bracketHighlight True if bracket highlighting should be - * enabled, false otherwise - */ - public final void setBracketHighlightEnabled(boolean bracketHighlight) - { - this.bracketHighlight = bracketHighlight; - invalidateLine(textArea.getBracketLine()); - } - - /** - * Returns true if the caret should be drawn as a block, false otherwise. - */ - public final boolean isBlockCaretEnabled() - { - return blockCaret; - } - - /** - * Sets if the caret should be drawn as a block, false otherwise. - * @param blockCaret True if the caret should be drawn as a block, - * false otherwise. - */ - public final void setBlockCaretEnabled(boolean blockCaret) - { - this.blockCaret = blockCaret; - invalidateSelectedLines(); - } - - /** - * Returns the EOL marker color. - */ - public final Color getEOLMarkerColor() - { - return eolMarkerColor; - } - - /** - * Sets the EOL marker color. - * @param eolMarkerColor The EOL marker color - */ - public final void setEOLMarkerColor(Color eolMarkerColor) - { - this.eolMarkerColor = eolMarkerColor; - repaint(); - } - - /** - * Returns true if EOL markers are drawn, false otherwise. - */ - public final boolean getEOLMarkersPainted() - { - return eolMarkers; - } - - /** - * Sets if EOL markers are to be drawn. - * @param eolMarkers True if EOL markers should be drawn, false otherwise - */ - public final void setEOLMarkersPainted(boolean eolMarkers) - { - this.eolMarkers = eolMarkers; - repaint(); - } - - /** - * Returns true if invalid lines are painted as red tildes (~), - * false otherwise. - */ - public boolean getInvalidLinesPainted() - { - return paintInvalid; - } - - /** - * Sets if invalid lines are to be painted as red tildes. - * @param paintInvalid True if invalid lines should be drawn, false otherwise - */ - public void setInvalidLinesPainted(boolean paintInvalid) - { - this.paintInvalid = paintInvalid; - } - - /** - * Adds a custom highlight painter. - * @param highlight The highlight - */ - public void addCustomHighlight(Highlight highlight) - { - highlight.init(textArea,highlights); - highlights = highlight; - } - - /** - * Highlight interface. - */ - public interface Highlight - { - /** - * Called after the highlight painter has been added. - * @param textArea The text area - * @param next The painter this one should delegate to - */ - void init(JEditTextArea textArea, Highlight next); - - /** - * This should paint the highlight and delgate to the - * next highlight painter. - * @param gfx The graphics context - * @param line The line number - * @param y The y co-ordinate of the line - */ - void paintHighlight(Graphics gfx, int line, int y); - - /** - * Returns the tool tip to display at the specified - * location. If this highlighter doesn't know what to - * display, it should delegate to the next highlight - * painter. - * @param evt The mouse event - */ - String getToolTipText(MouseEvent evt); - } - - /** - * Returns the tool tip to display at the specified location. - * @param evt The mouse event - */ - public String getToolTipText(MouseEvent evt) - { - if(highlights != null) - return highlights.getToolTipText(evt); - else - return null; - } - - /** - * Returns the font metrics used by this component. - */ - public FontMetrics getFontMetrics() - { - return fm; - } - - /** - * Sets the font for this component. This is overridden to update the - * cached font metrics and to recalculate which lines are visible. - * @param font The font - */ - @SuppressWarnings("deprecation") - public void setFont(Font font) - { - super.setFont(font); - fm = Toolkit.getDefaultToolkit().getFontMetrics(font); - textArea.recalculateVisibleLines(); - } - - /** - * Repaints the text. - * @param gfx The graphics context - */ - public void paint(Graphics gfx) - { - tabSize = fm.charWidth(' ') * ((Integer)textArea - .getDocument().getProperty( - PlainDocument.tabSizeAttribute)).intValue(); - - Rectangle clipRect = gfx.getClipBounds(); - - gfx.setColor(getBackground()); - gfx.fillRect(clipRect.x,clipRect.y,clipRect.width,clipRect.height); - //gfx.drawImage(backgroundImage,0,0,100,100,null); - - // We don't use yToLine() here because that method doesn't - // return lines past the end of the document - int height = fm.getHeight(); - int firstLine = textArea.getFirstLine(); - int firstInvalid = firstLine + clipRect.y / height; - // Because the clipRect's height is usually an even multiple - // of the font height, we subtract 1 from it, otherwise one - // too many lines will always be painted. - int lastInvalid = firstLine + (clipRect.y + clipRect.height - 1) / height; - - try - { - TokenMarker tokenMarker = textArea.getDocument() - .getTokenMarker(); - int x = textArea.getHorizontalOffset(); - - for(int line = firstInvalid; line <= lastInvalid; line++) - { - paintLine(gfx,tokenMarker,line,x); - } - - if(tokenMarker != null && tokenMarker.isNextLineRequested()) - { - int h = clipRect.y + clipRect.height; - repaint(0,h,getWidth(),getHeight() - h); - } - } - catch(Exception e) - { - System.err.println("Error repainting line" - + " range {" + firstInvalid + "," - + lastInvalid + "}:"); - e.printStackTrace(); - } - } - - /** - * Marks a line as needing a repaint. - * @param line The line to invalidate - */ - public final void invalidateLine(int line) - { - repaint(0,textArea.lineToY(line) + fm.getMaxDescent() + fm.getLeading(), - getWidth(),fm.getHeight()); - } - - /** - * Marks a range of lines as needing a repaint. - * @param firstLine The first line to invalidate - * @param lastLine The last line to invalidate - */ - public final void invalidateLineRange(int firstLine, int lastLine) - { - repaint(0,textArea.lineToY(firstLine) + fm.getMaxDescent() + fm.getLeading(), - getWidth(),(lastLine - firstLine + 1) * fm.getHeight()); - } - - /** - * Repaints the lines containing the selection. - */ - public final void invalidateSelectedLines() - { - invalidateLineRange(textArea.getSelectionStartLine(), - textArea.getSelectionEndLine()); - } - - /** - * Implementation of TabExpander interface. Returns next tab stop after - * a specified point. - * @param x The x co-ordinate - * @param tabOffset Ignored - * @return The next tab stop after x - */ - public float nextTabStop(float x, int tabOffset) - { - int offset = textArea.getHorizontalOffset(); - int ntabs = ((int)x - offset) / tabSize; - return (ntabs + 1) * tabSize + offset; - } - - /** - * Returns the painter's preferred size. - */ - public Dimension getPreferredSize() - { - Dimension dim = new Dimension(); - dim.width = fm.charWidth('w') * cols; - dim.height = fm.getHeight() * rows; - return dim; - } - - - /** - * Returns the painter's minimum size. - */ - public Dimension getMinimumSize() - { - return getPreferredSize(); - } - - // package-private members - int currentLineIndex; - Token currentLineTokens; - Segment currentLine; - - // protected members - protected JEditTextArea textArea; - - protected SyntaxStyle[] styles; - protected Color caretColor; - protected Color selectionColor; - protected Color lineHighlightColor; - protected Color bracketHighlightColor; - protected Color eolMarkerColor; - - protected boolean blockCaret; - protected boolean lineHighlight; - protected boolean bracketHighlight; - protected boolean paintInvalid; - protected boolean eolMarkers; - protected int cols; - protected int rows; - - protected int tabSize; - protected FontMetrics fm; - - protected Highlight highlights; - - protected void paintLine(Graphics gfx, TokenMarker tokenMarker, - int line, int x) - { - Font defaultFont = getFont(); - Color defaultColor = getForeground(); - - currentLineIndex = line; - int y = textArea.lineToY(line); - - if(line < 0 || line >= textArea.getLineCount()) - { - if(paintInvalid) - { - paintHighlight(gfx,line,y); - styles[Token.INVALID].setGraphicsFlags(gfx,defaultFont); - gfx.drawString("~",0,y + fm.getHeight()); - } - } - else if(tokenMarker == null) - { - paintPlainLine(gfx,line,defaultFont,defaultColor,x,y); - } - else - { - paintSyntaxLine(gfx,tokenMarker,line,defaultFont, - defaultColor,x,y); - } - } - - protected void paintPlainLine(Graphics gfx, int line, Font defaultFont, - Color defaultColor, int x, int y) - { - paintHighlight(gfx,line,y); - textArea.getLineText(line,currentLine); - - gfx.setFont(defaultFont); - gfx.setColor(defaultColor); - - y += fm.getHeight(); - x = Utilities.drawTabbedText(currentLine,x,y,gfx,this,0); - - if(eolMarkers) - { - gfx.setColor(eolMarkerColor); - gfx.drawString(".",x,y); - } - } - - protected void paintSyntaxLine(Graphics gfx, TokenMarker tokenMarker, - int line, Font defaultFont, Color defaultColor, int x, int y) - { - textArea.getLineText(currentLineIndex,currentLine); - currentLineTokens = tokenMarker.markTokens(currentLine, - currentLineIndex); - - paintHighlight(gfx,line,y); - - gfx.setFont(defaultFont); - gfx.setColor(defaultColor); - y += fm.getHeight(); - x = SyntaxUtilities.paintSyntaxLine(currentLine, - currentLineTokens,styles,this,gfx,x,y); - - if(eolMarkers) - { - gfx.setColor(eolMarkerColor); - gfx.drawString(".",x,y); - } - } - - protected void paintHighlight(Graphics gfx, int line, int y) - { - if(line >= textArea.getSelectionStartLine() - && line <= textArea.getSelectionEndLine()) - paintLineHighlight(gfx,line,y); - - if(highlights != null) - highlights.paintHighlight(gfx,line,y); - - if(bracketHighlight && line == textArea.getBracketLine()) - paintBracketHighlight(gfx,line,y); - - if(line == textArea.getCaretLine()) - paintCaret(gfx,line,y); - } - - protected void paintLineHighlight(Graphics gfx, int line, int y) - { - int height = fm.getHeight(); - y += fm.getLeading() + fm.getMaxDescent(); - - int selectionStart = textArea.getSelectionStart(); - int selectionEnd = textArea.getSelectionEnd(); - - if(selectionStart == selectionEnd) - { - if(lineHighlight) - { - gfx.setColor(lineHighlightColor); - gfx.fillRect(0,y,getWidth(),height); - } - } - else - { - gfx.setColor(selectionColor); - - int selectionStartLine = textArea.getSelectionStartLine(); - int selectionEndLine = textArea.getSelectionEndLine(); - int lineStart = textArea.getLineStartOffset(line); - - int x1, x2; - if(textArea.isSelectionRectangular()) - { - int lineLen = textArea.getLineLength(line); - x1 = textArea._offsetToX(line,Math.min(lineLen, - selectionStart - textArea.getLineStartOffset( - selectionStartLine))); - x2 = textArea._offsetToX(line,Math.min(lineLen, - selectionEnd - textArea.getLineStartOffset( - selectionEndLine))); - if(x1 == x2) - x2++; - } - else if(selectionStartLine == selectionEndLine) - { - x1 = textArea._offsetToX(line, - selectionStart - lineStart); - x2 = textArea._offsetToX(line, - selectionEnd - lineStart); - } - else if(line == selectionStartLine) - { - x1 = textArea._offsetToX(line, - selectionStart - lineStart); - x2 = getWidth(); - } - else if(line == selectionEndLine) - { - x1 = 0; - x2 = textArea._offsetToX(line, - selectionEnd - lineStart); - } - else - { - x1 = 0; - x2 = getWidth(); - } - - // "inlined" min/max() - gfx.fillRect(x1 > x2 ? x2 : x1,y,x1 > x2 ? - (x1 - x2) : (x2 - x1),height); - } - - } - - protected void paintBracketHighlight(Graphics gfx, int line, int y) - { - int position = textArea.getBracketPosition(); - if(position == -1) - return; - y += fm.getLeading() + fm.getMaxDescent(); - int x = textArea._offsetToX(line,position); - gfx.setColor(bracketHighlightColor); - // Hack!!! Since there is no fast way to get the character - // from the bracket matching routine, we use ( since all - // brackets probably have the same width anyway - gfx.drawRect(x,y,fm.charWidth('(') - 1, - fm.getHeight() - 1); - } - - protected void paintCaret(Graphics gfx, int line, int y) - { - if(textArea.isCaretVisible()) - { - int offset = textArea.getCaretPosition() - - textArea.getLineStartOffset(line); - int caretX = textArea._offsetToX(line,offset); - int caretWidth = ((blockCaret || - textArea.isOverwriteEnabled()) ? - fm.charWidth('w') : 1); - y += fm.getLeading() + fm.getMaxDescent(); - int height = fm.getHeight(); - - gfx.setColor(caretColor); - - if(textArea.isOverwriteEnabled()) - { - gfx.fillRect(caretX,y + height - 1, - caretWidth,1); - } - else - { - gfx.drawRect(caretX,y,caretWidth - 1,height - 1); - } - } - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextUtilities.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextUtilities.java deleted file mode 100644 index b2f548584..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TextUtilities.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * TextUtilities.java - Utility functions used by the text area classes - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.BadLocationException; -import javax.swing.text.Document; - -/** - * Class with several utility functions used by the text area component. - * @author Slava Pestov - * @version $Id: TextUtilities.java,v 1.4 1999/12/13 03:40:30 sp Exp $ - */ - -public class TextUtilities -{ - /** - * Returns the offset of the bracket matching the one at the - * specified offset of the document, or -1 if the bracket is - * unmatched (or if the character is not a bracket). - * @param doc The document - * @param offset The offset - * @exception BadLocationException If an out-of-bounds access - * was attempted on the document text - */ - public static int findMatchingBracket(Document doc, int offset) - throws BadLocationException - { - if(doc.getLength() == 0) - return -1; - char c = doc.getText(offset,1).charAt(0); - char cprime; // c` - corresponding character - boolean direction; // true = back, false = forward - - switch(c) - { - case '(': cprime = ')'; direction = false; break; - case ')': cprime = '('; direction = true; break; - case '[': cprime = ']'; direction = false; break; - case ']': cprime = '['; direction = true; break; - case '{': cprime = '}'; direction = false; break; - case '}': cprime = '{'; direction = true; break; - default: return -1; - } - - int count; - - // How to merge these two cases is left as an exercise - // for the reader. - - // Go back or forward - if(direction) - { - // Count is 1 initially because we have already - // `found' one closing bracket - count = 1; - - // Get text[0,offset-1]; - String text = doc.getText(0,offset); - - // Scan backwards - for(int i = offset - 1; i >= 0; i--) - { - // If text[i] == c, we have found another - // closing bracket, therefore we will need - // two opening brackets to complete the - // match. - char x = text.charAt(i); - if(x == c) - count++; - - // If text[i] == cprime, we have found a - // opening bracket, so we return i if - // --count == 0 - else if(x == cprime) - { - if(--count == 0) - return i; - } - } - } - else - { - // Count is 1 initially because we have already - // `found' one opening bracket - count = 1; - - // So we don't have to + 1 in every loop - offset++; - - // Number of characters to check - int len = doc.getLength() - offset; - - // Get text[offset+1,len]; - String text = doc.getText(offset,len); - - // Scan forwards - for(int i = 0; i < len; i++) - { - // If text[i] == c, we have found another - // opening bracket, therefore we will need - // two closing brackets to complete the - // match. - char x = text.charAt(i); - - if(x == c) - count++; - - // If text[i] == cprime, we have found an - // closing bracket, so we return i if - // --count == 0 - else if(x == cprime) - { - if(--count == 0) - return i + offset; - } - } - } - - // Nothing found - return -1; - } - - /** - * Locates the start of the word at the specified position. - * @param line The text - * @param pos The position - */ - public static int findWordStart(String line, int pos, String noWordSep) - { - char ch = line.charAt(pos - 1); - - if(noWordSep == null) - noWordSep = ""; - boolean selectNoLetter = (!Character.isLetterOrDigit(ch) - && noWordSep.indexOf(ch) == -1); - - int wordStart = 0; - for(int i = pos - 1; i >= 0; i--) - { - ch = line.charAt(i); - if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) && - noWordSep.indexOf(ch) == -1)) - { - wordStart = i + 1; - break; - } - } - - return wordStart; - } - - /** - * Locates the end of the word at the specified position. - * @param line The text - * @param pos The position - */ - public static int findWordEnd(String line, int pos, String noWordSep) - { - char ch = line.charAt(pos); - - if(noWordSep == null) - noWordSep = ""; - boolean selectNoLetter = (!Character.isLetterOrDigit(ch) - && noWordSep.indexOf(ch) == -1); - - int wordEnd = line.length(); - for(int i = pos; i < line.length(); i++) - { - ch = line.charAt(i); - if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) && - noWordSep.indexOf(ch) == -1)) - { - wordEnd = i; - break; - } - } - return wordEnd; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Token.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Token.java deleted file mode 100644 index bf74ff902..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/Token.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Token.java - Generic token - * Copyright (C) 1998, 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ - -/** - * A linked list of tokens. Each token has three fields - a token - * identifier, which is a byte value that can be looked up in the - * array returned by SyntaxDocument.getColors() - * to get a color value, a length value which is the length of the - * token in the text, and a pointer to the next token in the list. - * - * @author Slava Pestov - * @version $Id: Token.java,v 1.12 1999/12/13 03:40:30 sp Exp $ - */ -package com.ochafik.swing.syntaxcoloring; -public class Token -{ - /** - * Normal text token id. This should be used to mark - * normal text. - */ - public static final byte NULL = 0; - - /** - * Comment 1 token id. This can be used to mark a comment. - */ - public static final byte COMMENT1 = 1; - - /** - * Comment 2 token id. This can be used to mark a comment. - */ - public static final byte COMMENT2 = 2; - - - /** - * Literal 1 token id. This can be used to mark a string - * literal (eg, C mode uses this to mark "..." literals) - */ - public static final byte LITERAL1 = 3; - - /** - * Literal 2 token id. This can be used to mark an object - * literal (eg, Java mode uses this to mark true, false, etc) - */ - public static final byte LITERAL2 = 4; - - /** - * Label token id. This can be used to mark labels - * (eg, C mode uses this to mark ...: sequences) - */ - public static final byte LABEL = 5; - - /** - * Keyword 1 token id. This can be used to mark a - * keyword. This should be used for general language - * constructs. - */ - public static final byte KEYWORD1 = 6; - - /** - * Keyword 2 token id. This can be used to mark a - * keyword. This should be used for preprocessor - * commands, or variables. - */ - public static final byte KEYWORD2 = 7; - - /** - * Keyword 3 token id. This can be used to mark a - * keyword. This should be used for data types. - */ - public static final byte KEYWORD3 = 8; - - /** - * Operator token id. This can be used to mark an - * operator. (eg, SQL mode marks +, -, etc with this - * token type) - */ - public static final byte OPERATOR = 9; - - /** - * Invalid token id. This can be used to mark invalid - * or incomplete tokens, so the user can easily spot - * syntax errors. - */ - public static final byte INVALID = 10; - - /** - * The total number of defined token ids. - */ - public static final byte ID_COUNT = 11; - - /** - * The first id that can be used for internal state - * in a token marker. - */ - public static final byte INTERNAL_FIRST = 100; - - /** - * The last id that can be used for internal state - * in a token marker. - */ - public static final byte INTERNAL_LAST = 126; - - /** - * The token type, that along with a length of 0 - * marks the end of the token list. - */ - public static final byte END = 127; - - /** - * The length of this token. - */ - public int length; - - /** - * The id of this token. - */ - public byte id; - - /** - * The next token in the linked list. - */ - public Token next; - - /** - * Creates a new token. - * @param length The length of the token - * @param id The id of the token - */ - public Token(int length, byte id) - { - this.length = length; - this.id = id; - } - - /** - * Returns a string representation of this token. - */ - public String toString() - { - return "[id=" + id + ",length=" + length + "]"; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TokenMarker.java deleted file mode 100644 index 82202e1d8..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/TokenMarker.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * TokenMarker.java - Generic token marker - * Copyright (C) 1998, 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ -package com.ochafik.swing.syntaxcoloring; -import javax.swing.text.Segment; - -/** - * A token marker that splits lines of text into tokens. Each token carries - * a length field and an indentification tag that can be mapped to a color - * for painting that token.

      - * - * For performance reasons, the linked list of tokens is reused after each - * line is tokenized. Therefore, the return value of markTokens - * should only be used for immediate painting. Notably, it cannot be - * cached. - * - * @author Slava Pestov - * @version $Id: TokenMarker.java,v 1.32 1999/12/13 03:40:30 sp Exp $ - * - * @see Token - */ -public abstract class TokenMarker -{ - /** - * A wrapper for the lower-level markTokensImpl method - * that is called to split a line up into tokens. - * @param line The line - * @param lineIndex The line number - */ - public Token markTokens(Segment line, int lineIndex) - { - if(lineIndex >= length) - { - throw new IllegalArgumentException("Tokenizing invalid line: " - + lineIndex); - } - - lastToken = null; - - LineInfo info = lineInfo[lineIndex]; - LineInfo prev; - if(lineIndex == 0) - prev = null; - else - prev = lineInfo[lineIndex - 1]; - - byte oldToken = info.token; - byte token = markTokensImpl(prev == null ? - Token.NULL : prev.token,line,lineIndex); - - info.token = token; - - /* - * This is a foul hack. It stops nextLineRequested - * from being cleared if the same line is marked twice. - * - * Why is this necessary? It's all JEditTextArea's fault. - * When something is inserted into the text, firing a - * document event, the insertUpdate() method shifts the - * caret (if necessary) by the amount inserted. - * - * All caret movement is handled by the select() method, - * which eventually pipes the new position to scrollTo() - * and calls repaint(). - * - * Note that at this point in time, the new line hasn't - * yet been painted; the caret is moved first. - * - * scrollTo() calls offsetToX(), which tokenizes the line - * unless it is being called on the last line painted - * (in which case it uses the text area's painter cached - * token list). What scrollTo() does next is irrelevant. - * - * After scrollTo() has done it's job, repaint() is - * called, and eventually we end up in paintLine(), whose - * job is to paint the changed line. It, too, calls - * markTokens(). - * - * The problem was that if the line started a multiline - * token, the first markTokens() (done in offsetToX()) - * would set nextLineRequested (because the line end - * token had changed) but the second would clear it - * (because the line was the same that time) and therefore - * paintLine() would never know that it needed to repaint - * subsequent lines. - * - * This bug took me ages to track down, that's why I wrote - * all the relevant info down so that others wouldn't - * duplicate it. - */ - if(!(lastLine == lineIndex && nextLineRequested)) - nextLineRequested = (oldToken != token); - - lastLine = lineIndex; - - addToken(0,Token.END); - - return firstToken; - } - - /** - * An abstract method that splits a line up into tokens. It - * should parse the line, and call addToken() to - * add syntax tokens to the token list. Then, it should return - * the initial token type for the next line.

      - * - * For example if the current line contains the start of a - * multiline comment that doesn't end on that line, this method - * should return the comment token type so that it continues on - * the next line. - * - * @param token The initial token type for this line - * @param line The line to be tokenized - * @param lineIndex The index of the line in the document, - * starting at 0 - * @return The initial token type for the next line - */ - protected abstract byte markTokensImpl(byte token, Segment line, - int lineIndex); - - /** - * Returns if the token marker supports tokens that span multiple - * lines. If this is true, the object using this token marker is - * required to pass all lines in the document to the - * markTokens() method (in turn).

      - * - * The default implementation returns true; it should be overridden - * to return false on simpler token markers for increased speed. - */ - public boolean supportsMultilineTokens() - { - return true; - } - - /** - * Informs the token marker that lines have been inserted into - * the document. This inserts a gap in the lineInfo - * array. - * @param index The first line number - * @param lines The number of lines - */ - public void insertLines(int index, int lines) - { - if(lines <= 0) - return; - length += lines; - ensureCapacity(length); - int len = index + lines; - System.arraycopy(lineInfo,index,lineInfo,len, - lineInfo.length - len); - - for(int i = index + lines - 1; i >= index; i--) - { - lineInfo[i] = new LineInfo(); - } - } - - /** - * Informs the token marker that line have been deleted from - * the document. This removes the lines in question from the - * lineInfo array. - * @param index The first line number - * @param lines The number of lines - */ - public void deleteLines(int index, int lines) - { - if (lines <= 0) - return; - int len = index + lines; - length -= lines; - System.arraycopy(lineInfo,len,lineInfo, - index,lineInfo.length - len); - } - - /** - * Returns the number of lines in this token marker. - */ - public int getLineCount() - { - return length; - } - - /** - * Returns true if the next line should be repainted. This - * will return true after a line has been tokenized that starts - * a multiline token that continues onto the next line. - */ - public boolean isNextLineRequested() - { - return nextLineRequested; - } - - // protected members - - /** - * The first token in the list. This should be used as the return - * value from markTokens(). - */ - protected Token firstToken; - - /** - * The last token in the list. New tokens are added here. - * This should be set to null before a new line is to be tokenized. - */ - protected Token lastToken; - - /** - * An array for storing information about lines. It is enlarged and - * shrunk automatically by the insertLines() and - * deleteLines() methods. - */ - protected LineInfo[] lineInfo; - - /** - * The number of lines in the model being tokenized. This can be - * less than the length of the lineInfo array. - */ - protected int length; - - /** - * The last tokenized line. - */ - protected int lastLine; - - /** - * True if the next line should be painted. - */ - protected boolean nextLineRequested; - - /** - * Creates a new TokenMarker. This DOES NOT create - * a lineInfo array; an initial call to insertLines() - * does that. - */ - protected TokenMarker() - { - lastLine = -1; - } - - /** - * Ensures that the lineInfo array can contain the - * specified index. This enlarges it if necessary. No action is - * taken if the array is large enough already.

      - * - * It should be unnecessary to call this under normal - * circumstances; insertLine() should take care of - * enlarging the line info array automatically. - * - * @param index The array index - */ - protected void ensureCapacity(int index) - { - if(lineInfo == null) - lineInfo = new LineInfo[index + 1]; - else if(lineInfo.length <= index) - { - LineInfo[] lineInfoN = new LineInfo[(index + 1) * 2]; - System.arraycopy(lineInfo,0,lineInfoN,0, - lineInfo.length); - lineInfo = lineInfoN; - } - } - - /** - * Adds a token to the token list. - * @param length The length of the token - * @param id The id of the token - */ - protected void addToken(int length, byte id) - { - if(id >= Token.INTERNAL_FIRST && id <= Token.INTERNAL_LAST) - throw new InternalError("Invalid id: " + id); - - if(length == 0 && id != Token.END) - return; - - if(firstToken == null) - { - firstToken = new Token(length,id); - lastToken = firstToken; - } - else if(lastToken == null) - { - lastToken = firstToken; - firstToken.length = length; - firstToken.id = id; - } - else if(lastToken.next == null) - { - lastToken.next = new Token(length,id); - lastToken = lastToken.next; - } - else - { - lastToken = lastToken.next; - lastToken.length = length; - lastToken.id = id; - } - } - - /** - * Inner class for storing information about tokenized lines. - */ - public class LineInfo - { - /** - * Creates a new LineInfo object with token = Token.NULL - * and obj = null. - */ - public LineInfo() - { - } - - /** - * Creates a new LineInfo object with the specified - * parameters. - */ - public LineInfo(byte token, Object obj) - { - this.token = token; - this.obj = obj; - } - - /** - * The id of the last token of the line. - */ - public byte token; - - /** - * This is for use by the token marker implementations - * themselves. It can be used to store anything that - * is an object and that needs to exist on a per-line - * basis. - */ - public Object obj; - } -} diff --git a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/XMLTokenMarker.java b/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/XMLTokenMarker.java deleted file mode 100644 index 89ce30e87..000000000 --- a/libraries/jnaerator/ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/XMLTokenMarker.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ochafik.swing.syntaxcoloring; -/* - * XMLTokenMarker.java - XML token marker - * Copyright (C) 1999 Slava Pestov - * - * You may use and modify this package for any purpose. Redistribution is - * permitted, in both source and binary form, provided that this notice - * remains intact in all source distributions of this package. - */ - -/** - * XML token marker. - * - * @author Slava Pestov - * @version $Id: XMLTokenMarker.java,v 1.2 1999/12/13 03:40:30 sp Exp $ - */ -@SuppressWarnings({}) -public class XMLTokenMarker extends HTMLTokenMarker -{ - public XMLTokenMarker() - { - super(false); - } -} diff --git a/libraries/jnaerator/ochafik-util/.classpath b/libraries/jnaerator/ochafik-util/.classpath deleted file mode 100644 index 4cf68d6b7..000000000 --- a/libraries/jnaerator/ochafik-util/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/libraries/jnaerator/ochafik-util/.gitignore b/libraries/jnaerator/ochafik-util/.gitignore deleted file mode 100644 index 8e0d53252..000000000 --- a/libraries/jnaerator/ochafik-util/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -project/boot -project/target -*~ diff --git a/libraries/jnaerator/ochafik-util/.project b/libraries/jnaerator/ochafik-util/.project deleted file mode 100644 index dfb06a00a..000000000 --- a/libraries/jnaerator/ochafik-util/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - ochafik-util - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.iam.jdt.core.mavenIncrementalBuilder - - - - - - org.maven.ide.eclipse.maven2Nature - org.eclipse.iam.jdt.core.mavenNature - org.eclipse.jdt.core.javanature - - diff --git a/libraries/jnaerator/ochafik-util/.settings/org.eclipse.jdt.core.prefs b/libraries/jnaerator/ochafik-util/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b3c33f6ca..000000000 --- a/libraries/jnaerator/ochafik-util/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Jan 28 23:48:05 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/libraries/jnaerator/ochafik-util/.settings/org.maven.ide.eclipse.prefs b/libraries/jnaerator/ochafik-util/.settings/org.maven.ide.eclipse.prefs deleted file mode 100644 index 41ce2f24e..000000000 --- a/libraries/jnaerator/ochafik-util/.settings/org.maven.ide.eclipse.prefs +++ /dev/null @@ -1,9 +0,0 @@ -#Thu Jan 28 23:46:11 CET 2010 -activeProfiles= -eclipse.preferences.version=1 -fullBuildGoals=process-test-resources -includeModules=false -resolveWorkspaceProjects=true -resourceFilterGoals=process-resources resources\:testResources -skipCompilerPlugin=true -version=1 diff --git a/libraries/jnaerator/ochafik-util/pom.xml b/libraries/jnaerator/ochafik-util/pom.xml deleted file mode 100644 index 7e0fd8d21..000000000 --- a/libraries/jnaerator/ochafik-util/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - 4.0.0 - com.nativelibs4java - ochafik-util - OChafik's General Utilities - http://ochafik.free.fr/blog/ - jar - - - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - .. - - - - - diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/beans/BeansUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/beans/BeansUtils.java deleted file mode 100644 index 8ca7dbb88..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/beans/BeansUtils.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.beans; -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Method; - -import com.ochafik.util.string.StringUtils; -public class BeansUtils { - public static final void markTransientProperty(String name,Class classe) throws IntrospectionException { - BeanInfo info = Introspector.getBeanInfo(classe); - PropertyDescriptor[] propertyDescriptors = - info.getPropertyDescriptors(); - for (int i = 0; i < propertyDescriptors.length; ++i) { - PropertyDescriptor pd = propertyDescriptors[i]; - if (pd.getName().equals(name)) { - pd.setValue("transient", Boolean.TRUE); - } - } - } - - public static void addPropertyChangeListener(Object bean, final String propertyName, final PropertyChangeListener listener) { - if (bean == null) - throw new NullPointerException("Null bean !"); - - try { - bean.getClass().getMethod("addPropertyChangeListener", String.class, PropertyChangeListener.class).invoke(bean, propertyName, listener); - } catch (Exception ex) { - try { - bean.getClass().getMethod("addPropertyChangeListener", PropertyChangeListener.class).invoke(bean, new PropertyChangeListener() { - - public void propertyChange(PropertyChangeEvent evt) { - if (propertyName.equals(evt.getPropertyName())) - listener.propertyChange(evt); - } - }); - } catch (Exception ex2) { - throw new RuntimeException(ex); - } - } - } - public static void removePropertyChangeListener(Object bean, String propertyName, PropertyChangeListener listener) { - if (bean == null) - throw new NullPointerException("Null bean !"); - - try { - bean.getClass().getMethod("removePropertyChangeListener", PropertyChangeListener.class).invoke(bean, listener); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - public static Object get(Object bean, String propertyName) { - return get(bean, propertyName, Object.class); - } - - public static T get(Object bean, String propertyName, Class propertyClass) { - if (bean == null) - throw new NullPointerException("Null bean !"); - - try { - String cap = StringUtils.capitalize(propertyName); - Method m; - if (propertyClass == Boolean.class) { - try { - m = bean.getClass().getMethod("is" + cap); - } catch (NoSuchMethodException ex) { - m = bean.getClass().getMethod("get" + cap); - } - } else { - m = bean.getClass().getMethod("get" + cap); - } - return propertyClass.cast(m.invoke(bean)); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - public static void set(Object bean, String propertyName, Class propertyClass, T value) { - if (bean == null) - throw new NullPointerException("Null bean !"); - - try { - bean.getClass().getMethod("set" + StringUtils.capitalize(propertyName), propertyClass).invoke(bean, value); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/FileListUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/FileListUtils.java deleted file mode 100644 index 41eae6f60..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/FileListUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.io; - -import java.io.File; -import java.util.Collection; -import java.util.HashSet; - -public class FileListUtils { - - public static Collection resolveShellLikeFileList(String d) { - HashSet v=new HashSet(); - File f=new File(d); - String name=f.getName(); - File par=f.getParentFile(); - if (par==null) { - par=new File("."); - } - String fs[]=par.list(); - if (fs==null) return v; - for (int i=0; i. -*/ -package com.ochafik.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -import com.ochafik.util.progress.ProgressModel; - - -public class IOUtils { - - public static final long readWrite(InputStream in, OutputStream out) throws IOException { - byte[] b=new byte[4096]; - int len; - long total=0; - while ((len=in.read(b))>0) { - out.write(b, 0, len); - total+=len; - } - return total; - } - - public static final long readWrite(InputStream in, OutputStream out, int maxLen) throws IOException { - int bLen = 4096; - byte[] b=new byte[bLen]; - int len; - long total=0; - - int allowed = bLen <= maxLen ? bLen : maxLen; - while (allowed > 0 && (len=in.read(b, 0, allowed)) > 0) { - out.write(b, 0, len); - total+=len; - maxLen -= len; - allowed = bLen <= maxLen ? bLen : maxLen; - } - return total; - } - - - public static final long readWrite(InputStream in, OutputStream out, ProgressModel progressModel) throws IOException { - byte[] b=new byte[1024]; - int len; - long total=0; - while ((len=in.read(b))>0) { - out.write(b, 0, len); - total+=len; - progressModel.addProgress(len); - } - return total; - } - - public static void readWrite(Reader in, Writer out) throws IOException { - char[] b = new char[1024]; - int len; - long total=0; - while ((len = in.read(b))>0) { - out.write(b, 0, len); - total+=len; - } - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/JTextAreaOutputStream.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/JTextAreaOutputStream.java deleted file mode 100644 index 91f8709c0..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/JTextAreaOutputStream.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ochafik.io; -import java.io.OutputStream; - -import javax.swing.JTextArea; -import javax.swing.SwingUtilities; -public class JTextAreaOutputStream extends OutputStream { - JTextArea ta; - public JTextAreaOutputStream(JTextArea t) { - ta=t; - } - private class Appender implements Runnable { - public Appender(String st) { - string=st; - } - String string; - public void run() { - ta.append(string); - } - }; - public void close() {ta=null;} - public void write(int i) { - SwingUtilities.invokeLater(new Appender(new String(new byte[]{(byte)i}))); - } - public void write(byte b[]) { - SwingUtilities.invokeLater(new Appender(new String(b))); - } - public void write(byte b[],int s,int l) { - SwingUtilities.invokeLater(new Appender(new String(b,s,l))); - } -} - diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/ReadText.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/ReadText.java deleted file mode 100644 index 7db0d81a0..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/ReadText.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.io; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.regex.Pattern; - -//import javax.net.ssl.HostnameVerifier; -//import javax.net.ssl.HttpsURLConnection; -//import javax.net.ssl.SSLSession; - -import com.ochafik.util.string.RegexUtils; -public class ReadText { - public static final String readText(Reader in) throws IOException { - int len; - char ch[]=new char[1024]; - StringBuffer b=new StringBuffer(); - while ((len=in.read(ch))>0) b.append(ch,0,len); - return b.toString(); - } - public static final String readText(File f) { - if (f == null) - return null; - - try { - BufferedReader in=new BufferedReader(new FileReader(f)); - String l; - java.lang.StringBuffer buff=new java.lang.StringBuffer((int)f.length()); - boolean first = true; - while ((l=in.readLine())!=null) { - if (first) - first = false; - else - buff.append('\n'); - buff.append(l); - } - return buff.toString(); - } catch (Exception except) { - except.printStackTrace(); - return null; - } - } - public static final void writeProperties(Properties properties, File file) throws IOException { - File parentFile = file.getParentFile(); - if (!parentFile.exists()) parentFile.mkdirs(); - OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - properties.store(out, file.getName()); - out.close(); - } - public static final Properties readProperties(File file, boolean failIfNotExists) throws IOException { - Properties properties = new Properties(); - if (!file.exists()) { - if (failIfNotExists) { - return null; - } - } else { - InputStream in = new BufferedInputStream(new FileInputStream(file)); - properties.load(in); - in.close(); - } - return properties; - } - private static final Pattern charsetPattern = Pattern.compile(";\\s*charset\\s*=\\s*([\\w-_]+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); - public static final String readText(URL u) throws IOException { - if (u == null) return null; - - String encoding = null; - URLConnection con = u.openConnection(); -// if (con instanceof HttpsURLConnection) { -// ((HttpsURLConnection)con).setHostnameVerifier(new HostnameVerifier() { -// public boolean verify(String hostname, SSLSession session) { -// return true; -// } -// }); -// } - if (con instanceof HttpURLConnection) { - String contentType = con.getContentType(); - encoding = RegexUtils.findFirst(contentType, charsetPattern, 1); - } - InputStream in = con.getInputStream(); - String text = readText(in, encoding); - in.close(); - return text; - } - static Pattern[] embeddedCharsetPatterns = new Pattern[] { - Pattern.compile("CONTENT\\s*=\\s*\"text/\\w+;\\s*charset\\s*=\\s*([^\";\\s]+)\\s*\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL), - Pattern.compile("]*encoding\\s*=\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL), - }; - private static String readText(InputStream in, String encoding) throws IOException { - if (in == null) - return null; - - if (encoding == null) { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - IOUtils.readWrite(in, bout); - byte[] bytes = bout.toByteArray(); - String ascii = new String(bytes, "ascii"); - - for (Pattern charsetPat : embeddedCharsetPatterns) { - encoding = RegexUtils.findFirst(ascii, charsetPat, 1); - if (encoding != null) - break; - } - if (encoding != null) { - try { - return new String(bytes, encoding); - } catch (UnsupportedEncodingException ex) { - ex.printStackTrace(); - } - } - return new String(bytes); - } else { - - BufferedReader rin = new BufferedReader(encoding == null ? new InputStreamReader(in) : new InputStreamReader(in, encoding)); - String l; - StringBuffer buff=new StringBuffer(); - boolean first = true; - while ((l = rin.readLine()) != null) { - if (first) - first = false; - else - buff.append('\n'); - buff.append(l); - } - return buff.toString(); - } - } - public static final String readText(InputStream in) throws IOException { - return readText(in, null); - } - public static final List readLines(String s) throws IOException { - return readLines(new FileReader(s)); - } - public static final List readLines(URL u) throws IOException { - InputStream in = u.openStream(); - List r = readLines(in); - in.close(); - return r; - } - public static final List readLines(InputStream in) throws IOException { - if (in == null) - return null; - List r = readLines(new InputStreamReader(in)); - in.close(); - return r; - } - public static final List readLines(Reader r) throws IOException { - List v=new ArrayList(); - BufferedReader in=new BufferedReader(r); - String l; - while ((l=in.readLine())!=null) //if (!(l=l.trim()).equals("")) - v.add(l); - return v; - } - public static final String[] readLinesArray(String s) throws IOException { - List v=readLines(s); - String ret[]=new String[v.size()]; - int i=0; - for (String line : v) { - ret[i++]=line; - } - return ret; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/StringBufferOutputStream.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/StringBufferOutputStream.java deleted file mode 100644 index 76b814b6d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/StringBufferOutputStream.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.io; -import java.io.IOException; -import java.io.OutputStream; -public class StringBufferOutputStream extends OutputStream { - StringBuffer buffer; - public StringBufferOutputStream() { - buffer=new StringBuffer(); - } - public String toString() { return buffer.toString(); } - public StringBufferOutputStream(StringBuffer b) { - buffer=b; - } - public StringBufferOutputStream(String s) { - buffer=new StringBuffer(s); - } - public void close() throws IOException { - buffer=null; - } - public void flush() throws IOException {} - public void write(int i) throws IOException { - buffer.append((char)i); - } - public void write(byte[] b,int off,int l) throws IOException { - buffer.append(new String(b,off,l)); - } - public void write(byte[] b) throws IOException { - buffer.append(new String(b)); - } -} - diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/WriteText.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/WriteText.java deleted file mode 100644 index cb6e2184c..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/io/WriteText.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.io; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -public class WriteText { - public static final void writeText(String t,File f) throws IOException { - File p = f.getParentFile(); - if (p != null && !p.exists()) - p.mkdirs(); - - PrintWriter out=new PrintWriter(new FileWriter(f)); - String l; - BufferedReader in=new BufferedReader(new StringReader(t)); - while ((l=in.readLine())!=null) out.println(l); - out.close(); - in.close(); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/junit/ParameterizedWithDescription.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/junit/ParameterizedWithDescription.java deleted file mode 100644 index 28ee5b7ad..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/junit/ParameterizedWithDescription.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.junit; - - -public class ParameterizedWithDescription {} /*extends CompositeRunner { - static class TestClassRunnerForParameters extends JUnit4ClassRunner { - private final Object[] fParameters; - - private final int fParameterSetNumber; - - private final Constructor fConstructor; - - TestClassRunnerForParameters(TestClass testClass, Object[] parameters, int i) throws InitializationError { - super(testClass.getJavaClass()); //todo - fParameters= parameters; - fParameterSetNumber= i; - fConstructor= getOnlyConstructor(); - } - - @Override - protected Object createTest() throws Exception { - return fConstructor.newInstance(fParameters); - } - - @Override - protected String getName() { - try { - return String.valueOf(fParameters[0]).replaceAll("(?s)\n.*", "...");//replace('\n', ' '); - } catch (Throwable t) { - t.printStackTrace(); - } - return String.format("[%s]", fParameterSetNumber); - } - - @Override - protected String testName(final Method method) { - try { - return method.getName() + " : " + String.valueOf(fParameters[0]).replace('\n', ' '); - } catch (Throwable t) { - t.printStackTrace(); - } - return String.format("%s[%s]", method.getName(), fParameterSetNumber); - } - - private Constructor getOnlyConstructor() { - Constructor[] constructors= getTestClass().getJavaClass().getConstructors(); - Assert.assertEquals(1, constructors.length); - return constructors[0]; - } - - @Override - protected void validate() throws InitializationError { - // do nothing: validated before. - } - - @Override - public void run(RunNotifier notifier) { - runMethods(notifier); - } - } - - private final TestClass fTestClass; - - public ParameterizedWithDescription(Class klass) throws Exception { - super(klass.getName()); - fTestClass= new TestClass(klass); - - MethodValidator methodValidator= new MethodValidator(fTestClass); - methodValidator.validateStaticMethods(); - methodValidator.validateInstanceMethods(); - methodValidator.assertValid(); - - int i= 0; - for (final Object each : getParametersList()) { - if (each instanceof Object[]) - add(new TestClassRunnerForParameters(fTestClass, (Object[])each, i++)); - else - throw new Exception(String.format("%s.%s() must return a Collection of arrays.", fTestClass.getName(), getParametersMethod().getName())); - } - } - - @Override - public void run(final RunNotifier notifier) { - new ClassRoadie(notifier, fTestClass, getDescription(), new Runnable() { - public void run() { - runChildren(notifier); - } - }).runProtected(); - } - - private Collection getParametersList() throws IllegalAccessException, InvocationTargetException, Exception { - return (Collection) getParametersMethod().invoke(null); - } - - private Method getParametersMethod() throws Exception { - List methods= fTestClass.getAnnotatedMethods(Parameters.class); - for (Method each : methods) { - int modifiers= each.getModifiers(); - if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) - return each; - } - - throw new Exception("No public static parameters method on class " + getName()); - } - - public static Collection eachOne(Object... params) { - List results= new ArrayList(); - for (Object param : params) - results.add(new Object[] { param }); - return results; - } -}*/ diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/AssertUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/AssertUtils.java deleted file mode 100644 index 45be5c5f9..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/AssertUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang; - -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.Iterator; - -import com.ochafik.lang.reflect.DebugUtils; - -public class AssertUtils { - public static final boolean unorderedEqual(Collection c1, Collection c2) { - if (c1.size() != c2.size()) return false; - - return c1.containsAll(c2) && c2.containsAll(c1); - } - - public static final boolean orderedEqual(Collection c1, Collection c2) { - if (c1.size() != c2.size()) return false; - Iterator i1 = c1.iterator(), i2 = c2.iterator(); - while (i1.hasNext() && i2.hasNext()) { - T t1 = i1.next(), t2 = i2.next(); - if ((t1 == null) != (t2 == null)) return false; - if (t1 != null) { - if (!(t1.equals(t2) && t2.equals(t1))) return false; - } - } - return (i1.hasNext() == i2.hasNext()); - } - - public static class Test { - int value; - String strr = "This is\nA test..."; - - public String getStrr() { - return strr; - } - } - - - public static void main(String[] args) { - //print(new int[] { 1, 2, 3, 4}); - DebugUtils.println(new Object[] { new Test(), }, new DebugUtils.FieldAccessor() { - public Object access(Field f, Object target) throws IllegalArgumentException, IllegalAccessException { - return f.get(target); - } - }); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/ClassUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/ClassUtils.java deleted file mode 100644 index d68f42378..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/ClassUtils.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ochafik.lang; - -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLDecoder; - -public class ClassUtils { - public static URL getClassPath(Class c) { - String classFile = c.getName().replace('.', '/') + ".class"; - URL url = c.getClassLoader().getResource(classFile); - if (url == null) - return null; - - if (url.getProtocol().equals("jar")) { - String urlFile = url.getFile(); - int i = urlFile.indexOf("!"); - if (i > 0) { - try { - URL jarURL = new URL(URLDecoder.decode(urlFile.substring(0, i), "UTF-8")); - return jarURL; - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - String urlString = url.toString(); - if (urlString.endsWith(classFile)) { - try { - return new URL(urlString.substring(0, urlString.length() - classFile.length())); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - return null; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/SyntaxUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/SyntaxUtils.java deleted file mode 100644 index 34c2915ae..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/SyntaxUtils.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang; - -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.text.DateFormat; -import java.text.ParseException; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.NoSuchElementException; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -public class SyntaxUtils { - public static T[] array(T... elements) { - return elements; - } - - public static boolean equal(T a, T b) { - if (a == null) - return b == null; - if (b == null) - return false; - return a == b || a.equals(b); - } - - public static T as(Object value, Class c) { - if (value == null) - return null; - if (c.isAssignableFrom(value.getClass())) - return c.cast(value); - return null; - } - - interface Converter { - public T convert(Object value) throws Exception; - } - - public static void registerConverter(Class c, Converter converter) { - converters.put(c, converter); - } - - static Map, Converter> converters = new HashMap, Converter>(); - static { - registerConverter(Date.class, new Converter() { - public Date convert(Object value) throws ParseException { - String s = value.toString(); - Date date = DateFormat.getDateTimeInstance().parse(s); - if (date == null) - date = DateFormat.getDateInstance().parse(s); - return date; - } - }); - - registerConverter(Double.class, new Converter() { - public Double convert(Object value) throws ParseException { - if (value instanceof Number) - return ((Number)value).doubleValue(); - String s = value.toString(); - if (s.length() == 0) - return 0.0; - - return Double.parseDouble(s); - } - }); - registerConverter(Float.class, new Converter() { - public Float convert(Object value) throws ParseException { - if (value instanceof Number) - return ((Number)value).floatValue(); - String s = value.toString(); - if (s.length() == 0) - return 0f; - - return Float.parseFloat(s); - } - }); - registerConverter(Long.class, new Converter() { - public Long convert(Object value) throws ParseException { - if (value instanceof Number) - return ((Number)value).longValue(); - String s = value.toString(); - if (s.length() == 0) - return 0l; - - return Long.parseLong(s); - } - }); - registerConverter(Integer.class, new Converter() { - public Integer convert(Object value) throws ParseException { - if (value instanceof Number) - return ((Number)value).intValue(); - String s = value.toString(); - if (s.length() == 0) - return 0; - - return Integer.parseInt(s); - } - }); - registerConverter(Short.class, new Converter() { - public Short convert(Object value) throws ParseException { - if (value instanceof Number) - return ((Number)value).shortValue(); - String s = value.toString(); - if (s.length() == 0) - return 0; - - return Short.parseShort(s); - } - }); - registerConverter(String.class, new Converter() { - public String convert(Object value) throws ParseException { - if (value instanceof Date) - return DateFormat.getDateInstance().format((Date)value); - return value.toString(); - } - }); - registerConverter(File.class, new Converter() { - public File convert(Object value) throws ParseException { - if (value instanceof URI) - try { - value = ((URI)value).toURL(); - } catch (MalformedURLException e1) {} - - if (value instanceof String) { - try { - value = new URL((String)value); - } catch (MalformedURLException e) {} - } - if (value instanceof URL) - return new File(((URL)value).getFile()); - - String s = value.toString(); - if (s.length() == 0) - return null; - - return new File(s); - } - }); - registerConverter(URL.class, new Converter() { - public URL convert(Object value) { - if (value instanceof URI) - try { - return ((URI)value).toURL(); - } catch (MalformedURLException e1) {} - - if (value instanceof File) - try { - return ((File)value).toURI().toURL(); - } catch (MalformedURLException e1) {} - - String s = value.toString(); - if (s.length() == 0) - return null; - - try { - return new URL(s); - } catch (MalformedURLException e) {} - - try { - return new File(s).toURI().toURL(); - } catch (MalformedURLException e) {} - - return null; - } - }); - } - - @SuppressWarnings("unchecked") - public static T convert(Object value, Class c) { - if (value == null) - return null; - - Class type = value.getClass(); - if (c.isAssignableFrom(type)) - return c.cast(value); - - Converter converter = (Converter)converters.get(c); - if (converter != null) - try { - return converter.convert(value); - } catch (Exception e) { - e.printStackTrace(); - } - - for (Constructor cons : c.getConstructors()) { - Class[] parameterTypes = cons.getParameterTypes(); - if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(type)) { - try { - return (T)cons.newInstance(value); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - for (Method meth : c.getMethods()) { - String name = meth.getName(); - if ((meth.getModifiers() & Modifier.STATIC) == 0) - continue; - - if (!" parse createInstance newInstance ".contains(" " + name + " ")) - continue; - - Class[] parameterTypes = meth.getParameterTypes(); - if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(type)) { - try { - return (T)meth.invoke(null, value); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return null; - } - - public static class EasyMap extends LinkedHashMap { - private static final long serialVersionUID = -3087972422440202407L; - - public EasyMap add(K key, V value) { - put(key, value); - return this; - } - } - public static EasyMap map(K key, V value) { - return new EasyMap().add(key, value); - } - - @SuppressWarnings("unchecked") - public static Iterable iterable(final NodeList list) { - if (list == null) - return Collections.EMPTY_LIST; - - return new Iterable() { - int nextPos = 0; - public Iterator iterator() { - return new Iterator() { - public Node next() { - if (nextPos >= list.getLength()) - throw new NoSuchElementException(); - return list.item(nextPos++); - } - public boolean hasNext() { - return nextPos < list.getLength(); - } - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/Threads.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/Threads.java deleted file mode 100644 index 31d0e92f9..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/Threads.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -/** - * - */ -package com.ochafik.lang; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.Semaphore; - -/** - *

      - * Group of coordinated Runnable instances that can be started, interrupted and waited for together. - *

      - * Once you added as many runnable tasks as needed through the add(Runnable) method, - * there are two ways of waiting for the tasks to finish : - *

        - *
      • call join() in some thread. This will implicitely start the threads if start() was not called yet, and the join() method will not return until all the thread finished their execution - *
      • call start() and register some ActionListener instances. Whenever all threads finished their execution, the actionPerformed method of all the listeners will be called. - *
      • - * @author Olivier Chafik - */ -public final class Threads { - private final List runners = new ArrayList(); - private final Semaphore semaphore = new Semaphore(0); - private boolean fired = false, started = false; - - private List actionListeners; - - private class Runner extends Thread { - private final Runnable runnable; - public Runner(Runnable runnable) { - this.runnable = runnable; - } - public void run() { - try { - runnable.run(); - } finally { - int nThreads = runners.size(); - if (semaphore.tryAcquire(nThreads - 1)) { - semaphore.release(nThreads); - synchronized (this) { - if (!fired) { - fired = true; - fireActionPerformed(); - } - } - } else { - semaphore.release(); - } - } - } - } - - /** - * Add a task that is to be executed in its own thread. - * @param runnable task to be executed in its own thread - * @return the runnable argument unchanged - */ - public synchronized T add(T runnable) { - if (started) - throw new IllegalThreadStateException("Cannot add another runnable to " + getClass().getSimpleName() + " after it started !"); - - runners.add(new Runner(runnable)); - return runnable; - } - - /** - * Starts all the threads. - * @throws IllegalThreadStateException if the threads were already started. - * @throws NoSuchElementException if no runnable were added to this Threads instance. - */ - public synchronized void start() { - if (started) - throw new IllegalThreadStateException(getClass().getSimpleName() + " already started !"); - - if (runners.isEmpty()) - throw new NoSuchElementException("No runnable were added to this " + getClass().getSimpleName()); - - for (Runner t : runners) { - t.start(); - } - started = true; - } - - /** - * Calls interrupt() on each of the running threads. - * @throws IllegalThreadStateException if threads were not started - */ - public synchronized void interrupt() { - if (!started) - throw new IllegalThreadStateException(getClass().getSimpleName() + " not started !"); - - for (Runner t : runners) { - try { - t.interrupt(); - } catch (IllegalThreadStateException ex) { - // t might have finished its execution - ex.printStackTrace(); - } - } - } - - /** - * Waits for all runnable to have finished their execution. - * Can be called multiple times : after the first time, this method always returns immediately. - * If the Threads is not started yet, this method will start it implicitely. - * @throws InterruptedException if method interrupt() was called on the thread that is calling this method. - */ - public synchronized void join() throws InterruptedException { - int nThreads = runners.size(); - if (nThreads == 0) - return; - - if (!started) - start(); - - semaphore.acquire(nThreads); - semaphore.release(nThreads); - } - - public enum State { - NotStarted, Running, Finished, NoRunnables - } - - public synchronized State getState() { - int nThreads = runners.size(); - if (nThreads == 0) - return State.NoRunnables; - - if (!started) - return State.NotStarted; - - if (semaphore.tryAcquire(nThreads)) { - semaphore.release(nThreads); - return State.Finished; - } - return State.Running; - } - - /** - * Adds a listener that will be notified upon completion of all of the running threads. - * Its actionPerformed method will be called immediately if the threads already finished. - * @param actionListener - */ - public synchronized void addActionListener(ActionListener actionListener) { - if (actionListeners == null) - actionListeners = new ArrayList(); - - actionListeners.add(actionListener); - - if (fired) { - actionListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "")); - } - } - - private synchronized void fireActionPerformed() { - if (actionListeners == null) - return; - - ActionEvent a = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""); - for (ActionListener l : actionListeners) - l.actionPerformed(a); - } - -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/DebugUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/DebugUtils.java deleted file mode 100644 index b6c1b9fd5..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/DebugUtils.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.reflect; - -import java.io.PrintStream; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Set; -import java.util.TreeSet; - -import com.ochafik.io.StringBufferOutputStream; -import com.ochafik.lang.AssertUtils; - -public class DebugUtils { - - public static abstract class FieldAccessor { - public abstract Object access(Field f, Object target) throws IllegalArgumentException, IllegalAccessException; - //public Object access(Field f, Object target) throws IllegalArgumentException, IllegalAccessException { - //return f.get(target); - //} - } - - public static final void print(Object o, FieldAccessor accessor) { - print(o, System.out, false, false, "", accessor); - } - - public static final void printErr(Object o, FieldAccessor accessor) { - print(o, System.err, false, false, "", accessor); - } - - public static final void println(Object o, FieldAccessor accessor) { - print(o, System.out, true, false, "", accessor); - } - - public static final void printlnErr(Object o, FieldAccessor accessor) { - print(o, System.err, true, false, "", accessor); - } - - public static final void print(Object o) { - print(o, System.out, false, false, "", null); - } - - public static final void printErr(Object o) { - print(o, System.err, false, false, "", null); - } - - public static final void println(Object o) { - print(o, System.out, true, false, "", null); - } - public static final void println(Object o, PrintStream out) { - print(o, out, true, false, "", null); - } - - public static final void printlnErr(Object o) { - print(o, System.err, true, false, "", null); - } - - protected static String escape(String s) { - return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t").replace("\r", ""); - } - public static final void printAsCharSequence(CharSequence o, PrintStream out, boolean lines, boolean startIndent, String indent, FieldAccessor accessor) { - out.print('"'); - out.print(escape(((CharSequence)o).toString())); - out.print('"'); - if (lines) out.println(); - } - - public static final void printStructureInsides(Object o, PrintStream out, boolean lines, boolean startIndent, String indent, FieldAccessor accessor) { - Class type = o.getClass(); - Set fields = getFields(type); - int i = 0; - for (Field f : fields) { - boolean inaccessibleValue = false; - Object v; - try { - //f.isAccessible() - v = accessor == null ? f.get(o) : accessor.access(f, o); - } catch (IllegalAccessException ex) { - // field is private and from a different package than the accessor ! Try using a getter - String fn = f.getName(); - try { - Method m = type.getMethod("get" + fn.substring(0,1).toUpperCase() + fn.substring(1), new Class[0]); - v = m.invoke(o, new Object[0]); - } catch (Exception e) { - inaccessibleValue = true; - v = null; - } - } catch (Exception e) { - throw new RuntimeException(e); - } - if (lines) { - out.print(indent); - } else if (i++ != 0) out.print("; "); - - out.print(f.getName()); - out.print(" = "); - if (inaccessibleValue) { - out.print('?'); - } else { - print(v, out, lines, false, indent, accessor); - } - } - } - - public static final void print(Object o, PrintStream out, boolean lines, boolean startIndent, String indent, FieldAccessor accessor) { - if (lines && startIndent) out.print(indent); - - if (o == null) { - out.print(o); - if (lines) out.println(); - return; - } - Class type = o.getClass(); - boolean isCollection = o instanceof Collection; - - if (o instanceof CharSequence) { - out.print('"'); - out.print(escape(o.toString())); - out.print('"'); - if (lines) out.println(); - return; - } else if (type == Character.class) { - out.print('\''); - out.print(escape(o.toString())); - out.print('\''); - if (lines) out.println(); - return; - } else if (!isCollection && hasToStringMethod(type)) { - out.print(o); - if (lines) out.println(); - return; - } - out.print(type.getSimpleName()); - out.print(" {"); - if (lines) out.println(); - - String newIndent = indent + "\t"; - - if (type.isArray()) { - for (int i = 0, n = Array.getLength(o); i < n; i++) { - if (!lines && i != 0) out.print(", "); - print(Array.get(o, i), out, lines, true, newIndent, accessor); - } - } else if (isCollection) { - int i = 0; - for (Object e : (Collection)o) { - if (!lines && i++ != 0) out.print(", "); - print(e, out, lines, true, newIndent, accessor); - } - } else { - printStructureInsides(o, out, lines, startIndent, newIndent, accessor); - } - if (lines) out.print(indent); - out.print("}"); - if (lines) out.println(); - } - - public static Set getFields(Class type) { - Set fields = new TreeSet(new Comparator() { public int compare(Field o1, Field o2) { - return o1.getName().compareTo(o2.getName()); - }}); - fields.addAll(Arrays.asList(type.getFields())); - do { - fields.addAll(Arrays.asList(type.getDeclaredFields())); - } while ((type = type.getSuperclass()) != null); - return fields; - } - protected static void getFields_aux(Class type, Set fields) { - - } - - public static boolean hasToStringMethod(Class c) { - if (c == Object.class) return false; - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals("toString") && m.getParameterTypes().length == 0) { - return true; - } - } - return hasToStringMethod(c.getSuperclass()); - } - - public static void main(String[] args) { - //print(new int[] { 1, 2, 3, 4}); - println(new Object[] { new AssertUtils.Test(), }, new FieldAccessor() { - public Object access(Field f, Object target) throws IllegalArgumentException, IllegalAccessException { - return f.get(target); - } - }); - } - - public static String toString(Object object) { - StringBufferOutputStream out = new StringBufferOutputStream(); - print(object, new PrintStream(out), false, false,"", null); - return out.toString(); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/GettersAndSettersHelper.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/GettersAndSettersHelper.java deleted file mode 100644 index 719db0d0f..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/lang/reflect/GettersAndSettersHelper.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.lang.reflect; - -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import com.ochafik.util.string.RegexUtils; -import com.ochafik.util.string.StringUtils; - -public class GettersAndSettersHelper { - public static class GetterAndSetterInfo { - public Method getter; - public Method setter; - //public Field field; - public String fieldName; - public boolean isFull() { - return getter != null && setter != null; - } - public Class elementType; - public GetterAndSetterInfo(String fieldName, Class elementType, Method getter, Method setter, Field field) { - this.elementType = elementType; - this.fieldName = fieldName; - this.getter = getter; - this.setter = setter; - //this.field = field; - } - public GetterAndSetterInfo() {} - public boolean isConsistent() { - if (getter == null || setter == null) - return true; - - Class[] pts = setter.getParameterTypes(); - return pts.length == 1 && pts[0].isAssignableFrom(getter.getReturnType()); - } - } - - public final Map gettersAndSetters = new HashMap(); - - static Pattern getterSetterPattern = Pattern.compile("(is|get|set)([A-Z]\\w+)"); - - public GettersAndSettersHelper(Class type, FieldGetter fieldGetter) { - this.fieldGetter = fieldGetter; - for (Method method : type.getMethods()) { - int nParams = method.getParameterTypes().length; - if (nParams > 1) - continue; - - String name = method.getName(); - String match[] = RegexUtils.match(name, getterSetterPattern); - if (match != null) { - Class returnType = method.getReturnType(); - String fieldName = StringUtils.uncapitalize(match[2]); - boolean isGetter = !match[1].equals("set"); - if (isGetter) { - if (nParams == 0) { - GetterAndSetterInfo getterAndSetter = getOrCreatePair(fieldName); - if (getterAndSetter.getter != null) { - if (getterAndSetter.getter.getReturnType().isAssignableFrom(returnType)) { - // refinement - getterAndSetter.getter = method; - } - } else { - getterAndSetter.getter = method; - } - - if (!getterAndSetter.isConsistent()) - getterAndSetter.setter = null; - - } - //assertNull("Already found getter " + getterAndSetter.getter, getterAndSetter.getter); - //getterAndSetter.setFirst(method); - } else if (nParams == 1) { - GetterAndSetterInfo getterAndSetter = getOrCreatePair(fieldName); - //assertNull("Already found setter " + getterAndSetter.setter, getterAndSetter.setter); - //assert getterAndSetter.setter == null; - if (getterAndSetter.setter == null) { - getterAndSetter.setter = method; - if (!getterAndSetter.isConsistent()) - getterAndSetter.setter = null; - } - } - } - } - /* - for (Map.Entry e : gettersAndSetters.entrySet()) { - if (e.getValue().setter == null) - continue; - try { - e.getValue().field = fieldGetter == null ? type.getField(e.getKey()) : fieldGetter.getField(type, e.getKey()); - } catch (Exception ex) { - assertTrue("Failed to find field '" + e.getKey() + "' in " + type.getName(), false); - } - }*/ - /*for (Field field : type.getFields()) { - GetterAndSetterInfo info = gettersAndSetters.get(field.getName()); - if (info == null) - continue; - info.field = field; - }*/ - } - final FieldGetter fieldGetter; - public interface FieldGetter { - public Field getField(Class c, String name) throws SecurityException, NoSuchFieldException; - } - public Set getFieldNames() { - return gettersAndSetters.keySet(); - } - public Method getGetter(String fieldName) { - GetterAndSetterInfo pair = gettersAndSetters.get(fieldName); - return pair == null ? null : pair.getter; - } - public Method getSetter(String fieldName) { - GetterAndSetterInfo pair = gettersAndSetters.get(fieldName); - return pair == null ? null : pair.setter; - } - public Type getFieldType(String fieldName) { - GetterAndSetterInfo pair = gettersAndSetters.get(fieldName); - if (pair == null) - return null; - if (pair.getter != null) - return pair.getter.getGenericReturnType(); - if (pair.setter != null) - return pair.setter.getGenericParameterTypes()[0]; - return null; - } - public void assertConsistentPair(GetterAndSetterInfo p) { - if (p.getter != null && p.setter != null) { - Class getType = p.getter.getReturnType(), - setType = p.setter.getParameterTypes()[0]; - - //assertTrue("Setter argument cannot be given getter result", setType.isAssignableFrom(getType)); - assert setType.isAssignableFrom(getType); - } - } - protected GetterAndSetterInfo getOrCreatePair(String fieldName) { - GetterAndSetterInfo getterAndSetter = gettersAndSetters.get(fieldName); - if (getterAndSetter == null) - gettersAndSetters.put(fieldName, getterAndSetter = new GetterAndSetterInfo()); - - return getterAndSetter; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/Adapter.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/Adapter.java deleted file mode 100644 index 6da38c4d2..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/Adapter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util; - -public interface Adapter { - public V adapt(U value); - public U reAdapt(V value); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CollectionAdapter.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CollectionAdapter.java deleted file mode 100644 index 17662ac1c..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CollectionAdapter.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util; -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Iterator; -public class CollectionAdapter extends AbstractCollection { - protected Collection collection; - protected Adapter adapter; - public CollectionAdapter(Collection collection,Adapter adapter) { - this.collection=collection; - this.adapter=adapter; - } - @Override - public Iterator iterator() { - return new IteratorAdapter(collection.iterator()); - } - @Override - public int size() { - return collection.size(); - } - @Override - public boolean isEmpty() { - return collection.isEmpty(); - } - @Override - public void clear() { - collection.clear(); - } - @Override - public boolean add(V o) { - return collection.add(adapter.reAdapt(o)); - } - @Override - public boolean contains(Object o) { - for (U element : collection) { - if (adapter.adapt(element).equals(o)) { - return true; - } - } - return false; - } - protected class IteratorAdapter implements Iterator { - Iterator iterator; - public IteratorAdapter(Iterator iterator) { - this.iterator=iterator; - } - public boolean hasNext() { - return iterator.hasNext(); - } - public V next() { - return adapter.adapt(iterator.next()); - } - public void remove() { - iterator.remove(); - } - } - /*protected abstract V adapt(U value); - protected U reAdapt(V value) { - throw new UnsupportedOperationException(); - }*/ -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CompoundCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CompoundCollection.java deleted file mode 100644 index 96739ab84..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/CompoundCollection.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Vector; - -/* - * This is a Collection that gathers the content of several collections, without the need to create - * a big structure and add them all to it. It is space and speed efficient (except for containsAll(Collection)), - * however it does not implement add(U) and addAll(Collection) optional methods. - * - * It should be use in cases where you want to iterate through several collections as through one. - */ -public class CompoundCollection implements Collection { - Collection > collections; - public CompoundCollection() { - collections=new LinkedList >(); - } - public CompoundCollection(Collection> lists) { - collections = new ArrayList>(lists); - } - public CompoundCollection(Collection... lists) { - this(Arrays.asList(lists)); - } - public void addComponent(Collection col) { - collections.add(col); - } - public boolean removeComponent(Collection col) { - return collections.remove(col); - } - public int size() { - int s=0; - for (Collection col : collections) { - s+=col.size(); - } - return s; - } - public void clearComponents() { - collections.clear(); - } - public void clear() { - for (Collection col : collections) { - col.clear(); - } - } - public boolean isEmpty() { - for (Collection col : collections) { - if (!col.isEmpty()) { - return false; - } - } - return true; - } - public Object[] toArray() { - int len=size(); - Object[] a=new Object[len]; - int i=0; - for (U element : this) { - a[i]=element; - } - return a; - } - @SuppressWarnings("unchecked") - //@Deprecated - public T[] toArray(T[] objects) { - int size=size(); - Class clazz=(Class)objects.getClass().getComponentType(); - T[] array=(T[])Array.newInstance(clazz,size); - int i=0; - for (Object element : this) { - array[i]=clazz.cast(element); - } - return array; - } - @Deprecated - public boolean add(U object) { - throw new UnsupportedOperationException(); - } - public boolean contains(Object object) { - for (Collection col : collections) { - if (col.contains(object)) { - return true; - } - } - return false; - } - public boolean remove(Object object) { - boolean changed=false; - for (Collection col : collections) { - if (col.remove(object)) { - changed=true; - //return true; - } - } - return changed; - //return false; - } - @Deprecated - public boolean addAll(Collection col) { - boolean changed=false; - for (U u : col) { - changed=add(u) || changed; - } - return changed; - } - public boolean containsAll(Collection col) { - for (Object o : col) { - if (!contains(o)) { - return false; - } - } - return true; - } - public boolean removeAll(Collection col) { - boolean changed=false; - for (Object o : col) { - changed=remove(o) || changed; - } - return changed; - } - public boolean retainAll(Collection col) { - boolean changed=false; - for (Iterator it=iterator();it.hasNext();) { - if (!col.contains(it.next())) { - it.remove(); - changed=true; - } - } - return changed; - } - public Iterator iterator() { - //final Iterator firstIterator=first.iterator(),restIterator=rest.iterator(); - return new Iterator() { - Iterator> collectionsIterator=collections.iterator(); - Iterator currentCollectionIterator= - collectionsIterator.hasNext() ? - collectionsIterator.next().iterator() : - new Vector(0).iterator(); - public boolean hasNext() { - boolean collectionExhausted=false; - do { - collectionExhausted=true; - if (currentCollectionIterator.hasNext()) { - return true; - } else if (collectionsIterator.hasNext()) { - currentCollectionIterator=collectionsIterator.next().iterator(); - collectionExhausted=false; - } - } while (!collectionExhausted); - return false; - } - public U next() { - boolean collectionExhausted=false; - do { - collectionExhausted=true; - if (currentCollectionIterator.hasNext()) { - return currentCollectionIterator.next(); - } else { - currentCollectionIterator=collectionsIterator.next().iterator(); - collectionExhausted=false; - } - } while (!collectionExhausted); - return null; - } - public void remove() { - currentCollectionIterator.remove(); - } - }; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/DefaultAdapter.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/DefaultAdapter.java deleted file mode 100644 index 732dfbcf3..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/DefaultAdapter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util; - -public class DefaultAdapter implements Adapter, com.ochafik.util.listenable.Adapter { - public V adapt(U value) { - throw new UnsupportedOperationException(); - } - - public U reAdapt(V value) { - throw new UnsupportedOperationException(); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IntArray.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IntArray.java deleted file mode 100644 index 938263f94..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IntArray.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * - */ -package com.ochafik.util; - -import java.util.Iterator; - -public interface IntArray extends Iterable { - public int[] getBackingArray(); - public int size(); - public int get(int pos); - public int[] toArray(); - - public class IntIterator implements Iterator { - int i = -1; - IntArray array; - - public boolean hasNext() { - return i < array.size() - 1; - } - - public Integer next() { - return array.get(++i); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - } -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IteratorEnumeration.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IteratorEnumeration.java deleted file mode 100644 index 4433d961d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/IteratorEnumeration.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ochafik.util; -import java.util.Enumeration; -import java.util.Iterator; -@SuppressWarnings("unchecked") -public class IteratorEnumeration implements Enumeration { - Iterator it; - public IteratorEnumeration(Iterator it) { - this.it=it; - } - public boolean hasMoreElements() { - return it.hasNext(); - } - public Object nextElement() { - return it.next(); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SortedIntArray.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SortedIntArray.java deleted file mode 100644 index 90e0ecce3..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SortedIntArray.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ochafik.util; - -public interface SortedIntArray extends IntArray { - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SystemUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SystemUtils.java deleted file mode 100644 index 93a3ccad2..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/SystemUtils.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; - -public class SystemUtils { - public static final void runSystemCommand(String[] cmd) throws NoSuchMethodException { - try { - Runtime.getRuntime().exec(cmd); - } catch (Exception ex) { - ex.printStackTrace(); - throw new NoSuchMethodException(ex.toString()); - } - } - public static final void runSystemCommand(String cmd) throws NoSuchMethodException { - try { - Runtime.getRuntime().exec(cmd); - } catch (Exception ex) { - ex.printStackTrace(); - throw new NoSuchMethodException(ex.toString()); - } - } - static String osName; - static { - // For possible values, see http://lopica.sourceforge.net/os.html - osName = System.getProperty("os.name"); - } - - public static boolean isMacOSX() { - return osName.equals("Mac OS X"); - } - public static boolean isWindows() { - return osName.indexOf("Windows") >= 0; - } - public static boolean isLinux() { - return osName.indexOf("Linux") >= 0; - } - public static boolean isSolaris() { - return osName.indexOf("Solaris") >= 0 || osName.indexOf("SunOS") >= 0; - } - public static boolean isUnix() { - return File.separatorChar == '/'; - } - public static final void runSystemOpenURL(URL url) throws NoSuchMethodException, IOException { - if (isMacOSX()) { - runSystemCommand(new String[] {"open",url.toString()}); - } else if (isWindows()) { - runSystemCommand(new String[] {"rundll32","url.dll,FileProtocolHandler", url.toString()}); - } else if (isLinux()) { - if (hasUnixCommand("gnome-open")) { - runSystemCommand(new String[] {"gnome-open", url.toString()}); - } else { - runSystemCommand(new String[] {"konqueror", url.toString()}); - } - } else { - if (url.getProtocol().equals("file")) { - runSystemOpenFileParent(new File(url.getFile())); - } else { - runSystemCommand(new String[] {"mozilla",url.toString()}); - } - } - } - public static final boolean hasUnixCommand(String name) { - try { - Process p = Runtime.getRuntime().exec(new String[] {"which",name}); - return p.waitFor() == 0; - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - public static final void runSystemOpenFileWith(File fileToOpen) throws NoSuchMethodException, IOException { - runSystemCommand(new String[] {"RUNDLL32.EXE", "SHELL32.DLL,OpenAs_RunDLL",fileToOpen.getCanonicalPath()}); - } - public static final void runSystemOpenFile(File fileToOpen) throws NoSuchMethodException, IOException { - if (isMacOSX()) { - runSystemCommand(new String[] {"open",fileToOpen.getCanonicalPath()}); - } else if (isWindows()) { - runSystemCommand(new String[] {"start",fileToOpen.getCanonicalPath()}); - } else if (isLinux()) { - if (hasUnixCommand("gnome-open")) { - runSystemCommand(new String[] {"gnome-open", fileToOpen.getCanonicalPath()}); - } else { - runSystemCommand(new String[] {"konqueror", fileToOpen.getCanonicalPath()}); - } - } else if (isSolaris()) { - if (fileToOpen.isDirectory()) { - runSystemCommand(new String[] {"/usr/dt/bin/dtfile","-folder",fileToOpen.getCanonicalPath()}); - } - } - } - public static final void runSystemOpenDirectory(File file) throws NoSuchMethodException, IOException { - if (isWindows()) { - runSystemCommand(new String[] {"explorer", file.getCanonicalPath()}); - } else { - runSystemOpenFile(file); - } - } - public static final void runImageEditor(File imageFile) throws NoSuchMethodException, IOException { - if (!imageFile.exists()) throw new FileNotFoundException(imageFile.toString()); - if (isWindows()) { - Runtime.getRuntime().exec(new String[] { "mspaint.exe", imageFile.getAbsolutePath()}); - } else { - throw new NoSuchMethodException("Implement me ! Image editor on " + osName); - } - } - public static final void runSystemOpenFileParent(File fileToShow) throws NoSuchMethodException, IOException { - if (isMacOSX()) { - runSystemCommand(new String[] {"open",fileToShow.getParentFile().getAbsolutePath()}); - } else if (isWindows()) { - runSystemCommand("explorer /e,/select,\""+fileToShow.getCanonicalPath()+"\""); - } else if (isLinux()) { - if (hasUnixCommand("gnome-open")) { - runSystemCommand(new String[] {"gnome-open", fileToShow.getParentFile().getAbsolutePath()}); - } else { - runSystemCommand(new String[] {"konqueror", fileToShow.getParentFile().getAbsolutePath()}); - } - } else if (isSolaris()) { - runSystemCommand(new String[] {"/usr/dt/bin/dtfile","-folder",fileToShow.getParentFile().getCanonicalPath()}); - } - } - public static final JComponent createFileShowAndOpenWithPanel(final File file) { - String osName=System.getProperty("os.name").toLowerCase(); - if (osName.indexOf("windows") >= 0) { - //JButton bOpen=new JButton("Open"); - JButton bSee=new JButton("Dir."); - JButton bOpenWith=new JButton("Open with..."); - - bSee.setToolTipText("Browse directory :
        "+file.getParentFile().toString()+""); - //bOpen.setToolTipText("Open file :
        "+file.toString()+""); - - /*bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFile(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }});*/ - bSee.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFileParent(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }}); - bOpenWith.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFileWith(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }}); - - Box box=Box.createHorizontalBox(); - //box.add(bOpen); - box.add(bSee); - box.add(bOpenWith); - return box; - } else { - System.err.println("Does not handle OS '"+osName+"'"); - return null; - } - } - public static final JPopupMenu createOpenOpenWithShowDirPopupPanel(final File file) { - JPopupMenu menu=new JPopupMenu(); - - //JButton bOpen=new JButton("Open"); - JMenuItem miOpen=new JMenuItem("Open"); - JMenuItem miOpenWith=new JMenuItem("Open with..."); - JMenuItem miShowDir=new JMenuItem("Open parent directory"); - - boolean isWindows = osName.indexOf("windows") >= 0; - - miShowDir.setToolTipText("Browse directory :
        "+file.getParentFile().toString()+""); - //bOpen.setToolTipText("Open file :
        "+file.toString()+""); - - /*bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFile(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }});*/ - miShowDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFileParent(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }}); - miOpenWith.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenFileWith(file); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }}); - miOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - try { - runSystemOpenURL(file.toURI().toURL()); - } catch (IOException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(null, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); - } catch (NoSuchMethodException ex) { - ex.printStackTrace(); - } - }}); - menu.add(miOpen); - if (isWindows) - menu.add(miOpenWith); - - menu.addSeparator(); - menu.add(miShowDir); - return menu; - } - public static final boolean addOpenOpenWithShowDirPopupPanel(final File file, JComponent component) { - String osName=System.getProperty("os.name").toLowerCase(); - if (osName.indexOf("windows") >= 0) { - final JPopupMenu menu = createOpenOpenWithShowDirPopupPanel(file); - component.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { - if (evt.isPopupTrigger()||evt.getButton() > 1) { - //menu.show((Component)evt.getSource(),evt.getX(),evt.getY()); - menu.show(evt.getComponent(),evt.getX(),evt.getY()); - } - }}); - return true; - } else { - System.err.println("Does not handle OS '"+osName+"'"); - return false; - } - } - public static boolean isPopupTrigger(MouseEvent e) { - if (e.isPopupTrigger() || e.getButton() != MouseEvent.BUTTON1) - return true; - - if (isMacOSX()) - return e.isControlDown(); - - return false; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/AdaptedCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/AdaptedCollection.java deleted file mode 100644 index 7142f47ee..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/AdaptedCollection.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/ -*/ -package com.ochafik.util.listenable; - -import java.util.AbstractCollection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -/** - * ListenableCollection<V> that wraps a Collection<U>, using adapters from U to V (and optionally backwards, for support of the add(V) method).
        - * If the wrapped collection implements ListenableCollection, all its events will be adapted and propagated to listeners of the AdaptedCollection.
        - * This is useful to convert a collection to another type
        - * The resulting wrapped collection is listenable, and listens to modifications of its wrapped collection if it is an instance of ListenableCollection. - * @author Olivier Chafik - * @param type of the elements of the wrapped collection - * @param type of the elements of the adapted collection - */ -public class AdaptedCollection extends AbstractCollection implements ListenableCollection { - protected final Collection collection; - protected final Adapter forwardAdapter; - protected final Adapter backwardAdapter; - protected ListenableSupport collectionSupport; - protected boolean currentlyCausingChange = false; - - public AdaptedCollection(Collection collection, Adapter forwardAdapter) { - this(collection, forwardAdapter, null); - } - - public AdaptedCollection(Collection collection, Adapter forwardAdapter, Adapter backwardAdapter) { - super(); - if (forwardAdapter == null) - throw new NullPointerException("AdaptedCollection needs a non-null forward adapter"); - - this.collection = collection; - this.forwardAdapter = forwardAdapter; - this.backwardAdapter = backwardAdapter; - } - - public Adapter getForwardAdapter() { - return forwardAdapter; - } - - public Adapter getBackwardAdapter() { - return backwardAdapter; - } - - @Override - public Iterator iterator() { - return new IteratorAdapter(collection.iterator()); - } - - @Override - public int size() { - return collection.size(); - } - - @Override - public boolean isEmpty() { - return collection.isEmpty(); - } - - @Override - public void clear() { - if (collectionSupport != null && collectionSupport.hasListeners()) { - try { - currentlyCausingChange = true; - Collection removedElements = new ArrayList(AdaptedCollection.this); - collection.clear(); - collectionSupport.fireRemoved(AdaptedCollection.this, removedElements, 0, removedElements.size() - 1); - } finally { - currentlyCausingChange = false; - } - } else { - collection.clear(); - } - } - - @Override - public boolean add(V value) { - if (backwardAdapter == null) - throw new UnsupportedOperationException("No backward adapter in this AdapterCollection"); - - try { - currentlyCausingChange = true; - if (collection.add(backwardAdapter.adapt(value))) { - if (collectionSupport != null && collectionSupport.hasListeners()) - collectionSupport.fireAdded(this, Collections.singleton(value)); - - return true; - } - return false; - } finally { - currentlyCausingChange = false; - } - } - - @SuppressWarnings("unchecked") - @Override - public boolean remove(Object value) { - if (backwardAdapter == null) { - // Give index of removed element in collection event when it does not cost more - // (simplifies subclassing as List, as for the remove method there is only the need to reimplement removeWithoutBackWardAdapter) - int i = 0; - for (Iterator it = collection.iterator(); it.hasNext();) { - if (forwardAdapter.adapt(it.next()).equals(value)) { - try { - currentlyCausingChange = true; - it.remove(); - if (collectionSupport != null && collectionSupport.hasListeners()) - collectionSupport.fireRemoved(this, (Collection)Collections.singleton(value), i, i); - - return true; - } finally { - currentlyCausingChange = false; - } - } - i++; - } - return false; - } else { - return removeWithoutBackWardAdapter(value); - } - } - - @SuppressWarnings("unchecked") - protected boolean removeWithoutBackWardAdapter(Object value) { - try { - currentlyCausingChange = true; - if (collection.remove(backwardAdapter.adapt((V)value))) { - if (collectionSupport != null && collectionSupport.hasListeners()) - collectionSupport.fireRemoved(this, (Collection)Collections.singleton(value)); - - return true; - } - return false; - } finally { - currentlyCausingChange = false; - } - } - - @SuppressWarnings("unchecked") - @Override - public boolean contains(Object value) { - if (backwardAdapter != null) { - return collection.contains(backwardAdapter.adapt((V)value)); - } else { - for (U element : collection) { - if (forwardAdapter.adapt(element).equals(value)) { - return true; - } - } - } - return false; - } - - protected class IteratorAdapter implements Iterator { - protected Iterator iterator; - protected V lastValue; - public IteratorAdapter(Iterator iterator) { - this.iterator=iterator; - } - public boolean hasNext() { - return iterator.hasNext(); - } - public V next() { - return lastValue = forwardAdapter.adapt(iterator.next()); - } - public void remove() { - try { - currentlyCausingChange = true; - iterator.remove(); - - if (collectionSupport != null && collectionSupport.hasListeners()) - collectionSupport.fireRemoved(AdaptedCollection.this, Collections.singleton(lastValue)); - } finally { - currentlyCausingChange = false; - } - lastValue = null; - } - } - - public void addCollectionListener(CollectionListener l) { - if (collectionSupport == null) { - collectionSupport = new ListenableSupport(); - if (collection instanceof ListenableCollection) { - ((ListenableCollection)collection).addCollectionListener(new CollectionListener() { - public void collectionChanged(CollectionEvent e) { - // Do not propagate the event if we triggered it - if (currentlyCausingChange) - return; - - // Only propagate if someone is listening (CollectionSupport already tries not to fire anything when there is no listener, but here we are trying to avoid to create the wrapped elements collection) - if (collectionSupport == null || !collectionSupport.hasListeners()) - return; - - // Adapt the collection of changed / added / removed elements in the event - collectionSupport.fireEvent( - AdaptedCollection.this, - new AdaptedCollection(e.getElements(), AdaptedCollection.this.forwardAdapter, AdaptedCollection.this.backwardAdapter), - e.getType(), - e.getFirstIndex(), - e.getLastIndex()); - } - }); - } - } - - collectionSupport.addCollectionListener(l); - } - - public void removeCollectionListener(CollectionListener l) { - if (collectionSupport == null) - return; - - collectionSupport.removeCollectionListener(l); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Adapter.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Adapter.java deleted file mode 100644 index 9b8f1eca8..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Adapter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -public interface Adapter { - public V adapt(U value); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionEvent.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionEvent.java deleted file mode 100644 index 2e1d89e3f..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionEvent.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Collection; -import java.util.EventObject; - -/** - *

        - * Event that represents a modification of a listenable collection.
        - * An event can be of three types : addition, removal and update.
        - * Multiple elements can be packed in the same event instance.
        - * For instance, if a listenable collection is cleared then it may issue no more than a single REMOVED event with all of its elements as argument. - *

        - *
        - *

        - * The UPDATED event type is here to notify the listeners that something changed about the elements referred to by the event.
        - * It is typically triggered when one adds an existing element to a ListenableSet. - *

        - * @author Olivier Chafik - * @param Type of the elements of the collection from which the event originated - */ -public class CollectionEvent extends EventObject { - - private static final long serialVersionUID = -5266364113759541622L; - - /// Type of the event. - public enum EventType { - ADDED, - REMOVED, - UPDATED - } - - /// Type of the event - protected final EventType type; - - /// Elements affected by the event - protected final Collection elements; - - /// Index of the first affected element in the source, or -1 if not applicable - protected final int firstIndex; - - /// Index of the last affected element in the source, or -1 if not applicable - protected final int lastIndex; - - @SuppressWarnings("unchecked") - /** - * Get the source of the event - * @return listenable collection where the event originated from - */ - public ListenableCollection getSource() { - return (ListenableCollection)super.getSource(); - } - - /** - * Get the event type - * @return type of the event - */ - public EventType getType() { - return type; - } - - /** - * Get the elements affected by the event. - * @return the elements affected by the event. - */ - public Collection getElements() { - return elements; - } - - /** - * Get the index of the first affected element in the source, or -1 if not applicable - * @return Index of the first affected element in the source, or -1 if not applicable - */ - public int getFirstIndex() { - return firstIndex; - } - - /** - * Get the index of the last affected element in the source, or -1 if not applicable - * @return Index of the last affected element in the source, or -1 if not applicable - */ - public int getLastIndex() { - return lastIndex; - } - - public CollectionEvent(ListenableCollection source, Collection elements, EventType type) { - this(source, elements, type, -1, -1); - } - - public CollectionEvent(ListenableCollection source, Collection elements, EventType type, int firstIndex, int lastIndex) { - super(source); - this.elements = elements; - this.type = type; - this.firstIndex = firstIndex; - this.lastIndex = lastIndex; - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionListener.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionListener.java deleted file mode 100644 index e910dcc29..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/CollectionListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.EventListener; - -/** - * Post-modification collection event listener. - * @author Olivier Chafik - * - * @param Type of the elements of the collections that are listened to by the listener. - */ -public interface CollectionListener extends EventListener { - public void collectionChanged(CollectionEvent e); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableCollection.java deleted file mode 100644 index 75f58a897..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableCollection.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Default implementation of the ListenableCollection interface.
        - * This class follows both the decorator and proxy patterns : it wraps an existing java.util.Collection and adds the listenable feature to it.
        - * @author Olivier Chafik - * @param Type of the elements of the collection - */ -public class DefaultListenableCollection implements ListenableCollection { - protected Collection collection; - protected ListenableSupport collectionSupport; - - public void addCollectionListener(CollectionListener l) { - collectionSupport.addCollectionListener(l); - } - public void removeCollectionListener(CollectionListener l) { - collectionSupport.removeCollectionListener(l); - } - public DefaultListenableCollection(Collection collection) { - this(collection,new ListenableSupport()); - } - public DefaultListenableCollection(Collection collection, ListenableSupport collectionSupport) { - this.collection = collection; - this.collectionSupport = collectionSupport; - } - public boolean add(T o) { - boolean added = collection.add(o); - int index = collection instanceof List ? size() : -1; - if (added) { - collectionSupport.fireAdded(this,Collections.singleton(o), index, index); - } else { - collectionSupport.fireUpdated(this,Collections.singleton(o), index, index); - } - return added; - } - public boolean addAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.addAll(c); - - int max = c.size(); - Collection addedElements = new ArrayList(max), updatedElements = new ArrayList(max); - for (T t : c) { - (collection.add(t) ? addedElements : updatedElements).add(t); - } - int firstIndex = collection instanceof List ? size() : -1, - lastIndex = firstIndex < 0 ? -1 : firstIndex + addedElements.size() - 1; - collectionSupport.fireAdded(this, addedElements, firstIndex, lastIndex); - collectionSupport.fireUpdated(this, updatedElements, firstIndex, lastIndex); - - return !addedElements.isEmpty(); - } - public void clear() { - if (!collectionSupport.hasListeners()) { - collection.clear(); - return; - } - Collection copy = new ArrayList(collection); - collection.clear(); - collectionSupport.fireRemoved(this, copy); - } - public boolean contains(Object o) { - return collection.contains(o); - } - public boolean containsAll(Collection c) { - return collection.containsAll(c); - } - @Override - public boolean equals(Object obj) { - if (obj == this) - return true; - - return collection.equals(obj); - } - @Override - public int hashCode() { - return collection.hashCode(); - } - public boolean isEmpty() { - return collection.isEmpty(); - } - - protected class ListenableIterator implements Iterator { - Iterator iterator; - T lastValue; - DefaultListenableCollection listenableCollection; - public ListenableIterator(DefaultListenableCollection listenableCollection,Iterator iterator) { - this.iterator = iterator; - this.listenableCollection = listenableCollection; - } - public boolean hasNext() { - return iterator.hasNext(); - } - public T next() { - lastValue = iterator.next(); - return lastValue; - } - public void remove() { - iterator.remove(); - collectionSupport.fireRemoved(listenableCollection,Collections.singleton(lastValue)); - } - }; - - public Iterator iterator() { - return new ListenableIterator(this,collection.iterator()); - } - @SuppressWarnings("unchecked") - public boolean remove(Object o) { - boolean removed = collection.remove(o); - if (removed) { - collectionSupport.fireRemoved(this,Collections.singleton((T)o)); - } - return removed; - } - @SuppressWarnings("unchecked") - public boolean removeAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.removeAll(c); - - Collection removedElements = new ArrayList(c.size()); - for (Object t : c) { - boolean removed = collection.remove(t); - if (removed) - removedElements.add((T)t); - } - collectionSupport.fireRemoved(this, removedElements); - - return !removedElements.isEmpty(); - } - public boolean retainAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.retainAll(c); - - Collection removedElements = new ArrayList(c.size()); - for (Iterator it = iterator(); it.hasNext();) { - T e = it.next(); - if (!c.contains(e)) { - it.remove(); - removedElements.add(e); - } - } - collectionSupport.fireRemoved(this, removedElements); - return !removedElements.isEmpty(); - } - public int size() { - return collection.size(); - } - public Object[] toArray() { - return collection.toArray(); - } - public V[] toArray(V[] a) { - return collection.toArray(a); - } - @Override - public String toString() { - return collection.toString(); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableList.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableList.java deleted file mode 100644 index bde1839c6..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableList.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; - -/** - * Default implementation of the ListenableList interface.
        - * This class follows both the decorator and proxy patterns : it wraps an existing java.util.Collection and adds the listenable feature to it.
        - * @author Olivier Chafik - * @param Type of the elements of the list - */ -public class DefaultListenableList extends DefaultListenableCollection implements ListenableList{ - List list; - public DefaultListenableList(List ilistst) { - super(ilistst); - this.list = ilistst; - } - public DefaultListenableList(List list, ListenableSupport collectionSupport) { - super(list,collectionSupport); - this.list = list; - } - public boolean add(T o) { - add(size(), o); - return true; - } - public void add(int index, T element) { - list.add(index, element); - collectionSupport.fireAdded(this,Collections.singleton(element), index, index); - } - public boolean addAll(int index, Collection c) { - int initSize = list.size(); - if (!list.addAll(index, c)) { - if (list.size() != initSize) - throw new UnsupportedOperationException("Does not support listeners-enabled proxying of addAll(int, Collection) methods that are not atomical."); - - return false; - } - collectionSupport.fireAdded(this, new ArrayList(c), initSize, initSize + c.size() - 1); - return true; - } - public T get(int index) { - return list.get(index); - } - public int indexOf(Object o) { - return list.indexOf(o); - } - - /** - * Not supported yet. - */ - public ListIterator listIterator() { - throw new UnsupportedOperationException(); - } - public int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } - public T set(int index, T element) { - T value = list.set(index, element); - collectionSupport.fireUpdated(this, Collections.singleton(element), index, index); - return value; - } - - /** - * There are no more guarantees made on the behaviour of the sublists returned by this method upon list change than there are on java.util.List.subList. - */ - public List subList(int fromIndex, int toIndex) { - return new DefaultListenableList(list.subList(fromIndex, toIndex),collectionSupport); - } - - /** - * Not supported yet. - */ - public ListIterator listIterator(int index) { - throw new UnsupportedOperationException(); - } - - public T remove(int index) { - T removed = list.remove(index); - if (removed != null) { - collectionSupport.fireRemoved(this,Collections.singleton(removed), index, index); - } - return removed; - } - public boolean remove(Object o) { - int i = indexOf(o); - return i >= 0 && remove(i) != null; - } - public void clear() { - Collection copy = new ArrayList(this); - collection.clear(); - collectionSupport.fireRemoved(this, copy, 0, copy.size() - 1); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableMap.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableMap.java deleted file mode 100644 index aaaa3283b..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableMap.java +++ /dev/null @@ -1,296 +0,0 @@ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - - -/** - * Default implementation of the ListenableMao interface.
        - * This class follows both the decorator and proxy patterns : it wraps an existing java.util.Map and adds the listenable feature to it.
        - * @author Olivier Chafik - * @param Type of the keys of the map - * @param Type of the values of the map - */ -public class DefaultListenableMap implements ListenableMap { - - Map map; - - DefaultListenableSet keySet; - DefaultListenableSet> entrySet; - - ListenableSupport valuesSupport; - ListenableCollection values; - - public DefaultListenableMap(Map map) { - this.map = map; - } - public boolean containsKey(Object key) { - return map.containsKey(key); - } - public boolean containsValue(Object value) { - return map.containsValue(value); - } - public int size() { - return map.size(); - } - - @Override - public String toString() { - return map.toString(); - } - - public void clear() { - Collection> copy = new ArrayList>(map.entrySet()); - map.clear(); - propagateRemoved(copy); - } - @Override - public boolean equals(Object obj) { - return map.equals(obj); - } - public V get(Object key) { - return map.get(key); - } - @Override - public int hashCode() { - return map.hashCode(); - } - public boolean isEmpty() { - return map.isEmpty(); - } - - public V put(K key, V value) { - V v = map.put(key,value); - if (v !=null) { - propagateUpdated(key, v, value); - } else { - propagateAdded(key, value); - } - return v; - } - public void putAll(Map t) { - for (Map.Entry e : t.entrySet()) { - put(e.getKey(),e.getValue()); - } - } - @SuppressWarnings("unchecked") - public V remove(Object key) { - V v = map.remove(key); - if (v !=null) { - propagateRemoved(Collections.singletonMap((K)key, (V)v).entrySet()); - } - return v; - } - - void propagateAdded(K key, V value) { - if (keySet != null) - keySet.collectionSupport.fireAdded(keySet, Collections.singleton(key)); - - if (entrySet != null) { - entrySet.collectionSupport.fireAdded(entrySet, Collections.singleton((Map.Entry)new UnmodifiableEntry(key, value))); - } - - if (values != null) { - valuesSupport.fireAdded(values, Collections.singleton(value)); - } - } - void propagateRemoved(Collection> entries) { - if (keySet != null) - keySet.collectionSupport.fireRemoved(keySet, new AdaptedCollection, K>(entries, entryToKeyAdapter)); - - if (entrySet != null) { - entrySet.collectionSupport.fireRemoved(entrySet, entries); - } - - if (values != null) { - valuesSupport.fireRemoved(values, new AdaptedCollection, V>(entries, entryToValueAdapter)); - } - } - - void propagateUpdated(K key, V oldValue, V newValue) { - if (keySet != null) - keySet.collectionSupport.fireUpdated(keySet, Collections.singleton(key)); - - boolean different = !oldValue.equals(newValue); - - if (entrySet != null) { - Collection> newEntries = Collections.singleton((Map.Entry)new UnmodifiableEntry(key, newValue)); - if (different) { - Collection> oldEntries = Collections.singleton((Map.Entry)new UnmodifiableEntry(key, oldValue)); - entrySet.collectionSupport.fireRemoved(entrySet, oldEntries); - entrySet.collectionSupport.fireAdded(entrySet, newEntries); - } else { - entrySet.collectionSupport.fireUpdated(entrySet, newEntries); - } - } - - if (values != null) { - if (different) { - valuesSupport.fireRemoved(values, Collections.singleton(oldValue)); - valuesSupport.fireAdded(values, Collections.singleton(newValue)); - } else { - valuesSupport.fireUpdated(values, Collections.singleton(newValue)); - } - } - } - - public ListenableSet keySet() { - if (keySet == null) { - keySet = new DefaultListenableSet(map.keySet()) { - @SuppressWarnings("unchecked") - @Override - public boolean remove(Object o) { - V value = map.remove(o); - if (value != null) { - propagateRemoved(Collections.singletonMap((K)o, value).entrySet()); - return true; - } - return false; - } - @Override - public void clear() { - DefaultListenableMap.this.clear(); - } - @Override - public boolean removeAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.removeAll(c); - - boolean changed = false; - for (Object o : c) - changed = remove(o) || changed; - - return changed; - } - @Override - public boolean add(K o) { - throw new UnsupportedOperationException(); - } - @Override - public boolean addAll(Collection c) { - throw new UnsupportedOperationException(); - } - @Override - public boolean retainAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.retainAll(c); - - Collection> removedElements = new ArrayList>(c.size()); - for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry e = it.next(); - if (!c.contains(e.getKey())) { - it.remove(); - removedElements.add(e); - } - } - propagateRemoved(removedElements); - return !removedElements.isEmpty(); - } - @Override - public Iterator iterator() { - return new ListenableIterator(this,collection.iterator()) { - @Override - public void remove() { - // cannot use map.remove(lastValue), as the iterator would throw a concurrent modification exception :-( - V assoc = get(lastValue); - iterator.remove(); - propagateRemoved(Collections.singletonMap(lastValue, assoc).entrySet()); - } - }; - } - }; - } - - return keySet; - } - - protected Adapter, K> entryToKeyAdapter = new Adapter, K>() { public K adapt(Map.Entry value) { - return value.getKey(); - }}; - protected Adapter, V> entryToValueAdapter = new Adapter, V>() { public V adapt(Map.Entry value) { - return value.getValue(); - }}; - - public ListenableSet> entrySet() { - if (entrySet == null) { - entrySet = new DefaultListenableSet>(map.entrySet()) { - @SuppressWarnings("unchecked") - @Override - public boolean remove(Object o) { - Map.Entry entry = (Map.Entry)o; - V value = map.remove(entry.getKey()); - if (value != null) { - propagateRemoved(Collections.singleton(entry)); - return true; - } - return false; - } - @Override - public void clear() { - DefaultListenableMap.this.clear(); - } - @Override - public boolean removeAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.removeAll(c); - - boolean changed = false; - for (Object o : c) - changed = remove(o) || changed; - - return changed; - } - @Override - public boolean add(Map.Entry o) { - throw new UnsupportedOperationException(); - } - @Override - public boolean addAll(Collection> c) { - throw new UnsupportedOperationException(); - } - @Override - public boolean retainAll(Collection c) { - if (!collectionSupport.hasListeners()) - return collection.retainAll(c); - - Collection> removedElements = new ArrayList>(c.size()); - for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry e = it.next(); - if (!c.contains(e)) { - it.remove(); - removedElements.add(e); - } - } - propagateRemoved(removedElements); - return !removedElements.isEmpty(); - } - @Override - public Iterator> iterator() { - return new ListenableIterator(this,collection.iterator()) { - @Override - public void remove() { - iterator.remove(); - propagateRemoved(Collections.singleton(lastValue)); - } - }; - } - }; - } - - return entrySet; - } - - public ListenableCollection values() { - if (values == null) { - valuesSupport = new ListenableSupport(); - values = ListenableCollections.unmodifiableCollection(new DefaultListenableCollection(map.values(), valuesSupport)); - } - - return values; - } - - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSet.java deleted file mode 100644 index 4d1fed44d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSet.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Set; - -/** - * Default implementation of the ListenableSet interface.
        - * This class follows both the decorator and proxy patterns : it wraps an existing java.util.Set and adds the listenable feature to it.
        - * @author Olivier Chafik - * @param Type of the elements of the set - */ -class DefaultListenableSet extends DefaultListenableCollection implements ListenableSet { - public DefaultListenableSet(Set set, ListenableSupport collectionSupport) { - super(set,collectionSupport); - } - public DefaultListenableSet(Set set) { - super(set); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSortedSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSortedSet.java deleted file mode 100644 index d8533d9e4..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/DefaultListenableSortedSet.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Comparator; -import java.util.SortedSet; - -/** - * Default implementation of the ListenableSet and SortedSet interface.
        - * This class follows both the decorator and proxy patterns : it wraps an existing java.util.Set and adds the listenable feature to it.
        - * @author Olivier Chafik - * @param Type of the elements of the set - */ -class DefaultListenableSortedSet extends DefaultListenableSet implements ListenableSortedSet { - public DefaultListenableSortedSet(SortedSet set, ListenableSupport collectionSupport) { - super(set,collectionSupport); - } - public DefaultListenableSortedSet(SortedSet set) { - super(set); - } - public Comparator comparator() { - return ((SortedSet)collection).comparator(); - } - public T first() { - return ((SortedSet)collection).first(); - } - public SortedSet headSet(T toElement) { - return ((SortedSet)collection).headSet(toElement); - } - public T last() { - return ((SortedSet)collection).last(); - } - public SortedSet subSet(T fromElement, T toElement) { - return ((SortedSet)collection).subSet(fromElement, toElement); - } - public SortedSet tailSet(T fromElement) { - return ((SortedSet)collection).tailSet(fromElement); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Filter.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Filter.java deleted file mode 100644 index ff2952497..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Filter.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ochafik.util.listenable; - -public interface Filter { - public boolean accept(V value); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableCollection.java deleted file mode 100644 index d87d8f067..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableCollection.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -class FilteredListenableCollection implements ListenableCollection { - protected final ListenableCollection listenableCollection; - protected Collection> listeners; - - public FilteredListenableCollection(ListenableCollection listenableCollection) { - this.listenableCollection = listenableCollection; - - } - - public void addCollectionListener(CollectionListener l) { - if (listeners == null) { - listeners = new ArrayList>(); - listenableCollection.addCollectionListener(new CollectionListener() { - public void collectionChanged(CollectionEvent e) { - if (listeners != null && !listeners.isEmpty()) { - Collection filteredElements = e.getElements(); - CollectionEvent filteredEvent = new CollectionEvent(FilteredListenableCollection.this, filteredElements, e.getType(), e.getFirstIndex(), e.getLastIndex()); - for (CollectionListener listener : listeners) { - listener.collectionChanged(filteredEvent); - } - } - } - }); - } - - listeners.add(l); - } - - public void removeCollectionListener(CollectionListener l) { - if (listeners == null) - return; - - listeners.remove(l); - } - - public boolean add(T o) { - return listenableCollection.add(o); - } - - public boolean addAll(Collection c) { - return listenableCollection.addAll(c); - } - - public void clear() { - listenableCollection.clear(); - } - - public boolean contains(Object o) { - return listenableCollection.contains(o); - } - - public boolean containsAll(Collection c) { - return listenableCollection.containsAll(c); - } - - public boolean isEmpty() { - return listenableCollection.isEmpty(); - } - static class FilteredIterator implements Iterator { - Iterator iterator; - - public FilteredIterator(Iterator iterator) { - this.iterator = iterator; - } - public boolean hasNext() { - return iterator.hasNext(); - } - public T next() { - return iterator.next(); - } - public void remove() { - iterator.remove(); - } - } - public Iterator iterator() { - return new FilteredIterator(listenableCollection.iterator()); - } - - public boolean remove(Object o) { - return listenableCollection.remove(o); - } - - public boolean removeAll(Collection c) { - return listenableCollection.removeAll(c); - } - - public boolean retainAll(Collection c) { - return listenableCollection.retainAll(c); - } - - public int size() { - return listenableCollection.size(); - } - - public Object[] toArray() { - return listenableCollection.toArray(); - } - - @SuppressWarnings("hiding") - public T[] toArray(T[] a) { - return listenableCollection.toArray(a); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableMap.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableMap.java deleted file mode 100644 index 094cbba4f..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/FilteredListenableMap.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. - */ -package com.ochafik.util.listenable; - -import java.util.Map; - - -class FilteredListenableMap implements ListenableMap { - ListenableMap listenableMap; - - - public FilteredListenableMap(ListenableMap listenableMap) { - this.listenableMap = listenableMap; - } - - public void clear() { - listenableMap.clear(); - } - - public boolean containsKey(Object key) { - - return listenableMap.containsKey(key); - } - - public boolean containsValue(Object value) { - - return listenableMap.containsValue(value); - } - - public ListenableSet> entrySet() { - - return listenableMap.entrySet(); - } - - - public V get(Object key) { - - return listenableMap.get(key); - } - - public boolean isEmpty() { - - return listenableMap.isEmpty(); - } - - public ListenableSet keySet() { - - return listenableMap.keySet(); - } - - public V put(K key, V value) { - - return listenableMap.put(key, value); - } - - public void putAll(Map t) { - listenableMap.putAll(t); - - } - - public V remove(Object key) { - - return listenableMap.remove(key); - } - - public int size() { - - return listenableMap.size(); - } - - public ListenableCollection values() { - - return listenableMap.values(); - } - - public ListenableSet listenableKeySet() { - - return listenableMap.keySet(); - } - - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollection.java deleted file mode 100644 index 4d6bad6b8..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollection.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Collection; - -/** - * Interface for collections that support modification listeners. - * @author Olivier Chafik - * @param Type of the elements of the collection - */ -public interface ListenableCollection extends Collection{ - public void addCollectionListener(CollectionListener l); - public void removeCollectionListener(CollectionListener l); - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollections.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollections.java deleted file mode 100644 index 22f62bd79..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableCollections.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.RandomAccess; -import java.util.Set; -import java.util.SortedSet; - -import com.ochafik.lang.Threads; - -/** - * Utility methods to make the most out of listenable collections.
        - * Provides synchronized and read-only wrappers for listenable collections, lists, sets and maps.
        - * Also provides two-ways automated synchronization between listenable collections (that "knows" about the differences between sets, lists and other kinds of collections). - * @author ochafik - * - */ -public class ListenableCollections { - - /** - * Create a listenable list that will dynamically reflect the contents of the source listenable collection.
        - * This is useful for instance when you want to put the contents of a set in a swing JList (then use new JList(new ListenableListModel(ListenableCollections.asList(yourSet)))). - * @param type of the elements of the collection - * @param source collection that is to be adapted to a listenable list - * @return source if it is already a listenable list, otherwise a new listenable list that is two-ways bound to the source collection. - */ - public static ListenableList asList(ListenableCollection source) { - if (source instanceof ListenableList) - return (ListenableList)source; - - ListenableList out = new DefaultListenableList(new ArrayList(source)); - bind(source, out); - return out; - } - - /** - * Setup two-ways automated synchronization between listenable collections
        - * Tries to deal with sets, lists and collections in the most intuitive way possible (synchronization should happen as the common sense would dictate it).
        - * It is possible to bind collections of different kinds (say, a set with a list). - * @param type of the elements of both collections - * @param a collection to keep synchronized with b - * @param b collection to keep synchronized with a - */ - public static void bind(final ListenableCollection a, final ListenableCollection b) { - CollectionListener listener = new CollectionListener() { - boolean currentlyPropagating = false; - - @SuppressWarnings("unchecked") - void add(T t, ListenableCollection source, ListenableCollection recipient) { - if ((recipient instanceof List) && (source instanceof SortedSet)) { - ListenableList recipientList = (ListenableList)recipient; - Comparator comparator = (Comparator) ((SortedSet)source).comparator(); - int i; - if (comparator != null) { - i = Collections.binarySearch(recipientList, t, comparator); - } else { - // Assume T is comparable - i = Collections.binarySearch((List)recipientList, t); - } - if (i >= 0) { - recipientList.set(i, t); - } else { - recipientList.add(-i - 1, t); - } - } else { - recipient.add(t); - } - } - @SuppressWarnings("unchecked") - public void collectionChanged(CollectionEvent e) { - // Avoid infinite propagation of events - if (currentlyPropagating) - return; - - //System.out.println("Propagating "+e.getType() + " for elements "+e.getElements()); - try { - currentlyPropagating = true; - ListenableCollection source = e.getSource(), recipient = source == a ? b : a; - - for (T t : e.getElements()) { - switch (e.getType()) { - case ADDED: - add(t, source, recipient); - break; - case REMOVED: - recipient.remove(t); - break; - case UPDATED: - if (recipient instanceof List) { - List recipientList = (List)recipient; - int i = recipientList.indexOf(t); - recipientList.set(i, t); - } else if (recipient instanceof Set) { - add(t, source, recipient); - } else { - // Add might do a duplicate, so first remove element. - recipient.remove(t); - add(t, source, recipient); - } - break; - } - } - } finally { - currentlyPropagating = false; - } - } - }; - a.addCollectionListener(listener); - b.addCollectionListener(listener); - } - - public static final ListenableSet unmodifiableSet(ListenableSet set) { - return new UnmodifiableListenableSet(set); - } - - public static final ListenableCollection unmodifiableCollection(ListenableCollection col) { - return new UnmodifiableListenableCollection(col); - } - - public static final ListenableList unmodifiableList(ListenableList col) { - return new UnmodifiableListenableList(col); - } - - public static final ListenableMap unmodifiableMap(ListenableMap map) { - return new UnmodifiableListenableMap(map); - } - - public static final ListenableSet synchronizedSet(ListenableSet set) { - return new SynchronizedListenableSet(set); - } - - public static final ListenableCollection synchronizedCollection(ListenableCollection col) { - return new SynchronizedListenableCollection(col); - } - - public static final ListenableList synchronizedList(ListenableList col) { - return new SynchronizedListenableList(col); - } - - public static final ListenableMap synchronizedMap(ListenableMap map) { - return new SynchronizedListenableMap(map); - } - - /** - * Wraps a collection in a listenable collection.
        - * The type of the listenable collection returned will depend on that of the provided collection : - *
          - *
        • wrapping a Set will return a ListenableSet<T>, using ListenableCollections.listenableSet(Set<T>)
        • - *
        • wrapping a List will return a ListenableList<T>, using ListenableCollections.listenableList(List<T>)
        • - *
        • wrapping a ListenableCollection<T> will return the same object
        • - *
        • otherwise a instance of a ListenableCollection<T> will be returned.
        • - *
        - * @param - * @param collectionToWrap - * @return listenable collection that uses the provided collection as storage - */ - public static final ListenableCollection listenableCollection(Collection collectionToWrap) { - if (collectionToWrap instanceof ListenableCollection) - return (ListenableCollection)collectionToWrap; - - if (collectionToWrap instanceof Set) { - return listenableSet((Set)collectionToWrap); - } else if (collectionToWrap instanceof List) { - return listenableList((List)collectionToWrap); - } - return new DefaultListenableCollection(collectionToWrap); - } - - /** - * Wraps a list in a listenable list.
        - * If is provided with a list that implements the RandomAccess interface, this method returns a listenable list that also implements the RandomAccess interface. - * @param - * @param listToWrap - * @return listenable list that uses the provided list as storage - */ - public static final ListenableList listenableList(List listToWrap) { - if (listToWrap instanceof ListenableList) - return (ListenableList)listToWrap; - - if (listToWrap instanceof RandomAccess) { - class RandomAccessListenableList extends DefaultListenableList implements RandomAccess { - public RandomAccessListenableList(List l) { - super(l); - } - }; - return new RandomAccessListenableList(listToWrap); - } - return new DefaultListenableList(listToWrap); - } - - /** - * Wraps a set in a listenable set.
        - * If is provided with a set that implements the SortedSet interface, this method returns a listenable set that also implements the SortedSet interface. - * @param - * @param setToWrap - * @return listenable set that uses the provided set as storage - */ - public static final ListenableSet listenableSet(Set setToWrap) { - if (setToWrap instanceof ListenableSet) - return (ListenableSet)setToWrap; - - if (setToWrap instanceof SortedSet) { - return new DefaultListenableSortedSet((SortedSet)setToWrap); - } - return new DefaultListenableSet(setToWrap); - } - - public static final ListenableMap listenableMap(Map x) { - return new DefaultListenableMap(x); - } - - public static Collection adapt(Collection col, Adapter adapter) { - return new AdaptedCollection(col, adapter); - } - - - public static final class MapResult { - private final ListenableList values; - private final Threads threads; - private final ListenableList> errors; - public MapResult(Threads threads, ListenableList out, ListenableList> errorsOut) { - this.values = ListenableCollections.unmodifiableList(out); - this.threads = threads; - this.errors = ListenableCollections.unmodifiableList(errorsOut); - } - - public ListenableList getValues() { - return values; - } - public Threads getThreads() { - return threads; - } - public ListenableList> getErrors() { - return errors; - } - } - - /** - * Create a list of transformed values from a source collection, using an adapter. - * Operations are multithreaded depending on threadsCount : - *
          - *
        • if threadsCount == 0 : all operations happen in current thread - *
        • if threadCount > 0, mapping is done with threadCount threads - *
        • if threadCount < 0, mapping is done with -threadsCount * Runtime.getRuntime().availableProcessors() threads. For instance, on a single-processor, dual-core computer (with all cores available to Java), setting threadsCount to -2 will use 2 * 2 = 4 threads. - *
        - * In the case of multithreaded mapping, map returns immediately.
        - * One can listen to the listenable list of result values in MapResult.getValues(), and register ActionListener instances in MapResult.getThreads().
        - * One can also call MapResult.getThreads().join() to wait for all running threads to finish (blocking call).
        - * - * @param input elements type - * @param output elements type - * @param input input values that are to be transformed by the adapter - * @param mapper converter from the input type to the output type - * @param threadsCount 0 for no multithreading, X > 0 for X threads, -X for X threads per-core - * @return MapResult object - */ - public static MapResult map(Collection input, final Adapter mapper, int threadsCount) { - if (threadsCount < 0) - threadsCount = - threadsCount * Runtime.getRuntime().availableProcessors(); - - final Iterator it = input.iterator(); - final ListenableList out = ListenableCollections.synchronizedList(ListenableCollections.listenableList(new ArrayList(input.size()))); - final ListenableList> errorsOut = ListenableCollections.synchronizedList(ListenableCollections.listenableList(new ArrayList>())); - - Threads threadsJoint = new Threads(); - - Runnable worker = new Runnable() { public void run() { - for (;!Thread.interrupted();) { - U value; - synchronized (it) { - if (!it.hasNext()) - break; - value = it.next(); - } - - try { - V mappedValue = mapper.adapt(value); - synchronized (out) { - out.add(mappedValue); - } - } catch (Throwable th) { - synchronized (errorsOut) { - errorsOut.add(new Pair(value, th)); - } - } - //Thread.yield(); - } - }}; - - if (threadsCount == 0) { - worker.run(); - } else { - for (int iWorker = threadsCount; iWorker-- != 0;) - threadsJoint.add(worker); - - threadsJoint.start(); - } - return new MapResult(threadsJoint, out, errorsOut); - } - - public int removeIf(Collection collection, Filter filter) { - int removed = 0; - for (Iterator it = collection.iterator(); it.hasNext();) { - if (filter.accept(it.next())) { - it.remove(); - removed++; - } - } - return removed; - } - public int retainIf(Collection collection, Filter filter) { - int removed = 0; - for (Iterator it = collection.iterator(); it.hasNext();) { - if (!filter.accept(it.next())) { - it.remove(); - removed++; - } - } - return removed; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableComboModel.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableComboModel.java deleted file mode 100644 index 2e910b707..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableComboModel.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import javax.swing.ComboBoxModel; - -/** - * Swing combo box model (for use by JList) that dynamically reflects the contents of a listenable list.
        - * This model safely propagates events from the listenable list to any registered ListDataListener within the event dispatch thread, even if the events were received from an other thread. - * @see javax.swing.event.ListDataListener - * @see javax.swing.JList - * @see com.ochafik.util.listenable.SwingCollectionListener - * @author Olivier Chafik - * @param Type of the elements of the list - */ -public class ListenableComboModel extends ListenableListModel implements ComboBoxModel { - private static final long serialVersionUID = -8945907187555315122L; - - public ListenableComboModel(ListenableList list) { - super(list); - } - public ListenableComboModel() { - super(); - } - - T selectedItem; - - //@Override - public Object getSelectedItem() { - if (selectedItem != null && !getList().contains(selectedItem)) - selectedItem = null; - return selectedItem; - } - @SuppressWarnings("unchecked") - //@Override - public void setSelectedItem(Object anItem) { - if (getList().contains(anItem)) - selectedItem = (T)anItem; - else - selectedItem = null; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableList.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableList.java deleted file mode 100644 index a5f741b8c..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableList.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.List; - -/** - * Interface for lists that support modification listeners. - * @author Olivier Chafik - * @param Type of the elements of the list - */ -public interface ListenableList extends ListenableCollection, List { -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableListModel.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableListModel.java deleted file mode 100644 index 19c75f62d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableListModel.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import javax.swing.AbstractListModel; - -/** - * Swing list model (for use by JList) that dynamically reflects the contents of a listenable list.
        - * This model safely propagates events from the listenable list to any registered ListDataListener within the event dispatch thread, even if the events were received from an other thread. - * @see javax.swing.event.ListDataListener - * @see javax.swing.JList - * @see com.ochafik.util.listenable.SwingCollectionListener - * @author Olivier Chafik - * @param Type of the elements of the list - */ -public class ListenableListModel extends AbstractListModel { - private static final long serialVersionUID = 1794077239948305400L; - - private ListenableList list; - - public ListenableListModel(ListenableList list) { - setList(list); - } - public ListenableListModel() {} - - CollectionListener listener = new SwingCollectionListener(new CollectionListener() { - public void collectionChanged(CollectionEvent e) { - switch (e.getType()) { - case ADDED: - fireIntervalAdded(this, e.getFirstIndex(), e.getLastIndex()); - break; - case REMOVED: - fireIntervalRemoved(this, e.getFirstIndex(), e.getLastIndex()); - break; - case UPDATED: - fireContentsChanged(this, e.getFirstIndex(), e.getLastIndex()); - break; - } - } - }); - - /** - * Set or change the listenable list which content is reflected by this list model.
        - * May trigger DELETED events (if there was already a non-empty underlying list) and ADDED events (if the list being set is not empty). - * @param list - */ - public void setList(ListenableList list) { - ListenableList oldList = this.list; - if (oldList != null) { - this.list = null; - oldList.removeCollectionListener(listener); - if (!oldList.isEmpty()) { - fireIntervalRemoved(this, 0, oldList.size() - 1); - } - } - this.list = list; - if (list == null) - return; - - list.addCollectionListener(listener); - if (!list.isEmpty()) { - fireIntervalAdded(this, 0, list.size() - 1); - } - - } - - public Object getElementAt(int index) { - return list.get(index); - } - - public int getSize() { - return list == null ? 0 : list.size(); - } - public ListenableList getList() { - return list; - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableMap.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableMap.java deleted file mode 100644 index bf3170579..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableMap.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Map; - -/** - * Interface for maps which key set, entry set and values collection support modification listeners.
        - * @author Olivier Chafik - * @param Type of the keys of the map - * @param Type of the values of the map - */ -public interface ListenableMap extends Map { - public ListenableSet keySet(); - public ListenableSet> entrySet(); - public ListenableCollection values(); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSet.java deleted file mode 100644 index 66bac4a61..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Set; - -/** - * Interface for sets that support modification listeners.
        - * Listenable sets are required to trigger UPDATED events whenever one attempts to add an element that is already present in the set. - * @author Olivier Chafik - * @param Type of the elements of the set - */ -public interface ListenableSet extends ListenableCollection, Set { -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSortedSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSortedSet.java deleted file mode 100644 index 83c528171..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSortedSet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.SortedSet; - -/** - * Interface for sorted sets that support modification listeners.
        - * Listenable sorted sets are required to trigger UPDATED events whenever one attempts to add an element that is already present in the set. - * @author Olivier Chafik - * @param Type of the elements of the set - */ -public interface ListenableSortedSet extends ListenableCollection, SortedSet { -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSupport.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSupport.java deleted file mode 100644 index d58e8372d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/ListenableSupport.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Helper class that keeps track of registered CollectionListener instances and eases up the firing of CollectionEvent. - * @author Olivier Chafik - * @param type of the collections - */ -public class ListenableSupport { - protected Collection> listeners; - - public void addCollectionListener(CollectionListener l) { - if (listeners == null) - listeners = new ArrayList>(1); - - listeners.add(l); - } - - public void removeCollectionListener(CollectionListener l) { - if (listeners == null) - return; - - listeners.remove(l); - } - - public boolean hasListeners() { - return listeners != null && !listeners.isEmpty(); - } - - public void fireEvent(ListenableCollection source, Collection elements, CollectionEvent.EventType type, int firstIndex, int lastIndex) { - if (listeners == null || listeners.isEmpty() || elements.isEmpty()) - return; - - CollectionEvent event = new CollectionEvent(source,elements,type, firstIndex, lastIndex); - for (CollectionListener listener : listeners) { - listener.collectionChanged(event); - } - } - - public void fireAdded(ListenableCollection source, Collection elements) { - fireEvent(source, elements, CollectionEvent.EventType.ADDED, -1, -1); - } - public void fireAdded(ListenableCollection source, Collection elements, int firstIndex, int lastIndex) { - fireEvent(source, elements, CollectionEvent.EventType.ADDED, firstIndex, lastIndex); - } - - public void fireRemoved(ListenableCollection source, Collection elements) { - fireEvent(source, elements, CollectionEvent.EventType.REMOVED, -1, -1); - } - public void fireRemoved(ListenableCollection source, Collection elements, int firstIndex, int lastIndex) { - fireEvent(source, elements, CollectionEvent.EventType.REMOVED, firstIndex, lastIndex); - } - - public void fireUpdated(ListenableCollection source, Collection elements) { - fireEvent(source, elements, CollectionEvent.EventType.UPDATED, -1, -1); - } - public void fireUpdated(ListenableCollection source, Collection elements, int firstIndex, int lastIndex) { - fireEvent(source, elements, CollectionEvent.EventType.UPDATED, firstIndex, lastIndex); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Pair.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Pair.java deleted file mode 100644 index 641ba952d..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/Pair.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.ochafik.util.listenable; - -import java.util.Map; - -public class Pair implements Comparable>, Map.Entry { - private U first; - private V second; - - public Pair(U first, V second) { - this.first = first; - this.second = second; - } - - public Pair() {} - - public static Pair create(U u, V v) { - return new Pair(u, v); - } - public U getFirst() { - return first; - } - - public V getSecond() { - return second; - } - - public void setFirst(U first) { - this.first = first; - } - - public void setSecond(V second) { - this.second = second; - } - - @SuppressWarnings("unchecked") - public int compareTo(Pair o) { - Comparable cu = (Comparable)getFirst(); - if (cu == null) { - if (first != null) - return 1; - } else { - int d = cu.compareTo(o.getFirst()); - if (d != 0) - return d; - } - - Comparable cv = (Comparable)getSecond(); - if (cv == null) - return second != null ? 1 : -1; - return cv.compareTo(o.getSecond()); - } - - @Override - public String toString() { - return "Pair("+first+", "+second+")"; - } - - public U getKey() { - return first; - } - - public V getValue() { - return second; - } - - public V setValue(V value) { - V oldValue = second; - second = value; - return oldValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Pair other = (Pair) obj; - if (first == null) { - if (other.first != null) - return false; - } else if (!first.equals(other.first)) - return false; - if (second == null) { - if (other.second != null) - return false; - } else if (!second.equals(other.second)) - return false; - return true; - } - - public boolean isFull() { - return getFirst() != null && getSecond() != null; - } - - public boolean isEmpty() { - return getFirst() == null && getSecond() == null; - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SwingCollectionListener.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SwingCollectionListener.java deleted file mode 100644 index de16a4730..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SwingCollectionListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import javax.swing.SwingUtilities; - -/** - * Collection listener proxy that forwards in the event dispatch thread all the events it receives. - * @author Olivier Chafik - * @param type of the elements of the collections that are listened to by this listener - */ -public class SwingCollectionListener implements CollectionListener { - final CollectionListener listener; - - public SwingCollectionListener(CollectionListener listener) { - this.listener = listener; - } - - public void collectionChanged(final CollectionEvent e) { - if (SwingUtilities.isEventDispatchThread()) - listener.collectionChanged(e); - else - SwingUtilities.invokeLater(new Runnable() { public void run() { - listener.collectionChanged(e); - }}); - - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableCollection.java deleted file mode 100644 index d6975dd6e..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableCollection.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Collection; -import java.util.Iterator; - -class SynchronizedListenableCollection extends DefaultListenableCollection { - protected Object mutex; - - - public SynchronizedListenableCollection(Collection collection, ListenableSupport collectionSupport) { - super(collection, collectionSupport); - this.mutex = this; - } - public SynchronizedListenableCollection(Collection collection) { - super(collection); - this.mutex = this; - } - public SynchronizedListenableCollection(Collection collection, ListenableSupport collectionSupport, Object mutex) { - super(collection, collectionSupport); - this.mutex = mutex; - } - public SynchronizedListenableCollection(Collection collection, Object mutex) { - super(collection); - this.mutex = mutex; - } - - @Override - public boolean add(T o) { - synchronized (mutex) { - return super.add(o); - } - } - @Override - public boolean addAll(Collection c) { - synchronized (mutex) { - return super.addAll(c); - } - } - @Override - public void addCollectionListener(CollectionListener l) { - synchronized (mutex) { - super.addCollectionListener(l); - } - } - @Override - public void clear() { - synchronized (mutex) { - super.clear(); - } - } - @Override - protected Object clone() throws CloneNotSupportedException { - synchronized (mutex) { - return super.clone(); - } - } - @Override - public boolean contains(Object o) { - synchronized (mutex) { - return super.contains(o); - } - } - @Override - public boolean containsAll(Collection c) { - synchronized (mutex) { - return super.containsAll(c); - } - } - @Override - public boolean equals(Object obj) { - synchronized (mutex) { - return super.equals(obj); - } - } - @Override - public int hashCode() { - synchronized (mutex) { - return super.hashCode(); - } - } - @Override - public boolean isEmpty() { - synchronized (mutex) { - return super.isEmpty(); - } - } - - protected class SynchronizedListenableIterator implements Iterator { - final Iterator it; - public SynchronizedListenableIterator() { - this.it = SynchronizedListenableCollection.super.iterator(); - } - public boolean hasNext() { - synchronized (mutex) { - return it.hasNext(); - } - } - public T next() { - synchronized (mutex) { - return it.next(); - } - } - public void remove() { - synchronized (mutex) { - it.remove(); - } - } - }; - - @Override - public Iterator iterator() { - synchronized (mutex) { - return new SynchronizedListenableIterator();//super.iterator()); - } - } - @Override - public boolean remove(Object o) { - synchronized (mutex) { - return super.remove(o); - } - } - @Override - public boolean removeAll(Collection c) { - synchronized (mutex) { - return super.removeAll(c); - } - } - @Override - public void removeCollectionListener(CollectionListener l) { - synchronized (mutex) { - super.removeCollectionListener(l); - } - } - @Override - public boolean retainAll(Collection c) { - synchronized (mutex) { - return super.retainAll(c); - } - } - @Override - public int size() { - synchronized (mutex) { - return super.size(); - } - } - @Override - public Object[] toArray() { - synchronized (mutex) { - return super.toArray(); - } - } - @Override - public V[] toArray(V[] a) { - synchronized (mutex) { - return super.toArray(a); - } - } - @Override - public String toString() { - synchronized (mutex) { - return super.toString(); - } - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableList.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableList.java deleted file mode 100644 index 7b61ebb51..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableList.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.ochafik.util.listenable; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -class SynchronizedListenableList extends SynchronizedListenableCollection implements ListenableList { - List list; - - public SynchronizedListenableList(List list) { - super(list); - this.list = list; - } - - public void add(int index, T element) { - synchronized (mutex) { - list.add(index, element); - } - } - - public boolean addAll(int index, Collection c) { - synchronized (mutex) { - return list.addAll(index, c); - } - } - - public T get(int index) { - synchronized (mutex) { - return list.get(index); - } - } - - public int indexOf(Object o) { - synchronized (mutex) { - return list.indexOf(o); - } - } - - public int lastIndexOf(Object o) { - synchronized (mutex) { - return list.lastIndexOf(o); - } - } - - public ListIterator listIterator() { -// if (true) -// throw new UnsupportedOperationException(); - - synchronized (mutex) { - return list.listIterator(); - } - } - - public ListIterator listIterator(int index) { -// if (true) -// throw new UnsupportedOperationException(); - - synchronized (mutex) { - return list.listIterator(index); - } - } - - public T remove(int index) { - synchronized (mutex) { - return list.remove(index); - } - } - - public T set(int index, T element) { - synchronized (mutex) { - return list.set(index, element); - } - } - - public List subList(int fromIndex, int toIndex) { -// if (true) -// throw new UnsupportedOperationException(); - - synchronized (mutex) { - return list.subList(fromIndex, toIndex); - } - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableMap.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableMap.java deleted file mode 100644 index a6bfe0af1..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableMap.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Map; - -class SynchronizedListenableMap extends DefaultListenableMap { - Object mutex; - - public SynchronizedListenableMap(Map map) { - super(map); - mutex = this; - } - @Override - public void clear() { - synchronized (mutex) { - super.clear(); - } - } - @Override - protected Object clone() throws CloneNotSupportedException { - synchronized (mutex) { - return super.clone(); - } - } - - @Override - public boolean containsKey(Object key) { - synchronized (mutex) { - return super.containsKey(key); - } - } - @Override - public boolean containsValue(Object value) { - synchronized (mutex) { - return super.containsValue(value); - } - } - @Override - public ListenableSet> entrySet() { - synchronized (mutex) { - return new SynchronizedListenableSet>(super.entrySet(), mutex); - } - } - @Override - public boolean equals(Object obj) { - synchronized (mutex) { - return super.equals(obj); - } - } - @Override - public V get(Object key) { - synchronized (mutex) { - return super.get(key); - } - } - @Override - public int hashCode() { - synchronized (mutex) { - return super.hashCode(); - } - } - @Override - public boolean isEmpty() { - synchronized (mutex) { - return super.isEmpty(); - } - } - - @Override - public ListenableSet keySet() { - synchronized (mutex) { - return new SynchronizedListenableSet(super.keySet()); - } - } - @Override - public V put(K key, V value) { - synchronized (mutex) { - return super.put(key, value); - } - } - @Override - public void putAll(Map t) { - synchronized (mutex) { - super.putAll(t); - } - } - @Override - public V remove(Object key) { - synchronized (mutex) { - return super.remove(key); - } - } - @Override - public int size() { - synchronized (mutex) { - return super.size(); - } - } - @Override - public String toString() { - synchronized (mutex) { - return super.toString(); - } - } - @Override - public ListenableCollection values() { - synchronized (mutex) { - return new SynchronizedListenableCollection(super.values()); - } - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableSet.java deleted file mode 100644 index 54ad015bb..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/SynchronizedListenableSet.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Collection; - -class SynchronizedListenableSet extends SynchronizedListenableCollection implements ListenableSet { - - public SynchronizedListenableSet(Collection collection, ListenableSupport collectionSupport, Object mutex) { - super(collection, collectionSupport, mutex); - } - - public SynchronizedListenableSet(Collection collection, Object mutex) { - super(collection, mutex); - } - - public SynchronizedListenableSet(Collection collection) { - super(collection); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableEntry.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableEntry.java deleted file mode 100644 index 3e316dc91..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableEntry.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Map; - -class UnmodifiableEntry implements Map.Entry { - K key; - V value; - - public UnmodifiableEntry(K key, V value) { - this.key = key; - this.value = value; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - public V setValue(V value) { - throw new UnsupportedOperationException(); - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Map.Entry)) - return false; - - Map.Entry e = (Map.Entry)obj; - if (key == null) { - if (e.getKey() != null) - return false; - } else if (!key.equals(e.getKey())) - return false; - - if (value == null) { - if (e.getValue() != null) - return false; - } - return value.equals(e.getValue()); - } - - @Override - public String toString() { - return "<"+getKey()+", "+getValue()+">"; - } -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableCollection.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableCollection.java deleted file mode 100644 index 3c35212ab..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableCollection.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Collection; -import java.util.Iterator; - -class UnmodifiableListenableCollection extends FilteredListenableCollection { - public UnmodifiableListenableCollection(ListenableCollection listenableCollection) { - super(listenableCollection); - } - @Override - public boolean add(T o) { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - - @Override - public boolean addAll(Collection c) { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - - @Override - public void clear() { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - - @Override - public Iterator iterator() { - return new FilteredIterator(listenableCollection.iterator()) { - @Override - public void remove() { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - }; - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException("Unmodifiable listenable collection !"); - } -} \ No newline at end of file diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableList.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableList.java deleted file mode 100644 index aef6c9043..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableList.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ochafik.util.listenable; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -class UnmodifiableListenableList extends UnmodifiableListenableCollection implements ListenableList { - final ListenableList listenableList; - public UnmodifiableListenableList( - ListenableList listenableList) { - super(listenableList); - this.listenableList = listenableList; - } - - void ex() { - throw new UnsupportedOperationException("Unmodifiable list"); - } - public void add(int index, T element) { - ex(); - } - - - public boolean addAll(int index, Collection c) { - ex(); - return false; - } - - public T get(int index) { - return listenableList.get(index); - } - - public int indexOf(Object o) { - return listenableList.indexOf(o); - } - - public int lastIndexOf(Object o) { - return listenableList.lastIndexOf(o); - } - - public ListIterator listIterator() { - ex(); - return null; - } - - public ListIterator listIterator(int index) { - ex(); - return null; - } - - public T remove(int index) { - ex(); - return null; - } - - public T set(int index, T element) { - ex(); - return null; - } - - public List subList(int fromIndex, int toIndex) { - ex(); - return null; - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableMap.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableMap.java deleted file mode 100644 index 87a432f59..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableMap.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - -import java.util.Map; - - -class UnmodifiableListenableMap extends FilteredListenableMap{ - - - public UnmodifiableListenableMap(ListenableMap listenableMap) { - super(listenableMap); - } - @Override - public void clear() { - throw new UnsupportedOperationException("Unmodifiable map !"); - } - @Override - public ListenableSet> entrySet() { - return ListenableCollections.unmodifiableSet(listenableMap.entrySet()); - } - @Override - public ListenableCollection values() { - return ListenableCollections.unmodifiableCollection(listenableMap.values()); - } - @Override - public ListenableSet keySet() { - return new UnmodifiableListenableSet(listenableMap.keySet()); - //return Collections.unmodifiableSet(listenableMap.keySet()); - } - @Override - public ListenableSet listenableKeySet() { - return new UnmodifiableListenableSet(listenableMap.keySet()); - } - @Override - public V put(K key, V value) { - throw new UnsupportedOperationException("Unmodifiable map !"); - } - @Override - public void putAll(Map t) { - throw new UnsupportedOperationException("Unmodifiable map !"); - } - @Override - public V remove(Object key) { - throw new UnsupportedOperationException("Unmodifiable map !"); - } -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableSet.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableSet.java deleted file mode 100644 index 703e93af5..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/listenable/UnmodifiableListenableSet.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2008 Olivier Chafik - - Licensed under the Apache License, Version 2.0 (the License); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an AS IS BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - This file comes from the Jalico project (Java Listenable Collections) - - http://jalico.googlecode.com/. -*/ -package com.ochafik.util.listenable; - - -class UnmodifiableListenableSet extends UnmodifiableListenableCollection implements ListenableSet { - - public UnmodifiableListenableSet(ListenableCollection listenableCollection) { - super(listenableCollection); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/progress/ProgressModel.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/progress/ProgressModel.java deleted file mode 100644 index 0bde1ed7c..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/progress/ProgressModel.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ochafik.util.progress; - -public interface ProgressModel { - public void setIndeterminate(boolean value); - public boolean isIndeterminate(); - public void addProgress(long value); - public void setProgress(long value); - public long getProgress(); - public void addMaximum(long value); - public void setMaximum(long max); - public long getMaximum(); - public String getTitle(); - public String getComment(); - public void setTitle(String t); - public void setComment(String t); - public void setShowRemainingTime(boolean value); - public boolean getShowRemainingTime(); - - public boolean isInterrupted(); - public void setInterrupted(boolean value); -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/RegexUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/RegexUtils.java deleted file mode 100644 index b585ed2b4..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/RegexUtils.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util.string; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.listenable.Pair; - -public class RegexUtils { - static final String[][] simplePatternReplacements=new String[][] { - {"(\\.|\\+|\\[|\\]|\\{|\\})","\\\\."}, - {"(\\*|\\?)",".$1"}, - /*{"[a\u00e0\u00e2\u00e4]","[a\u00e0\u00e2\u00e4]"}, - {"[e\u00e9\u00e8\u00ea\u00eb]","[e\u00e9\u00e8\u00ea\u00eb]"}, - {"[i\u00ee\u00ef\u00ec]","[i\u00ee\u00ef\u00ec]"}, - {"[o\u00f4\u00f6\u00f2]","[o\u00f4\u00f6\u00f2]"}, - {"[u\u00fb\u00fc\u00f9]","[u\u00fb\u00fc\u00f9]"}, - {"[y\u00ff]","[y\u00ff]"}, - {"[c\u00e7]","[c\u00e7]"},*/ - {",","|"} - }; - static final Pattern[] simplePatternReplacementPatterns; - static { - simplePatternReplacementPatterns=new Pattern[simplePatternReplacements.length]; - for (int i=simplePatternReplacements.length;i--!=0;) { - simplePatternReplacementPatterns[i]=Pattern.compile(simplePatternReplacements[i][0]); - } - } - private static final String replaceSimplePatterByRegex(String string) { - for (int i=simplePatternReplacements.length;i--!=0;) { - string=simplePatternReplacementPatterns[i].matcher(string).replaceAll(simplePatternReplacements[i][1]); - } - return string; - } - public static final Pattern simplePatternToRegex(String pattern) { - try { - return Pattern.compile(replaceSimplePatterByRegex(pattern),Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); - } catch (Exception ex) { - return Pattern.compile(pattern,Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE|Pattern.LITERAL); - } - } - public static interface Replacer { - String replace(String[] groups); - } - public static String regexReplace(Pattern pattern, String string, final MessageFormat replacement) { - return regexReplace(pattern, string, new Replacer() { - - public String replace(String[] groups) { - if (replacement!=null) - return replacement.format(groups); - else - return groups[0]; - } - - }); - } - public static String regexReplace(Pattern pattern, String string, Replacer replacer) { - StringBuffer b=new StringBuffer(string.length()); - int iLastCommitted=0; - Matcher matcher=pattern.matcher(string); - while (matcher.find(iLastCommitted)) { - int start=matcher.start(); - String s = string.substring(iLastCommitted,start); - String g = matcher.group(0); - b.append(s); - b.append(replacer.replace(getGroups(matcher))); - - iLastCommitted = start + g.length(); - } - b.append(string.substring(iLastCommitted)); - return b.toString(); - } - public static final boolean findLast(Matcher matcher) { - matcher.reset(); - int n = 0; - while (matcher.find()) { - n++; - } - matcher.reset(); - for (int i = 0; i < n; i++) matcher.find(); - return n > 0; - } - - public static final List> grep(Collection list, Pattern p) { - List> ret = new ArrayList>(list.size()); - for (String s : list) { - Matcher matcher = p.matcher(s); - if (matcher.find()) - ret.add(new Pair(s, getGroups(matcher))); - } - return ret; - } - - public static String[] getGroups(Matcher matcher) { - String[] groups = new String[matcher.groupCount() + 1]; - for (int i = groups.length; i-- != 0;) { - groups[i] = matcher.group(i); - } - return groups; - } - public static final List grep(String s, Pattern p) { - List ret = new ArrayList(); - Matcher matcher = p.matcher(s); - while (matcher.find()) - ret.add(getGroups(matcher)); - - return ret; - } - public static final String[] match(String s, Pattern p) { - Matcher matcher = p.matcher(s); - if (matcher.matches()) - return getGroups(matcher); - - return null; - } - public static List find(String string, String pattern) { - return find(string, Pattern.compile(pattern)); - } - - public static List find(String string, Pattern pattern) { - List ret = new LinkedList(); - - Matcher matcher = pattern.matcher(string); - while (matcher.find()) - ret.add(getGroups(matcher)); - - return ret; - } - public static Collection find(String string, String pattern, final int iGroup) { - return find(string, Pattern.compile(pattern), iGroup); - } - public static Collection find(String string, Pattern pattern, final int iGroup) { - List ret= new ArrayList(); - Matcher matcher = pattern.matcher(string); - while (matcher.find()) { - ret.add(matcher.group(iGroup)); - } - return ret; - } - public static String findFirst(String string, Pattern pattern, int iGroup) { - if (string == null) - return null; - - Matcher matcher = pattern.matcher(string); - return matcher.find() ? matcher.group(iGroup) : null; - } - public static String regexReplace(String pat, String text, String rep) { - return regexReplace(Pattern.compile(pat), text, new MessageFormat(rep)); - } - public static String regexReplace(Pattern pattern, String string, Adapter adapter) { - StringBuffer b=new StringBuffer(string.length()); - int iLastCommitted=0; - Matcher matcher=pattern.matcher(string); - while (matcher.find(iLastCommitted)) { - int start=matcher.start(); - String s = string.substring(iLastCommitted,start); - String g = matcher.group(0); - b.append(s); - if (adapter!=null) - b.append(adapter.adapt(getGroups(matcher))); - else - b.append(g); - iLastCommitted = start + g.length(); - } - b.append(string.substring(iLastCommitted)); - return b.toString(); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java deleted file mode 100644 index 767f041de..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.util.string; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -public class StringUtils { - public static String htmlize(String text) { - return text.startsWith("") ? - text : ""+ - text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\n","
        ")+ - ""; - } - - static Pattern spacePattern; - public static List explode(String s) { - if (spacePattern == null) { - spacePattern = Pattern.compile("\\s+"); - } - return explode(s, spacePattern); - } - public static List explode(String s, String sep) { - StringTokenizer st=new StringTokenizer(s,sep); - List v = new ArrayList(); - for (;st.hasMoreTokens();) { - v.add(st.nextToken()); - } - return v; - } - - public static String trimUnderscores(String s) { - return trimChar(s, '_'); - } - - public static String trimChar(String s, char t) { - if (s == null) - return null; - int start = 0, n = s.length(), end = n; - for (int i = 0; i < n; i++) { - char c = s.charAt(i); - if (c != t) { - start = i; - break; - } - } - for (int i = n - 1; i >= 0; i--) { - char c = s.charAt(i); - if (c != t) { - end = i + 1; - break; - } - } - return s.substring(start, end); - } -/* - public static final String implode(Object[] strings, String separator) { - return implode(Arrays.asList(strings), separator); - } -*/ - public static String implode(double[] array, String separator) { - StringBuffer out = new StringBuffer(); - boolean first = true; - for (double v : array) { - if (first) first = false; - else out.append(separator); - out.append(v); - } - return out.toString(); - } - - public static String implode(Object[] values) { - return implode(values, ", "); - } - public static String implode(Object[] values, Object separator) { - return implode(Arrays.asList(values), separator); - } - public static final String implode(Iterable elements, Object separator) { - String sepStr = separator.toString(); - StringBuilder out = new StringBuilder(); - boolean first = true; - for (Object s : elements) { - if (s == null) - continue; - - if (first) - first = false; - else - out.append(sepStr); - out.append(s); - } - return out.toString(); - } - public static final String implode(Iterable strings) { - return implode(strings, ", "); - } - /* - public static final String implode(Collection strings, String separator) { - int size = 0, n = strings.size(); - for (Object s : strings) - if (s != null) - size += s.toString().length(); - - StringBuffer out = new StringBuffer(size + separator.length() * (n == 0 ? 0 : n - 1)); - boolean first = true; - for (Object s : strings) { - if (s == null) - continue; - - if (first) first = false; - else out.append(separator); - out.append(s); - } - return out.toString(); - } - */ - public static final List explode(String string, Pattern separator) { - int lastIndex = 0, len = string.length(); - - Matcher matcher = separator.matcher(string); - List ret = new LinkedList(); - - while (matcher.find()) { - String s = string.substring(lastIndex, matcher.start()); - if (s.length() > 0) ret.add(s); - lastIndex = matcher.end(); - } - String s = string.substring(lastIndex, len); - if (s.length() > 0) ret.add(s); - - return ret; - } - - public static String replace(String pattern, String replace, String s) { - return concatWithSeparator(explode(s,pattern).toArray(new String[0]),replace); - } - public static final String concat(String[] a) { - StringBuffer b=new StringBuffer(); - for (int i=0;i127||Character.isISOControl(c)) { - b.append("\\u"); - String nb=Integer.toString((int)c,16); - int nblen=nb.length(); - switch (nblen) { - case 1: - b.append(0); - case 2: - b.append(0); - case 3: - b.append(0); - case 4: - b.append(nb); - break; - default: - throw new IllegalArgumentException("Should not happen !"); - } - } else b.append(c); - } - } - return b.toString(); - } - public static final String javaUnEscape(String s) { - char c; - int len=s.length(); - StringBuffer b=new StringBuffer(len); - for (int i=0;i strings, String separator) { - List cap = new ArrayList(strings.size()); - for (String s : strings) - cap.add(capitalize(s)); - return implode(cap, separator); - } - - public static String underscoredToCamel(String string) { - String[] a = string.split("_"); - for (int i = 0, n = a.length; i < n; i++) { - String s = a[i].trim(); - a[i] = capitalize(a[i]); - } - return implode(a, ""); - } - - public static String uncapitalize(String string) { - return string.length() == 0 ? "" : Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - public static final String LINE_SEPARATOR; - static { - LINE_SEPARATOR = System.getProperty("line.separator"); - } - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XMLUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XMLUtils.java deleted file mode 100644 index 99da2fbb8..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XMLUtils.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.xml; -import java.io.File; -import java.io.StringWriter; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.regex.Pattern; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.ochafik.util.listenable.Adapter; -import com.ochafik.util.string.RegexUtils; -//import ochafik.babel.*; -public class XMLUtils { - public static String getAttribute(Node node, String name) { - NamedNodeMap m=node.getAttributes(); - if (m==null) return null; - Node att=m.getNamedItem(name); - if (att==null) return null; - return att.getNodeValue(); - } - public static Node getFirstNamedNode(Node node, String name) { - if (node.getNodeName().equalsIgnoreCase(name)) return node; - else { - NodeList list=node.getChildNodes(); - for (int i=0,len=list.getLength();i getByName(Node node, String name) { - List result = new LinkedList(); - getByName(node, name, result); - return result; - } - - private static void getByName(Node node, String name, List result) { - if (node.getNodeName().equalsIgnoreCase(name)) { - result.add(node); - } else { - NodeList list=node.getChildNodes(); - for (int i=0,len=list.getLength();i getChildrenByName(Node node, String name) { - Collection nodes=new ArrayList(); - getChildrenByName(node,name,nodes); - return nodes; - } - private static void getChildrenByName(Node node, String name, Collection nodes) { - NodeList list=node.getChildNodes(); - for (int i=0,len=list.getLength();i getChildElements(Node node) { - NodeList children = node.getChildNodes(); - int childCount = children.getLength(); - List nodes = new ArrayList(childCount); - for (int i = 0; i < childCount; i++) { - Node child = children.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - nodes.add(child); - } - } - return nodes; - } - public static List getAttributes(Node node) { - NamedNodeMap attrs = node.getAttributes(); - int attrCount = attrs.getLength(); - List nodes = new ArrayList(attrCount); - for (int i = 0; i < attrCount; i++) { - nodes.add(attrs.item(i)); - } - return nodes; - } - public static StringBuffer gatherTextPCDATAAndCDATADescendants(Node node,StringBuffer sb,String separator) { - if (sb==null) sb=new StringBuffer(); - int t=node.getNodeType(); - if (t==Node.CDATA_SECTION_NODE || t==Node.TEXT_NODE) { - //sb.append("================= "+node.getNodeName()+" ================="); - sb.append(node.getNodeValue()); - } else { - NodeList list = node.getChildNodes(); - for (int i=0,len=list.getLength();i", ">"); - } - - - private static final Pattern xmlTagPattern=Pattern.compile("|]*(?:(?:\"[^\"]*\")[\">]*)*>"); - private static final Pattern spacesPattern=Pattern.compile("\\s+"); - private static final MessageFormat spaceMessageFormat=new MessageFormat(" "); - - public static String stripTags(String xmlString) { - String strippedHtml = RegexUtils.regexReplace(xmlTagPattern, xmlString, (Adapter)null); - return RegexUtils.regexReplace(spacesPattern,strippedHtml,spaceMessageFormat).trim(); - } - public static Document readXML(File file) throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); // never forget this! - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - return documentBuilder.parse(file); - } - public static List list(NodeList nodeList) { - if (nodeList == null) - return null; - - int len = nodeList.getLength(); - List list = new ArrayList(len); - for (int i = 0; i < len; i++) - list.add(nodeList.item(i)); - return list; - } - - -} diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XPathUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XPathUtils.java deleted file mode 100644 index 5dea4b7bc..000000000 --- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/xml/XPathUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved - - This file is part of JNAerator (http://jnaerator.googlecode.com/). - - JNAerator is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - JNAerator is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with JNAerator. If not, see . -*/ -package com.ochafik.xml; - -import java.lang.ref.SoftReference; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.ochafik.lang.SyntaxUtils; - -public class XPathUtils { - public static Map> xPathExpressionsCache = new HashMap>(); - private static SoftReference sharedXPath; - public static XPath getSharedXPath() { - XPath xPath = null; - if (sharedXPath != null) - xPath = sharedXPath.get(); - if (xPath == null) { - XPathFactory xPathFactory = XPathFactory.newInstance(); - sharedXPath = new SoftReference(xPath = xPathFactory.newXPath()); - } - return xPath; - } - public static List findNodesByXPath(String xPathString, Object source) throws XPathExpressionException { - return XMLUtils.list((NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET)); - } - public static Iterable findNodesIterableByXPath(String xPathString, Object source) throws XPathExpressionException { - return SyntaxUtils.iterable((NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET)); - } - public static Node findNodeByXPath(String xPathString, Object source) throws XPathExpressionException { - NodeList list = (NodeList)getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET); - int len = list.getLength(); - return len == 0 ? null : list.item(0); - } - public static String findStringByXPath(String xPathString, Object source) throws XPathExpressionException { - return (String)getXPathExpression(xPathString).evaluate(source, XPathConstants.STRING); - } - public static XPathExpression getXPathExpression(String xPathString) throws XPathExpressionException { - SoftReference ref = xPathExpressionsCache.get(xPathString); - XPathExpression expression = ref == null ? null : ref.get(); - if (expression == null) - xPathExpressionsCache.put(xPathString, new SoftReference(expression = getSharedXPath().compile(xPathString))); - - return expression; - } - -} diff --git a/libraries/jnaerator/pom.xml b/libraries/jnaerator/pom.xml deleted file mode 100644 index d775a5c91..000000000 --- a/libraries/jnaerator/pom.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - 4.0.0 - com.nativelibs4java - jnaerator-parent - 0.11-SNAPSHOT - pom - 2009 - JNAerator Parent Project - - - com.nativelibs4java - nativelibs4java-parent - 1.8-SNAPSHOT - .. - - - - 3.4.0 - 0.5 - - - - anarres - ochafik-util - ochafik-swing - jna-jnaerator - jnaerator-runtime - jnaerator-rococoa-runtime - jnaerator-parser - - maven-jnaerator-plugin - jnaerator - - - - - LGPL 2.1 - http://www.gnu.org/copyleft/lesser.html - repo - - - - - - - - com.nativelibs4java - ochafik-util - ${project.version} - - - com.nativelibs4java - ochafik-swing - ${project.version} - - - com.nativelibs4java - jna-jnaerator - ${project.version} - - - com.nativelibs4java - jnaerator-runtime - ${project.version} - - - com.nativelibs4java - jnaerator-rococoa-runtime - ${project.version} - - - com.nativelibs4java - jnaerator-parser - ${project.version} - - - com.nativelibs4java - maven-jnaerator-plugin - ${project.version} - - - com.nativelibs4java - jnaerator - ${project.version} - - - com.nativelibs4java - jnaerator - shaded - ${project.version} - - - - com.nativelibs4java - bridj - ${bridj.version} - - - net.java.dev.jna - jna - ${jna.version} - - - org.rococoa - rococoa-core - ${rococoa.version} - - - org.antlr - antlr-runtime - 3.4 - - - com.nativelibs4java - anarres-jnaerator - 1.2.8-SNAPSHOT - - - org.eclipse.jdt.core.compiler - ecj - 3.7.2 - - - - - - - - - org.antlr - antlr3-maven-plugin - 3.4 - - - - antlr - - - - - - - - diff --git a/libraries/jnaerator/resources/JNAeratorStudio.jnlp b/libraries/jnaerator/resources/JNAeratorStudio.jnlp deleted file mode 100644 index 4c700a8cb..000000000 --- a/libraries/jnaerator/resources/JNAeratorStudio.jnlp +++ /dev/null @@ -1,30 +0,0 @@ - - - - JNAerator Studio - Olivier Chafik - - JNAerator : Java gets to love native libraries ! - JNAerator Studio : wrap C and Objective-C libraries in Java. - - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/rococoa-jnaerator/deploy-to-nativelibs4java b/libraries/jnaerator/rococoa-jnaerator/deploy-to-nativelibs4java deleted file mode 100644 index f3f2e30b3..000000000 --- a/libraries/jnaerator/rococoa-jnaerator/deploy-to-nativelibs4java +++ /dev/null @@ -1,10 +0,0 @@ -mvn deploy:deploy-file \ - -Dfile=target/rococoa-core-0.5.jar \ - -Durl=scp://shell.sourceforge.net/home/groups/j/jn/jnaerator/htdocs/maven \ - -DrepositoryId=jnaerator-repo \ - -DgroupId=org.rococoa \ - -DartifactId=rococoa-core \ - -Dpackaging=jar \ - -DuniqueVersion=true \ - "-Dversion=0.5" \ - -f pom.xml diff --git a/libraries/jnaerator/webstart/JNAeratorStudio.jnlp b/libraries/jnaerator/webstart/JNAeratorStudio.jnlp deleted file mode 100644 index 45394f34d..000000000 --- a/libraries/jnaerator/webstart/JNAeratorStudio.jnlp +++ /dev/null @@ -1,29 +0,0 @@ - - - - JNAerator Studio - Olivier Chafik - - JNAerator : Java gets to love native libraries ! - JNAerator Studio : wrap C and Objective-C libraries in Java. - - - - - - - - - - - - - - - - - - diff --git a/libraries/jnaerator/webstart/appIcon128.gif b/libraries/jnaerator/webstart/appIcon128.gif deleted file mode 100644 index 685be207d..000000000 Binary files a/libraries/jnaerator/webstart/appIcon128.gif and /dev/null differ diff --git a/libraries/jnaerator/webstart/appIcon128.jpg b/libraries/jnaerator/webstart/appIcon128.jpg deleted file mode 100644 index d26dd58d3..000000000 Binary files a/libraries/jnaerator/webstart/appIcon128.jpg and /dev/null differ diff --git a/libraries/jnaerator/webstart/appIcon128.png b/libraries/jnaerator/webstart/appIcon128.png deleted file mode 100644 index 80f727bb1..000000000 Binary files a/libraries/jnaerator/webstart/appIcon128.png and /dev/null differ diff --git a/libraries/jnaerator/webstart/fileIcon128.gif b/libraries/jnaerator/webstart/fileIcon128.gif deleted file mode 100644 index 8144b863d..000000000 Binary files a/libraries/jnaerator/webstart/fileIcon128.gif and /dev/null differ diff --git a/libraries/jnaerator/webstart/fileIcon128.jpg b/libraries/jnaerator/webstart/fileIcon128.jpg deleted file mode 100644 index 03ce151bf..000000000 Binary files a/libraries/jnaerator/webstart/fileIcon128.jpg and /dev/null differ diff --git a/libraries/jnaerator/webstart/fileIcon128.png b/libraries/jnaerator/webstart/fileIcon128.png deleted file mode 100644 index 9e46105e1..000000000 Binary files a/libraries/jnaerator/webstart/fileIcon128.png and /dev/null differ diff --git a/libraries/scripts/googlecode_upload.py b/libraries/scripts/googlecode_upload.py new file mode 100755 index 000000000..e12cc4031 --- /dev/null +++ b/libraries/scripts/googlecode_upload.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python +# +# Copyright 2006, 2007 Google Inc. All Rights Reserved. +# Author: danderson@google.com (David Anderson) +# +# olivier.chafik@gmail.com: Modified script to add optional description. +# +# Script for uploading files to a Google Code project. +# +# This is intended to be both a useful script for people who want to +# streamline project uploads and a reference implementation for +# uploading files to Google Code projects. +# +# To upload a file to Google Code, you need to provide a path to the +# file on your local machine, a small summary of what the file is, a +# project name, and a valid account that is a member or owner of that +# project. You can optionally provide a list of labels that apply to +# the file. The file will be uploaded under the same name that it has +# in your local filesystem (that is, the "basename" or last path +# component). Run the script with '--help' to get the exact syntax +# and available options. +# +# Note that the upload script requests that you enter your +# googlecode.com password. This is NOT your Gmail account password! +# This is the password you use on googlecode.com for committing to +# Subversion and uploading files. You can find your password by going +# to http://code.google.com/hosting/settings when logged in with your +# Gmail account. If you have already committed to your project's +# Subversion repository, the script will automatically retrieve your +# credentials from there (unless disabled, see the output of '--help' +# for details). +# +# If you are looking at this script as a reference for implementing +# your own Google Code file uploader, then you should take a look at +# the upload() function, which is the meat of the uploader. You +# basically need to build a multipart/form-data POST request with the +# right fields and send it to https://PROJECT.googlecode.com/files . +# Authenticate the request using HTTP Basic authentication, as is +# shown below. +# +# Licensed under the terms of the Apache Software License 2.0: +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Questions, comments, feature requests and patches are most welcome. +# Please direct all of these to the Google Code users group: +# http://groups.google.com/group/google-code-hosting + +"""Google Code file uploader script. +""" + +__author__ = 'danderson@google.com (David Anderson)' + +import httplib +import os.path +import optparse +import getpass +import base64 +import sys + + +def upload(file, project_name, user_name, password, summary, description, labels=None): + """Upload a file to a Google Code project's file server. + + Args: + file: The local path to the file. + project_name: The name of your project on Google Code. + user_name: Your Google account name. + password: The googlecode.com password for your account. + Note that this is NOT your global Google Account password! + summary: A small description for the file. + description: full description for the file. + + labels: an optional list of label strings with which to tag the file. + + Returns: a tuple: + http_status: 201 if the upload succeeded, something else if an + error occured. + http_reason: The human-readable string associated with http_status + file_url: If the upload succeeded, the URL of the file on Google + Code, None otherwise. + """ + # The login is the user part of user@gmail.com. If the login provided + # is in the full user@domain form, strip it down. + if user_name.endswith('@gmail.com'): + user_name = user_name[:user_name.index('@gmail.com')] + + form_fields = [('summary', summary), ('description', description)] + if labels is not None: + form_fields.extend([('label', l.strip()) for l in labels]) + + content_type, body = encode_upload_request(form_fields, file) + + upload_host = '%s.googlecode.com' % project_name + upload_uri = '/files' + auth_token = base64.b64encode('%s:%s'% (user_name, password)) + headers = { + 'Authorization': 'Basic %s' % auth_token, + 'User-Agent': 'Googlecode.com uploader v0.9.4', + 'Content-Type': content_type, + } + + server = httplib.HTTPSConnection(upload_host) + server.request('POST', upload_uri, body, headers) + resp = server.getresponse() + server.close() + + if resp.status == 201: + location = resp.getheader('Location', None) + else: + location = None + return resp.status, resp.reason, location + + +def encode_upload_request(fields, file_path): + """Encode the given fields and file into a multipart form body. + + fields is a sequence of (name, value) pairs. file is the path of + the file to upload. The file will be uploaded to Google Code with + the same file name. + + Returns: (content_type, body) ready for httplib.HTTP instance + """ + BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' + CRLF = '\r\n' + + body = [] + + # Add the metadata about the upload first + for key, value in fields: + body.extend( + ['--' + BOUNDARY, + 'Content-Disposition: form-data; name="%s"' % key, + '', + value, + ]) + + # Now add the file itself + file_name = os.path.basename(file_path) + f = open(file_path, 'rb') + file_content = f.read() + f.close() + + body.extend( + ['--' + BOUNDARY, + 'Content-Disposition: form-data; name="filename"; filename="%s"' + % file_name, + # The upload server determines the mime-type, no need to set it. + 'Content-Type: application/octet-stream', + '', + file_content, + ]) + + # Finalize the form body + body.extend(['--' + BOUNDARY + '--', '']) + + return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) + + +def upload_find_auth(file_path, project_name, summary, description, labels=None, + user_name=None, password=None, tries=3): + """Find credentials and upload a file to a Google Code project's file server. + + file_path, project_name, summary, description, and labels are passed as-is to upload. + + Args: + file_path: The local path to the file. + project_name: The name of your project on Google Code. + summary: A small description for the file. + description: full description for the file. + labels: an optional list of label strings with which to tag the file. + config_dir: Path to Subversion configuration directory, 'none', or None. + user_name: Your Google account name. + tries: How many attempts to make. + """ + + if user_name is None or password is None: + from netrc import netrc + authenticators = netrc().authenticators("code.google.com") + if authenticators: + if user_name is None: + user_name = authenticators[0] + if password is None: + password = authenticators[2] + + while tries > 0: + if user_name is None: + # Read username if not specified or loaded from svn config, or on + # subsequent tries. + sys.stdout.write('Please enter your googlecode.com username: ') + sys.stdout.flush() + user_name = sys.stdin.readline().rstrip() + if password is None: + # Read password if not loaded from svn config, or on subsequent tries. + print 'Please enter your googlecode.com password.' + print '** Note that this is NOT your Gmail account password! **' + print 'It is the password you use to access Subversion repositories,' + print 'and can be found here: http://code.google.com/hosting/settings' + password = getpass.getpass() + + status, reason, url = upload(file_path, project_name, user_name, password, + summary, description, labels) + # Returns 403 Forbidden instead of 401 Unauthorized for bad + # credentials as of 2007-07-17. + if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: + # Rest for another try. + user_name = password = None + tries = tries - 1 + else: + # We're done. + break + + return status, reason, url + + +def main(): + parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' + '-p PROJECT [options] FILE') + parser.add_option('-s', '--summary', dest='summary', + help='Short description of the file') + parser.add_option('-d', '--description', dest='description', + help='Long description of the file') + parser.add_option('-p', '--project', dest='project', + help='Google Code project name') + parser.add_option('-u', '--user', dest='user', + help='Your Google Code username') + parser.add_option('-w', '--password', dest='password', + help='Your Google Code password') + parser.add_option('-l', '--labels', dest='labels', + help='An optional list of comma-separated labels to attach ' + 'to the file') + + options, args = parser.parse_args() + + if not options.summary: + parser.error('File summary is missing.') + elif not options.project: + parser.error('Project name is missing.') + elif len(args) < 1: + parser.error('File to upload not provided.') + elif len(args) > 1: + parser.error('Only one file may be specified.') + + file_path = args[0] + + if options.labels: + labels = options.labels.split(',') + else: + labels = None + + status, reason, url = upload_find_auth(file_path, options.project, + options.summary, options.description, labels, + options.user, options.password) + if url: + print 'The file was uploaded successfully.' + print 'URL: %s' % url + return 0 + else: + print 'An error occurred. Your file was not uploaded.' + print 'Google Code upload server said: %s (%s)' % (reason, status) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/libraries/scripts/listRuntime b/libraries/scripts/listRuntime index 9feef848a..d1069bc23 100755 --- a/libraries/scripts/listRuntime +++ b/libraries/scripts/listRuntime @@ -1,7 +1,7 @@ #!/bin/bash function listFile { - unzip -l $1 | sed -E 's/^.*[0-9]+:[0-9]+ +//' | grep '\.' | grep -v "META-INF" | grep -v "Archive: " | sort | tee jnaerator/src/main/resources/$2 + unzip -l $1 | sed -E 's/^.*[0-9]+:[0-9]+ +//' | grep '\.' | grep -v "META-INF" | grep -v "Archive: " | sort > jnaerator/src/main/resources/$2 } # unzip -l jna-jnaerator/target/jna-jnaerator-3.2.7.jar | sed -E 's/^.*[0-9]+:[0-9]+ +//' | grep '\.' | sort | tee jnaerator/src/main/resources/jna-runtime.jar.files @@ -9,9 +9,15 @@ function listFile { # unzip -l ~/nativelibs4java/Structs/target/nl4j-runtime-structs-jna-*.jar | sed -E 's/^.*[0-9]+:[0-9]+ +//' | grep '\.' | sort | tee jnaerator/src/main/resources/nl4j-runtime-structs-jna.jar.files # unzip -l ~/nativelibs4java/BridJ/target/bridj-0.6.jar | sed -E 's/^.*[0-9]+:[0-9]+ +//' | grep '\.' | sort | tee jnaerator/src/main/resources/bridj.jar.files -JNA_VERSION=3.4.0 -JNAERATOR_VERSION=0.11-SNAPSHOT -BRIDJ_VERSION=0.6.2-SNAPSHOT +cd `dirname $0` +cd ../jnaerator + +JNA_VERSION=`cat pom.xml | grep jna.version | head -n 1 | sed 's/[^>]*>//' | sed 's/<.*//'` + +JNAERATOR_VERSION=`cat pom.xml | grep "" | head -n 1 | sed 's/[^>]*>//' | sed 's/<.*//'` +BRIDJ_VERSION=`cat ../pom.xml | grep bridj.version | head -n 1 | sed 's/[^>]*>//' | sed 's/<.*//'` + +[[ -n "$JNA_VERSION" && -n "$JNAERATOR_VERSION" && -n "$BRIDJ_VERSION" ]] || ( echo "Failed to get versions: JNA = $JNA_VERSION, JNAerator = $JNAERATOR_VERSION, BridJ = $BRIDJ_VERSION" ; exit 1 ) listFile ~/.m2/repository/net/java/dev/jna/jna/$JNA_VERSION/jna-$JNA_VERSION.jar jna-runtime.jar.files listFile jnaerator-runtime/target/jnaerator-runtime-*-shaded.jar jnaerator-runtime.jar.files diff --git a/libraries/scripts/prepareReleaseNotes b/libraries/scripts/prepareReleaseNotes new file mode 100755 index 000000000..ea8ea7ce5 --- /dev/null +++ b/libraries/scripts/prepareReleaseNotes @@ -0,0 +1,13 @@ +#!/bin/bash + +ISSUES= +for F in BridJ/CHANGELOG jnaerator/CHANGELOG OpenCL/CHANGELOG; do + cat $F | \ + perl -p -e 's/&/&/' | \ + perl -p -e 's//>/' | \ + perl -p -e 's/(http:[^ \$]+)/(\1<\/a>/' | \ + perl -p -e 's/([iI]ssue) #([0-9]+)/\1 #\2<\/a>/' | \ + perl -p -e 's/^([ \t]*)- (.*)/\1
      • \2<\/li>/' | \ + tee $F.html +done diff --git a/libraries/scripts/prependLicenseHeader b/libraries/scripts/prependLicenseHeader new file mode 100755 index 000000000..1c9b66464 --- /dev/null +++ b/libraries/scripts/prependLicenseHeader @@ -0,0 +1,23 @@ +#!/bin/bash + +LICENSE="$1" + +shift +FILES=$@ + +#ROOT="src/" +#GLOB="*.java" +#FILES=`find $ROOT -name "$GLOB"` + +for F in $FILES ; do + cat $LICENSE > $F.tmp + cat $F >> $F.tmp + mv $F $F.old + mv $F.tmp $F +done + +echo 'Finalize with: + + find '$ROOT' -name "'$GLOB'.old" -exec rm '"'"'{}'"'"' '"'"';'"'"' + +' diff --git a/libraries/scripts/svnDiffSorted b/libraries/scripts/svnDiffSorted new file mode 100755 index 000000000..115b4c692 --- /dev/null +++ b/libraries/scripts/svnDiffSorted @@ -0,0 +1,12 @@ +#!/bin/bash + +# svn has recently started outputting diffs in a random order: +# http://comments.gmane.org/gmane.comp.version-control.subversion.user/109502 + +FILES=`svn status $@ | awk '{ print $2 }' | sort` + +for FILE in $FILES ; do + if [[ -f $FILE ]]; then + svn diff $FILE + fi +done diff --git a/libraries/scripts/tagAndUpload_BridJ_JNAerator_JavaCL b/libraries/scripts/tagAndUpload_BridJ_JNAerator_JavaCL new file mode 100755 index 000000000..054f41f09 --- /dev/null +++ b/libraries/scripts/tagAndUpload_BridJ_JNAerator_JavaCL @@ -0,0 +1,110 @@ +#!/bin/bash +# +# http://code.google.com/p/support/wiki/ScriptedUploads +# +# http://code.google.com/p/nativelibs4java/source/browse/trunk/libraries/jnaerator/CHANGELOG +# +function fail { + echo "#" >&2 + echo "# ERROR: $@" >&2 + echo "#" >&2 + exit 1 +} + +function getVersion { + POM=$1 + [[ -f "$POM" ]] || fail "No such POM file: $POM" + cat "$POM" | grep "" | head -n 1 | sed 's/[^>]*>//' | sed 's/<.*//' +} + +function listPOMs { + find $1 -name pom.xml +} + +cd `dirname $0` +cd .. + +BRIDJ_VERSION=`getVersion BridJ/pom.xml` +JNAERATOR_VERSION=`getVersion jnaerator/pom.xml` +JAVACL_VERSION=`getVersion OpenCL/pom.xml` +ROOT_VERSION=`getVersion pom.xml` + +HAS_SNAPSHOT_VERSION=0 +for POM in pom.xml `listPOMs BridJ` `listPOMs jnaerator` `listPOMs OpenCL`; do + VERSION=`getVersion "$POM"` + if [[ $VERSION =~ .*-SNAPSHOT ]]; then + HAS_SNAPSHOT_VERSION=1 + echo "Found SNAPSHOT version in '$POM': $VERSION" + fi +done + +[[ $HAS_SNAPSHOT_VERSION -eq 0 ]] || fail "Please update versions to release versions and try again" + +USER=$1 +PASSWORD=$2 + +[[ -n "$USER" && -n "$PASSWORD" ]]Ê|| fail "Please provide a username and a password for Google Code" + +mvn clean javadoc:jar deploy -DskipTests -Pgpg,coordinated-release || fail "Deployment failed" + +git -a bridj-$BRIDJ_VERSION "BridJ version $BRIDJ_VERSION" || fail "Failed to create git tag for BridJ" +git -a jnaerator-$JNAERATOR_VERSION "JNAerator version $JNAERATOR_VERSION" || fail "Failed to create git tag for JNAerator" +git -a javacl-$JAVACL_VERSION "JavaCL version $JAVACL_VERSION" || fail "Failed to create git tag for JavaCL" +git push --tags || fail "Failed to push newly-created git tags" + +# Modified script to add full description: +# wget http://support.googlecode.com/svn/trunk/scripts/googlecode_upload.py + +function upload_artifact() { + DIR_NAME="$1" + PROJECT="$2" + NAME="$3" + VERSION="$4" + CLASSIFIER="$5" + SUMMARY="$6" + + SUMMARY_FILE="${PROJECT}_SUMMARY" + [[ -f "$SUMMARY_FILE" ]]Ê|| fail "Summary file '$SUMMARY_FILE' not found" + + DESCRIPTION="`cat "$SUMMARY_FILE"` + +For more details, see https://github.com/ochafik/nativelibs4java/blob/master/libraries/$DIR_NAME/CHANGELOG" + + if [[ -z "$CLASSIFIER" ]]; then + CLASSIFIER_SUFFIX="" + else + CLASSIFIER_SUFFIX="-$CLASSIFIER" + fi + + FILE="$HOME/.m2/repository/com/nativelibs4java/$NAME/$VERSION/$NAME-$VERSION$CLASSIFIER_SUFFIX.jar" + + if [[ ! -f "${PROJECT}_SUMMARY" ]]; then + echo "Failed to read ${PROJECT}_SUMMARY" + exit 1 + fi + if [[ ! -f "$FILE" ]]; then + echo "Failed to read $FILE" + exit 1 + fi + + + $(dirname $0)/googlecode_upload.py -u "$USER" -w "$PASSWORD" -l Featured -s "$SUMMARY" -d "$DESCRIPTION" -p $PROJECT "$FILE" || ( echo "Upload failed" ; exit 1 ) +} + + +upload_artifact jnaerator jnaerator jnaerator $JNAERATOR_VERSION shaded "JNAerator $JNAERATOR_VERSION" + +for CLASSIFIER in "" "unix-only" "linux-only" "windows-only" "c-only" "android"; do + if [[ -z "$CLASSIFIER" ]]; then + SUMMARY_SUFFIX="" + else + SUMMARY_SUFFIX=" (`echo "$CLASSIFIER" | tr - " "`)" + fi + upload_artifact BridJ bridj bridj $BRIDJ_VERSION "$CLASSIFIER" "BridJ $BRIDJ_VERSION$SUMMARY_SUFFIX" +done + +upload_artifact OpenCL javacl javacl $JAVACL_VERSION shaded "JavaCL $JAVACL_VERSION" +upload_artifact OpenCL javacl javacl-jna $JAVACL_VERSION shaded "JavaCL $JAVACL_VERSION (JNA version)" +upload_artifact OpenCL javacl javacl-demos $JAVACL_VERSION shaded "JavaCL Demos $JAVACL_VERSION" +upload_artifact OpenCL javacl javacl-interactive-image-demo $JAVACL_VERSION shaded "JavaCL Interactive Image Demo $JAVACL_VERSION" + diff --git a/libraries/scripts/uploadJavadoc b/libraries/scripts/uploadJavadoc index a9d841c3f..cea8a0c26 100755 --- a/libraries/scripts/uploadJavadoc +++ b/libraries/scripts/uploadJavadoc @@ -27,11 +27,11 @@ cp -R apidocs $DIR_NAME rm -fR $ZIP_NAME zip -r $ZIP_NAME $DIR_NAME -ssh opentator,nativelibs4java@shell.sourceforge.net "cd $REMOTE_BASE/$REMOTE_PATH ; rm -fR $ZIP_NAME" || echo "Please open a session with : +/usr/bin/ssh opentator,nativelibs4java@shell.sourceforge.net "cd $REMOTE_BASE/$REMOTE_PATH ; rm -fR $ZIP_NAME" || echo "Please open a session with : ssh -t opentator,nativelibs4java@shell.sourceforge.net create " -scp $ZIP_NAME opentator,nativelibs4java@shell.sourceforge.net:$REMOTE_BASE/$REMOTE_PATH/$ZIP_NAME +/usr/bin/scp $ZIP_NAME opentator,nativelibs4java@shell.sourceforge.net:$REMOTE_BASE/$REMOTE_PATH/$ZIP_NAME -ssh opentator,nativelibs4java@shell.sourceforge.net "cd $REMOTE_BASE/$REMOTE_PATH ; rm -fR $DIR_NAME ; unzip $ZIP_NAME ; rm $ZIP_NAME" +/usr/bin/ssh opentator,nativelibs4java@shell.sourceforge.net "cd $REMOTE_BASE/$REMOTE_PATH ; rm -fR $DIR_NAME ; unzip $ZIP_NAME ; rm $ZIP_NAME" diff --git a/libraries/scripts/uploadWebstart b/libraries/scripts/uploadWebstart new file mode 100755 index 000000000..e9d2a990d --- /dev/null +++ b/libraries/scripts/uploadWebstart @@ -0,0 +1,67 @@ +#!/bin/bash + +# uploadJavadoc development bridj/api +# uploadJavadoc 0.6.1 bridj/api + +cd `dirname $0`/.. +ROOT="$PWD" + +REMOTE_BASE=/home/project-web/nativelibs4java/htdocs + +/usr/bin/ssh opentator,nativelibs4java@shell.sourceforge.net "cd $REMOTE_BASE/$REMOTE_PATH ; rm -fR $ZIP_NAME" || echo "Please open a session with : +ssh -t opentator,nativelibs4java@shell.sourceforge.net create +" + +function fail() { + echo "# $@" >&2 + exit 1 +} + +function pomVersion() { + POM="$1" + cat "$POM" | grep '\(.*\)<\/version>.*/\1/g' +} + +function upload() { + FILE=$1 + PATH=$2 + [[ -f "$FILE" ]] || fail "File '$FILE' does not exist" + /usr/bin/scp "$FILE" "opentator,nativelibs4java@shell.sourceforge.net:$REMOTE_BASE/webstart/$PATH/" || fail "Remote copy failed" +} + +function assertIsSnapshot() { + VERSION=$1 + [[ $VERSION =~ .*-SNAPSHOT ]] || fail "Version '$VERSION' is not a snapshot" +} + +function assertReferences() { + FILE=$1 + PATTERN=$2 + cat "$FILE" | grep "$PATTERN" > /dev/null || fail "$FILE does not refer to $PATTERN" +} + +JNAERATOR_VERSION="`pomVersion jnaerator/pom.xml`" +JNAERATOR_JNLP="$ROOT/jnaerator/webstart/JNAeratorStudio.jnlp" +JNAERATOR_JAR_NAME="jnaerator-$JNAERATOR_VERSION-shaded.jar" +assertIsSnapshot $JNAERATOR_VERSION +assertReferences $JNAERATOR_JNLP "$JNAERATOR_JAR_NAME" + +JAVACL_VERSION="`pomVersion OpenCL/pom.xml`" +assertIsSnapshot $JAVACL_VERSION + +# cd $ROOT/jnaerator +# mvn -Pwebstart -Dstorepass=$KEYSTORE_PASS -DskipTests clean install || fail "Build failed" +# upload $ROOT/jnaerator/jnaerator/target/$JNAERATOR_JAR_NAME jnaerator +# upload "$JNAERATOR_JNLP" jnaerator + +cd $ROOT/OpenCL +mvn -Pwebstart -Dstorepass=$KEYSTORE_PASS -DskipTests clean install || fail "Build failed" +upload $ROOT/OpenCL/Demos/target/javacl-demos-$JAVACL_VERSION-shaded.jar javacl +upload $ROOT/OpenCL/OpenGLDemos/target/javacl-opengl-demos-$JAVACL_VERSION-shaded.jar javacl +upload $ROOT/OpenCL/InteractiveImageDemo/target/javacl-interactive-image-demo-$JAVACL_VERSION-shaded.jar javacl + +for NAME in HardwareReport InteractiveImageTransformDemo MandelbrotDemo ParticlesDemo JavaCL; do + JNLP="$ROOT/OpenCL/Core/src/main/jnlp/$NAME.jnlp" + #assertReferences "$JNLP" "-$JAVACL_VERSION-shaded.jar" + upload "$JNLP" javacl +done diff --git a/libraries/pom.xml b/pom.xml similarity index 55% rename from libraries/pom.xml rename to pom.xml index 7e203b3a0..19515a6a1 100644 --- a/libraries/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.nativelibs4java nativelibs4java-parent - 1.8-SNAPSHOT + 1.10-SNAPSHOT pom 2009 NativeLibs4Java Common Configuration @@ -14,61 +14,34 @@ 7 + + 2.2.1 + + sonatype Sonatype OSS Snapshots Repository http://oss.sonatype.org/content/groups/public - - typesafe - typesafe-releases - http://repo.typesafe.com/typesafe/maven-releases - - - typesafe2 - Typesafe Repository - http://repo.typesafe.com/typesafe/releases/ - - + sonatype Sonatype OSS Snapshots Repository http://oss.sonatype.org/content/groups/public - - typesafe - typesafe-releases - http://repo.typesafe.com/typesafe/maven-releases - - - typesafe2 - Typesafe Repository - http://repo.typesafe.com/typesafe/releases/ - - + - 0.6.2-SNAPSHOT - 0.8-SNAPSHOT - 0.11-SNAPSHOT + 0.7.1-SNAPSHOT + 0.10-SNAPSHOT + 0.13-SNAPSHOT - - - 2.9.2 true shaded @@ -105,34 +78,11 @@ Most of these wrappers are created automatically by JNAerator. - scm:git:git@github.com:ochafik/nativelibs4java.git - scm:git:git@github.com:ochafik/nativelibs4java.git - git@github.com:ochafik/nativelibs4java.git + scm:git:git@github.com:nativelibs4java/nativelibs4java.git + scm:git:git@github.com:nativelibs4java/nativelibs4java.git + git@github.com:nativelibs4java/nativelibs4java.git - - - junit - junit - 4.10 - test - - - - - - - org.scala-lang - scala-library - ${scala.version} - - - org.scala-lang - scala-compiler - ${scala.version} - - - @@ -179,28 +129,6 @@ Most of these wrappers are created automatically by JNAerator. --> - - org.scala-tools - scala-maven-plugin - 3.1.0 - - - - compile - testCompile - - - - - - -optimise - - - -Xms64m - -Xmx1024m - - - com.nativelibs4java maven-velocity-plugin @@ -241,42 +169,26 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-shade-plugin - 1.6 - - - - full-package - package - - shade - - - ${shadedArtifactAttached} - - - - org.scala-lang:scala-* - junit:junit - com.google.android.tools:dx - - - - - - *:* - - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - META-INF/maven/** - - - - - - - + 3.6.0 + + + + org.scala-lang:scala-* + junit:junit + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + META-INF/maven/** + + + + org.eclipse.m2e @@ -318,7 +230,7 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-jar-plugin - 2.4 + 3.4.2 test-jar @@ -343,7 +255,7 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-source-plugin - 2.1.2 + 3.3.1 attach-sources @@ -356,7 +268,24 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-javadoc-plugin - 2.8 + 3.7.0 + + 128m + 512 + true + true + 8 + false + true + public + + com.nativelibs4java.opencl.library + + attach-javadocs @@ -364,23 +293,6 @@ Most of these wrappers are created automatically by JNAerator. aggregate jar - - 128m - 512 - true - true - 1.5 - false - true - public - - http://download.oracle.com/javase/6/docs/api/ - http://nativelibs4java.sourceforge.net/bridj/api/stable/ - http://nativelibs4java.sourceforge.net/javacl/api/stable/ - - com.nativelibs4java.opencl.library - - @@ -402,10 +314,10 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.12.1 - 1.5 - 1.5 + 8 + 8 UTF-8 @@ -413,17 +325,17 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-surefire-plugin - 2.12 - + 3.3.0 + + + github - https://github.com/ochafik/nativelibs4java/issues + https://github.com/nativelibs4java/nativelibs4java/issues - - devel - - true - - - true - - - InteropIntegration - Velocity - BridJ - BridJ-OSGi - jnaerator - ScalaCL - Scalaxy - OpenCL - OpenCL-JNA - Mono - DirectX - PThread - Utils - IdleTime - JarShrinker - - - - coordinated-release - - true - - - Velocity - BridJ - BridJ-OSGi - jnaerator - ScalaCL - Scalaxy - OpenCL - OpenCL-JNA - Utils - - - - bridj-jnaerator-release - - false - - - Velocity - BridJ - BridJ-OSGi - jnaerator - - - - javacl-release - - false - - - OpenCL - OpenCL-JNA - Utils - - - - scalacl-release - - false - - - Scalaxy - ScalaCL - - gpg @@ -521,7 +357,7 @@ Most of these wrappers are created automatically by JNAerator. org.apache.maven.plugins maven-gpg-plugin - 1.4 + 3.2.4 sign-artifacts @@ -535,6 +371,12 @@ Most of these wrappers are created automatically by JNAerator. + + regenerate + + false + + webstart @@ -546,42 +388,10 @@ Most of these wrappers are created automatically by JNAerator. - org.apache.maven.plugins maven-jarsigner-plugin - 1.2 + 3.0.0 sign