src/spacenav-lib-hack.c
branchv_0
changeset 5 26e9fb705faf
parent 4 650e0a578dab
child 8 1dab2b99f51d
--- a/src/spacenav-lib-hack.c	Fri Mar 08 23:05:15 2019 +0100
+++ b/src/spacenav-lib-hack.c	Sat Mar 09 12:30:52 2019 +0100
@@ -22,6 +22,7 @@
 #include <dlfcn.h>
 #include <stdlib.h>
 #include <unistd.h>
+#include <pthread.h>
 
 #include <X11/Xlib.h>
 #include <spnav.h>
@@ -41,12 +42,14 @@
  *    were not initialized spnav_x11_open() and thus the library funcion is not working.
  * 
  * This solution works and allows using e.g. FreeCAD with domain socket instead of X11, but:
- *	- the background process never ends and must be terminated by: killall freecad
  *  - is very hackish and should be reimplemented as a separate process which will work partly
  *    as a libspnav client and partly emulate spacenavd daemon and will bridge the domain socket
  *    and th X11. Other solution is to emulate the hardware and keep spacenavd and libspnav untouched.
  */
 
+static pthread_t spacenav_hack_thread;
+static Window spacenav_hack_win;
+
 // from proto_x11.c (spacenavd)
 static Atom xa_event_motion, xa_event_bpress, xa_event_brelease, xa_event_cmd;
 static float x11_sens = 1.0;
@@ -100,16 +103,16 @@
 	XFlush(dpy);
 }
 
-static void spacenav_hack_translate_events(Window win) {
+static void* spacenav_hack_translate_events(void* arg) {
+	fprintf(stderr, "spnav-lib-hack: pthread running, PID=%d\n", getpid());
 	spnav_event event;
 	Display* dpy = XOpenDisplay(0);
 
 	while (1) {
 		if (spnav_wait_event(&event)) {
-			send_xevent(&event, dpy, win);
+			send_xevent(&event, dpy, spacenav_hack_win);
 		}
 	}
-	// FIXME: this process never ends and must be killed manually
 }
 
 int spnav_x11_open(Display* dpy, Window win) {
@@ -122,11 +125,8 @@
 	xa_event_cmd = XInternAtom(dpy, "CommandEvent", False);
 
 	if (result == 0) {
-		pid_t pid = fork();
-		fprintf(stderr, "spnav-lib-hack: fork() = %d; PID=%d\n", pid, getpid());
-		if (pid == -1) return 1; // error
-		if (pid == 0) spacenav_hack_translate_events(win); // child
-		else; // parent
+		spacenav_hack_win = win;
+		pthread_create(&spacenav_hack_thread, NULL, spacenav_hack_translate_events, NULL);
 	}
 
 	return result;