]> sigrok.org Git - libsigrok.git/blobdiff - bindings/java/org/sigrok/core/classes/classes.i
bindings/java: Fix build issue with SWIG 4.x.
[libsigrok.git] / bindings / java / org / sigrok / core / classes / classes.i
index 52eace85a7acfc7ed778b6fe07a8d3bf821dcd19..e953fe5d8331052215b59e5c97608c50e851da8a 100644 (file)
@@ -7,31 +7,45 @@
   }
 %}
 
-/* Import interfaces. */
+/* Documentation & importing interfaces. */
 %pragma(java) jniclassimports=%{
-  import org.sigrok.core.interfaces.LogCallback;
-  import org.sigrok.core.interfaces.DatafeedCallback;
-  import org.sigrok.core.interfaces.SourceCallback;
+/**
+ * @mainpage API Reference
+ *
+ * Introduction
+ * ------------
+ *
+ * The sigrok-java API provides an object-oriented Java interface to the
+ * functionality in libsigrok. It is built on top of the libsigrokcxx C++ API.
+ *
+ * Getting started
+ * ---------------
+ *
+ * Usage of the sigrok-java API needs to begin with a call to Context.create().
+ * This will create the global libsigrok context and returns a Context object.
+ * Methods on this object provide access to the hardware drivers, input and
+ * output formats supported by the library, as well as means of creating other
+ * objects such as sessions and triggers.
+ *
+ * Error handling
+ * --------------
+ *
+ * When any libsigrok C API call returns an error, an Error exception is raised,
+ * which provides access to the error code and description.
+ */
+
+import org.sigrok.core.interfaces.LogCallback;
+import org.sigrok.core.interfaces.DatafeedCallback;
 %}
 
-/* Map Java FileDescriptor objects to int fds */
-%typemap(jni) int fd "jobject"
-%typemap(jtype) int fd "java.io.FileDescriptor"
-%typemap(jstype) int fd "java.io.FileDescriptor"
-%typemap(javain) int fd "$javainput"
-
-%typemap(in) int fd {
-  jclass FileDescriptor = jenv->FindClass("java/io/FileDescriptor");
-  jfieldID fd = jenv->GetFieldID(FileDescriptor, "fd", "I");
-  $1 = jenv->GetIntField($input, fd);
-}
-
 /* Map Glib::VariantBase to a Variant class in Java */
 %rename(Variant) VariantBase;
 namespace Glib {
   class VariantBase {};
 }
 
+%include "bindings/swig/templates.i"
+
 /* Map between std::vector and java.util.Vector */
 %define VECTOR(CValue, JValue)
 
@@ -40,20 +54,12 @@ namespace Glib {
 %typemap(jstype) std::vector< CValue > "java.util.Vector<JValue>"
 
 %typemap(javain,
-    pre="  $javaclassname temp$javainput = $javaclassname.convertVector($javainput);",
+    pre="  $javaclassname temp$javainput = new $javaclassname();
+  for (JValue value : $javainput)
+    temp$javainput.add(value);",
     pgcppname="temp$javainput")
   std::vector< CValue > "$javaclassname.getCPtr(temp$javainput)"
 
-%typemap(javacode) std::vector< CValue > %{
-  static $javaclassname convertVector(java.util.Vector<JValue> in)
-  {
-    $javaclassname out = new $javaclassname();
-    for (JValue value : in)
-      out.add(value);
-    return out;
-  }
-%}
-
 %typemap(javaout) std::vector< CValue > {
   return (java.util.Vector<JValue>)$jnicall;
 }
@@ -66,11 +72,11 @@ namespace Glib {
   jclass Value = jenv->FindClass("org/sigrok/core/classes/" #JValue);
   jmethodID Value_init = jenv->GetMethodID(Value, "<init>", "(JZ)V");
   $result = jenv->NewObject(Vector, Vector_init);
-  jlong value;
+  jlong value = 0;
   for (auto entry : $1)
   {
     *(CValue **) &value = new CValue(entry);
-    jenv->CallObjectMethod($result, Vector_add,
+    jenv->CallBooleanMethod($result, Vector_add,
       jenv->NewObject(Value, Value_init, value, true));
   }
 }
@@ -88,20 +94,20 @@ VECTOR(std::shared_ptr<sigrok::HardwareDevice>, HardwareDevice)
   "java.util.Map<JKey, JValue>"
 
 %typemap(javain,
-    pre="  $javaclassname temp$javainput = $javaclassname.convertMap($javainput);",
+/* SWIG 4.0.0 changed the std::map wrappers in an incompatible way. */
+#if SWIG_VERSION >= 0x040000
+    pre="  $javaclassname temp$javainput = new $javaclassname();
+    for (java.util.Map.Entry<JKey, JValue> entry : $javainput.entrySet())
+      temp$javainput.put(entry.getKey(), entry.getValue());",
+    pgcppname="temp$javainput")
+#else
+    pre="  $javaclassname temp$javainput = new $javaclassname();
+    for (java.util.Map.Entry<JKey, JValue> entry : $javainput.entrySet())
+      temp$javainput.set(entry.getKey(), entry.getValue());",
     pgcppname="temp$javainput")
+#endif
   std::map< CKey, CValue > "$javaclassname.getCPtr(temp$javainput)"
 
-%typemap(javacode) std::map< CKey, CValue > %{
-  static $javaclassname convertMap(java.util.Map<JKey,JValue> in)
-  {
-    $javaclassname out = new $javaclassname();
-    for (java.util.Map.Entry<JKey, JValue> entry : in.entrySet())
-      out.set(entry.getKey(), entry.getValue());
-    return out;
-  }
-%}
-
 %typemap(javaout) std::map< CKey, CValue > {
   return (java.util.Map<JKey, JValue>)$jnicall;
 }
@@ -112,6 +118,11 @@ VECTOR(std::shared_ptr<sigrok::HardwareDevice>, HardwareDevice)
 
 MAP_COMMON(std::string, std::string, String, String)
 
+%typemap(jni) std::map<std::string, std::string>
+  "jobject"
+%typemap(jtype) std::map<std::string, std::string>
+  "java.util.Map<String,String>"
+
 %typemap(out) std::map<std::string, std::string> {
   jclass HashMap = jenv->FindClass("java/util/HashMap");
   jmethodID init = jenv->GetMethodID(HashMap, "<init>", "()V");
@@ -143,7 +154,7 @@ MAP_COMMON(std::string, std::shared_ptr<sigrok::ClassName>, String, ClassName)
   jclass Value = jenv->FindClass("org/sigrok/core/classes/" #ClassName);
   jmethodID Value_init = jenv->GetMethodID(Value, "<init>", "(JZ)V");
   $result = jenv->NewObject(HashMap, HashMap_init);
-  jlong value;
+  jlong value = 0;
   for (auto entry : $1)
   {
     *(std::shared_ptr< sigrok::ClassName > **)&value =
@@ -178,8 +189,8 @@ MAP_COMMON(const sigrok::ConfigKey *, Glib::VariantBase, ConfigKey, Variant)
   jclass Variant = jenv->FindClass("org/sigrok/core/classes/Variant");
   jmethodID Variant_init = jenv->GetMethodID(Variant, "<init>", "(JZ)V");
   $result = jenv->NewObject(HashMap, HashMap_init);
-  jlong key;
-  jlong value;
+  jlong key = 0;
+  jlong value = 0;
   for (auto entry : $1)
   {
     *(const sigrok::ConfigKey **) &key = entry.first;
@@ -190,30 +201,77 @@ MAP_COMMON(const sigrok::ConfigKey *, Glib::VariantBase, ConfigKey, Variant)
   }
 }
 
-/* Support Driver.scan() with no arguments. */
-%extend sigrok::Driver {
-  std::vector<std::shared_ptr<sigrok::HardwareDevice> > scan()
-  {
-    std::map<const sigrok::ConfigKey *, Glib::VariantBase> options;
-    return $self->scan(options);
+/* Pass JNIEnv parameter to C++ extension methods requiring it. */
+
+%typemap(in, numinputs=0) JNIEnv * %{
+   $1 = jenv;
+%}
+
+/* Thread safe JNIEnv handling */
+
+%inline {
+namespace {
+  class ScopedEnv {
+    public:
+      ScopedEnv(JavaVM *jvm);
+      ~ScopedEnv();
+      JNIEnv* operator-> () { return env; }
+      operator bool () const { return (bool)env; }
+    private:
+      JavaVM *jvm;
+      JNIEnv *env;
+      int env_status;
+  };
+  ScopedEnv::ScopedEnv(JavaVM *jvm) : jvm(jvm), env(NULL) {
+    env_status = jvm->GetEnv((void **)&env, JNI_VERSION_1_2);
+    if (env_status == JNI_EDETACHED) {
+%#if defined(__ANDROID__)
+      jvm->AttachCurrentThread(&env, NULL);
+%#else
+      jvm->AttachCurrentThread((void **)&env, NULL);
+%#endif
+    }
+  }
+  ScopedEnv::~ScopedEnv() {
+    if (env_status == JNI_EDETACHED) {
+      jvm->DetachCurrentThread();
+    }
   }
 }
+}
+
+/* "Smartpointer" for Java references. */
 
-/* Support OutputFormat.create_output(device) with no options. */
-%extend sigrok::OutputFormat {
-  std::shared_ptr<sigrok::Output> create_output(
-    std::shared_ptr<sigrok::Device> device)
+%inline {
+namespace {
+  class GlobalRefBase
   {
-    std::map<std::string, Glib::VariantBase> options;
-    return $self->create_output(device, options);
+    protected:
+      GlobalRefBase (JavaVM *jvm, jobject ref);
+      ~GlobalRefBase ();
+      JavaVM *jvm;
+      jobject jref;
+  };
+  GlobalRefBase::GlobalRefBase (JavaVM *jvm, jobject ref) : jvm(jvm), jref(0) {
+    ScopedEnv env(jvm);
+    if (env && ref)
+      jref = env->NewGlobalRef(ref);
   }
+  GlobalRefBase::~GlobalRefBase () {
+    ScopedEnv env(jvm);
+    if(env && jref)
+      env->DeleteGlobalRef(jref);
+  }
+  template <class Jtype>
+  class GlobalRef : private GlobalRefBase
+  {
+    public:
+      GlobalRef (JavaVM *jvm, Jtype ref) : GlobalRefBase(jvm, ref) {}
+      GlobalRef (const GlobalRef &ref) : GlobalRefBase(ref.jvm, ref.jref) {}
+      operator Jtype () const { return static_cast<Jtype>(jref); }
+  };
+}
 }
-
-/* Pass JNIEnv parameter to C++ extension methods requiring it. */
-
-%typemap(in, numinputs=0) JNIEnv * %{
-   $1 = jenv;
-%} 
 
 /* Support Java log callbacks. */
 
@@ -233,19 +291,23 @@ typedef jobject jlogcallback;
 {
   void add_log_callback(JNIEnv *env, jlogcallback obj)
   {
+    JavaVM *jvm = NULL;
+    env->GetJavaVM(&jvm);
     jclass obj_class = env->GetObjectClass(obj);
     jmethodID method = env->GetMethodID(obj_class, "run",
       "(Lorg/sigrok/core/classes/LogLevel;Ljava/lang/String;)V");
-    jclass LogLevel = (jclass) env->NewGlobalRef(
-        env->FindClass("org/sigrok/core/classes/LogLevel"));
+    GlobalRef<jclass> LogLevel(jvm, env->FindClass("org/sigrok/core/classes/LogLevel"));
     jmethodID LogLevel_init = env->GetMethodID(LogLevel, "<init>", "(JZ)V");
-    jobject obj_ref = env->NewGlobalRef(obj);
+    GlobalRef<jobject> obj_ref(jvm, obj);
 
     $self->set_log_callback([=] (
       const sigrok::LogLevel *loglevel,
       std::string message)
     {
-      jlong loglevel_addr;
+      ScopedEnv env(jvm);
+      if (!env)
+        throw sigrok::Error(SR_ERR);
+      jlong loglevel_addr = 0;
       *(const sigrok::LogLevel **) &loglevel_addr = loglevel;
       jobject loglevel_obj = env->NewObject(
         LogLevel, LogLevel_init, loglevel_addr, false);
@@ -275,23 +337,26 @@ typedef jobject jdatafeedcallback;
 {
   void add_datafeed_callback(JNIEnv *env, jdatafeedcallback obj)
   {
+    JavaVM *jvm = NULL;
+    env->GetJavaVM(&jvm);
     jclass obj_class = env->GetObjectClass(obj);
     jmethodID method = env->GetMethodID(obj_class, "run",
       "(Lorg/sigrok/core/classes/Device;Lorg/sigrok/core/classes/Packet;)V");
-    jclass Device = (jclass) env->NewGlobalRef(
-        env->FindClass("org/sigrok/core/classes/Device"));
+    GlobalRef<jclass> Device(jvm, env->FindClass("org/sigrok/core/classes/Device"));
     jmethodID Device_init = env->GetMethodID(Device, "<init>", "(JZ)V");
-    jclass Packet = (jclass) env->NewGlobalRef(
-       env->FindClass("org/sigrok/core/classes/Packet"));
+    GlobalRef<jclass> Packet(jvm, env->FindClass("org/sigrok/core/classes/Packet"));
     jmethodID Packet_init = env->GetMethodID(Packet, "<init>", "(JZ)V");
-    jobject obj_ref = env->NewGlobalRef(obj);
+    GlobalRef<jobject> obj_ref(jvm, obj);
 
     $self->add_datafeed_callback([=] (
       std::shared_ptr<sigrok::Device> device,
       std::shared_ptr<sigrok::Packet> packet)
     {
-      jlong device_addr;
-      jlong packet_addr;
+      ScopedEnv env(jvm);
+      if (!env)
+        throw sigrok::Error(SR_ERR);
+      jlong device_addr = 0;
+      jlong packet_addr = 0;
       *(std::shared_ptr<sigrok::Device> **) &device_addr =
         new std::shared_ptr<sigrok::Device>(device);
       *(std::shared_ptr<sigrok::Packet> **) &packet_addr =
@@ -307,42 +372,15 @@ typedef jobject jdatafeedcallback;
   }
 }
 
-/* Support Java event source callbacks. */
-
-%typemap(javaimports) sigrok::EventSource
-  "import org.sigrok.core.interfaces.SourceCallback;"
-
-%inline {
-typedef jobject jsourcecallback;
-}
+%include "doc.i"
 
-%typemap(jni) jsourcecallback "jsourcecallback"
-%typemap(jtype) jsourcecallback "SourceCallback"
-%typemap(jstype) jsourcecallback "SourceCallback"
-%typemap(javain) jsourcecallback "$javainput"
-
-%extend sigrok::EventSource
-{
-  std::shared_ptr<sigrok::EventSource> create(
-    int fd, Glib::IOCondition events, int timeout,
-    JNIEnv *env, jsourcecallback obj)
-  {
-    (void) $self;
-    jclass obj_class = env->GetObjectClass(obj);
-    jmethodID method = env->GetMethodID(obj_class, "run", "(I)V");
-    jobject obj_ref = env->NewGlobalRef(obj);
-
-    return sigrok::EventSource::create(fd, events, timeout, [=] (int revents)
-    {
-      bool result = env->CallBooleanMethod(obj_ref, method, revents);
-      if (env->ExceptionCheck())
-        throw sigrok::Error(SR_ERR);
-      return result;
-    });
-  }
-}
+%define %enumextras(Class)
+%enddef
 
-/* Currently broken due to some std::map typemap issues. */
-%ignore sigrok::Meta::get_config;
+/* Ignore these for now, need fixes. */
+%ignore sigrok::Context::create_analog_packet;
+%ignore sigrok::Context::create_meta_packet;
+%ignore sigrok::Meta::config;
 
 %include "bindings/swig/classes.i"
+