1""" Utilities for accessing the platform's clipboard.
2"""
3from __future__ import annotations
4
5import os
6import subprocess
7
8from IPython.core.error import TryNext
9from IPython.utils.encoding import DEFAULT_ENCODING
10
11
12class ClipboardEmpty(ValueError):
13 pass
14
15
16def win32_clipboard_get():
17 """ Get the current clipboard's text on Windows.
18
19 Requires Mark Hammond's pywin32 extensions.
20 """
21 try:
22 import win32clipboard
23 except ImportError as e:
24 raise TryNext("Getting text from the clipboard requires the pywin32 "
25 "extensions: http://sourceforge.net/projects/pywin32/") from e
26 win32clipboard.OpenClipboard()
27 try:
28 text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
29 except (TypeError, win32clipboard.error):
30 try:
31 text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
32 text = text if isinstance(text, str) else text.decode(DEFAULT_ENCODING, "replace")
33 except (TypeError, win32clipboard.error) as e:
34 raise ClipboardEmpty from e
35 finally:
36 win32clipboard.CloseClipboard()
37 return text
38
39
40def osx_clipboard_get() -> str:
41 """ Get the clipboard's text on OS X.
42 """
43 p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
44 stdout=subprocess.PIPE)
45 bytes_, stderr = p.communicate()
46 # Text comes in with old Mac \r line endings. Change them to \n.
47 bytes_ = bytes_.replace(b'\r', b'\n')
48 text = bytes_.decode(DEFAULT_ENCODING, "replace")
49 return text
50
51
52def tkinter_clipboard_get():
53 """ Get the clipboard's text using Tkinter.
54
55 This is the default on systems that are not Windows or OS X. It may
56 interfere with other UI toolkits and should be replaced with an
57 implementation that uses that toolkit.
58 """
59 try:
60 from tkinter import Tk, TclError
61 except ImportError as e:
62 raise TryNext("Getting text from the clipboard on this platform requires tkinter.") from e
63
64 root = Tk()
65 root.withdraw()
66 try:
67 text = root.clipboard_get()
68 except TclError as e:
69 raise ClipboardEmpty from e
70 finally:
71 root.destroy()
72 text = text if isinstance(text, str) else text.decode(DEFAULT_ENCODING, "replace")
73 return text
74
75
76def wayland_clipboard_get():
77 """Get the clipboard's text under Wayland using wl-paste command.
78
79 This requires Wayland and wl-clipboard installed and running.
80 """
81 if os.environ.get("XDG_SESSION_TYPE") != "wayland":
82 raise TryNext("wayland is not detected")
83
84 try:
85 with subprocess.Popen(["wl-paste"], stdout=subprocess.PIPE) as p:
86 raw, err = p.communicate()
87 if p.wait():
88 raise TryNext(err)
89 except FileNotFoundError as e:
90 raise TryNext(
91 "Getting text from the clipboard under Wayland requires the wl-clipboard "
92 "extension: https://github.com/bugaevc/wl-clipboard"
93 ) from e
94
95 if not raw:
96 raise ClipboardEmpty
97
98 try:
99 text = raw.decode(DEFAULT_ENCODING, "replace")
100 except UnicodeDecodeError as e:
101 raise ClipboardEmpty from e
102
103 return text