Something went wrong. Try again.
Collection of macros
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Cross-platform screen capture.
Windows, macOS and Linux/X11 use ``mss``. Under Wayland ``mss`` cannot see thecompositor's framebuffer, so we ask the desktop environment instead:
GNOME Shell screencast service (no shutter flash/sound) KDE Plasma ``spectacle`` wlroots/niri ``grim`` (``zwlr_screencopy``)
On GNOME the XDG screenshot portal is used as a fallback, but its backendhardcodes ``flash=true``, which makes the Shell flash the screen and play thecamera shutter sound. The screencast service can run a custom GStreamerpipeline, so we use it to encode a single frame quietly.
The Wayland tools are tried in a sensible order and fall back to each other, soa missing ``grim``/``spectacle`` does not break capture on a desktop that has aworking portal (and vice versa)."""
import osimport shutilimport subprocessimport sysimport tempfileimport timefrom urllib.parse import unquote, urlparse
import mssfrom PIL import Image
def _capture_mss(monitor=1): with mss.mss() as sct: mon = sct.monitors[monitor] sct_img = sct.grab(mon) img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX") return img, mon["width"], mon["height"]
def _capture_with(cmd): """Run a screenshot command that writes to a path, then load the image.""" tmpdir = tempfile.mkdtemp(prefix="macrolib-shot-") path = os.path.join(tmpdir, "shot.png") try: subprocess.run(cmd(path), capture_output=True, check=True) for _ in range(200): if os.path.exists(path) and os.path.getsize(path) > 0: break time.sleep(0.02) img = Image.open(path).convert("RGB") return img, img.width, img.height finally: shutil.rmtree(tmpdir, ignore_errors=True)
def _capture_grim(): return _capture_with(lambda p: ["grim", p])
def _capture_spectacle(): return _capture_with(lambda p: ["spectacle", "-b", "-n", "-f", "-o", p])
def _capture_gnome_screencast(timeout=10): """Capture a frame on GNOME without the shutter flash, sound or notification.
The XDG screenshot portal asks the Shell for a screenshot with ``flash=true``, which fires both the screen flash and the camera shutter sound. GNOME's (legacy) screencast service instead accepts a custom GStreamer pipeline, so we let it encode frames with ``pngenc`` and stop the recording normally as soon as the first frame is ready.
Stopping via ``StopScreencast`` matters: ending the pipeline with EOS on its own makes GNOME show a "Screencast ended unexpectedly" notification. """ try: from jeepney import DBusAddress, new_method_call from jeepney.io.blocking import open_dbus_connection except ImportError as exc: raise RuntimeError( "jeepney is required for the GNOME screencast capture backend" ) from exc
address = DBusAddress( "/org/gnome/Shell/Screencast", bus_name="org.gnome.Shell.Screencast", interface="org.gnome.Shell.Screencast", ) tmpdir = tempfile.mkdtemp(prefix="macrolib-shot-") stem = os.path.join(tmpdir, "shot") conn = open_dbus_connection(bus="SESSION") path = None started = False stopped = False try: options = { # snapshot=false keeps writing frames until we stop it; snapshot=true # would end with EOS and make the Shell report a failed screencast. "pipeline": ("s", "videoconvert ! pngenc snapshot=false"), "draw-cursor": ("b", False), "framerate": ("i", 1), } call = new_method_call(address, "Screencast", "sa{sv}", (stem, options)) reply = conn.send_and_get_reply(call, timeout=timeout) success, path = reply.body if not success or not path: raise RuntimeError("GNOME screencast service did not start") started = True
deadline = time.monotonic() + timeout while True: try: with Image.open(path) as probe: probe.load() break except Exception: pass if time.monotonic() >= deadline: raise TimeoutError("timed out waiting for a screencast frame") time.sleep(0.01)
try: stop = new_method_call(address, "StopScreencast", "", ()) conn.send_and_get_reply(stop, timeout=timeout) stopped = True except Exception: # The frame is already complete; the finally block will retry the # stop so the Shell does not report an unexpected disconnection. pass
# Re-open after stopping: the encoder may have been mid-write when we # saw the first complete PNG. img = Image.open(path).convert("RGB") return img, img.width, img.height finally: if started and not stopped: try: stop = new_method_call(address, "StopScreencast", "", ()) conn.send_and_get_reply(stop, timeout=min(timeout, 2)) except Exception: pass conn.close() shutil.rmtree(tmpdir, ignore_errors=True)
def _capture_portal(timeout=20): """Capture through the XDG desktop portal (used on GNOME Wayland).
The portal is asynchronous: ``Screenshot`` returns a request handle, then emits ``org.freedesktop.portal.Request.Response`` on that handle. The portal saves the image to a file and returns its URI, which we read and then delete (it is a temporary capture, not something the user asked to keep). """ try: from jeepney import DBusAddress, HeaderFields, MatchRule, new_method_call from jeepney.io.blocking import open_dbus_connection except ImportError as exc: raise RuntimeError( "jeepney is required for the desktop portal screenshot backend" ) from exc
address = DBusAddress( "/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop", interface="org.freedesktop.portal.Screenshot", ) conn = open_dbus_connection(bus="SESSION") try: token = "macrolib_{}_{}".format(os.getpid(), time.time_ns()) options = {"interactive": ("b", False), "handle_token": ("s", token)} call = new_method_call(address, "Screenshot", "sa{sv}", ("", options))
# Subscribe before calling so a fast Response cannot be missed. rule = MatchRule( type="signal", interface="org.freedesktop.portal.Request", member="Response", ) with conn.filter(rule) as queue: reply = conn.send_and_get_reply(call, timeout=timeout) handle = reply.body[0] deadline = time.monotonic() + timeout while True: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError("timed out waiting for the screenshot portal") signal = conn.recv_until_filtered(queue, timeout=remaining) if signal.header.fields.get(HeaderFields.path) == handle: break
response, results = signal.body if response != 0: raise RuntimeError( "screenshot portal returned response {} ({} = denied)".format( response, "cancelled" if response == 1 else "error" ) )
uri = results.get("uri") if isinstance(uri, tuple): # jeepney represents variants as (type, value) uri = uri[1] if not uri: raise RuntimeError("screenshot portal did not return a file URI")
path = unquote(urlparse(uri).path) try: img = Image.open(path).convert("RGB") return img, img.width, img.height finally: try: os.remove(path) except OSError: pass finally: conn.close()
def _capture_wayland(): """Try the Wayland capture backends in the order that suits the desktop.""" from . import _linux
candidates = [] if _linux.is_kde(): candidates.append(("spectacle", _capture_spectacle)) if _linux.is_gnome(): # Prefer the quiet screencast path; the portal is only a fallback # because it always flashes the screen and plays the shutter sound. candidates.append(("gnome-screencast", _capture_gnome_screencast)) candidates.append(("xdg-desktop-portal", _capture_portal)) candidates.append(("grim", _capture_grim)) if not _linux.is_gnome(): candidates.append(("xdg-desktop-portal", _capture_portal))
errors = [] for name, backend in candidates: try: return backend() except FileNotFoundError: errors.append("{}: not installed".format(name)) except Exception as exc: errors.append("{}: {}".format(name, exc))
raise RuntimeError( "could not capture the screen on Wayland ({}). " "Install the tool for your desktop (grim, spectacle, or " "xdg-desktop-portal) and try again.".format("; ".join(errors)) )
def capture(monitor=1): """Capture the primary screen.
Returns ``(pil_image, width, height)`` where the image is an RGB PIL Image and width/height are the monitor's pixel dimensions. """ if sys.platform == "linux": from . import _linux
if _linux.is_wayland(): return _capture_wayland() return _capture_mss(monitor)