qr-scan-difficulty-check / server /reading_java.py
devmandan's picture
Claude Opus 5.5
Fix small issues: shown-number statuses, hoverable tips, right-pile line
2a2a176 verified
Raw History Blame Contribute Delete
3.53 kB
"""The Java process: ZXing as Android's Settings app calls it (see reading.py). One process, shared by every reading,
reads the staged frames one at a time; it is replaced when it dies or a frame runs past TIMEOUT_S.
"""
from __future__ import annotations
import base64
import itertools
import json
import os
import queue
import subprocess
import threading
import time
from .reading_rules import TIMEOUT_S, VENDOR
class _Java:
def __init__(self):
cp = os.pathsep.join([str(VENDOR / "zxing" / "core-3.5.2.jar"), str(VENDOR / "zxing" / "classes")])
self.cmd = ["java", "-Djava.awt.headless=true", "-Xmx512m", "-cp", cp, "ZxingServer"]
self.lock = threading.Lock()
self.ids = itertools.count()
self._spawn()
def _spawn(self) -> None:
self.proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1)
self.lines: queue.Queue = queue.Queue()
threading.Thread(target=self._pump, args=(self.proc.stdout, self.lines), daemon=True).start()
@staticmethod
def _pump(stream, lines: queue.Queue) -> None:
for line in stream:
lines.put(line)
lines.put(None)
def close(self) -> None:
self.proc.kill()
self.proc.wait(5)
try:
self.proc.stdin.close()
except OSError: # its pipe broke with it
pass
def read(self, paths: list[str], deadline: float) -> list[list[bytes] | None]:
"""Per frame, ZXing's contents (empty: no read, a timeout included); None where the deadline left it unread."""
out: list[list[bytes] | None] = [None] * len(paths)
deaths = 0
for k, p in enumerate(paths):
# one frame at a time, so two pictures read at once take turns; never waiting past this one's deadline
if not self.lock.acquire(timeout=max(0.0, deadline - time.monotonic())):
break
try:
left = deadline - time.monotonic()
if left <= 0:
break
if self.proc.poll() is not None: # it died since its last answer (while idle): not a miss
self.close()
self._spawn()
rid = next(self.ids)
obj, died = None, False
try:
self.proc.stdin.write(f"{rid}\t{p}\n")
self.proc.stdin.flush()
line = self.lines.get(timeout=min(TIMEOUT_S, left))
died = line is None # its output ended: it exited without answering
obj = json.loads(line) if line else None
except OSError: # its pipe broke: it exited
died = True
except (ValueError, queue.Empty):
pass
if not isinstance(obj, dict) or obj.get("id") != rid: # a timeout, a crash or a stray line: a miss
self.close()
self._spawn()
deaths += died
if deaths > 1: # it keeps dying: this frame and the rest are unread, not misses
break
out[k] = [] if time.monotonic() < deadline else None
continue
out[k] = [base64.b64decode(c) for c in obj.get("contents", [])]
finally:
self.lock.release()
return out