Skip to content

CLI for SidePulse

Python

Render QR codes with solid terminal cells

Peter Kuharc4eac7d559cb
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.py
index 126e776..3b8af33 100644
--- a/src/sidepulse/cli.py
+++ b/src/sidepulse/cli.py
@@ -8,7 +8,6 @@ import select
import shutil
import subprocess
import sys
-import tempfile
import threading
import time
import uuid
@@ -52,7 +51,6 @@ from .links import (
new_pairing_channel,
normalize_apns_token,
pairing_url,
- render_pairing_qr_page,
render_terminal_qr,
send_ios_program,
store_ios_link,
@@ -373,7 +371,6 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
server = bridge_server()
channel = new_pairing_channel()
url = pairing_url(server, channel)
- qr_page = render_pairing_qr_page(url)
qr = render_terminal_qr(
url,
ansi=sys.stdout.isatty()
@@ -395,42 +392,16 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
)
listener.start()
- pairing_page_path: Path | None = None
- if sys.platform == "darwin" and sys.stdout.isatty() and "SSH_TTY" not in os.environ:
- try:
- with tempfile.NamedTemporaryFile(
- mode="w",
- encoding="utf-8",
- prefix="sidepulse-link-",
- suffix=".html",
- delete=False,
- ) as pairing_page:
- pairing_page.write(qr_page)
- pairing_page_path = Path(pairing_page.name)
- subprocess.run(
- ["open", str(pairing_page_path)],
- check=True,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
- except (OSError, subprocess.CalledProcessError):
- if pairing_page_path is not None:
- pairing_page_path.unlink(missing_ok=True)
- pairing_page_path = None
-
existing = load_ios_links()
if existing:
print("Linked phones: " + ", ".join(link.name for link in existing))
print()
print("Link your iPhone")
print()
- if pairing_page_path is not None:
- print("Scan the QR code opened in your browser.")
- else:
- print("Scan this QR code with your phone:")
- print()
- print(qr)
- print()
+ print("Scan this QR code with your phone:")
+ print()
+ print(qr)
+ print()
print("Or paste the push token shown in the SidePulse app.")
input_enabled = True
@@ -479,8 +450,6 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
return 1
finally:
stop.set()
- if pairing_page_path is not None:
- pairing_page_path.unlink(missing_ok=True)
if prompt_visible:
print()
diff --git a/src/sidepulse/links.py b/src/sidepulse/links.py
index 0356492..b6c1e22 100644
--- a/src/sidepulse/links.py
+++ b/src/sidepulse/links.py
@@ -181,101 +181,27 @@ def _qr_matrix(value: str, *, border: int) -> list[list[bool]]:
def render_terminal_qr(value: str, *, ansi: bool = False) -> str:
matrix = _qr_matrix(value, border=2)
- pixels = {
- (False, False): " ",
- (True, False): "▀",
- (False, True): "▄",
- (True, True): "█",
- }
- ansi_pixels = {
- (False, False): ("\033[107m", " "),
- (True, False): ("\033[30;107m", "▀"),
- (False, True): ("\033[97;40m", "▀"),
- (True, True): ("\033[40m", " "),
- }
+ pixels = {False: " ", True: "██"}
+ ansi_pixels = {False: "\033[107m", 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)
- pairs = list(zip(top, bottom))
+ for row in matrix:
if not ansi:
- lines.append("".join(pixels[pair] for pair in pairs))
+ lines.append("".join(pixels[cell] for cell in row))
continue
parts: list[str] = []
active_style = ""
- for pair in pairs:
- style, character = ansi_pixels[pair]
+ for cell in row:
+ style = ansi_pixels[cell]
if style != active_style:
parts.append(style)
active_style = style
- parts.append(character)
+ parts.append(" ")
parts.append("\033[0m")
lines.append("".join(parts))
return "\n".join(lines)
-def render_pairing_qr_page(value: str) -> str:
- matrix = _qr_matrix(value, border=4)
- size = len(matrix)
- path_parts: list[str] = []
- for row_index, row in enumerate(matrix):
- column = 0
- while column < size:
- if not row[column]:
- column += 1
- continue
- run_start = column
- while column < size and row[column]:
- column += 1
- path_parts.append(
- f"M{run_start} {row_index}h{column - run_start}v1H{run_start}z"
- )
- qr_pixels = size * 12
- qr_path = "".join(path_parts)
- return f"""<!doctype html>
-<html lang="en">
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Link SidePulse</title>
-<style>
- * {{ box-sizing: border-box; }}
- body {{
- margin: 0;
- min-height: 100vh;
- display: grid;
- place-items: center;
- background: #f5f5f7;
- color: #1d1d1f;
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }}
- main {{
- width: min(92vw, 500px);
- padding: 28px;
- border: 1px solid #dedee3;
- border-radius: 24px;
- background: white;
- box-shadow: 0 16px 48px rgb(0 0 0 / 10%);
- text-align: center;
- }}
- h1 {{ margin: 0 0 6px; font-size: 24px; letter-spacing: -0.02em; }}
- p {{ margin: 0 0 20px; color: #6e6e73; font-size: 15px; }}
- svg {{ display: block; width: 100%; height: auto; }}
-</style>
-<main>
- <h1>Link your iPhone</h1>
- <p>Scan with your iPhone Camera.</p>
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {size} {size}"
- width="{qr_pixels}" height="{qr_pixels}" shape-rendering="crispEdges"
- role="img" aria-label="SidePulse pairing QR code">
- <rect width="{size}" height="{size}" fill="#fff"/>
- <path d="{qr_path}" fill="#000"/>
- </svg>
-</main>
-</html>
-"""
-
-
def parse_ios_registration(value: str, *, server: str) -> IOSLink:
try:
payload = json.loads(value)
diff --git a/tests/test_links.py b/tests/test_links.py
index e10191d..6532446 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -25,7 +25,6 @@ from sidepulse.links import ( # noqa: E402
normalize_apns_token,
pairing_url,
parse_ios_registration,
- render_pairing_qr_page,
render_terminal_qr,
save_ios_links,
store_ios_link,
@@ -87,9 +86,9 @@ class LinkStorageTests(unittest.TestCase):
)
rendered = render_terminal_qr(url)
lines = rendered.splitlines()
- self.assertTrue(any(character in rendered for character in "▀▄█"))
- self.assertLessEqual(len(lines), 20)
- self.assertLessEqual(max(map(len, lines)), 40)
+ self.assertIn("██", rendered)
+ self.assertLessEqual(len(lines), 40)
+ self.assertLessEqual(max(map(len, lines)), 80)
self.assertNotIn("sidepulse://", rendered)
def test_pairing_qr_uses_solid_backgrounds_in_ansi_terminals(self) -> None:
@@ -98,13 +97,6 @@ class LinkStorageTests(unittest.TestCase):
self.assertIn("\033[40m", rendered)
self.assertTrue(all(line.endswith("\033[0m") for line in rendered.splitlines()))
- def test_pairing_qr_page_is_vector_and_does_not_expose_the_link(self) -> None:
- rendered = render_pairing_qr_page("sidepulse://p/7kP2_xQ9mLs")
- self.assertIn("<svg", rendered)
- self.assertIn('shape-rendering="crispEdges"', rendered)
- self.assertIn("<path", rendered)
- self.assertNotIn("sidepulse://", rendered)
-
def test_sse_parser_returns_complete_data_events(self) -> None:
response = iter(
[