master
AdityaAngajala Preserve source for molecule-publish-3.0.0 33f54d8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
"""Altium Designer .PcbDoc to a minimal .kicad_pcb that names.py and the metadata importer read.

A PcbDoc is an OLE2 compound file (CFB) whose storages hold one record stream each
(Board6/Data, Components6/Data, Pads6/Data, ...). The records are read field by field as KiCad
10's Altium importer reads them (pcbnew/pcb_io/altium), with board-to-molecule's rs/src/altium
as the reference port. Altium lengths are 1/10000 mil; every length is converted exactly
(1 mil = 0.0254 mm, no rounding), so a 43 mil drill is 1.0922 mm.

What the KiCad file carries. Each component of Components6 becomes a footprint: its name is
PATTERN as Altium has it (no library prefix), its Reference is the component's designator text
(Texts6, through WideStrings6), else SOURCEDESIGNATOR when the text is missing or a special
string such as .Designator, its Value is the comment text the same way, and its layer is F.Cu or
B.Cu from LAYER. Its placement is X, Y and ROTATION. Every Pads6 pad on the top, bottom or multi
layer, and every pad with a hole, is a pad of its component with its name, position, angle,
shape and size (the top layer's, for a pad stack), drill (round, or oval for a slot) and plated
or not; a pad of no component becomes a footprint of its own with no name or reference, as
KiCad's importer makes it. The file name of each 3D model a ComponentBodies6 record gives the
component (MODEL.NAME, else the Models/Data entry it names) is a (model) of its footprint, in
record order. Board6's outline vertices are lines and arcs on Edge.Cuts.

The frame is Altium's, measured from the board origin (Board6 ORIGINX, ORIGINY), with Y negated
because KiCad's Y grows downward; both readers negate it again. Nothing is renamed. Routing,
nets, vias, zones, text, silkscreen, board cutouts and pads without a hole on other layers are
left out; the report counts them and lists what may surprise as warnings.

Python 3.9 or newer, standard library only. A file that is not a binary PcbDoc, or that cannot
be read, raises ValueError with a one-line reason.

  pcbdoc.py <in.PcbDoc> <out.kicad_pcb> [--report report.json]
"""
import itertools, json, math, struct, sys
from decimal import Decimal, InvalidOperation
from pathlib import Path, PureWindowsPath

CFB_MAGIC = bytes.fromhex('d0cf11e0a1b11ae1')
NOSTREAM = 0xFFFFFFFF
LAST_SECTOR = 0xFFFFFFFA
MM_PER_MIL = Decimal('0.0254')
UNITS_PER_MIL = 10000
NO_COMPONENT = 0xFFFF
TOP, BOTTOM, MULTI = 1, 32, 74
SLOT, SQUARE = 2, 1
ROUNDRECT = 9
EDGE_WIDTH = '0.05'


# ---------------------------------------------------------------- compound file

class Cfb:
    """An OLE2 compound file read whole: stream(path) returns the bytes of 'Board6/Data'."""

    def __init__(self, data):
        if len(data) < 512 or data[:8] != CFB_MAGIC:
            if data[:8].lstrip(b'\xef\xbb\xbf').startswith(b'|RECORD='):
                raise ValueError('it is an ASCII PcbDoc; save the board as a binary PcbDoc')
            raise ValueError('it is not an OLE2 compound file (no CFB signature)')
        major = struct.unpack_from('<H', data, 0x1A)[0]
        shift, mini_shift = struct.unpack_from('<HH', data, 0x1E)
        if shift not in (9, 12) or mini_shift != 6:
            raise ValueError(f'its compound file header is damaged (sector shift {shift}, mini sector shift {mini_shift})')
        self.data, self.size = data, 1 << shift
        n_fat, first_dir, _, self.cutoff, first_mini, _, first_difat, _ = struct.unpack_from('<8I', data, 0x2C)
        per = self.size // 4
        difat = list(struct.unpack_from('<109I', data, 0x4C))
        seen = set()
        s = first_difat
        while s < LAST_SECTOR and len(difat) < n_fat + 109:
            if s in seen:
                raise ValueError('its compound file DIFAT chain loops')
            seen.add(s)
            entries = struct.unpack(f'<{per}I', self._sector(s, 'DIFAT'))
            difat += entries[:-1]
            s = entries[-1]
        fat_sectors = [x for x in difat if x < LAST_SECTOR][:n_fat]
        if len(fat_sectors) < n_fat:
            raise ValueError('its compound file FAT is incomplete')
        self.fat = struct.unpack(f'<{per * n_fat}I', b''.join(self._sector(x, 'FAT') for x in fat_sectors))
        directory = self._chain_bytes(first_dir, self.fat, self.size, self._sector, 'directory')
        self.entries = []
        for i in range(len(directory) // 128):
            e = directory[i * 128:(i + 1) * 128]
            n = min(struct.unpack_from('<H', e, 64)[0], 64)
            left, right, child = struct.unpack_from('<III', e, 68)
            start, size = struct.unpack_from('<IQ', e, 116)
            self.entries.append({'name': e[:max(n - 2, 0)].decode('utf-16-le', errors='replace'), 'type': e[66],
                                 'left': left, 'right': right, 'child': child, 'start': start,
                                 'size': size & 0xFFFFFFFF if major == 3 else size})
        if not self.entries or self.entries[0]['type'] != 5:
            raise ValueError('its compound file has no root entry')
        root = self.entries[0]
        self.mini_fat = ()
        self.mini = b''
        if root['start'] < LAST_SECTOR:
            self.mini = self._chain_bytes(root['start'], self.fat, self.size, self._sector, 'mini stream')[:root['size']]
            if first_mini < LAST_SECTOR:
                raw = self._chain_bytes(first_mini, self.fat, self.size, self._sector, 'mini FAT')
                self.mini_fat = struct.unpack(f'<{len(raw) // 4}I', raw[:len(raw) // 4 * 4])
        self.paths = {}
        self._walk()

    def _sector(self, s, what):
        """Sector `s`; a stream's last sector may be cut short, a FAT or DIFAT sector may not."""
        off = (s + 1) * self.size
        if off >= len(self.data) or (what in ('FAT', 'DIFAT') and off + self.size > len(self.data)):
            raise ValueError(f'its compound file {what} points past the end of the file (truncated?)')
        return self.data[off:off + self.size]

    def _mini_sector(self, s, what):
        off = s * 64
        if off >= len(self.mini):
            raise ValueError(f'its compound file {what} points past the end of the mini stream')
        return self.mini[off:off + 64]

    @staticmethod
    def _chain_bytes(start, table, size, read, what):
        out, seen, s = [], set(), start
        while s < LAST_SECTOR:
            if s >= len(table) or s in seen:
                raise ValueError(f'its compound file {what} chain is broken')
            seen.add(s)
            out.append(read(s, what))
            s = table[s]
        return b''.join(out)

    def _walk(self):
        todo, seen = [(self.entries[0]['child'], '')], set()
        while todo:
            i, prefix = todo.pop()
            if i == NOSTREAM:
                continue
            if i >= len(self.entries) or i in seen:
                raise ValueError('its compound file directory tree is broken')
            seen.add(i)
            e = self.entries[i]
            todo += [(e['left'], prefix), (e['right'], prefix)]
            if e['type'] == 1:
                todo.append((e['child'], prefix + e['name'] + '/'))
            elif e['type'] == 2:
                self.paths[(prefix + e['name']).lower()] = i

    def stream(self, path):
        """The bytes of the stream at `path` ('Pads6/Data', case ignored), or None."""
        i = self.paths.get(path.lower())
        if i is None:
            return None
        e = self.entries[i]
        if e['size'] < self.cutoff:
            data = self._chain_bytes(e['start'], self.mini_fat, 64, self._mini_sector, path)
        else:
            data = self._chain_bytes(e['start'], self.fat, self.size, self._sector, path)
        if len(data) < e['size']:
            raise ValueError(f'{path} is shorter than its directory entry says (truncated?)')
        return data[:e['size']]


# ---------------------------------------------------------------- records

def props(payload):
    """A |KEY=VALUE|... record: keys upper-cased, values Latin-1 (UTF-8 under a %UTF8% key), trimmed; the first of a repeated key wins."""
    out = {}
    for tok in payload.split(b'\0', 1)[0].split(b'|'):
        k, eq, v = tok.partition(b'=')
        if eq:
            key = k.decode('latin-1').strip(' \t\r\n').upper()
            out.setdefault(key, (v.decode('utf-8', errors='replace') if key.startswith('%UTF8%') else v.decode('latin-1')).strip(' \t\r\n'))
    return out


def prop(p, key, default=''):
    return p.get('%UTF8%' + key, p.get(key, default))


def prop_unicode(p, key):
    """KiCad's ReadUnicodeString: UNICODE__KEY (comma-separated code points) when UNICODE says EXISTS."""
    if 'EXISTS' in p.get('UNICODE', '') and 'UNICODE__' + key in p:
        try:
            return ''.join(chr(int(c)) for c in p['UNICODE__' + key].split(',') if c.strip())
        except (ValueError, OverflowError):
            pass
    return prop(p, key)


def mil(p, key):
    """A '1234.5678mil' property in units of 1/10000 mil, exactly, or None (also beyond Altium's 32-bit range)."""
    v = prop(p, key, None)
    if v is None or not v.endswith('mil'):
        return None
    try:
        d = Decimal(v[:-3].strip().lstrip('+')) * UNITS_PER_MIL
    except InvalidOperation:
        return None
    return d if d.is_finite() and abs(d) < 2 ** 31 else None


def number(p, key):
    """A plain number property (an angle, a kind), exactly; 0 when missing, malformed or absurd."""
    try:
        d = Decimal(prop(p, key, '0').strip() or '0')
    except InvalidOperation:
        return Decimal(0)
    return d if d.is_finite() and abs(d) < 10 ** 9 else Decimal(0)


def text_records(data, stream):
    """A run of u32 length + property record (KiCad's ReadProperties)."""
    out, i = [], 0
    while len(data) - i >= 4:
        n = struct.unpack_from('<I', data, i)[0]
        binary, n = n & 0xFF000000, n & 0x00FFFFFF
        if i + 4 + n > len(data):
            raise ValueError(f'{stream} record {len(out)} runs past the end of the stream')
        if not binary:
            out.append(props(data[i + 4:i + 4 + n]))
        i += 4 + n
    return out


def binary_records(data, subrecords, kind, stream):
    """A run of u8 record type + `subrecords` u32-length subrecords."""
    out, i = [], 0
    while len(data) - i >= 4:
        if data[i] != kind:
            raise ValueError(f'{stream} record {len(out)} has type {data[i]}, not {kind}')
        i += 1
        subs = []
        for _ in range(subrecords):
            if i + 4 > len(data):
                raise ValueError(f'{stream} record {len(out)} is truncated')
            n = struct.unpack_from('<I', data, i)[0]
            if i + 4 + n > len(data):
                raise ValueError(f'{stream} record {len(out)} runs past the end of the stream')
            subs.append(data[i + 4:i + 4 + n])
            i += 4 + n
        out.append(subs)
    return out


def wide_strings(data):
    """WideStrings6: u32 index, u32 byte length, UTF-16LE text with its NUL."""
    out, i = {}, 0
    while len(data) - i >= 8:
        idx, n = struct.unpack_from('<II', data, i)
        i += 8
        if n <= 2:
            out[idx] = ''
            continue
        if i + n > len(data):
            break
        out[idx] = data[i:i + n - 2].decode('utf-16-le', errors='replace')
        i += n
    return out


def pascal(b):
    n = b[0] if b else 0
    return b[1:1 + n].decode('latin-1')


def i32(b, off):
    return struct.unpack_from('<i', b, off)[0]


def u16(b, off):
    return struct.unpack_from('<H', b, off)[0]


def angle(b, off):
    """A little-endian double, in degrees; 0 when it is not finite."""
    a = struct.unpack_from('<d', b, off)[0]
    return a if math.isfinite(a) else 0.0


def pad_record(subs, index):
    """APAD6: the fields of subrecords 1, 5 and 6 a footprint pad needs."""
    s5, s6 = subs[4], subs[5]
    if not subs[0] or len(s5) < 110:
        raise ValueError(f'Pads6/Data record {index} is too short ({len(s5)}-byte subrecord 5)')
    x, y, w, h = struct.unpack_from('<4i', s5, 13)
    pad = {'name': pascal(subs[0]), 'layer': s5[0], 'component': u16(s5, 7), 'x': x, 'y': y, 'w': w, 'h': h, 'hole': i32(s5, 45),
           'shape': s5[49], 'direction': angle(s5, 52), 'plated': s5[60] != 0, 'mode': s5[62],
           'holeshape': 0, 'slot': 0, 'slotrot': 0.0, 'offset': (0, 0), 'alt': 0, 'radius': 0}
    if len(s6) >= 596:
        pad.update(holeshape=s6[262], slot=i32(s6, 263), slotrot=angle(s6, 267),
                   offset=(i32(s6, 275), i32(s6, 403)), alt=s6[532], radius=s6[564])
    return pad


def text_record(subs, strings):
    """ATEXT6: component, designator/comment flags and the string (WideStrings6, else the legacy one)."""
    a = subs[0]
    if len(a) < 9:
        return None
    long = len(a) >= 123
    widx = struct.unpack_from('<I', a, 115)[0] if long else None
    text = strings[widx] if widx in strings else pascal(subs[1])
    return {'component': u16(a, 7), 'comment': long and a[40] != 0, 'designator': long and a[41] != 0, 'text': text.replace('\r\n', '\n')}


def body_record(subs):
    """ACOMPONENTBODY6: the component index and the property block (MODEL.NAME, MODELID, ...)."""
    s = subs[0]
    if len(s) < 22:
        return None
    n = struct.unpack_from('<I', s, 18)[0] & 0x00FFFFFF
    return u16(s, 7), props(s[22:22 + n])


# ---------------------------------------------------------------- geometry

def mm(units):
    """KiCad text for a length in 1/10000 mil: exact for a Decimal or int, to 1e-6 mm for a float."""
    if isinstance(units, float):
        return num(units * 0.0254 / UNITS_PER_MIL)
    s = format((Decimal(units) * MM_PER_MIL / UNITS_PER_MIL).normalize(), 'f')
    return '0' if s in ('-0', '0') else s


def num(v):
    """KiCad text for an angle or a float length in mm, to 1e-6."""
    if isinstance(v, Decimal):
        s = format(v.normalize(), 'f')
    else:
        s = format(Decimal(repr(round(v, 6) + 0.0)).normalize(), 'f')
    return '0' if s in ('-0', '0') else s


def rotate(x, y, angle):
    """(x, y) rotated by `angle` degrees counter-clockwise (Y up); exact for multiples of 90."""
    q = angle / 90
    if q == q.to_integral_value():
        return [(x, y), (-y, x), (-x, -y), (y, -x)][int(q) % 4]
    a = math.radians(float(angle))
    fx, fy = float(x), float(y)
    return fx * math.cos(a) - fy * math.sin(a), fx * math.sin(a) + fy * math.cos(a)


def outline(board, origin):
    """Board6's vertices as Edge.Cuts pieces [(start, end, mid or None)] in units, read as KiCad
    reads them: a line vertex is a corner; an arc vertex is its arc from the centre, starting at
    the end nearer the vertex point; consecutive pieces are joined by straight edges and the
    chain is closed."""
    pieces = []
    for i in itertools.count():
        vx, vy = mil(board, f'VX{i}'), mil(board, f'VY{i}')
        if vx is None or vy is None:
            break
        p = (vx - origin[0], vy - origin[1])
        r = mil(board, f'R{i}') or Decimal(0)
        if number(board, f'KIND{i}') != 0:
            cx, cy = (mil(board, f'CX{i}') or Decimal(0)) - origin[0], (mil(board, f'CY{i}') or Decimal(0)) - origin[1]
            sa, ea = float(number(board, f'SA{i}')), float(number(board, f'EA{i}'))
            at = lambda deg: (Decimal(round(float(cx) + float(r) * math.cos(math.radians(deg)))), Decimal(round(float(cy) + float(r) * math.sin(math.radians(deg)))))
            a, b = at(sa), at(ea)
            sweep = (ea - sa) % 360
            short = math.hypot(float(a[0] - b[0]), float(a[1] - b[1])) < 0.001 / 0.0254 * UNITS_PER_MIL or sweep < 0.2
            mid = None if short else at(sa + sweep / 2)
            near = lambda q: math.hypot(float(q[0] - p[0]), float(q[1] - p[1]))
            pieces.append((a, b, mid) if near(a) < near(b) else (b, a, mid))
        else:
            pieces.append((p, p, None))
    out = []
    for i, (s, e, m) in enumerate(pieces):
        if m is not None or s != e:
            out.append((s, e, m))
        nxt = pieces[(i + 1) % len(pieces)][0]
        if len(pieces) > 1 and e != nxt:
            out.append((e, nxt, None))
    return out


# ---------------------------------------------------------------- KiCad text

LAYERS = ('(layers (0 "F.Cu" signal) (2 "B.Cu" signal) (9 "F.Adhes" user "F.Adhesive") (11 "B.Adhes" user "B.Adhesive") '
          '(13 "F.Paste" user) (15 "B.Paste" user) (5 "F.SilkS" user "F.Silkscreen") (7 "B.SilkS" user "B.Silkscreen") '
          '(1 "F.Mask" user) (3 "B.Mask" user) (25 "Edge.Cuts" user) (31 "F.CrtYd" user "F.Courtyard") '
          '(29 "B.CrtYd" user "B.Courtyard") (35 "F.Fab" user) (33 "B.Fab" user))')


def q(s):
    """A KiCad quoted string."""
    return '"' + s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + '"'


def xy(p):
    return f'{mm(p[0])} {mm(-p[1])}'


def pad_text(pad, at, warn):
    """One (pad ...) at the footprint-local point `at` (units, Y up), with the pad's own angle,
    which KiCad stores absolute, and its shape as KiCad's importer maps Altium's."""
    w, h = pad['w'], pad['h']
    if pad['shape'] == 2:
        shape, extra = 'rect', ''
    elif pad['shape'] == 1 and pad['alt'] == ROUNDRECT:
        shape, extra = 'roundrect', f' (roundrect_rratio {num(Decimal(pad["radius"]) / 200)})'
    elif pad['shape'] == 1:
        shape, extra = ('circle' if w == h else 'oval'), ''
    elif pad['shape'] == 3:
        shape, extra = 'roundrect', ' (roundrect_rratio 0) (chamfer_ratio 0.25) (chamfer top_left top_right bottom_left bottom_right)'
    else:
        shape, extra = 'rect', ''
        warn('unknown-shape', f"pad {pad['name']!r} of {pad['owner']} has pad shape {pad['shape']}, written as rect")
    if pad['hole'] > 0:
        if pad['layer'] != MULTI:
            warn('hole-off-multi', f"pad {pad['name']!r} of {pad['owner']} has a hole on layer {pad['layer']}, not the multi layer; written as a through-hole pad")
        kind = 'thru_hole' if pad['plated'] else 'np_thru_hole'
        layers = '"*.Cu" "*.Mask"'
        d = mm(pad['hole'])
        if pad['holeshape'] == SLOT:
            rot = pad['slotrot'] % 180
            if abs(rot - 90) < 1e-9:
                drill = f'(drill oval {d} {mm(pad["slot"])}'
            else:
                drill = f'(drill oval {mm(pad["slot"])} {d}'
                if rot > 1e-9 and abs(rot - 180) > 1e-9:
                    warn('slot-angle', f"pad {pad['name']!r} of {pad['owner']} has a slot at {num(pad['slotrot'])} degrees; written along the pad's x axis")
        else:
            if pad['holeshape'] == SQUARE:
                warn('square-hole', f"pad {pad['name']!r} of {pad['owner']} has a square hole, written as a round drill of its size")
            drill = f'(drill {d}'
        if pad['offset'] != (0, 0):
            drill += f' (offset {mm(pad["offset"][0])} {mm(-pad["offset"][1])})'
        drill = ' ' + drill + ')'
    else:
        kind, drill = 'smd', ''
        layers = '"B.Cu" "B.Paste" "B.Mask"' if pad['layer'] == BOTTOM else '"F.Cu" "F.Paste" "F.Mask"' if pad['layer'] == TOP else '"*.Cu" "*.Mask"'
    rot = '' if pad['direction'] == 0 else ' ' + num(pad['direction'])
    return f'\t\t(pad {q(pad["name"])} {kind} {shape} (at {xy(at)}{rot}) (size {mm(w)} {mm(h)}){drill} (layers {layers}){extra})\n'


def footprint_text(name, ref, value, layer, at, rotation, pads, models):
    out = [f'\t(footprint {q(name)} (layer {q(layer)}) (at {xy(at)}' + ('' if rotation == 0 else ' ' + num(rotation)) + ')\n',
           f'\t\t(property "Reference" {q(ref)} (at 0 0 0) (layer "F.Fab") (hide yes) (effects (font (size 1 1) (thickness 0.15))))\n',
           f'\t\t(property "Value" {q(value)} (at 0 0 0) (layer "F.Fab") (hide yes) (effects (font (size 1 1) (thickness 0.15))))\n']
    out += pads
    out += [f'\t\t(model {q(m)})\n' for m in models]
    out.append('\t)\n')
    return ''.join(out)


# ---------------------------------------------------------------- conversion

class Warnings:
    """Warning sentences by kind; lines() gives five of each kind and the count of the rest."""

    def __init__(self):
        self.kinds = {}

    def __call__(self, kind, text):
        self.kinds.setdefault(kind, []).append(text)

    def lines(self):
        out = []
        for kind, texts in self.kinds.items():
            out += texts[:5] + ([f'and {len(texts) - 5} more {kind} warnings'] if len(texts) > 5 else [])
        return out


def read(src):
    """The board of the PcbDoc at `src`: {origin, components, free, outline, counts, warn}."""
    try:
        data = Path(src).read_bytes()
    except OSError as e:
        raise ValueError(f'it cannot be read ({e.strerror or type(e).__name__})')
    cf = Cfb(data)
    board_data = cf.stream('Board6/Data')
    if board_data is None:
        raise ValueError('it is a compound file but not an Altium PcbDoc (no Board6/Data stream)')
    warn = Warnings()
    boards = text_records(board_data, 'Board6/Data')
    board = boards[0] if boards else {}
    origin = (mil(board, 'ORIGINX') or Decimal(0), mil(board, 'ORIGINY') or Decimal(0))
    stream = lambda path: cf.stream(path) or b''

    comps = []
    for p in text_records(stream('Components6/Data'), 'Components6/Data'):
        layer = prop(p, 'LAYER').upper()
        if layer not in ('TOP', 'BOTTOM'):
            warn('component-layer', f"component {prop(p, 'SOURCEDESIGNATOR')!r} is on layer {layer!r}; written on the top")
        comps.append({'source': prop(p, 'SOURCEDESIGNATOR'), 'designator': None, 'value': None, 'name': prop_unicode(p, 'PATTERN'),
                      'bottom': layer == 'BOTTOM', 'x': (mil(p, 'X') or Decimal(0)) - origin[0], 'y': (mil(p, 'Y') or Decimal(0)) - origin[1],
                      'rotation': number(p, 'ROTATION'), 'pads': [], 'models': []})

    strings = wide_strings(stream('WideStrings6/Data'))
    for subs in binary_records(stream('Texts6/Data'), 2, 5, 'Texts6/Data'):
        t = text_record(subs, strings)
        if not t or t['component'] >= len(comps) or t['text'].startswith('.'):
            continue
        c = comps[t['component']]
        if t['designator'] and c['designator'] is None:
            c['designator'] = t['text']
        elif t['comment'] and c['value'] is None:
            c['value'] = t['text']
    for c in comps:
        if c['designator'] is None:
            c['designator'] = c['source']
        elif c['source'] and c['designator'] != c['source']:
            warn('designator-differs', f"component {c['designator']!r} has SOURCEDESIGNATOR {c['source']!r}; its designator text is written")
        if not c['designator']:
            warn('no-designator', f"a component with footprint {c['name']!r} at ({mm(c['x'])}, {mm(c['y'])}) mm has no designator")

    models = {}
    for p in text_records(stream('Models/Data'), 'Models/Data'):
        models.setdefault(prop(p, 'ID'), prop(p, 'NAME'))
    for subs in binary_records(stream('ComponentBodies6/Data'), 1, 12, 'ComponentBodies6/Data'):
        b = body_record(subs)
        if not b or b[0] >= len(comps):
            continue
        name = prop(b[1], 'MODEL.NAME') or models.get(prop(b[1], 'MODELID'), '')
        name = PureWindowsPath(name).name if name else ''
        if name and name not in comps[b[0]]['models']:
            comps[b[0]]['models'].append(name)

    free, skipped, total = [], {}, 0
    for i, subs in enumerate(binary_records(stream('Pads6/Data'), 6, 2, 'Pads6/Data')):
        pad = pad_record(subs, i)
        total += 1
        if pad['component'] != NO_COMPONENT and pad['component'] >= len(comps):
            raise ValueError(f'Pads6/Data record {i} names component {pad["component"]} of {len(comps)}')
        if pad['layer'] not in (TOP, BOTTOM, MULTI) and pad['hole'] <= 0:
            skipped[pad['layer']] = skipped.get(pad['layer'], 0) + 1
            continue
        owner = comps[pad['component']] if pad['component'] != NO_COMPONENT else None
        pad.update(x=pad['x'] - origin[0], y=pad['y'] - origin[1], owner=repr(owner['designator']) if owner else 'no component')
        if pad['mode'] != 0:
            warn('pad-stack', f"pad {pad['name']!r} of {pad['owner']} has a {'top-middle-bottom' if pad['mode'] == 1 else 'full'} pad stack; "
                              "its top layer's shape and size are written")
        (owner['pads'] if owner else free).append(pad)
    if skipped:
        warn('pad-layer', f"{sum(skipped.values())} pads on layers other than top, bottom and multi (Altium layers {', '.join(str(k) for k in sorted(skipped))}) are left out")

    edge = outline(board, origin)
    if not edge:
        warn('no-outline', 'Board6 has no outline vertices; the KiCad file has no Edge.Cuts')
    for c in comps:
        for s in [c['name'], c['designator'], c['value'] or ''] + c['models']:
            if any(ch in s for ch in '"\\\n'):
                warn('escaped', f'{s!r} holds a quote, backslash or line break, which KiCad escapes and names.py and the importer read escaped')
    return {'origin': origin, 'components': comps, 'free': free, 'outline': edge, 'warn': warn,
            'counts': {'components': len(comps), 'pads': sum(len(c['pads']) for c in comps), 'freePads': len(free),
                       'padsLeftOut': sum(skipped.values()), 'padsInFile': total,
                       'bottomComponents': sum(c['bottom'] for c in comps), 'models': sum(len(c['models']) for c in comps)}}


def kicad_text(board):
    """The .kicad_pcb text of a board from read()."""
    warn = board['warn']
    out = ['(kicad_pcb (version 20241229) (generator "pcbdoc.py") (generator_version "1")\n',
           '\t(general (thickness 1.6) (legacy_teardrops no))\n\t(paper "A3")\n\t' + LAYERS + '\n',
           '\t(setup (pad_to_mask_clearance 0))\n\t(net 0 "")\n']
    for s, e, m in board['outline']:
        if m is None:
            out.append(f'\t(gr_line (start {xy(s)}) (end {xy(e)}) (stroke (width {EDGE_WIDTH}) (type solid)) (layer "Edge.Cuts"))\n')
        else:
            out.append(f'\t(gr_arc (start {xy(s)}) (mid {xy(m)}) (end {xy(e)}) (stroke (width {EDGE_WIDTH}) (type solid)) (layer "Edge.Cuts"))\n')
    for c in board['components']:
        pads = [pad_text(p, rotate(p['x'] - c['x'], p['y'] - c['y'], -c['rotation']), warn) for p in c['pads']]
        out.append(footprint_text(c['name'], c['designator'], c['value'] or '', 'B.Cu' if c['bottom'] else 'F.Cu', (c['x'], c['y']), c['rotation'], pads, c['models']))
    for p in board['free']:
        layer = 'B.Cu' if p['layer'] == BOTTOM else 'F.Cu'
        out.append(footprint_text('', '', '', layer, (p['x'], p['y']), Decimal(0), [pad_text(p, (0, 0), warn)], []))
    out.append(')\n')
    return ''.join(out)


def convert(src, out):
    """Write the .kicad_pcb of the PcbDoc `src` to `out`. Returns the report: {source, components,
    pads, freePads, padsLeftOut, padsInFile, bottomComponents, models, outline {found, lines, arcs},
    originMm, warnings}. Raises ValueError when `src` is not a binary PcbDoc or cannot be read."""
    board = read(src)
    text = kicad_text(board)
    Path(out).write_text(text, encoding='utf-8', newline='\n')
    edge = board['outline']
    return {'source': Path(src).name, **board['counts'],
            'outline': {'found': bool(edge), 'lines': sum(m is None for _, _, m in edge), 'arcs': sum(m is not None for _, _, m in edge)},
            'originMm': [float(mm(board['origin'][0])), float(mm(board['origin'][1]))],
            'frame': 'Altium coordinates from the board origin, Y negated',
            'warnings': board['warn'].lines()}


def main(argv):
    args, report = list(argv), None
    if '--report' in args:
        i = args.index('--report')
        report = args[i + 1] if i + 1 < len(args) else None
        del args[i:i + 2]
    if len(args) != 2 or ('--report' in argv and not report):
        print(__doc__.split('\n\n')[-1], file=sys.stderr)
        return 2
    try:
        result = convert(args[0], args[1])
    except ValueError as e:
        print(f'Error: {Path(args[0]).name} could not be read: {e}', file=sys.stderr)
        return 1
    if report:
        Path(report).write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
    print(f"{result['components']} components, {result['pads']} pads, {result['freePads']} free pads, outline "
          f"{'found' if result['outline']['found'] else 'missing'}, {len(result['warnings'])} warnings")
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))