protected MemorySegment getValue;
protected MemorySegment sourceListGetValue;
+ protected MemorySegment threadFuncPtr;
+
+ private HashMap<Integer, ThreadCallback> threadCallbacks = new HashMap<>();
+
private Toolkit(String appName) {
// load shared library
System.loadLibrary("uitk");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
+
+ // threadfunc wrapper
+ try {
+ MethodHandle threadFuncCallback = MethodHandles.lookup().findStatic(
+ Thread.class,
+ "threadFunc",
+ MethodType.methodType(int.class, MemorySegment.class));
+ FunctionDescriptor threadFuncDescriptor = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS);
+ threadFuncPtr = linker.upcallStub(
+ threadFuncCallback,
+ threadFuncDescriptor,
+ staticArena);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
}
public static Toolkit getInstance() {
Context listCtx = Toolkit.getInstance().getContext(listCtxPtr);
return listCtx.getList((int)listIndex);
}
+
+ private static int threadFunc(MemorySegment ptr) {
+ int key = (int)ptr.address();
+ Toolkit toolkit = Toolkit.getInstance();
+ ThreadCallback callback = toolkit.threadCallbacks.get(key);
+ if(callback != null) {
+ callback.callback();
+ }
+ return 0;
+ }
+
+ private synchronized ThreadCallback getThreadCallback(int key) {
+ return threadCallbacks.remove(key);
+ }
+
+ public synchronized void invokeMainThread(ThreadCallback callback) {
+ int key = threadCallbacks.size();
+ threadCallbacks.put(key, callback);
+ MemorySegment ckey = MemorySegment.ofAddress((long)key);
+ try {
+ ToolkitFuncs.getInstance().call_mainthread.invoke(threadFuncPtr, ckey);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
}
public MethodHandle text_set;
public MethodHandle text_get;
+ public MethodHandle call_mainthread;
+
// some libc stuff
public MethodHandle malloc;
public MethodHandle free;
MemorySegment text_set_addr = lib.find("ui_text_set").orElseThrow();
MemorySegment text_get_addr = lib.find("ui_text_get").orElseThrow();
+ MemorySegment call_mainthread_addr = lib.find("ui_call_mainthread").orElseThrow();
+
MemorySegment malloc_addr = lib.find("malloc").orElseThrow();
MemorySegment free_addr = lib.find("free").orElseThrow();
text_set = linker.downcallHandle(text_set_addr, sigv_mm);
text_get = linker.downcallHandle(text_get_addr, sigm_m);
+ call_mainthread = linker.downcallHandle(call_mainthread_addr, sigv_mm);
+
malloc = linker.downcallHandle(malloc_addr, sigm_l);
free = linker.downcallHandle(free_addr, sigv_m);
}