hyprcam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hyprcam/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """hyprcam: a minimal, frameless webcam window for Hyprland."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.1.0"
hyprcam/__main__.py ADDED
@@ -0,0 +1,190 @@
1
+ """Command-line entry point and the frameless camera window."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import subprocess
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from PySide6.QtCore import Qt, QTimer
13
+ from PySide6.QtGui import QCloseEvent, QContextMenuEvent, QPixmap
14
+ from PySide6.QtWidgets import QApplication, QLabel
15
+
16
+ from .camera import CameraThread
17
+ from .config import Config, default_config_path, load_config, overrides_from_args
18
+ from .devices import format_devices, list_devices
19
+ from .settings_dialog import SettingsDialog
20
+
21
+ TILED_TITLE = "hyprcam"
22
+ FLOATING_TITLE = "hyprcam-float"
23
+ CAPTURE_KEYS = ("device", "width", "height", "fps", "pixel_format", "mirror")
24
+
25
+
26
+ def build_parser() -> argparse.ArgumentParser:
27
+ """Build the argument parser for ``hyprcam``."""
28
+ parser = argparse.ArgumentParser(
29
+ prog="hyprcam",
30
+ description="Minimal frameless webcam window that tiles in Hyprland.",
31
+ )
32
+ parser.add_argument("--list-devices", action="store_true", help="list V4L2 cameras and exit")
33
+ parser.add_argument("--settings", action="store_true", help="open the settings dialog")
34
+ parser.add_argument("--device", help="V4L2 device path, e.g. /dev/video0")
35
+ parser.add_argument("--width", type=int, help="requested capture width")
36
+ parser.add_argument("--height", type=int, help="requested capture height")
37
+ parser.add_argument("--fps", type=int, help="requested capture frame rate")
38
+ parser.add_argument("--pixel-format", dest="pixel_format", help="FOURCC, e.g. MJPG or YUYV")
39
+ parser.add_argument(
40
+ "--mirror", dest="mirror", action="store_true", default=None, help="mirror the image"
41
+ )
42
+ parser.add_argument(
43
+ "--no-mirror", dest="mirror", action="store_false", help="do not mirror the image"
44
+ )
45
+ parser.add_argument(
46
+ "--float", dest="float", action="store_true", default=None, help="use a floating window"
47
+ )
48
+ parser.add_argument("--no-float", dest="float", action="store_false", help="use a tiled window")
49
+ parser.add_argument("--config", type=Path, help="path to an alternative config.toml")
50
+ return parser
51
+
52
+
53
+ def apply_hyprland_float(floating: bool) -> str | None:
54
+ """Switch the window's floating state via Hyprland IPC.
55
+
56
+ Hyprland applies window rules at window creation, so a live change is sent
57
+ through ``hyprctl dispatch``. Returns an error message if every dispatcher
58
+ spelling fails (in which case relaunching the window may be required).
59
+ """
60
+ selector = FLOATING_TITLE if floating else TILED_TITLE
61
+ value = str(floating).lower()
62
+ lua = f'hl.dsp.window.float({{ window = "title:{selector}", floating = {value} }})'
63
+ commands = [
64
+ ["hyprctl", "dispatch", lua],
65
+ [
66
+ "hyprctl",
67
+ "dispatch",
68
+ f"setfloating title:{selector}" if floating else f"settiled title:{selector}",
69
+ ],
70
+ ]
71
+ errors: list[str] = []
72
+ for command in commands:
73
+ try:
74
+ result = subprocess.run(command, capture_output=True, text=True, timeout=4, check=False)
75
+ except (OSError, subprocess.SubprocessError) as exc:
76
+ errors.append(str(exc))
77
+ continue
78
+ output = f"{result.stdout} {result.stderr}".strip().lower()
79
+ if result.returncode == 0 and "error" not in output:
80
+ return None
81
+ errors.append(output or f"exit status {result.returncode}")
82
+ return "; ".join(errors) or "hyprctl dispatch failed"
83
+
84
+
85
+ class CameraWindow(QLabel):
86
+ """A frameless QLabel that displays live camera frames."""
87
+
88
+ def __init__(self, config: Config, config_path: Path, parent: Any | None = None) -> None:
89
+ super().__init__(parent)
90
+ self.config = config
91
+ self.config_path = config_path
92
+ self.settings_dialog: SettingsDialog | None = None
93
+
94
+ self.setWindowTitle(self.title_for(config))
95
+ self.setWindowFlags(self.windowFlags() | Qt.WindowType.FramelessWindowHint)
96
+ self.setAlignment(Qt.AlignmentFlag.AlignCenter)
97
+ self.setStyleSheet("background-color: black; color: white;")
98
+ self.setMinimumSize(160, 120)
99
+ self.resize(config.width, config.height)
100
+
101
+ self.camera = self._new_camera(config)
102
+ self.camera.start()
103
+
104
+ @staticmethod
105
+ def title_for(config: Config) -> str:
106
+ """Return the window title that selects the matching Hyprland rule."""
107
+ return FLOATING_TITLE if config.floating else TILED_TITLE
108
+
109
+ def _new_camera(self, config: Config) -> CameraThread:
110
+ thread = CameraThread(config, self)
111
+ thread.frame_ready.connect(self.show_frame)
112
+ thread.error.connect(self.show_error)
113
+ return thread
114
+
115
+ def show_frame(self, image: Any) -> None:
116
+ """Scale a frame to the window while preserving its aspect ratio."""
117
+ scaled = image.scaled(
118
+ self.size(),
119
+ Qt.AspectRatioMode.KeepAspectRatio,
120
+ Qt.TransformationMode.SmoothTransformation,
121
+ )
122
+ self.setPixmap(QPixmap.fromImage(scaled))
123
+
124
+ def show_error(self, message: str) -> None:
125
+ """Show a concise error message inside the frameless window."""
126
+ self.setText(f"hyprcam: {message}")
127
+
128
+ def apply_config(self, config: Config) -> None:
129
+ """Apply live settings changes from the dialog."""
130
+ previous = self.config
131
+ self.config = config
132
+ if previous.floating != config.floating:
133
+ self.setWindowTitle(self.title_for(config))
134
+ QTimer.singleShot(
135
+ 250, lambda: self._report_float_result(apply_hyprland_float(config.floating))
136
+ )
137
+ if any(getattr(previous, key) != getattr(config, key) for key in CAPTURE_KEYS):
138
+ self.camera.stop()
139
+ self.camera = self._new_camera(config)
140
+ self.camera.start()
141
+
142
+ def _report_float_result(self, error: str | None) -> None:
143
+ if error:
144
+ self.show_error(f"float change needs a window restart ({error})")
145
+
146
+ def open_settings(self) -> None:
147
+ """Show the settings dialog, reusing it if it is already open."""
148
+ if self.settings_dialog is None:
149
+ dialog = SettingsDialog(self.config, self.config_path, self)
150
+ dialog.config_changed.connect(self.apply_config)
151
+ dialog.finished.connect(lambda: setattr(self, "settings_dialog", None))
152
+ self.settings_dialog = dialog
153
+ self.settings_dialog.show()
154
+ self.settings_dialog.raise_()
155
+ self.settings_dialog.activateWindow()
156
+
157
+ def contextMenuEvent(self, event: QContextMenuEvent) -> None:
158
+ self.open_settings()
159
+ event.accept()
160
+
161
+ def closeEvent(self, event: QCloseEvent) -> None:
162
+ self.camera.stop()
163
+ super().closeEvent(event)
164
+
165
+
166
+ def run_gui(config: Config, config_path: Path, show_settings: bool) -> int:
167
+ """Start the Qt application and show the camera window."""
168
+ application = QApplication.instance() or QApplication(sys.argv)
169
+ application.setApplicationName("hyprcam")
170
+ window = CameraWindow(config, config_path)
171
+ window.show()
172
+ if show_settings:
173
+ window.open_settings()
174
+ return int(application.exec())
175
+
176
+
177
+ def main(argv: Sequence[str] | None = None) -> int:
178
+ """Parse arguments, handle information flags, then launch the GUI."""
179
+ args = build_parser().parse_args(argv)
180
+ if args.list_devices:
181
+ print(format_devices(list_devices()))
182
+ return 0
183
+
184
+ config_path = args.config or default_config_path()
185
+ config = load_config(config_path).with_overrides(overrides_from_args(args))
186
+ return run_gui(config, config_path, args.settings)
187
+
188
+
189
+ if __name__ == "__main__":
190
+ raise SystemExit(main())
hyprcam/camera.py ADDED
@@ -0,0 +1,103 @@
1
+ """OpenCV V4L2 capture running in a Qt worker thread."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import cv2
8
+ from PySide6.QtCore import QThread, Signal
9
+ from PySide6.QtGui import QImage
10
+
11
+ from .config import Config
12
+
13
+ FALLBACK_FORMATS = ("MJPG", "YUYV", "YUY2")
14
+
15
+
16
+ def fourcc(code: str) -> int:
17
+ """Pack a four-character pixel-format code the way OpenCV's FOURCC does."""
18
+ return sum(ord(character) << (8 * index) for index, character in enumerate(code))
19
+
20
+
21
+ def open_capture(config: Config) -> tuple[Any, str]:
22
+ """Open a V4L2 capture, trying the requested format before the fallbacks."""
23
+ candidates = list(dict.fromkeys((config.pixel_format, *FALLBACK_FORMATS)))
24
+ last_error = ""
25
+ for code in candidates:
26
+ capture = cv2.VideoCapture(config.device, cv2.CAP_V4L2)
27
+ capture.set(cv2.CAP_PROP_FOURCC, fourcc(code))
28
+ capture.set(cv2.CAP_PROP_FRAME_WIDTH, config.width)
29
+ capture.set(cv2.CAP_PROP_FRAME_HEIGHT, config.height)
30
+ capture.set(cv2.CAP_PROP_FPS, config.fps)
31
+ if capture.isOpened():
32
+ return capture, code
33
+ last_error = f" (tried {code})"
34
+ capture.release()
35
+ raise RuntimeError(f"Could not open {config.device} with OpenCV/V4L2{last_error}")
36
+
37
+
38
+ def frame_to_qimage(frame: Any, mirror: bool) -> QImage:
39
+ """Convert an OpenCV BGR frame to an owned RGB QImage."""
40
+ working = cv2.flip(frame, 1) if mirror else frame
41
+ conversion = cv2.COLOR_BGRA2RGB if working.shape[2] == 4 else cv2.COLOR_BGR2RGB
42
+ rgb = cv2.cvtColor(working, conversion)
43
+ height, width, channels = rgb.shape
44
+ image = QImage(
45
+ rgb.data,
46
+ width,
47
+ height,
48
+ channels * width,
49
+ QImage.Format.Format_RGB888,
50
+ )
51
+ return image.copy()
52
+
53
+
54
+ class CameraThread(QThread):
55
+ """Capture frames and emit them as QImages until stopped."""
56
+
57
+ frame_ready = Signal(QImage)
58
+ error = Signal(str)
59
+ format_selected = Signal(str)
60
+
61
+ def __init__(self, config: Config, parent: Any | None = None) -> None:
62
+ super().__init__(parent)
63
+ self.config = config
64
+
65
+ def run(self) -> None:
66
+ """Open the camera and emit frames until interruption or failure."""
67
+ try:
68
+ capture, selected_format = open_capture(self.config)
69
+ except Exception as exc:
70
+ self.error.emit(str(exc))
71
+ return
72
+
73
+ self.format_selected.emit(selected_format)
74
+ failures = 0
75
+ try:
76
+ while not self.isInterruptionRequested():
77
+ ok, frame = capture.read()
78
+ if not ok or frame is None:
79
+ failures += 1
80
+ if failures >= 25:
81
+ self.error.emit("Camera stopped delivering frames.")
82
+ break
83
+ self.msleep(40)
84
+ continue
85
+ failures = 0
86
+ try:
87
+ image = frame_to_qimage(frame, self.config.mirror)
88
+ except Exception as exc:
89
+ self.error.emit(f"Could not process camera frame: {exc}")
90
+ break
91
+ self.frame_ready.emit(image)
92
+ self.msleep(5)
93
+ finally:
94
+ capture.release()
95
+
96
+ def stop(self) -> None:
97
+ """Ask the thread to stop and wait for it to finish."""
98
+ if not self.isRunning():
99
+ return
100
+ self.requestInterruption()
101
+ if not self.wait(2000):
102
+ self.terminate()
103
+ self.wait(1000)
hyprcam/config.py ADDED
@@ -0,0 +1,158 @@
1
+ """Configuration loading, validation and persistence.
2
+
3
+ Configuration precedence is: built-in defaults, then ``config.toml``, then
4
+ command-line overrides (see :func:`overrides_from_args`).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import sys
12
+ import tomllib
13
+ from collections.abc import Mapping
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ DEFAULTS: dict[str, Any] = {
19
+ "device": "/dev/video0",
20
+ "width": 640,
21
+ "height": 480,
22
+ "fps": 30,
23
+ "pixel_format": "MJPG",
24
+ "mirror": True,
25
+ "float": False,
26
+ }
27
+
28
+
29
+ def config_dir() -> Path:
30
+ """Return the directory holding hyprcam's configuration file."""
31
+ xdg = os.environ.get("XDG_CONFIG_HOME")
32
+ return Path(xdg) / "hyprcam" if xdg else Path.home() / ".config" / "hyprcam"
33
+
34
+
35
+ def default_config_path() -> Path:
36
+ """Return the default path of the TOML configuration file."""
37
+ return config_dir() / "config.toml"
38
+
39
+
40
+ def _as_positive_int(value: Any, fallback: int) -> int:
41
+ try:
42
+ number = int(value)
43
+ except (TypeError, ValueError):
44
+ return fallback
45
+ return number if 0 < number <= 100_000 else fallback
46
+
47
+
48
+ def _as_bool(value: Any, fallback: bool) -> bool:
49
+ if isinstance(value, bool):
50
+ return value
51
+ if isinstance(value, (int, float)) and value in (0, 1):
52
+ return bool(value)
53
+ if isinstance(value, str):
54
+ lowered = value.strip().lower()
55
+ if lowered in {"1", "true", "yes", "on"}:
56
+ return True
57
+ if lowered in {"0", "false", "no", "off"}:
58
+ return False
59
+ return fallback
60
+
61
+
62
+ def _as_fourcc(value: Any, fallback: str) -> str:
63
+ if not isinstance(value, str):
64
+ return fallback
65
+ code = value.strip().upper()
66
+ return code if len(code) == 4 and code.isascii() and code.isalnum() else fallback
67
+
68
+
69
+ def from_dict(values: Mapping[str, Any]) -> Config:
70
+ """Build a :class:`Config`, normalising and validating every field."""
71
+ merged = {**DEFAULTS, **{key: value for key, value in values.items() if key in DEFAULTS}}
72
+ return Config(
73
+ device=str(merged["device"] or DEFAULTS["device"]),
74
+ width=_as_positive_int(merged["width"], DEFAULTS["width"]),
75
+ height=_as_positive_int(merged["height"], DEFAULTS["height"]),
76
+ fps=_as_positive_int(merged["fps"], DEFAULTS["fps"]),
77
+ pixel_format=_as_fourcc(merged["pixel_format"], DEFAULTS["pixel_format"]),
78
+ mirror=_as_bool(merged["mirror"], DEFAULTS["mirror"]),
79
+ floating=_as_bool(merged["float"], DEFAULTS["float"]),
80
+ )
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class Config:
85
+ """Validated application settings.
86
+
87
+ ``floating`` maps to the ``float`` TOML key because ``float`` is a Python
88
+ keyword.
89
+ """
90
+
91
+ device: str = DEFAULTS["device"]
92
+ width: int = DEFAULTS["width"]
93
+ height: int = DEFAULTS["height"]
94
+ fps: int = DEFAULTS["fps"]
95
+ pixel_format: str = DEFAULTS["pixel_format"]
96
+ mirror: bool = DEFAULTS["mirror"]
97
+ floating: bool = DEFAULTS["float"]
98
+
99
+ @property
100
+ def as_dict(self) -> dict[str, Any]:
101
+ """Return the settings using their TOML key names."""
102
+ return {
103
+ "device": self.device,
104
+ "width": self.width,
105
+ "height": self.height,
106
+ "fps": self.fps,
107
+ "pixel_format": self.pixel_format,
108
+ "mirror": self.mirror,
109
+ "float": self.floating,
110
+ }
111
+
112
+ def with_overrides(self, overrides: Mapping[str, Any]) -> Config:
113
+ """Return a copy with non-``None`` overrides applied."""
114
+ values = self.as_dict
115
+ for key, value in overrides.items():
116
+ if key in values and value is not None:
117
+ values[key] = value
118
+ return from_dict(values)
119
+
120
+
121
+ def load_config(path: Path | None = None) -> Config:
122
+ """Load configuration from ``path`` or the default location."""
123
+ target = path or default_config_path()
124
+ try:
125
+ with target.open("rb") as handle:
126
+ raw = tomllib.load(handle)
127
+ except FileNotFoundError:
128
+ return Config()
129
+ except (OSError, tomllib.TOMLDecodeError) as exc:
130
+ print(f"hyprcam: ignoring invalid config {target}: {exc}", file=sys.stderr)
131
+ return Config()
132
+ return from_dict(raw)
133
+
134
+
135
+ def save_config(config: Config, path: Path | None = None) -> Path:
136
+ """Write ``config`` as TOML and return the path that was written."""
137
+ target = path or default_config_path()
138
+ target.parent.mkdir(parents=True, exist_ok=True)
139
+ values = config.as_dict
140
+ lines = ["# hyprcam configuration", "# Managed by hyprcam --settings"]
141
+ for key, default in DEFAULTS.items():
142
+ value = values[key]
143
+ if isinstance(default, bool):
144
+ rendered = "true" if value else "false"
145
+ elif isinstance(default, str):
146
+ rendered = json.dumps(str(value))
147
+ else:
148
+ rendered = str(value)
149
+ lines.append(f"{key} = {rendered}")
150
+ target.write_text("\n".join(lines) + "\n", encoding="utf-8")
151
+ return target
152
+
153
+
154
+ def overrides_from_args(args: Any) -> dict[str, Any]:
155
+ """Extract configuration overrides from parsed command-line arguments."""
156
+ return {
157
+ key: value for key, value in vars(args).items() if key in DEFAULTS and value is not None
158
+ }
hyprcam/devices.py ADDED
@@ -0,0 +1,155 @@
1
+ """Webcam discovery via v4l2-ctl, with an OpenCV fallback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ FOURCC_RE = re.compile(r"'([A-Za-z0-9]{4})'")
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class DeviceInfo:
19
+ """One discovered video device."""
20
+
21
+ path: str
22
+ name: str = ""
23
+ status: str = "unknown"
24
+ formats: tuple[str, ...] = ()
25
+
26
+ def render(self) -> str:
27
+ """Return a single informative terminal line."""
28
+ details: list[str] = []
29
+ if self.name:
30
+ details.append(self.name)
31
+ if self.formats:
32
+ details.append("formats: " + ", ".join(self.formats))
33
+ suffix = f" ({', '.join(details)})" if details else ""
34
+ return f"{self.path} [{self.status}]{suffix}"
35
+
36
+
37
+ def format_devices(devices: list[DeviceInfo]) -> str:
38
+ """Render device discovery results for the command line."""
39
+ if not devices:
40
+ return "No webcam devices found. Check that a V4L2 camera is attached and unlocked."
41
+ return "\n".join(device.render() for device in devices)
42
+
43
+
44
+ def parse_v4l2ctl_output(text: str) -> list[DeviceInfo]:
45
+ """Parse the indented device listing produced by ``v4l2-ctl --list-devices``."""
46
+ devices: list[DeviceInfo] = []
47
+ name = ""
48
+ for line in text.splitlines():
49
+ if not line.strip():
50
+ continue
51
+ if not line[0].isspace():
52
+ name = line.strip().rstrip(":")
53
+ continue
54
+ path = line.strip()
55
+ if path.startswith("/dev/video") and path not in {device.path for device in devices}:
56
+ devices.append(DeviceInfo(path=path, name=name, status="available"))
57
+ return devices
58
+
59
+
60
+ def list_formats_v4l2(path: str, v4l2ctl: str | None = None) -> tuple[str, ...]:
61
+ """Ask v4l2-ctl for supported pixel formats; return an empty tuple on failure."""
62
+ executable = v4l2ctl if v4l2ctl is not None else shutil.which("v4l2-ctl")
63
+ if not executable:
64
+ return ()
65
+ try:
66
+ result = subprocess.run(
67
+ [executable, "-d", path, "--list-formats"],
68
+ capture_output=True,
69
+ text=True,
70
+ timeout=5,
71
+ check=False,
72
+ )
73
+ except (OSError, subprocess.SubprocessError):
74
+ return ()
75
+ if result.returncode != 0:
76
+ return ()
77
+ seen: dict[str, None] = {}
78
+ for match in FOURCC_RE.finditer(result.stdout):
79
+ seen.setdefault(match.group(1), None)
80
+ return tuple(seen)
81
+
82
+
83
+ def _sysfs_name(path: str) -> str:
84
+ name_file = Path("/sys/class/video4linux") / Path(path).name / "name"
85
+ try:
86
+ return name_file.read_text(encoding="utf-8").strip()
87
+ except OSError:
88
+ return ""
89
+
90
+
91
+ def probe_device(
92
+ path: str,
93
+ capture_factory: Callable[[str], Any] | None = None,
94
+ v4l2ctl: str | None = None,
95
+ ) -> DeviceInfo:
96
+ """Probe one device with OpenCV when v4l2-ctl cannot describe it."""
97
+ open_capture = capture_factory
98
+ if open_capture is None:
99
+ import cv2 # imported lazily so --list-devices stays fast
100
+
101
+ def open_capture(device: str) -> Any:
102
+ return cv2.VideoCapture(device, cv2.CAP_V4L2)
103
+
104
+ capture = None
105
+ try:
106
+ capture = open_capture(path)
107
+ opened = bool(capture is not None and capture.isOpened())
108
+ except Exception: # a busy or exotic device may raise from OpenCV
109
+ opened = False
110
+ finally:
111
+ if capture is not None:
112
+ try:
113
+ capture.release()
114
+ except Exception:
115
+ pass
116
+ status = "available" if opened else "busy or unavailable"
117
+ return DeviceInfo(
118
+ path=path,
119
+ name=_sysfs_name(path),
120
+ status=status,
121
+ formats=list_formats_v4l2(path, v4l2ctl),
122
+ )
123
+
124
+
125
+ def list_devices(v4l2ctl: str | None = None) -> list[DeviceInfo]:
126
+ """List webcams, preferring v4l2-ctl and falling back to OpenCV probing.
127
+
128
+ Pass an empty string for ``v4l2ctl`` to force the fallback (used by tests).
129
+ """
130
+ executable = shutil.which("v4l2-ctl") if v4l2ctl is None else v4l2ctl
131
+ if executable:
132
+ try:
133
+ result = subprocess.run(
134
+ [executable, "--list-devices"],
135
+ capture_output=True,
136
+ text=True,
137
+ timeout=5,
138
+ check=False,
139
+ )
140
+ except (OSError, subprocess.SubprocessError):
141
+ result = None
142
+ if result is not None and result.returncode == 0:
143
+ listed = parse_v4l2ctl_output(result.stdout)
144
+ if listed:
145
+ return [
146
+ DeviceInfo(
147
+ path=device.path,
148
+ name=device.name,
149
+ status="available",
150
+ formats=list_formats_v4l2(device.path, executable),
151
+ )
152
+ for device in listed
153
+ ]
154
+
155
+ return [probe_device(path, v4l2ctl=executable) for path in sorted(glob.glob("/dev/video*"))]
@@ -0,0 +1,145 @@
1
+ """Settings dialog with live preview of every setting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from PySide6.QtCore import QTimer, Signal
9
+ from PySide6.QtGui import QHideEvent
10
+ from PySide6.QtWidgets import (
11
+ QCheckBox,
12
+ QComboBox,
13
+ QDialog,
14
+ QDialogButtonBox,
15
+ QFormLayout,
16
+ QLabel,
17
+ QSpinBox,
18
+ QVBoxLayout,
19
+ )
20
+
21
+ from .config import Config, save_config
22
+ from .devices import list_devices
23
+
24
+ PIXEL_FORMATS = ("MJPG", "YUYV", "YUY2", "NV12", "H264")
25
+
26
+
27
+ class SettingsDialog(QDialog):
28
+ """Edit settings; changes are emitted before ``Apply`` is pressed.
29
+
30
+ The parent window connects :attr:`config_changed` to its live-apply handler.
31
+ ``Apply`` persists the current values to the TOML configuration file.
32
+ """
33
+
34
+ config_changed = Signal(object)
35
+ saved = Signal(object)
36
+
37
+ def __init__(self, config: Config, path: Path, parent: Any | None = None) -> None:
38
+ super().__init__(parent)
39
+ self.path = path
40
+ self.setWindowTitle("hyprcam-settings")
41
+ self.setMinimumWidth(420)
42
+
43
+ self.device = QComboBox(self)
44
+ self.device.setEditable(True)
45
+ known = [info.path for info in list_devices()]
46
+ if config.device not in known:
47
+ known.insert(0, config.device)
48
+ self.device.addItems(known)
49
+ self.device.setCurrentText(config.device)
50
+
51
+ self.width_spin = QSpinBox(self)
52
+ self.width_spin.setRange(160, 4096)
53
+ self.width_spin.setValue(config.width)
54
+ self.height_spin = QSpinBox(self)
55
+ self.height_spin.setRange(120, 4096)
56
+ self.height_spin.setValue(config.height)
57
+ self.fps_spin = QSpinBox(self)
58
+ self.fps_spin.setRange(1, 240)
59
+ self.fps_spin.setValue(config.fps)
60
+
61
+ self.pixel_format = QComboBox(self)
62
+ self.pixel_format.setEditable(True)
63
+ self.pixel_format.addItems(list(PIXEL_FORMATS))
64
+ self.pixel_format.setCurrentText(config.pixel_format)
65
+
66
+ self.mirror = QCheckBox("Mirror image horizontally", self)
67
+ self.mirror.setChecked(config.mirror)
68
+ self.floating = QCheckBox("Float the camera window", self)
69
+ self.floating.setChecked(config.floating)
70
+
71
+ form = QFormLayout()
72
+ form.addRow("Device", self.device)
73
+ form.addRow("Width", self.width_spin)
74
+ form.addRow("Height", self.height_spin)
75
+ form.addRow("FPS", self.fps_spin)
76
+ form.addRow("Pixel format", self.pixel_format)
77
+ form.addRow("", self.mirror)
78
+ form.addRow("", self.floating)
79
+
80
+ self.status = QLabel("Changes apply live. Press Apply to save them.", self)
81
+ self.status.setWordWrap(True)
82
+
83
+ buttons = QDialogButtonBox(
84
+ QDialogButtonBox.StandardButton.Apply | QDialogButtonBox.StandardButton.Close,
85
+ self,
86
+ )
87
+ buttons.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(self.save)
88
+ buttons.rejected.connect(self.reject)
89
+
90
+ layout = QVBoxLayout(self)
91
+ layout.addLayout(form)
92
+ layout.addWidget(self.status)
93
+ layout.addWidget(buttons)
94
+
95
+ self.preview_timer = QTimer(self)
96
+ self.preview_timer.setSingleShot(True)
97
+ self.preview_timer.setInterval(350)
98
+ self.preview_timer.timeout.connect(self._emit_preview)
99
+
100
+ for widget in (
101
+ self.device,
102
+ self.width_spin,
103
+ self.height_spin,
104
+ self.fps_spin,
105
+ self.pixel_format,
106
+ self.mirror,
107
+ self.floating,
108
+ ):
109
+ self._connect_change_signal(widget)
110
+
111
+ def _connect_change_signal(self, widget: Any) -> None:
112
+ for signal_name in ("currentTextChanged", "valueChanged", "toggled", "editTextChanged"):
113
+ signal = getattr(widget, signal_name, None)
114
+ if signal is not None:
115
+ signal.connect(self._schedule_preview)
116
+
117
+ def _schedule_preview(self, *_: Any) -> None:
118
+ self.preview_timer.start()
119
+
120
+ def _emit_preview(self) -> None:
121
+ self.config_changed.emit(self.current_config())
122
+
123
+ def current_config(self) -> Config:
124
+ """Return the configuration currently shown in the dialog."""
125
+ return Config(
126
+ device=self.device.currentText().strip(),
127
+ width=self.width_spin.value(),
128
+ height=self.height_spin.value(),
129
+ fps=self.fps_spin.value(),
130
+ pixel_format=self.pixel_format.currentText().strip().upper(),
131
+ mirror=self.mirror.isChecked(),
132
+ floating=self.floating.isChecked(),
133
+ )
134
+
135
+ def save(self) -> Path:
136
+ """Persist the current settings and notify listeners."""
137
+ config = self.current_config()
138
+ written = save_config(config, self.path)
139
+ self.status.setText(f"Saved to {written}")
140
+ self.saved.emit(written)
141
+ return written
142
+
143
+ def hideEvent(self, event: QHideEvent) -> None:
144
+ self.preview_timer.stop()
145
+ super().hideEvent(event)
hyprcam/toggle.py ADDED
@@ -0,0 +1,100 @@
1
+ """Launch/stop hyprcam from a single keybinding using a runtime pidfile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+
14
+ PID_NAME = "hyprcam.pid"
15
+
16
+
17
+ def runtime_dir() -> Path:
18
+ """Return the XDG runtime directory (or a temporary fallback)."""
19
+ return Path(os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir())
20
+
21
+
22
+ def pid_path() -> Path:
23
+ """Return the path of hyprcam's pidfile."""
24
+ return runtime_dir() / PID_NAME
25
+
26
+
27
+ def read_pid(path: Path | None = None) -> int | None:
28
+ """Read a live hyprcam PID from the pidfile, pruning stale entries."""
29
+ target = path or pid_path()
30
+ try:
31
+ pid = int(target.read_text(encoding="utf-8").strip())
32
+ except (OSError, ValueError):
33
+ return None
34
+ if pid <= 0 or not process_is_hyprcam(pid):
35
+ target.unlink(missing_ok=True)
36
+ return None
37
+ return pid
38
+
39
+
40
+ def process_is_hyprcam(pid: int) -> bool:
41
+ """Check that ``pid`` still refers to a hyprcam process."""
42
+ try:
43
+ os.kill(pid, 0)
44
+ cmdline = Path(f"/proc/{pid}/cmdline").read_bytes().lower()
45
+ except (OSError, ProcessLookupError):
46
+ return False
47
+ return b"hyprcam" in cmdline
48
+
49
+
50
+ def start(path: Path | None = None) -> int:
51
+ """Start hyprcam detached and write its PID."""
52
+ target = path or pid_path()
53
+ launcher = Path.home() / ".local" / "bin" / "hyprcam"
54
+ command = [str(launcher)] if launcher.is_file() else [sys.executable, "-m", "hyprcam"]
55
+ process = subprocess.Popen(
56
+ command,
57
+ stdin=subprocess.DEVNULL,
58
+ stdout=subprocess.DEVNULL,
59
+ stderr=subprocess.DEVNULL,
60
+ start_new_session=True,
61
+ )
62
+ target.parent.mkdir(parents=True, exist_ok=True)
63
+ target.write_text(f"{process.pid}\n", encoding="utf-8")
64
+ return process.pid
65
+
66
+
67
+ def stop(path: Path | None = None) -> bool:
68
+ """Terminate the running instance, if any."""
69
+ target = path or pid_path()
70
+ pid = read_pid(target)
71
+ if pid is None:
72
+ return False
73
+ try:
74
+ os.kill(pid, 15)
75
+ for _ in range(20):
76
+ if not process_is_hyprcam(pid):
77
+ break
78
+ time.sleep(0.05)
79
+ except OSError:
80
+ pass
81
+ target.unlink(missing_ok=True)
82
+ return True
83
+
84
+
85
+ def main(argv: Sequence[str] | None = None) -> int:
86
+ """Toggle hyprcam: stop it when running, otherwise start it."""
87
+ parser = argparse.ArgumentParser(
88
+ prog="hyprcam-toggle", description="Toggle the hyprcam camera window."
89
+ )
90
+ parser.parse_args(argv)
91
+ if stop():
92
+ print("hyprcam stopped")
93
+ return 0
94
+ pid = start()
95
+ print(f"hyprcam started (pid {pid})")
96
+ return 0
97
+
98
+
99
+ if __name__ == "__main__":
100
+ raise SystemExit(main())
@@ -0,0 +1,413 @@
1
+ Metadata-Version: 2.4
2
+ Name: hyprcam
3
+ Version: 0.1.0
4
+ Summary: Frameless, tiled webcam window for Hyprland with live settings and OBS-friendly screen capture
5
+ Author-email: mhdztr <zakkithoriq@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/mhdztr/hyprcam
8
+ Project-URL: Source, https://github.com/mhdztr/hyprcam
9
+ Project-URL: Repository, https://github.com/mhdztr/hyprcam
10
+ Project-URL: Issues, https://github.com/mhdztr/hyprcam/issues
11
+ Project-URL: Documentation, https://github.com/mhdztr/hyprcam#readme
12
+ Project-URL: Changelog, https://github.com/mhdztr/hyprcam/blob/main/CHANGELOG.md
13
+ Project-URL: Releases, https://github.com/mhdztr/hyprcam/releases
14
+ Keywords: hyprland,wayland,webcam,v4l2,obs,qt,pyside6,opencv,screen-capture,arch-linux,tiling-window-manager
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Environment :: X11 Applications :: Qt
17
+ Classifier: Intended Audience :: End Users/Desktop
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Desktop Environment :: Window Managers
25
+ Classifier: Topic :: Multimedia :: Video :: Capture
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: PySide6>=6.6
30
+ Requires-Dist: opencv-python-headless>=4.8
31
+ Provides-Extra: dev
32
+ Requires-Dist: build>=1.0; extra == "dev"
33
+ Requires-Dist: mypy>=1.8; extra == "dev"
34
+ Requires-Dist: pytest>=7.0; extra == "dev"
35
+ Requires-Dist: ruff>=0.4; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # hyprcam
39
+
40
+ [![CI](https://github.com/mhdztr/hyprcam/actions/workflows/ci.yml/badge.svg)](https://github.com/mhdztr/hyprcam/actions/workflows/ci.yml)
41
+ [![Release](https://img.shields.io/github/v/release/mhdztr/hyprcam)](https://github.com/mhdztr/hyprcam/releases)
42
+ [![License: MIT](https://img.shields.io/github/license/mhdztr/hyprcam)](LICENSE)
43
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)](https://www.python.org/downloads/)
44
+ [![PyPI](https://img.shields.io/pypi/v/hyprcam)](https://pypi.org/project/hyprcam/)
45
+ [![AUR](https://img.shields.io/aur/version/hyprcam)](https://aur.archlinux.org/packages/hyprcam)
46
+
47
+ > The PyPI and AUR badges display "not found" until the first PyPI upload and
48
+ > the AUR submission are live.
49
+
50
+ A minimal webcam window for [Hyprland](https://hypr.land/). It opens as a normal
51
+ **tiled, frameless** window, so OBS can capture your face by recording a region
52
+ of the screen — no virtual camera, no OBS overlay, no `ffplay` wrapper, no video
53
+ mixer configuration.
54
+
55
+ The video window has no chrome or controls. Right-click it (or use
56
+ `hyprcam --settings`) to open the settings dialog.
57
+
58
+ > **Status:** early-stage (v0.1.0), Linux/V4L2 only. AUR packaging and PyPI
59
+ > publishing are prepared in this repository but no package has been submitted
60
+ > or published yet. See [Installation](#installation) and
61
+ > [Publishing](#publishing-maintainers).
62
+
63
+ ## Contents
64
+
65
+ - [Highlights](#highlights)
66
+ - [Requirements](#requirements)
67
+ - [Installation](#installation)
68
+ - [Hyprland setup](#hyprland-setup)
69
+ - [Usage](#usage)
70
+ - [Configuration](#configuration)
71
+ - [Device discovery](#device-discovery)
72
+ - [OBS workflow](#obs-workflow)
73
+ - [Screenshots](#screenshots)
74
+ - [Troubleshooting](#troubleshooting)
75
+ - [FAQ](#faq)
76
+ - [Publishing (maintainers)](#publishing-maintainers)
77
+ - [Development](#development)
78
+ - [Contributing](#contributing)
79
+ - [License](#license)
80
+
81
+ ## Highlights
82
+
83
+ - **Direct V4L2 capture** through OpenCV (`cv2.VideoCapture` with `CAP_V4L2`); no
84
+ portal or PipeWire virtual device needed.
85
+ - **Tiled by default.** The frameless window behaves like any other Hyprland
86
+ client, so it is easy to region-capture from OBS.
87
+ - **Two window titles for rules:** `hyprcam` (tiled) and `hyprcam-float`
88
+ (floating). The settings dialog uses `hyprcam-settings`.
89
+ - **Settings that apply live.** Device, resolution, FPS, pixel format, mirroring
90
+ and floating state update without restarting; **Apply** saves them to TOML.
91
+ - **CLI overrides** for one-off launches, on top of a validated config file with
92
+ sane defaults.
93
+ - **Single-key toggle.** `hyprcam-toggle` uses a pidfile in `$XDG_RUNTIME_DIR`
94
+ and works with a `Super+B` binding.
95
+ - **Device discovery.** `hyprcam --list-devices` uses `v4l2-ctl` when available,
96
+ with an OpenCV `/dev/video*` probe fallback.
97
+ - **Small, testable core.** 17 tests cover config, CLI and device discovery; CI
98
+ runs lint, format, type checks and tests on Python 3.11–3.13.
99
+
100
+ ## Requirements
101
+
102
+ - Linux with a V4L2 webcam exposed as `/dev/video*`.
103
+ - Python 3.11 or newer.
104
+ - Qt 6 via PySide6 and OpenCV (installed by pip, or from Arch system packages).
105
+ - Hyprland for the suggested keybinding and window rules. The Qt window itself
106
+ also runs on other Wayland/X11 desktops, but the rules and `hyprctl` calls are
107
+ Hyprland-specific.
108
+ - Optional: `v4l-utils` for detailed device and format reporting.
109
+
110
+ ## Installation
111
+
112
+ Pick one path. All of them provide the same `hyprcam` and `hyprcam-toggle`
113
+ commands.
114
+
115
+ ### Arch Linux / AUR packaging
116
+
117
+ AUR-ready files live in [`packaging/aur/`](packaging/aur/) (`PKGBUILD`,
118
+ `.SRCINFO` and submission notes). **No AUR package has been submitted yet**, so
119
+ build and install it locally for now:
120
+
121
+ ```sh
122
+ sudo pacman -S --needed base-devel
123
+ git clone https://github.com/mhdztr/hyprcam.git
124
+ cd hyprcam/packaging/aur
125
+ makepkg -si
126
+ ```
127
+
128
+ The package builds from the `v0.1.0` source tarball with
129
+ `python -m build --wheel --no-isolation` and installs the wheel with
130
+ `python -m installer`, using Arch's system `pyside6`, `python-opencv` and
131
+ `python` packages. Once a package is listed on AUR, the usual
132
+ `yay -S hyprcam` (or another AUR helper) will work instead. See
133
+ [`packaging/aur/AUR-README.md`](packaging/aur/AUR-README.md) for the exact
134
+ submission commands.
135
+
136
+ ### pip / PyPI
137
+
138
+ There is no PyPI release yet — publishing is opt-in and gated (see below). The
139
+ tagged Git source can already be installed with pip:
140
+
141
+ ```sh
142
+ python3 -m pip install 'git+https://github.com/mhdztr/hyprcam.git@v0.1.0'
143
+ hyprcam --list-devices
144
+ ```
145
+
146
+ After the first successful publish workflow run, the normal path becomes:
147
+
148
+ ```sh
149
+ python3 -m pip install hyprcam
150
+ ```
151
+
152
+ A virtual environment is recommended (`python3 -m venv .venv && . .venv/bin/activate`).
153
+
154
+ ### Source checkout (Arch system packages)
155
+
156
+ Install the runtime libraries from pacman, then run the idempotent user
157
+ installer from a checkout:
158
+
159
+ ```sh
160
+ sudo pacman -S pyside6 python-opencv v4l-utils
161
+ git clone https://github.com/mhdztr/hyprcam.git
162
+ cd hyprcam
163
+ chmod +x scripts/hyprcam-install-user
164
+ ./scripts/hyprcam-install-user
165
+ ```
166
+
167
+ It creates `~/.local/bin/hyprcam` and `~/.local/bin/hyprcam-toggle` symlinks,
168
+ installs `hyprcam.desktop` into `~/.local/share/applications/`, and seeds
169
+ `~/.config/hyprcam/config.toml` from `config.example.toml` without overwriting
170
+ an existing config. Re-running it is safe; if `~/.local/bin` is not on `PATH`, it
171
+ prints a warning instead of failing.
172
+
173
+ Make sure `~/.local/bin` is on your `PATH`, or `hyprcam` only works by full path
174
+ and the desktop entry's `Exec=hyprcam` will fail. For zsh, uncomment (or add)
175
+ this line in `~/.zshrc`, above the Oh My Zsh setup:
176
+
177
+ ```sh
178
+ export PATH=$HOME/bin:$HOME/.local/bin:/usr/local/bin:$PATH
179
+ ```
180
+
181
+ For fish, add this near the top of `~/.config/fish/config.fish`:
182
+
183
+ ```fish
184
+ fish_add_path $HOME/.local/bin
185
+ ```
186
+
187
+ Open a new shell (or re-login) and confirm `command -v hyprcam` prints a path.
188
+ Desktop environments pick up the installed `.desktop` file on next login;
189
+ `update-desktop-database ~/.local/share/applications` refreshes it immediately.
190
+
191
+ The wrapper scripts resolve their own real path with `readlink -f`, add `src/`
192
+ to `PYTHONPATH`, and exec `python3 -m hyprcam`, so symlinks work without
193
+ installing the package. Alternatively use an editable install for development:
194
+
195
+ ```sh
196
+ python3 -m pip install -e '.[dev]'
197
+ ```
198
+
199
+ ## Hyprland setup
200
+
201
+ Add a variable in `variables.lua` under `-- Apps`:
202
+
203
+ ```lua
204
+ kbHyprcam = "SUPER + B",
205
+ ```
206
+
207
+ Add the bind in `hyprland/keybinds.lua` under `-- Apps`:
208
+
209
+ ```lua
210
+ create_bind(vars.kbHyprcam, hl.dsp.exec_cmd("~/.local/bin/hyprcam-toggle"))
211
+ ```
212
+
213
+ Add the rules in `hyprland/rules.lua` under `-- Per app rules`:
214
+
215
+ ```lua
216
+ -- hyprcam: frameless tiled camera window; floating variant selected by title
217
+ hl.window_rule({ match = { title = "^hyprcam$" }, border_size = 0, tile = true })
218
+ hl.window_rule({ match = { title = "^hyprcam-float$" }, border_size = 0, float = true, size = "480 360", center = true })
219
+ hl.window_rule({ match = { title = "^hyprcam-settings$" }, float = true, size = "520 420", center = true })
220
+ ```
221
+
222
+ Then run `hyprctl reload` and confirm `hyprctl configerrors` is clean. The
223
+ equivalent legacy `.conf` lines are:
224
+
225
+ ```conf
226
+ bind = SUPER, B, exec, ~/.local/bin/hyprcam-toggle
227
+ windowrulev2 = noborder, class:^hyprcam$
228
+ windowrulev2 = float, title:^hyprcam-float$
229
+ ```
230
+
231
+ Press `Super+B` to open the tiled camera; press it again to close it.
232
+
233
+ ## Usage
234
+
235
+ ```sh
236
+ hyprcam # launch with saved defaults
237
+ hyprcam --settings # launch and open settings
238
+ hyprcam --list-devices # list cameras and formats
239
+ hyprcam --device /dev/video1 --width 1280 --height 720 --fps 30
240
+ hyprcam --pixel-format YUYV --no-mirror # FOURCC and mirroring
241
+ hyprcam --float # floating variant for this launch
242
+ hyprcam --no-float # force tiled variant
243
+ hyprcam --config /path/to/config.toml # alternative config file
244
+ hyprcam-toggle # same action as Super+B
245
+ ```
246
+
247
+ Right-click the video window to open settings. Changes in the dialog apply
248
+ live; **Apply** writes the current values back to the TOML file. The dialog has
249
+ a normal decorated window (title `hyprcam-settings`) and is placed by the rule
250
+ above.
251
+
252
+ ## Configuration
253
+
254
+ Location: `~/.config/hyprcam/config.toml`, or
255
+ `$XDG_CONFIG_HOME/hyprcam/config.toml` when that variable is set. See
256
+ [`config.example.toml`](config.example.toml). The user installer seeds this file
257
+ on first run; until then hyprcam uses built-in defaults.
258
+
259
+ ```toml
260
+ device = "/dev/video0"
261
+ width = 640
262
+ height = 480
263
+ fps = 30
264
+ pixel_format = "MJPG"
265
+ mirror = true
266
+ float = false
267
+ ```
268
+
269
+ | Key | Default | Meaning |
270
+ | --- | --- | --- |
271
+ | `device` | `/dev/video0` | V4L2 device path; see `hyprcam --list-devices`. |
272
+ | `width` | `640` | Requested capture width (160–4096 in the dialog). |
273
+ | `height` | `480` | Requested capture height (120–4096 in the dialog). |
274
+ | `fps` | `30` | Requested frame rate (1–240 in the dialog). |
275
+ | `pixel_format` | `MJPG` | Four-character FOURCC code. |
276
+ | `mirror` | `true` | Flip the image horizontally. |
277
+ | `float` | `false` | Tiled `hyprcam` window; `true` selects `hyprcam-float`. |
278
+
279
+ Precedence: **built-in defaults → config file → command-line flags**. Invalid or
280
+ missing values fall back to defaults rather than crashing the app.
281
+
282
+ `pixel_format` is a four-character FOURCC code. The requested format is tried
283
+ first; MJPG, YUYV and YUY2 are then tried as fallbacks (MJPG usually gives a
284
+ usable frame rate). The settings dialog offers MJPG, YUYV, YUY2, NV12 and H264.
285
+
286
+ When float is toggled in the dialog, hyprcam updates the title and asks Hyprland
287
+ to change the window state via `hyprctl dispatch`. If your Hyprland version
288
+ rejects that dispatcher, close and reopen the window once to pick up the rule.
289
+
290
+ ## Device discovery
291
+
292
+ ```text
293
+ $ hyprcam --list-devices
294
+ /dev/video0 [available] (Integrated Camera, formats: MJPG, YUYV)
295
+ ```
296
+
297
+ `hyprcam --list-devices` uses `v4l2-ctl --list-devices` (from `v4l-utils`) when
298
+ available, including the camera name and supported FOURCC formats. If it is not
299
+ installed or the camera is busy, hyprcam probes `/dev/video*` with OpenCV and
300
+ reports each device as `available` or `busy or unavailable` instead of failing.
301
+
302
+ ## OBS workflow
303
+
304
+ 1. Open hyprcam with `Super+B` (or `hyprcam`); it tiles on your current workspace.
305
+ 2. In OBS, add a **Display Capture (Wayland)** or **Window Capture** source.
306
+ 3. Select/region-capture the tiled hyprcam window and crop to your face.
307
+ 4. Leave the window tiled and unobstructed — OBS records the tiled feed
308
+ directly, without a separate camera source or overlay.
309
+
310
+ For best results, request a capture size that matches your OBS canvas (for
311
+ example 1280×720 at 30 FPS via config or CLI flags) and use MJPG if your camera
312
+ supports it. hyprcam does not create a virtual camera device and does not
313
+ record or stream anything itself.
314
+
315
+ ## Screenshots
316
+
317
+ No screenshots are bundled yet. To add one for a future release: launch hyprcam
318
+ in tiled mode, run `grim -g "$(slurp)" docs/screenshots/tiled.png` (requires
319
+ `grim` and `slurp`), and commit the image with a short caption. For the settings
320
+ dialog, run `hyprcam --settings` first and repeat the capture.
321
+
322
+ ## Troubleshooting
323
+
324
+ - **No image / black window**: check `hyprcam --list-devices`; another app may
325
+ have the camera open. Close it and try again.
326
+ - **Poor frame rate**: switch `pixel_format` to `MJPG`, or lower width, height
327
+ or FPS.
328
+ - **Window not frameless**: make sure the Lua window rules above are loaded and
329
+ `hyprctl reload` succeeded; verify with `hyprctl clients` and
330
+ `hyprctl configerrors`.
331
+ - **Float change did not take effect**: some Hyprland versions only apply window
332
+ rules at window creation; close and reopen hyprcam.
333
+ - **Stale toggle state**: delete `$XDG_RUNTIME_DIR/hyprcam.pid` and press
334
+ `Super+B` again. The toggle prefers `~/.local/bin/hyprcam`, then falls back to
335
+ `python3 -m hyprcam`.
336
+ - **`Exec=hyprcam` fails from the desktop entry**: `~/.local/bin` is missing
337
+ from `PATH` in the desktop session; see the PATH notes above and re-login.
338
+ - **`hyprcam --list-devices` shows only `/dev/video*` with no name**: install
339
+ `v4l-utils` for detailed names and formats; the OpenCV fallback still works.
340
+
341
+ ## FAQ
342
+
343
+ **Is this a virtual camera for OBS?** No. It is a real window that you capture
344
+ with OBS Display/Window Capture. It does not use `v4l2loopback` or expose a new
345
+ `/dev/video*` device.
346
+
347
+ **Does it work outside Hyprland?** The Qt window and V4L2 capture can run on
348
+ other Linux desktops, but the toggle keybinding, window rules and float
349
+ dispatcher are Hyprland-specific. There is no xdg-desktop-portal fallback yet.
350
+
351
+ **Does hyprcam record, stream or apply effects?** No. It only displays live
352
+ frames. Mirroring is the only image transform today.
353
+
354
+ **Can I open two cameras at once?** Not yet. One device per process; per-device
355
+ profiles are on the feature ideas list.
356
+
357
+ **Is it on AUR or PyPI?** Not yet. AUR packaging and a gated PyPI workflow are
358
+ included, but the user must submit/publish them. See below.
359
+
360
+ **Why does my camera reject the requested resolution?** Cameras only support
361
+ discrete modes; OpenCV may silently pick a nearby one. Use
362
+ `hyprcam --list-devices` to see supported formats and try MJPG/YUYV with a
363
+ smaller size.
364
+
365
+ ## Publishing (maintainers)
366
+
367
+ Pushing a `v*` tag always builds an sdist and wheel and attaches them to a
368
+ GitHub Release via `.github/workflows/release.yml`.
369
+
370
+ PyPI publishing is opt-in so the workflow never fails before it is configured:
371
+
372
+ 1. Create/verify a PyPI account at <https://pypi.org/account/register/>.
373
+ 2. In the GitHub repository, go to **Settings → Secrets and variables →
374
+ Actions → Variables → New repository variable** and create
375
+ `ENABLE_PYPI_PUBLISH` with value `true`. Until this exists, the PyPI job is
376
+ skipped.
377
+ 3. On PyPI, open <https://pypi.org/manage/account/publishing/> and add a
378
+ **trusted publisher** with: PyPI Project Name `hyprcam`, Owner `mhdztr`,
379
+ Repository `hyprcam`, Workflow `Publish to PyPI`, Environment `pypi`.
380
+ 4. Push a new tag, for example
381
+ `git tag -a v0.2.0 -m "hyprcam v0.2.0" && git push origin v0.2.0`. The
382
+ `pypi` environment is created on first use. PyPI filenames are immutable, so
383
+ do not try to republish `v0.1.0`.
384
+
385
+ The workflow uses `pypa/gh-action-pypi-publish@release/v1` with OIDC
386
+ (`id-token: write`); no PyPI token is stored in the repository. A PyPI or AUR
387
+ badge will be added once those listings exist.
388
+
389
+ ## Development
390
+
391
+ ```sh
392
+ python3 -m pip install -e '.[dev]'
393
+ ruff check .
394
+ ruff format --check .
395
+ mypy src
396
+ pytest -q
397
+ ```
398
+
399
+ If the tools are installed but not on `PATH`, prefix with `python3 -m` (for
400
+ example `python3 -m ruff check .`). CI runs the same checks on Python 3.11–3.13
401
+ with `QT_QPA_PLATFORM=offscreen`; tests do not need a camera.
402
+
403
+ ## Contributing
404
+
405
+ Bug reports, feature requests and pull requests are welcome. Start with
406
+ [`CONTRIBUTING.md`](CONTRIBUTING.md), the
407
+ [issue templates](.github/ISSUE_TEMPLATE/), the
408
+ [pull request template](.github/PULL_REQUEST_TEMPLATE.md), the
409
+ [changelog](CHANGELOG.md) and the [code of conduct](CODE_OF_CONDUCT.md).
410
+
411
+ ## License
412
+
413
+ MIT © 2026 mhdztr. See [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ hyprcam/__init__.py,sha256=7DtQ16wiz1aOXKiQB3VpDN_Dc4vBlmAAH5a6V3uaOd4,114
2
+ hyprcam/__main__.py,sha256=M2-3x2choF-p-wbqoow5cb3aF_DsqyPBqA768-B9Yko,7671
3
+ hyprcam/camera.py,sha256=Kx4ge0rt3YpYDATcA2qqxQy8am85ENBMymwN5ls0zA8,3481
4
+ hyprcam/config.py,sha256=Mbp-lvsYGerzBwfy2FJKGdYRUig55ZyA3WLRP128jUc,5228
5
+ hyprcam/devices.py,sha256=Jf_PsZMQmLiPUI0IXUK-vuRI90NGwOEqzaHc8myCs8k,5032
6
+ hyprcam/settings_dialog.py,sha256=IexxQw13UZVapMbjsxT2to-SMx3U9qfpHCTluH3Vik0,4954
7
+ hyprcam/toggle.py,sha256=D51MogebYmjcaU8EzWZOzIP3h8Lhx3ktBp3ZKVZNPOo,2796
8
+ hyprcam-0.1.0.dist-info/licenses/LICENSE,sha256=BeWlwlWHINHae-2-em6z-yunXyFI2-uXaeoxjzrLU0E,1063
9
+ hyprcam-0.1.0.dist-info/METADATA,sha256=hs42Ch4kLo6i8I-dyyBAOnX4mpNJfpltV38ZIsmVfqM,16948
10
+ hyprcam-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ hyprcam-0.1.0.dist-info/entry_points.txt,sha256=DXY3ghXykkzfZZpYltt9TSuUVlxc6RJGQbSb7HXyGRM,87
12
+ hyprcam-0.1.0.dist-info/top_level.txt,sha256=e2fNMNThPp8dX6wi9e10wgld-RT-7zpuGjUZ87znTo0,8
13
+ hyprcam-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ hyprcam = hyprcam.__main__:main
3
+ hyprcam-toggle = hyprcam.toggle:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mhdztr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ hyprcam