Set content to clipboard with proper error handling. Args: content: The content to copy to clipboard Returns: Tuple[bool, str]: (success, error_message)
(content: str)
| 1316 | |
| 1317 | |
| 1318 | def set_clipboard_content(content: str) -> Tuple[bool, str]: |
| 1319 | """Set content to clipboard with proper error handling. |
| 1320 | |
| 1321 | Args: |
| 1322 | content: The content to copy to clipboard |
| 1323 | |
| 1324 | Returns: |
| 1325 | Tuple[bool, str]: (success, error_message) |
| 1326 | """ |
| 1327 | try: |
| 1328 | # Validate content is proper UTF-8 before attempting to copy |
| 1329 | try: |
| 1330 | input_bytes = content.encode("utf-8") |
| 1331 | except UnicodeError: |
| 1332 | return False, "Content contains invalid Unicode characters" |
| 1333 | |
| 1334 | # macOS - use pbcopy |
| 1335 | if PLATFORM == "darwin": |
| 1336 | run(["pbcopy"], input=input_bytes, check=True) |
| 1337 | # Windows - fallback to pyperclip if available |
| 1338 | elif PLATFORM == "win32": |
| 1339 | try: |
| 1340 | import pyperclip |
| 1341 | |
| 1342 | pyperclip.copy(content) |
| 1343 | except ImportError: |
| 1344 | return ( |
| 1345 | False, |
| 1346 | "The pyperclip module is required for clipboard operations on Windows.\nPlease install it with: pip install pyperclip", |
| 1347 | ) |
| 1348 | except Exception as e: |
| 1349 | return False, f"Windows clipboard error: {str(e)}" |
| 1350 | # Linux - use xclip |
| 1351 | else: |
| 1352 | run(["xclip", "-selection", "clipboard"], input=input_bytes, check=True) |
| 1353 | return True, "" |
| 1354 | except FileNotFoundError: |
| 1355 | if PLATFORM == "darwin": |
| 1356 | return ( |
| 1357 | False, |
| 1358 | "Could not access clipboard. Please ensure you have the proper permissions.", |
| 1359 | ) |
| 1360 | elif PLATFORM == "win32": |
| 1361 | return ( |
| 1362 | False, |
| 1363 | "Windows clipboard access failed. Try installing pyperclip with: pip install pyperclip", |
| 1364 | ) |
| 1365 | else: |
| 1366 | return ( |
| 1367 | False, |
| 1368 | "xclip is not installed. Please install it with: sudo apt-get install xclip", |
| 1369 | ) |
| 1370 | except CalledProcessError as e: |
| 1371 | return False, f"Failed to copy to clipboard: {e.stderr}" |
| 1372 | except Exception as e: |
| 1373 | return False, f"Unexpected error copying to clipboard: {str(e)}" |
| 1374 | |
| 1375 |