Skip to content

Commit

Permalink
Add session type check in grabclipboard for Linux
Browse files Browse the repository at this point in the history
  • Loading branch information
TheNooB2706 committed Aug 11, 2023
1 parent f39f74f commit bc658e1
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/PIL/ImageGrab.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,24 @@ def grabclipboard():
return BmpImagePlugin.DibImageFile(data)
return None
else:
if shutil.which("wl-paste"):
if shutil.which("loginctl"):
try:
loginctl = subprocess.check_output("loginctl").decode().split("\n")
except subprocess.CalledProcessError:
loginctl = None
else:
loginctl = None

if loginctl is not None:
username = subprocess.check_output("whoami").decode().strip("\n")
sessionid = [line.split()[0] for line in loginctl if username in line.split()][0]
sessiontype = subprocess.check_output(
["loginctl", "show-session", sessionid, "-p", "Type"]
).decode().strip("\n").split("=")[1]
else: # Session type check failed
sessiontype = None

if shutil.which("wl-paste") and ((sessiontype == "wayland") or (sessiontype is None)):
output = subprocess.check_output(["wl-paste", "-l"]).decode()
mimetypes = output.splitlines()
if "image/png" in mimetypes:
Expand All @@ -153,11 +170,12 @@ def grabclipboard():
args = ["wl-paste"]
if mimetype:
args.extend(["-t", mimetype])
elif shutil.which("xclip"):
elif shutil.which("xclip") and ((sessiontype == "x11") or (sessiontype is None)):
args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
else:
msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
raise NotImplementedError(msg)

p = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
err = p.stderr
if err:
Expand Down

0 comments on commit bc658e1

Please sign in to comment.