fix: screenshot thread safety - use fresh mss context per capture

- Remove persistent mss.mss() instance from AutoScreenshot
- Use context manager 'with mss.mss() as sct:' for each capture
- Fixes '_thread._local' object has no attribute 'srcdc' error
- Allows screenshots to work from hotkey callbacks in background threads
This commit is contained in:
LemonNexus 2026-02-11 13:14:44 +00:00
parent b06b98e6cc
commit 53f7896dfa
1 changed files with 14 additions and 11 deletions

View File

@ -24,7 +24,6 @@ class AutoScreenshot:
self.screenshot_dir = screenshot_dir or Path.home() / ".lemontropia" / "screenshots" self.screenshot_dir = screenshot_dir or Path.home() / ".lemontropia" / "screenshots"
self.screenshot_dir.mkdir(parents=True, exist_ok=True) self.screenshot_dir.mkdir(parents=True, exist_ok=True)
self.capture = mss.mss()
self.session_screenshots: List[Path] = [] self.session_screenshots: List[Path] = []
# Settings # Settings
@ -41,11 +40,13 @@ class AutoScreenshot:
filepath = self.screenshot_dir / filename filepath = self.screenshot_dir / filename
try: try:
monitor = self.capture.monitors[1] # Primary monitor # Create fresh mss context for thread safety
screenshot = self.capture.grab(monitor) with mss.mss() as sct:
img = np.array(screenshot) monitor = sct.monitors[1] # Primary monitor
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) screenshot = sct.grab(monitor)
cv2.imwrite(str(filepath), img) img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
cv2.imwrite(str(filepath), img)
self.session_screenshots.append(filepath) self.session_screenshots.append(filepath)
logger.info(f"Screenshot saved: {filepath}") logger.info(f"Screenshot saved: {filepath}")
@ -63,11 +64,13 @@ class AutoScreenshot:
filepath = self.screenshot_dir / filename filepath = self.screenshot_dir / filename
try: try:
monitor = {"left": x, "top": y, "width": w, "height": h} # Create fresh mss context for thread safety
screenshot = self.capture.grab(monitor) with mss.mss() as sct:
img = np.array(screenshot) monitor = {"left": x, "top": y, "width": w, "height": h}
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) screenshot = sct.grab(monitor)
cv2.imwrite(str(filepath), img) img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
cv2.imwrite(str(filepath), img)
self.session_screenshots.append(filepath) self.session_screenshots.append(filepath)
logger.info(f"Region screenshot saved: {filepath}") logger.info(f"Region screenshot saved: {filepath}")