Skip to content

CLI for SidePulse

Python

Render seamless terminal QR codes

Peter Kuhar77b35ad20f67
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.py
index 6e8c4e4..3b8af33 100644
--- a/src/sidepulse/cli.py
+++ b/src/sidepulse/cli.py
@@ -371,7 +371,12 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
server = bridge_server()
channel = new_pairing_channel()
url = pairing_url(server, channel)
- qr = render_terminal_qr(url)
+ qr = render_terminal_qr(
+ url,
+ ansi=sys.stdout.isatty()
+ and os.environ.get("TERM") != "dumb"
+ and "NO_COLOR" not in os.environ,
+ )
except LinkError as exc:
print(f"sidepulse link: {exc}", file=sys.stderr)
return 1
diff --git a/src/sidepulse/links.py b/src/sidepulse/links.py
index e5abff9..afc4a19 100644
--- a/src/sidepulse/links.py
+++ b/src/sidepulse/links.py
@@ -166,7 +166,7 @@ def pairing_url(server: str, channel: str, sender: str | None = None) -> str:
return "sidepulse://pair?" + urllib.parse.urlencode(query)
-def render_terminal_qr(value: str) -> str:
+def render_terminal_qr(value: str, *, ansi: bool = False) -> str:
try:
import qrcode
from qrcode.constants import ERROR_CORRECT_M
@@ -183,11 +183,31 @@ def render_terminal_qr(value: str) -> str:
(False, True): "▄",
(True, True): "█",
}
+ ansi_pixels = {
+ (False, False): ("\033[107m", " "),
+ (True, False): ("\033[30;107m", "▀"),
+ (False, True): ("\033[97;40m", "▀"),
+ (True, True): ("\033[40m", " "),
+ }
lines: list[str] = []
for row_index in range(0, len(matrix), 2):
top = matrix[row_index]
bottom = matrix[row_index + 1] if row_index + 1 < len(matrix) else [False] * len(top)
- lines.append("".join(pixels[(top_cell, bottom_cell)] for top_cell, bottom_cell in zip(top, bottom)))
+ pairs = list(zip(top, bottom))
+ if not ansi:
+ lines.append("".join(pixels[pair] for pair in pairs))
+ continue
+
+ parts: list[str] = []
+ active_style = ""
+ for pair in pairs:
+ style, character = ansi_pixels[pair]
+ if style != active_style:
+ parts.append(style)
+ active_style = style
+ parts.append(character)
+ parts.append("\033[0m")
+ lines.append("".join(parts))
return "\n".join(lines)
diff --git a/tests/test_links.py b/tests/test_links.py
index 21d81c2..15dd14a 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -91,6 +91,12 @@ class LinkStorageTests(unittest.TestCase):
self.assertLessEqual(max(map(len, lines)), 40)
self.assertNotIn("sidepulse://", rendered)
+ def test_pairing_qr_uses_solid_backgrounds_in_ansi_terminals(self) -> None:
+ rendered = render_terminal_qr("sidepulse://p/7kP2_xQ9mLs", ansi=True)
+ self.assertIn("\033[107m", rendered)
+ self.assertIn("\033[40m", rendered)
+ self.assertTrue(all(line.endswith("\033[0m") for line in rendered.splitlines()))
+
def test_sse_parser_returns_complete_data_events(self) -> None:
response = iter(
[