1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use super::JniRustType;
use async_channel::Receiver;
use jni::{
    errors::*,
    objects::{GlobalRef, JClass, JObject, JValue},
    signature::{JavaType, TypeSignature},
    JNIEnv,
};
use std::collections::HashMap;

#[derive(Clone)]
pub struct JniSingleton {
    name: String,
    instance: GlobalRef,
    methods: HashMap<String, JniSingletonMethod>,
    signals: HashMap<String, Vec<JavaType>>,
    receiver: Receiver<Signal>,
}

#[derive(Clone, Debug)]
pub struct Signal {
    pub name: String,
    pub args: Vec<JniRustType>,
}

#[derive(Clone)]
pub struct JniSingletonMethod {
    class: GlobalRef,
    signature: TypeSignature,
}

impl JniSingleton {
    pub fn new(name: &str, instance: GlobalRef, receiver: Receiver<Signal>) -> Self {
        Self {
            name: name.to_string(),
            instance,
            methods: HashMap::new(),
            signals: HashMap::new(),
            receiver,
        }
    }

    pub fn get_instance(&self) -> JObject {
        self.instance.as_obj()
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }

    pub fn get_receiver(&self) -> &Receiver<Signal> {
        &self.receiver
    }

    pub fn get_method(&self, name: &str) -> Option<&JniSingletonMethod> {
        self.methods.get(name)
    }

    pub fn get_methods(&self) -> &HashMap<String, JniSingletonMethod> {
        &self.methods
    }

    pub(crate) fn add_method(&mut self, name: &str, class: GlobalRef, signature: TypeSignature) {
        self.methods
            .insert(name.to_owned(), JniSingletonMethod { class, signature });
    }

    pub(crate) fn add_signal_info(&mut self, name: &str, args: Vec<JavaType>) {
        self.signals.insert(name.to_owned(), args);
    }

    pub fn call_method<'a>(
        &'a self,
        env: &'a JNIEnv,
        name: &str,
        args: &[JValue],
    ) -> Result<JValue<'a>> {
        let method = match self.get_method(name) {
            Some(method) => method,
            None => Err(Error::MethodNotFound {
                name: name.to_owned(),
                sig: "".to_owned(),
            })?,
        };
        let class: JClass = method.class.as_obj().into();
        let method_id = env.get_method_id(class, name, method.signature.to_string())?;

        let result = env.call_method_unchecked(
            self.get_instance(),
            method_id,
            method.signature.ret.clone(),
            args,
        )?;
        env.exception_check()?;
        Ok(result)
    }
}