#!/usr/bin/env python3
# Copyright (c) 2026 T E Vaughan.
# SPDX-License-Identifier: GPL-3.0-or-later
"""Negotiate Glyph Protocol, register one glyf outline, and print it."""
import base64
import os
import re
import select
import struct
import sys
import termios
import time
import tty

if not sys.stdin.isatty() or not sys.stdout.isatty():
    raise SystemExit('Run this example inside a terminal pane.')

def send(body):
    sys.stdout.write('\033_25a1;' + body + '\033\\')
    sys.stdout.flush()

points = [(500,950),(610,620),(960,620),(680,410),(790,70),(500,280),(210,70),(320,410),(40,620),(390,620)]
xs, ys = [p[0] for p in points], [p[1] for p in points]
outline = struct.pack('>hhhhhHH', 1, min(xs), min(ys), max(xs), max(ys), len(points)-1, 0)
outline += bytes([1] * len(points))
for coordinates in (xs, ys):
    previous = 0
    for value in coordinates:
        outline += struct.pack('>h', value-previous)
        previous = value

fd = sys.stdin.fileno()
saved = termios.tcgetattr(fd)
try:
    tty.setcbreak(fd)
    settings = termios.tcgetattr(fd)
    settings[3] &= ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, settings)
    send('s')
    response, deadline = b'', time.monotonic() + 2
    while b'\033\\' not in response and time.monotonic() < deadline:
        if select.select([fd], [], [], .1)[0]:
            response += os.read(fd, 4096)
    formats = re.search(rb';fmt=([^;\x1b]+)', response)
    if not formats or b'glyf' not in formats.group(1).split(b','):
        raise SystemExit('The terminal did not advertise glyf support.')
    payload = base64.b64encode(outline).decode('ascii')
    send('r;cp=100000;fmt=glyf;reply=0;aw=1000;lh=1000;width=2;pad=0.08,0.08,0.08,0.08;' + payload)
finally:
    termios.tcsetattr(fd, termios.TCSANOW, saved)
print('\033[38;2;126;212;202m' + chr(0x100000) + '  Glyph Protocol\033[0m')
