--- /dev/null
+package kaka.cakelight;
+
+import java.io.File;
+import java.util.Optional;
+import java.util.function.Consumer;
+
+import static kaka.cakelight.Main.log;
+
+public class VideoDeviceListener {
+ private Thread thread;
+ private Consumer<Optional<File>> changeConsumer;
+ private File lastDevice = null;
+
+ public void startListening() {
+ thread = new Thread() {
+ public void run() {
+ try {
+ while (!isInterrupted()) {
+ Optional<File> device = findVideoDevice();
+ if (!device.equals(Optional.ofNullable(lastDevice))) {
+ log("Video device change: %s", device.map(File::getAbsolutePath).orElse("none"));
+ changeConsumer.accept(device);
+ lastDevice = device.orElseGet(() -> null);
+ }
+ Thread.sleep(1000);
+ }
+ } catch (InterruptedException e) {
+ }
+ }
+ };
+ thread.start();
+ }
+
+ public void stopListening() {
+ thread.interrupt();
+ }
+
+ private Optional<File> findVideoDevice() {
+ File[] files = new File("/dev").listFiles((dir, name) -> name.matches("video[0-9]+"));
+ if (files == null || files.length == 0) {
+ return Optional.empty();
+ } else {
+ return Optional.of(files[0]);
+ }
+ }
+
+ public void onVideoDeviceChange(Consumer<Optional<File>> consumer) {
+ changeConsumer = consumer;
+ }
+}