c2f896d1d5d207af4cb8da720553ddaa100a190e
[kaka/cakelight.git] / src / kaka / cakelight / CakeLight.java
1 package kaka.cakelight;
2
3 import org.jnativehook.GlobalScreen;
4 import org.jnativehook.NativeHookException;
5 import org.jnativehook.keyboard.NativeKeyAdapter;
6 import org.jnativehook.keyboard.NativeKeyEvent;
7 import org.jnativehook.mouse.NativeMouseEvent;
8 import org.jnativehook.mouse.NativeMouseMotionAdapter;
9
10 public class CakeLight {
11     private Configuration config;
12     private Mode mode;
13     private LedController ledController;
14
15     public CakeLight(Configuration config, LedController ledController) {
16         this.config = config;
17         this.ledController = ledController;
18         Color.calculateGammaCorrection(config.gamma);
19     }
20
21     public void setMode(Mode mode) {
22         cleanup();
23         this.mode = mode;
24         mode.setFrameListener(ledController::onFrame);
25         mode.enter(config);
26     }
27
28     public void cleanup() {
29         if (this.mode != null) {
30             this.mode.setFrameListener(ledFrame -> {}); // To avoid any frame being sent to the controller while the thread is exiting
31             this.mode.exit();
32         }
33     }
34
35     public void startLoop() {
36         Console.start(this, config);
37         initNativeHook();
38         // TODO
39 //        FrameGrabber grabber = FrameGrabber.from(config);
40 //        grabber.prepare();
41 //        VideoFrame frame = grabber.grabFrame();
42 //        double time = 0;
43 //        for (int i = 0; i < 100; i++) {
44 //            time += timeIt("frame", () -> grabber.grabFrame());
45 //        }
46 //        System.out.println("time = " + time);
47 //        grabber.close();
48 //      byte[] data = frame.getData();
49 //      saveFile(data, "/home/kaka/test.img");
50     }
51
52     private void initNativeHook() {
53         try {
54             GlobalScreen.registerNativeHook();
55             GlobalScreen.addNativeKeyListener(new NativeKeyAdapter() {
56                 @Override
57                 public void nativeKeyPressed(NativeKeyEvent e) {
58                     System.out.println("key code = " + e.getKeyCode() + ", key text = '" + NativeKeyEvent.getKeyText(e.getKeyCode()) + "'");
59                 }
60             });
61             GlobalScreen.addNativeMouseMotionListener(new NativeMouseMotionAdapter() {
62                 @Override
63                 public void nativeMouseMoved(NativeMouseEvent e) {
64                     System.out.println("mouse point = " + e.getPoint());
65                 }
66             });
67         } catch (NativeHookException e) {
68             e.printStackTrace();
69         }
70     }
71
72     public void turnOff() {
73         cleanup();
74         ledController.onFrame(LedFrame.from(config).fillColor(0, 0, 0));
75     }
76 }