"""AAFInspector's reader: pyaaf2 on one side, a JSON-shaped answer on the other.

This module is the whole Python half of AAFInspector.  It runs unchanged
under CPython and under Pyodide -- nothing here imports a C extension or
assumes a display -- and under Pyodide it runs inside a Web Worker, against a
file mounted with Emscripten's WORKERFS.

It follows AVBrowse's reader.  A tree node is a *handle*, a short string the
page passes back to ask the next question:

    Session(path, name)     open the file (reads the CFB header and FAT only)
    meta()                  file-level facts
    index(progress)         census, mob roots and summaries, referrers
    node(h)                 one object's properties, grouped by declaring class
    children(lens, h)       one node's children in that lens
    search(q)               matching index entries
    subtree(lens, h)        everything under h, for an export
    plain(h)                one object as plain data, for an export
    dump_xml(h)             the strong-reference tree under h as XML

Three handle kinds, all memoised so the same thing always gets the same
string:

    o12   an AAF object, by its CFB storage path -- pyaaf2 stores every
          object as a storage and re-reads it from there on demand
    p7    a collection property (a strong or weak reference vector or set),
          by its owner's path and PID
    c31   a CFB directory entry, for the storage lens
    s4    an object with no storage: a built-in class or type definition
          from pyaaf2's model rather than this file

What makes the worker worth it is that none of this holds the file.  The
bytes stay on disk behind WORKERFS; `_BlockFile` below reads them in 64 KB
blocks through a bounded cache, pyaaf2 keeps at most a few hundred objects
alive, and essence -- which is nearly all of a large AAF -- is never read at
all, only measured.

Values are formatted here and shipped as display strings.  Turning an AUID
into a SMPTE UL, a MobID into a UMID, a frame count into timecode, are claims
about the format, and claims live on this side of the wall.
"""

from __future__ import (
    unicode_literals,
    absolute_import,
    print_function,
    division,
    )

import io
import json
import re
import struct
import datetime
from collections import OrderedDict

import aaf2
import aaf2.file
from aaf2 import properties as _props
from aaf2.mobid import MobID
from aaf2.auid import AUID
from aaf2.rational import AAFRational

MODEL_VERSION = 1

try:
    unicode
except NameError:                                    # pragma: no cover - py3
    unicode = str


# ------------------------------------------------------------ file access

class _BlockFile(io.RawIOBase):
    """A read-only file that reads in fixed blocks through a bounded LRU.

    pyaaf2 reads a CFB the way any CFB reader does: a sector here, a 64-byte
    directory entry there, a properties stream assembled from mini-stream
    sectors scattered across the file.  Under WORKERFS every one of those is
    a `FileReaderSync` call into the browser, and a few hundred thousand tiny
    calls cost more than the reading.  So the file is read in 64 KB blocks,
    and the most recent 128 of them (8 MB) are kept.  AAF metadata clusters
    -- the directory, the FAT and the mini stream sit in a few runs of
    sectors -- so the hit rate is high and the resident set stays flat no
    matter how big the essence makes the file.
    """

    BLOCK = 64 * 1024
    KEEP = 128

    def __init__(self, path):
        io.RawIOBase.__init__(self)
        self._raw = io.open(path, 'rb', buffering=0)
        self._raw.seek(0, io.SEEK_END)
        self.size = self._raw.tell()
        self._pos = 0
        self._blocks = OrderedDict()
        self.bytes_read = 0
        self.block_reads = 0
        self.calls = 0

    def readable(self):
        return True

    def seekable(self):
        return True

    def writable(self):
        return False

    def tell(self):
        return self._pos

    def seek(self, offset, whence=io.SEEK_SET):
        if whence == io.SEEK_SET:
            self._pos = offset
        elif whence == io.SEEK_CUR:
            self._pos += offset
        else:
            self._pos = self.size + offset
        return self._pos

    def _block(self, n):
        b = self._blocks.get(n)
        if b is not None:
            self._blocks.move_to_end(n)
            return b
        self._raw.seek(n * self.BLOCK)
        b = self._raw.read(self.BLOCK) or b''
        self.bytes_read += len(b)
        self.block_reads += 1
        self._blocks[n] = b
        if len(self._blocks) > self.KEEP:
            self._blocks.popitem(last=False)
        return b

    def read(self, n=-1):
        self.calls += 1
        if n is None or n < 0:
            n = self.size - self._pos
        n = max(0, min(n, self.size - self._pos))
        if n == 0:
            return b''
        out = []
        pos, end = self._pos, self._pos + n
        while pos < end:
            blk, off = divmod(pos, self.BLOCK)
            data = self._block(blk)
            take = data[off:off + (end - pos)]
            if not take:
                break
            out.append(take)
            pos += len(take)
        self._pos = pos
        return b''.join(out)

    def readinto(self, buf):
        data = self.read(len(buf))
        buf[:len(data)] = data
        return len(data)

    def close(self):
        if not self.closed:
            self._blocks.clear()
            self._raw.close()
        io.RawIOBase.close(self)


class _IOShim(object):
    """`aaf2.file.AAFFile` opens its file with `io.open(path, ...)` and has
    no way to be handed a file object instead.  For the length of one
    constructor call, its module-level `io` is this, so the file it opens is
    a `_BlockFile`."""

    DEFAULT_BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE

    def __init__(self):
        self.opened = None

    def open(self, path, mode='rb', buffering=None):
        if 'w' in mode or '+' in mode:
            raise IOError('AAFInspector opens files read-only')
        self.opened = _BlockFile(path)
        return self.opened

    def __getattr__(self, name):
        return getattr(io, name)


def _open_aaf(path):
    shim = _IOShim()
    saved = aaf2.file.io
    aaf2.file.io = shim
    try:
        f = aaf2.file.AAFFile(path, 'r')
    finally:
        aaf2.file.io = saved
    return f, shim.opened


# ------------------------------------------------------------- formatting

_TEXT_CAP = 300
_PEEK = 16
_LIST_CAP = 24

_SF_NAMES = {
    0x82: 'Data', 0x42: 'DataStream', 0x22: 'StrongRef',
    0x32: 'StrongRefVector', 0x3A: 'StrongRefSet', 0x02: 'WeakRef',
    0x12: 'WeakRefVector', 0x1A: 'WeakRefSet',
    0x03: 'WeakRefStoredObjectID', 0x86: 'UniqueObjectID',
    0x40: 'OpaqueStream', 0xD2: 'DataVector', 0xDA: 'DataSet',
}

_StrongRef = _props.StrongRefProperty
_StrongVec = _props.StrongRefVectorProperty
_StrongSet = _props.StrongRefSetProperty
_WeakRef = _props.WeakRefProperty
_WeakArr = getattr(_props, 'WeakRefArrayProperty', ())
_Stream = _props.StreamProperty
_COLLECTIONS = tuple(c for c in (_StrongVec, _StrongSet, _WeakArr) if c)


def human(n):
    units = ['bytes', 'KB', 'MB', 'GB', 'TB']
    i = 0
    n = float(n)
    while n >= 1024 and i < len(units) - 1:
        n /= 1024
        i += 1
    return ('%d %s' % (n, units[i])) if i == 0 else ('%.1f %s' % (n, units[i]))


def auid_text(auid):
    """An AUID as the string a person would look it up by.

    An AUID whose last eight bytes start 06.0e.2b.34 is a SMPTE Universal
    Label stored the AAF way, with its halves swapped so it fits the UUID
    layout.  Swapped back and printed in dotted 32-bit groups it is the UL
    as SMPTE registers it -- `urn:smpte:ul:060e2b34.01010101.0d010101...`,
    which is what goes into a registry search.  Anything else is a UUID.
    """
    h = '%032x' % auid.int
    if h[16:24] == '060e2b34':
        ul = h[16:32] + h[0:16]
        return 'urn:smpte:ul:' + '.'.join(ul[i:i + 8] for i in range(0, 32, 8))
    return 'urn:uuid:%s-%s-%s-%s-%s' % (h[:8], h[8:12], h[12:16], h[16:20],
                                       h[20:])


def mobid_text(mobid):
    return mobid.urn


def _is_zero_mobid(mobid):
    try:
        return int(mobid) == 0
    except Exception:
        return False


def timecode(frames, fps, drop=False):
    """Frame count -> HH:MM:SS:FF, or HH:MM:SS;FF for drop-frame.

    Drop-frame is SMPTE 12M's: two frame numbers (four at 59.94) skipped at
    the start of every minute except each tenth.  Frame counts in an AAF
    are always non-drop counts; drop is a property of how they are shown.
    """
    try:
        frames = int(frames)
        fps = int(round(float(fps)))
    except Exception:
        return ''
    if fps <= 0:
        return ''
    neg = frames < 0
    frames = abs(frames)
    sep = ':'
    if drop and fps in (30, 60):
        sep = ';'
        d = 2 if fps == 30 else 4
        per10 = fps * 600 - d * 9
        per1 = fps * 60 - d
        tens, rem = divmod(frames, per10)
        if rem > d:
            frames += d * 9 * tens + d * ((rem - d) // per1)
        else:
            frames += d * 9 * tens
    ff = frames % fps
    s = frames // fps
    out = '%02d:%02d:%02d%s%02d' % (s // 3600, (s // 60) % 60, s % 60, sep, ff)
    return '-' + out if neg else out


def _cap(text):
    if len(text) > _TEXT_CAP:
        return text[:_TEXT_CAP] + '…', text
    return text, None


def _hex(data, limit=_PEEK):
    b = bytes(data[:limit])
    s = ' '.join('%02x' % c for c in bytearray(b))
    return s + (' …' if len(data) > limit else '')


def pretty(value, typedef=None):
    """-> (kind, display, full-or-None, note-or-None)."""
    if value is None:
        return 'empty', '', None, None
    if isinstance(value, bool):
        return 'bool', 'True' if value else 'False', None, None
    if isinstance(value, MobID):
        return 'id', mobid_text(value), None, None
    if isinstance(value, AUID):
        return 'id', auid_text(value), None, None
    if isinstance(value, AAFRational):
        num, den = value.numerator, value.denominator
        note = None
        if den:
            f = num / den
            note = ('= %g' % f) if den != 1 else None
        return 'rational', '%d/%d' % (num, den), None, note
    if isinstance(value, (int, float)):
        kind = 'enum' if _is_enum(typedef) else 'num'
        return kind, unicode(value), None, None
    if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
        return 'time', value.isoformat(), None, None
    if isinstance(value, (bytes, bytearray)):
        return 'bytes', _hex(value), ' '.join(
            '%02x' % c for c in bytearray(value[:65536])), '%d bytes' % len(value)
    if isinstance(value, (str, unicode)):
        kind = 'enum' if _is_enum(typedef) else 'str'
        text = value.replace('\x00', '')
        shown, full = _cap(text)
        return kind, shown, full, None
    if isinstance(value, dict):
        parts = []
        for k, v in value.items():
            parts.append('%s: %s' % (k, pretty(v)[1]))
        shown, full = _cap(', '.join(parts))
        return 'record', shown, full, None
    if isinstance(value, (list, tuple, set)):
        items = list(value)
        shown_items = [pretty(v)[1] for v in items[:_LIST_CAP]]
        text = '[' + ', '.join(shown_items) + (', …' if len(items) > _LIST_CAP else '') + ']'
        full = None
        if len(items) > _LIST_CAP:
            full = '[' + ', '.join(pretty(v)[1] for v in items[:4096]) + ']'
        shown, capped = _cap(text)
        return 'array', shown, full or capped, '%d items' % len(items)
    if hasattr(value, 'classdef'):
        return 'object', _class_name(value), None, None
    text = unicode(value)
    shown, full = _cap(text)
    return 'other', shown, full, None


def _is_enum(typedef):
    if typedef is None:
        return False
    n = type(typedef).__name__
    return n in ('TypeDefEnum', 'TypeDefExtEnum')


def _class_name(obj):
    try:
        cd = obj.classdef
        if cd is not None:
            return cd.class_name
    except Exception:
        pass
    return type(obj).__name__


def _type_name(p):
    try:
        td = p.typedef
        if td is not None:
            return td.type_name
    except Exception:
        pass
    return ''


def _prop_name(p):
    try:
        n = p.name
        if n:
            return n
    except Exception:
        pass
    return 'pid 0x%04x' % p.pid


def _safe(fn, default=None):
    try:
        return fn()
    except Exception:
        return default


def _get(obj, name):
    """A property's decoded value, or None -- without the KeyError, and
    without consulting `allkeys`, which would conjure an empty optional
    property out of the class definition."""
    for p in obj.properties():
        if _prop_name(p) == name:
            try:
                return p.value
            except Exception:
                return None
    return None


# ------------------------------------------------------------- media kinds

_KIND_SHORT = [
    ('picture', 'V'), ('matte', 'V'), ('sound', 'A'), ('timecode', 'TC'),
    ('edgecode', 'EC'), ('descriptive', 'DM'), ('auxiliary', 'AUX'),
]


def _media_kind(obj):
    """The short name of an object's data definition: Picture, Sound."""
    dd = _safe(lambda: obj['DataDefinition'].value)
    if dd is None:
        seg = _safe(lambda: obj['Segment'].value)
        if seg is not None:
            dd = _safe(lambda: seg['DataDefinition'].value)
    if dd is None:
        return ''
    name = _safe(lambda: dd.short_name) or _safe(lambda: dd.name) or ''
    return name


def _kind_letter(kind):
    k = (kind or '').lower()
    for key, letter in _KIND_SHORT:
        if key in k:
            return letter
    return 'D' if k else '?'


def _ranges(nums):
    nums = sorted(set(nums))
    out = []
    i = 0
    while i < len(nums):
        j = i
        while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1:
            j += 1
        out.append(str(nums[i]) if i == j else '%d-%d' % (nums[i], nums[j]))
        i = j + 1
    return ','.join(out)


# ------------------------------------------------------------------ session

class Session(object):

    def __init__(self, path, name='file.aaf'):
        self.path = path
        self.name = name
        self.f, self.io = _open_aaf(path)
        self._h2key = {}
        self._key2h = {}
        self._synthetic = {}
        self._n = 0
        self._indexed = False
        self._mobs = OrderedDict()       # handle -> summary
        self._mob_by_urn = {}            # urn -> handle
        self._roots = OrderedDict()
        self._census = {}
        self._census_ext = {}
        self._by_class = {}
        self._referrers = {}             # mob handle -> [clip handles]
        self._essence = {}               # mob urn -> {handle, size}
        self._pidmap = {}                # class auid hex -> {pid: class name}
        self._defnames = None
        self._slotnums = {}

    # ---------------------------------------------------------- handles
    def _handle(self, key):
        h = self._key2h.get(key)
        if h is None:
            self._n += 1
            h = key[0] + str(self._n)
            self._key2h[key] = h
            self._h2key[h] = key
        return h

    def handle_of(self, obj):
        if obj is None:
            return None
        d = getattr(obj, 'dir', None)
        if d is not None:
            return self._handle(('o', d.path()))
        key = ('s', id(obj))
        h = self._handle(key)
        self._synthetic[h] = obj         # built-in definitions; they live anyway
        return h

    def coll_handle(self, owner, prop):
        if owner.dir is None:
            return None
        return self._handle(('p', owner.dir.path(), prop.pid))

    def entry_handle(self, entry):
        return self._handle(('c', entry.path()))

    def resolve(self, handle):
        """handle -> ('o', obj) | ('p', (owner, prop)) | ('c', entry) | None"""
        key = self._h2key.get(handle)
        if key is None:
            return None
        kind = key[0]
        if kind == 'o':
            if key[1] == '/':
                return 'o', self.f.root
            return 'o', self.f.manager.read_object(key[1])
        if kind == 's':
            return 'o', self._synthetic.get(handle)
        if kind == 'p':
            owner = self.f.manager.read_object(key[1]) if key[1] != '/' else self.f.root
            prop = owner.property_entries.get(key[2])
            return 'p', (owner, prop)
        if kind == 'c':
            entry = self.f.cfb.find(key[1]) if key[1] != '/' else self.f.cfb.root
            return 'c', entry
        return None

    def _obj(self, handle):
        r = self.resolve(handle)
        if r and r[0] == 'o':
            return r[1]
        if r and r[0] == 'c':
            return self._entry_object(r[1])
        return None

    def _entry_object(self, entry):
        if entry is None or not entry.isdir():
            return None
        if entry.isroot():
            return self.f.root
        try:
            return self.f.manager.read_object(entry)
        except Exception:
            return None

    # ------------------------------------------------------------- meta
    def meta(self):
        cfb = self.f.cfb
        header = self.f.header
        ident = None
        idents = _safe(lambda: list(header['IdentificationList'].value), [])
        if idents:
            ident = idents[-1]
        out = {
            'name': self.name,
            'size': self.io.size,
            'cfbVersion': _safe(lambda: cfb.major_version, 0) or 0,
            'sectorSize': _safe(lambda: cfb.sector_size, 0),
            'rootHandle': self.handle_of(self.f.root),
            'headerHandle': self.handle_of(header),
            'storageRoot': self.entry_handle(cfb.root),
            'pyaaf2': getattr(aaf2, '__version__', ''),
            'model': MODEL_VERSION,
        }
        ver = _get(header, 'Version')
        if ver is not None:
            out['version'] = pretty(ver)[1]
        out['objectModelVersion'] = _safe(lambda: unicode(_get(header, 'ObjectModelVersion')), '')
        lm = _get(header, 'LastModified')
        if lm is not None:
            out['lastModified'] = pretty(lm)[1]
        op = _get(header, 'OperationalPattern')
        if op is not None:
            out['operationalPattern'] = self._def_name(op) or auid_text(op)
        if ident is not None:
            company = _get(ident, 'CompanyName') or ''
            product = _get(ident, 'ProductName') or ''
            pver = _get(ident, 'ProductVersionString') or ''
            out['creator'] = ' '.join(x for x in (company, product, pver) if x)
            out['platform'] = _get(ident, 'Platform') or ''
        return out

    def stats(self):
        return {
            'bytesRead': self.io.bytes_read,
            'blockReads': self.io.block_reads,
            'calls': self.io.calls,
            'cachedBlocks': len(self.io._blocks),
            'cachedBytes': sum(len(b) for b in self.io._blocks.values()),
            'liveObjects': len(self.f.manager.path_cache),
            'handles': len(self._h2key),
        }

    # ------------------------------------------------------- definitions
    def _def_name(self, auid):
        """An AUID -> the name of the definition it identifies, if this file
        or pyaaf2's model defines one.  Data definitions, containers,
        codecs, operations, parameters, interpolations, classes, types."""
        if self._defnames is None:
            names = {}
            d = self.f.dictionary
            for key in ('DataDefinitions', 'ContainerDefinitions',
                        'CodecDefinitions', 'OperationDefinitions',
                        'ParameterDefinitions', 'InterpolationDefinitions',
                        'TaggedValueDefinitions', 'PluginDefinitions',
                        'KLVDataDefinitions'):
                p = _safe(lambda: d[key])
                if p is None:
                    continue
                for obj in _safe(lambda: list(p.values()), []) or []:
                    a = _safe(lambda: obj.auid)
                    n = _safe(lambda: obj.name)
                    if a is not None and n:
                        names[a.int] = n
            md = self.f.metadict
            for a, cd in _safe(lambda: list(md.classdefs_by_auid.items()), []) or []:
                names.setdefault(a.int, cd.class_name)
            for a, td in _safe(lambda: list(md.typedefs_by_auid.items()), []) or []:
                names.setdefault(a.int, _safe(lambda: td.type_name, ''))
            self._defnames = names
        try:
            return self._defnames.get(auid.int)
        except Exception:
            return None

    # ------------------------------------------------------------ labels
    def label(self, obj):
        """What an object is called, if it is called anything."""
        if obj is None:
            return ''
        cls = _class_name(obj)
        try:
            if cls in ('ClassDefinition',):
                return obj.class_name
            if cls.startswith('TypeDefinition'):
                return obj.type_name
            if cls == 'PropertyDefinition':
                return obj.property_name
        except Exception:
            pass
        name = None
        for key in ('Name', 'SlotName', 'URLString', 'ProductName'):
            v = _get(obj, key)
            if v:
                name = v
                break
        if cls.endswith('MobSlot') or cls == 'MobSlot':
            short = self._slot_short(obj)
            return short + (' · ' + name if name and name != short else '')
        if name:
            return unicode(name)
        return ''

    def _slot_short(self, slot):
        """`A2`: the media kind's letter and the track number.  The number
        is PhysicalTrackNumber when the slot has one, which is what Media
        Composer writes; otherwise the slot's place among the slots of its
        kind in its mob, which is how the Tracks column counts them too."""
        letter = _kind_letter(_media_kind(slot))
        n = _get(slot, 'PhysicalTrackNumber')
        if n is None:
            n = self._slot_numbers(slot).get(slot.dir.path() if slot.dir else None)
        if n is None:
            n = _get(slot, 'SlotID')
        return '%s%s' % (letter, n if n is not None else '')

    def _slot_numbers(self, slot):
        d = slot.dir
        if d is None or d.parent is None:
            return {}
        key = d.parent.path()
        got = self._slotnums.get(key)
        if got is None:
            got = {}
            mob = self._entry_object(d.parent)
            counters = {}
            for s in _safe(lambda: list(mob['Slots']), []) or [] if mob is not None else []:
                letter = _kind_letter(_media_kind(s))
                counters[letter] = counters.get(letter, 0) + 1
                if s.dir is not None:
                    got[s.dir.path()] = counters[letter]
            self._slotnums[key] = got
        return got

    def summary(self, obj):
        """One line about an object for the tree's value column: a clip's
        length and start, a timecode's start as timecode, a descriptor's
        format.  Empty for anything that has nothing short to say."""
        cls = _class_name(obj)
        g = lambda k: _get(obj, k)
        try:
            if cls == 'Timecode':
                return '%s · %s fps%s' % (
                    timecode(g('Start') or 0, g('FPS') or 0, g('Drop')),
                    g('FPS'), ' DF' if g('Drop') else '')
            if cls in ('SourceClip',):
                return 'len %s · start %s' % (g('Length'), g('StartTime'))
            if cls == 'Sequence':
                comps = _safe(lambda: len(obj['Components']), 0)
                return '%d components · len %s' % (comps, g('Length'))
            if cls == 'Transition':
                return 'len %s · cut %s' % (g('Length'), g('CutPoint'))
            if cls == 'OperationGroup':
                op = g('Operation')
                n = _safe(lambda: op.name) if op is not None else ''
                return '%s · len %s' % (n or 'operation', g('Length'))
            if cls == 'TaggedValue':
                return '= ' + pretty(g('Value'))[1]
            if cls == 'EssenceData':
                s = self._essence_size(obj)
                return human(s) if s is not None else ''
            if cls == 'PCMDescriptor' or cls == 'WAVEDescriptor' or cls == 'AIFCDescriptor':
                rate = g('AudioSamplingRate')
                return '%s Hz · %s ch · %s-bit' % (
                    pretty(rate)[1].split('/')[0] if rate is not None else '?',
                    g('Channels'), g('QuantizationBits'))
            if cls in ('CDCIDescriptor', 'RGBADescriptor', 'DigitalImageDescriptor'):
                return '%s×%s · %s' % (g('StoredWidth'), g('StoredHeight'),
                                               g('FrameLayout') or '')
            if 'MobSlot' in cls:
                er = g('EditRate')
                return ('@ ' + pretty(er)[1]) if er is not None else ''
            if g('Length') is not None and cls not in ('MasterMob', 'CompositionMob', 'SourceMob'):
                return 'len %s' % g('Length')
        except Exception:
            return ''
        return ''

    # -------------------------------------------------------------- index
    def index(self, progress=None):
        """One walk of the strong-reference tree under the Header.

        Each object is read, counted and let go: pyaaf2 holds objects
        through weak references and a 512-entry LRU, so what stays resident
        is the summaries, not the graph.  The walk is what lets search, the
        class census, the mob groups and the referrer counts be answered
        without a second pass.  EssenceData's data stream is a stream, not
        a strong reference, so the walk never touches essence.
        """
        if self._indexed:
            return self._index_answer()
        content = self.f.content
        mobs = _safe(lambda: list(content['Mobs'].references.keys()), []) or []
        total = len(mobs)
        done = [0]

        def tick(force=False):
            done[0] += 1
            if progress is not None and (force or done[0] % 25 == 0):
                try:
                    progress(done[0], total)
                except Exception:
                    pass

        # essence data first: which mobs have their essence in this file
        for ed in _safe(lambda: list(content['EssenceData'].values()), []) or []:
            mid = _get(ed, 'MobID')
            if mid is None:
                continue
            self._essence[mid.urn] = {'handle': self.handle_of(ed),
                                      'size': self._essence_size(ed)}
            self._count(ed)

        for mob in content['Mobs'].values():
            h = self.handle_of(mob)
            s = self._mob_summary(mob, h)
            self._mobs[h] = s
            if s['mobId']:
                self._mob_by_urn[s['mobId']] = h
            self._walk(mob, h, 0)
            tick()
        tick(True)

        # the rest of the Header: dictionary, identification list
        header = self.f.header
        self._count(header)
        self._count(content)
        for key in ('Dictionary', 'IdentificationList'):
            p = _safe(lambda: header[key])
            if p is None:
                continue
            for obj in self._strong_values(p):
                self._walk(obj, None, 0)

        # referrers: by mob, from every SourceReference that names one
        refs = {}
        for target_urn, clips in self._pending_refs.items():
            th = self._mob_by_urn.get(target_urn)
            if th:
                refs[th] = clips
        self._referrers = refs
        del self._pending_refs

        for kind in ('toplevel', 'composition', 'master', 'file', 'physical', 'other'):
            self._roots[kind] = [h for h, s in self._mobs.items() if s['kind'] == kind]
        self._indexed = True
        return self._index_answer()

    _pending_refs = None

    def _count(self, obj):
        cls = _class_name(obj)
        self._census[cls] = self._census.get(cls, 0) + 1
        if cls not in self._census_ext:
            cd = _safe(lambda: obj.classdef)
            self._census_ext[cls] = bool(cd is not None and getattr(cd, 'dir', None) is not None)
        lst = self._by_class.setdefault(cls.lower(), [])
        if len(lst) < 5000:
            lst.append(self.handle_of(obj))

    def _strong_values(self, p):
        if isinstance(p, _StrongRef):
            v = _safe(lambda: p.value)
            return [v] if v is not None else []
        if isinstance(p, (_StrongVec, _StrongSet)):
            return [v for v in _safe(lambda: list(p.values() if isinstance(p, _StrongSet) else p), []) or [] if v is not None]
        return []

    def _walk(self, obj, mob_handle, depth):
        if self._pending_refs is None:
            self._pending_refs = {}
        self._count(obj)
        if depth > 200:
            return
        sid = None
        for p in list(obj.properties()):
            if isinstance(p, (_StrongRef, _StrongVec, _StrongSet)):
                for child in self._strong_values(p):
                    self._walk(child, mob_handle, depth + 1)
            elif _prop_name(p) == 'SourceID':
                sid = _safe(lambda: p.value)
        if sid is not None and not _is_zero_mobid(sid):
            self._pending_refs.setdefault(sid.urn, []).append(self.handle_of(obj))

    def _mob_kind(self, mob):
        cls = _class_name(mob)
        if cls == 'CompositionMob':
            usage = _get(mob, 'UsageCode')
            return 'toplevel' if usage and 'TopLevel' in unicode(usage) else 'composition'
        if cls == 'MasterMob':
            return 'master'
        if cls == 'SourceMob':
            desc = _safe(lambda: mob['EssenceDescription'].value)
            if desc is None:
                return 'other'
            md = self.f.metadict
            fd = _safe(lambda: md.lookup_classdef('FileDescriptor'))
            if fd is not None and _safe(lambda: fd.isinstance(desc.classdef)):
                return 'file'
            return 'physical'
        return 'other'

    def _mob_summary(self, mob, h):
        mid = _get(mob, 'MobID')
        urn = mid.urn if mid is not None else ''
        desc = _safe(lambda: mob['EssenceDescription'].value) if _class_name(mob) == 'SourceMob' else None
        ess = self._essence.get(urn)
        return {
            'handle': h,
            'kind': self._mob_kind(mob),
            'cls': _class_name(mob),
            'name': _get(mob, 'Name') or '',
            'mobId': urn,
            'tracks': self._tracks(mob),
            'usage': unicode(_get(mob, 'UsageCode') or ''),
            'desc': _class_name(desc) if desc is not None else '',
            'essence': ess['size'] if ess else None,
            'essenceHandle': ess['handle'] if ess else None,
        }

    def _tracks(self, mob):
        """`V1 A1-4 TC1`: the slots of a mob in the shorthand an editor
        reads a timeline by, consecutive numbers collapsed to a range."""
        by = OrderedDict()
        counters = {}
        for slot in _safe(lambda: list(mob['Slots']), []) or []:
            letter = _kind_letter(_media_kind(slot))
            n = _get(slot, 'PhysicalTrackNumber')
            if n is None:
                counters[letter] = counters.get(letter, 0) + 1
                n = counters[letter]
            by.setdefault(letter, []).append(int(n))
        order = ['V', 'A', 'TC', 'EC', 'DM', 'AUX', 'D', '?']
        parts = []
        for letter in sorted(by, key=lambda k: order.index(k) if k in order else 99):
            parts.append(letter + _ranges(by[letter]))
        return ' '.join(parts)

    def _essence_size(self, ed):
        p = None
        for q in ed.properties():
            if isinstance(q, _Stream):
                p = q
                break
        if p is None:
            return None
        entry = _safe(lambda: p.value)
        return entry.byte_size if entry is not None else None

    def _index_answer(self):
        return {
            'mobs': self._mobs,
            'roots': self._roots,
            'census': self._census,
            'censusExt': self._census_ext,
            'referrers': dict((h, len(v)) for h, v in self._referrers.items()),
            'essenceTotal': sum((e['size'] or 0) for e in self._essence.values()),
            'essenceCount': len(self._essence),
        }

    # --------------------------------------------------------------- node
    def _pid_owner(self, obj):
        """pid -> the class in the chain that declares it.  pyaaf2 walks
        `relatives()` from the class itself to InterchangeObject; the grid
        groups root-first, so the inheritance reads top-down."""
        cd = obj.classdef
        if cd is None:
            return {}, []
        key = cd.auid.int
        got = self._pidmap.get(key)
        if got is not None:
            return got
        owner = {}
        chain = []
        for c in _safe(lambda: list(cd.relatives()), [cd]) or [cd]:
            chain.append(c.class_name)
            for pd in _safe(lambda: list(c.propertydefs), []) or []:
                owner.setdefault(pd.pid, c.class_name)
        chain.reverse()
        self._pidmap[key] = (owner, chain)
        return owner, chain

    def _row(self, obj, p):
        name = _prop_name(p)
        row = {'n': name, 'pid': '0x%04x' % p.pid,
               't': _type_name(p), 'sf': _SF_NAMES.get(p.format, '0x%02x' % p.format)}
        try:
            if isinstance(p, _StrongRef):
                child = p.value
                row.update(k='object', v=_class_name(child) if child is not None else '(missing)',
                           ref=self.handle_of(child))
                lab = self.label(child) if child is not None else ''
                if lab:
                    row['refLabel'] = lab
            elif isinstance(p, _COLLECTIONS):
                n = len(p)
                word = 'set' if isinstance(p, _StrongSet) else 'vector'
                if _WeakArr and isinstance(p, _WeakArr):
                    word = 'weak refs'
                row.update(k='list', v='%s (%d)' % (word, n),
                           ref=self.coll_handle(obj, p) if n else None)
            elif isinstance(p, _WeakRef):
                target = p.value
                ref_key = getattr(p, 'ref', None)
                lab = self.label(target) if target is not None else ''
                row.update(k='weak', v=lab or (_class_name(target) if target is not None else '(unresolved)'),
                           ref=self.handle_of(target) if target is not None else None)
                if ref_key is not None:
                    row['note'] = auid_text(ref_key) if isinstance(ref_key, AUID) else unicode(ref_key)
            elif isinstance(p, _Stream):
                entry = p.value
                size = entry.byte_size if entry is not None else 0
                row.update(k='stream', v=human(size),
                           note=getattr(p, 'stream_name', '') or None,
                           ref=self.entry_handle(entry) if entry is not None else None)
            else:
                value = p.value
                kind, shown, full, note = pretty(value, _safe(lambda: p.typedef))
                row.update(k=kind, v=shown)
                if full:
                    row['full'] = full
                if note:
                    row['note'] = note
                tn = row['t']
                if tn == 'Indirect' or tn == 'Opaque':
                    inner = _safe(lambda: p.typedef.decode_typedef(p.data))
                    if inner is not None:
                        row['t'] = '%s → %s' % (tn, inner.type_name)
                if isinstance(value, AUID):
                    dn = self._def_name(value)
                    if dn:
                        row['note'] = dn
                if isinstance(value, MobID) and name in ('SourceID', 'MobID') \
                        and not _is_zero_mobid(value):
                    th = self._mob_by_urn.get(value.urn)
                    own = getattr(obj, 'dir', None) is not None and self.handle_of(obj) == th
                    if th and not own:
                        row['ref'] = th
                        row['refLabel'] = self._mobs[th]['name'] or 'mob'
                    elif not th and name == 'SourceID':
                        row['note'] = 'not in this file'
                if name == 'SourceMobSlotID':
                    slot = self._target_slot(obj)
                    if slot is not None:
                        row['ref'] = self.handle_of(slot)
                        row['refLabel'] = self.label(slot)
                if name == 'ByteOrder' and value in (0x4949, 0x4d4d):
                    row['note'] = 'little-endian (II)' if value == 0x4949 else 'big-endian (MM)'
                if name in ('Start', 'StartTime') and _class_name(obj) == 'Timecode':
                    row['note'] = timecode(value, _get(obj, 'FPS') or 0, _get(obj, 'Drop'))
        except Exception as e:
            row.update(k='error', v='cannot decode: %s' % (e,),
                       note=_hex(p.data or b'') if isinstance(p.data, (bytes, bytearray)) else None)
        return row

    def node(self, handle):
        r = self.resolve(handle)
        if r is None:
            return None
        if r[0] == 'c':
            entry = r[1]
            obj = self._entry_object(entry)
            if obj is None:
                return self._entry_node(handle, entry)
            out = self._object_node(self.handle_of(obj), obj)
            out['handle'] = handle
            out['objectHandle'] = self.handle_of(obj)
            return out
        if r[0] == 'p':
            owner, prop = r[1]
            return {
                'handle': handle, 'cls': '', 'py': 'property',
                'label': _prop_name(prop) if prop is not None else '',
                'groups': [{'name': 'Collection', 'rows': [
                    {'n': 'owner', 'k': 'object', 'v': _class_name(owner),
                     'ref': self.handle_of(owner), 'refLabel': self.label(owner)},
                    {'n': 'property', 'k': 'str', 'v': _prop_name(prop) if prop else ''},
                    {'n': 'pid', 'k': 'num', 'v': '0x%04x' % prop.pid if prop else ''},
                    {'n': 'type', 'k': 'str', 'v': _type_name(prop) if prop else ''},
                    {'n': 'count', 'k': 'num', 'v': unicode(len(prop)) if prop else '0'},
                ]}],
            }
        return self._object_node(handle, r[1])

    def _object_node(self, handle, obj):
        if obj is None:
            return None
        owner, chain = self._pid_owner(obj)
        groups = OrderedDict((c, []) for c in chain)
        extra = []
        for p in obj.properties():
            row = self._row(obj, p)
            g = owner.get(p.pid)
            if g is None:
                extra.append(row)
            else:
                groups[g].append(row)
        out_groups = [{'name': k, 'rows': v} for k, v in groups.items() if v]
        if extra:
            out_groups.append({'name': 'Not in the class definition', 'rows': extra})
        d = getattr(obj, 'dir', None)
        if d is not None:
            out_groups.append({'name': 'Storage', 'storage': True,
                               'rows': self._entry_rows(d, short=True)})
        cd = obj.classdef
        out = {
            'handle': handle,
            'cls': _class_name(obj),
            'py': type(obj).__name__,
            'label': self.label(obj),
            'classId': auid_text(cd.auid) if cd is not None else '',
            'path': d.path() if d is not None else '',
            'groups': out_groups,
        }
        mob = self._mobs.get(handle)
        if mob:
            out['mob'] = mob
        return out

    def _entry_rows(self, entry, short=False):
        rows = [
            {'n': 'path', 'k': 'str', 'v': entry.path()},
            {'n': 'type', 'k': 'enum', 'v': entry.type},
        ]
        cid = _safe(lambda: entry.class_id)
        if cid is not None and entry.isdir():
            nm = self._def_name(cid)
            rows.append({'n': 'CLSID', 'k': 'id', 'v': auid_text(cid),
                         'note': nm or None})
        if not short:
            rows.append({'n': 'size', 'k': 'num', 'v': unicode(entry.byte_size),
                         'note': human(entry.byte_size)})
            cutoff = _safe(lambda: self.f.cfb.min_stream_max_size, 4096) or 4096
            if entry.isfile():
                rows.append({'n': 'stored in', 'k': 'enum',
                             'v': 'mini stream' if entry.byte_size < cutoff else 'FAT sectors'})
            rows.append({'n': 'start sector', 'k': 'num',
                         'v': unicode(entry.sector_id) if entry.sector_id is not None else ''})
            rows.append({'n': 'directory id', 'k': 'num', 'v': unicode(entry.dir_id)})
        else:
            stream = _safe(lambda: entry.get('properties'))
            if stream is not None:
                rows.append({'n': 'properties stream', 'k': 'stream',
                             'v': human(stream.byte_size),
                             'ref': self.entry_handle(stream)})
            rows.append({'n': 'directory id', 'k': 'num', 'v': unicode(entry.dir_id)})
            rows.append({'n': 'storage', 'k': 'str', 'v': 'show in storage lens',
                         'ref': self.entry_handle(entry)})
        return rows

    def _entry_node(self, handle, entry):
        if entry is None:
            return None
        groups = [{'name': 'Directory entry', 'rows': self._entry_rows(entry)}]
        if entry.isfile():
            parent_obj = self._entry_object(entry.parent) if entry.parent is not None else None
            if parent_obj is not None:
                groups[0]['rows'].insert(0, {
                    'n': 'owner', 'k': 'object', 'v': _class_name(parent_obj),
                    'ref': self.handle_of(parent_obj), 'refLabel': self.label(parent_obj)})
            if entry.name == 'properties':
                groups.append(self._properties_table(entry, parent_obj))
            elif entry.name.endswith(' index'):
                groups.append(self._index_table(entry))
            if entry.byte_size:
                peek = _safe(lambda: entry.open('r').read(64), b'') or b''
                groups.append({'name': 'First %d bytes' % len(peek), 'rows': [
                    {'n': '%04x' % i, 'k': 'bytes',
                     'v': ' '.join('%02x' % c for c in bytearray(peek[i:i + 16])),
                     'note': ''.join(chr(c) if 32 <= c < 127 else '.'
                                     for c in bytearray(peek[i:i + 16]))}
                    for i in range(0, len(peek), 16)]})
        return {'handle': handle, 'cls': '', 'py': entry.type,
                'label': entry.name, 'path': entry.path(), 'groups': groups}

    def _properties_table(self, entry, owner):
        """The header of a properties stream, entry by entry: what is on
        disk before pyaaf2 decodes any of it."""
        rows = []
        try:
            data = entry.open('r').read()
            bo, ver, count = struct.unpack('<BBH', data[:4])
            rows.append({'n': 'byte order', 'k': 'enum',
                         'v': 'little-endian' if bo == 0x4c else '0x%02x' % bo})
            rows.append({'n': 'version', 'k': 'num', 'v': unicode(ver)})
            rows.append({'n': 'entries', 'k': 'num', 'v': unicode(count)})
            off = 4 + 6 * count
            names = {}
            if owner is not None:
                for p in owner.properties():
                    names[p.pid] = _prop_name(p)
            for i in range(count):
                pid, fmt, size = struct.unpack('<HHH', data[4 + 6 * i:10 + 6 * i])
                rows.append({'n': '0x%04x' % pid, 'k': 'str',
                             'v': names.get(pid, '?'),
                             'note': '%s · %d bytes @ %d' % (
                                 _SF_NAMES.get(fmt, '0x%02x' % fmt), size, off)})
                off += size
        except Exception as e:
            rows.append({'n': 'error', 'k': 'error', 'v': unicode(e)})
        return {'name': 'Property table', 'rows': rows}

    def _index_table(self, entry):
        rows = []
        try:
            data = entry.open('r').read(12)
            count, nxt, last = struct.unpack('<III', data[:12])
            rows = [{'n': 'count', 'k': 'num', 'v': unicode(count)},
                    {'n': 'next free key', 'k': 'num', 'v': unicode(nxt)},
                    {'n': 'last free key', 'k': 'num', 'v': '0x%08x' % last}]
        except Exception as e:
            rows.append({'n': 'error', 'k': 'error', 'v': unicode(e)})
        return {'name': 'Index', 'rows': rows}

    # ----------------------------------------------------------- children
    def children(self, lens, handle):
        if lens == 'cfb':
            return self._cfb_children(handle)
        if lens == 'content':
            return self._content_children(handle)
        return self._raw_children(handle)

    def children_many(self, lens, handles):
        out = {}
        for h in handles:
            try:
                out[h] = self.children(lens, h)
            except Exception as e:
                out[h] = [{'name': 'error', 'kind': 'error', 'value': unicode(e)}]
        return out

    def _raw_children(self, handle):
        r = self.resolve(handle)
        if r is None:
            return []
        if r[0] == 'o' or r[0] == 'c':
            obj = r[1] if r[0] == 'o' else self._entry_object(r[1])
            if obj is None:
                return []
            out = []
            for p in obj.properties():
                row = self._row(obj, p)
                child = {'name': row['n'], 'kind': row['k'], 'value': row['v'],
                         'full': row.get('full', ''), 'note': row.get('note', ''),
                         'handle': row.get('ref'), 'cls': '', 't': row.get('t', '')}
                if row['k'] == 'object':
                    child['cls'] = row['v']
                    child['value'] = row.get('refLabel', '')
                    child['has'] = True
                elif row['k'] == 'list':
                    child['has'] = bool(row.get('ref'))
                elif row['k'] == 'weak':
                    child['has'] = bool(row.get('ref'))
                    child['follow'] = True
                elif row.get('ref'):
                    child['follow'] = True
                    child['has'] = row['k'] == 'id' or row['n'] == 'SourceMobSlotID'
                    child['value'] = row['v'] + ' → ' + row.get('refLabel', '')
                self._mob_cols(child)
                out.append(child)
            return out
        owner, prop = r[1]
        if prop is None:
            return []
        out = []
        if isinstance(prop, _StrongSet):
            items = list(prop.items())
        else:
            items = list(enumerate(prop))
        for key, obj in items:
            name = ('[%d]' % key) if isinstance(key, int) else self.label(obj) or unicode(key)
            child = {'name': name, 'kind': 'object', 'cls': _class_name(obj),
                     'value': self.label(obj) if isinstance(key, int) else '',
                     'note': '' if isinstance(key, int) else (
                         key.urn if isinstance(key, MobID) else auid_text(key)
                         if isinstance(key, AUID) else unicode(key)),
                     'handle': self.handle_of(obj), 'has': True}
            if _WeakArr and isinstance(prop, _WeakArr):
                child['follow'] = True
            self._mob_cols(child)
            out.append(child)
        return out

    def _mob_cols(self, child):
        mob = self._mobs.get(child.get('handle'))
        if mob:
            child['umid'] = mob['mobId']
            child['tracks'] = mob['tracks']

    def _target_mob(self, clip):
        sid = _get(clip, 'SourceID')
        if sid is None or _is_zero_mobid(sid):
            return None, None
        return sid, self._mob_by_urn.get(sid.urn)

    def _target_slot(self, clip):
        sid, mh = self._target_mob(clip)
        if not mh:
            return None
        slot_id = _get(clip, 'SourceMobSlotID')
        mob = self._obj(mh)
        if mob is None:
            return None
        for slot in _safe(lambda: list(mob['Slots']), []) or []:
            if _get(slot, 'SlotID') == slot_id:
                return slot
        return None

    def _content_entry(self, obj, role, follow=''):
        h = self.handle_of(obj)
        name = self.label(obj)
        e = {'handle': h, 'role': role, 'cls': _class_name(obj),
             'name': name or _class_name(obj), 'unnamed': not name,
             'value': self.summary(obj), 'has': self._content_has(obj),
             'kind': 'object'}
        if follow:
            e['follow'] = follow
        self._mob_cols(e)
        return e

    def _content_has(self, obj):
        for p in obj.properties():
            if isinstance(p, _StrongRef):
                return True
            if isinstance(p, (_StrongVec, _StrongSet)) and len(p):
                return True
            if _prop_name(p) == 'SourceID':
                v = _safe(lambda: p.value)
                if v is not None and not _is_zero_mobid(v):
                    return True
        mob = self._mobs.get(self.handle_of(obj))
        return bool(mob and mob.get('essenceHandle'))

    def _content_children(self, handle):
        """Objects only, with collection properties made transparent and
        MobID references followed.

        A Sequence's `Components` vector is not a thing anyone clicks
        through on the way to a SourceClip, so its items are hoisted and
        the property name becomes the row's role.  A SourceClip's
        `SourceID` is a MobID, a scalar as far as the file is concerned --
        but what it names is the next mob down the derivation chain, so it
        is followed, and `SourceMobSlotID` to the one slot in that mob it
        cuts from.  Mob first, then slot, then file order."""
        obj = self._obj(handle)
        if obj is None:
            return []
        follows = []
        out = []
        for p in obj.properties():
            name = _prop_name(p)
            if isinstance(p, _StrongRef):
                child = _safe(lambda: p.value)
                if child is not None:
                    out.append(self._content_entry(child, name))
            elif isinstance(p, (_StrongVec, _StrongSet)):
                for child in self._strong_values(p):
                    out.append(self._content_entry(child, name))
            elif name == 'SourceID':
                sid, mh = self._target_mob(obj)
                if sid is None:
                    continue
                if mh:
                    mob = self._obj(mh)
                    follows.insert(0, self._content_entry(mob, 'SourceID', 'mob'))
                    slot = self._target_slot(obj)
                    if slot is not None:
                        follows.append(self._content_entry(slot, 'SourceMobSlotID', 'slot'))
                    else:
                        follows.append({'handle': None, 'role': 'SourceMobSlotID',
                                        'follow': 'missing', 'kind': 'missing',
                                        'name': 'no slot %s in that mob' % _get(obj, 'SourceMobSlotID')})
                else:
                    follows.insert(0, {'handle': None, 'role': 'SourceID', 'follow': 'missing',
                                       'kind': 'missing', 'name': 'not in this file',
                                       'umid': sid.urn})
        mob = self._mobs.get(handle) or self._mobs.get(self.handle_of(obj))
        if mob and mob.get('essenceHandle'):
            ed = self._obj(mob['essenceHandle'])
            if ed is not None:
                follows.append(self._content_entry(ed, 'essence', 'essence'))
        return follows + out

    def _cfb_children(self, handle):
        r = self.resolve(handle)
        if r is None:
            return []
        entry = r[1] if r[0] == 'c' else getattr(r[1], 'dir', None)
        if entry is None or not entry.isdir():
            return []
        out = []
        kids = _safe(lambda: list(entry.listdir()), []) or []
        kids.sort(key=lambda e: (e.isfile(), e.name))
        for e in kids:
            obj = self._entry_object(e) if e.isdir() else None
            c = {'name': e.name, 'handle': self.entry_handle(e),
                 'kind': 'storage' if e.isdir() else 'stream',
                 'cls': _class_name(obj) if obj is not None else '',
                 'value': human(e.byte_size) if e.isfile() else (self.label(obj) if obj is not None else ''),
                 'has': e.isdir(),
                 'alt': self.handle_of(obj) if obj is not None else None}
            cid = _safe(lambda: e.class_id) if e.isdir() else None
            if cid is not None:
                c['umid'] = auid_text(cid)
            out.append(c)
        return out

    # ------------------------------------------------------------- search
    def search(self, query, limit=2000):
        """Mob names, MobIDs and class names, over the index rather than
        the file -- a query costs a scan of a few thousand short strings.

        A query that is exactly an AAF class name (`SourceClip`) returns
        every object of that class the index pass saw."""
        q = (query or '').strip()
        if not q:
            return None
        ql = q.lower()
        out = []
        seen = set()

        def add(h, name, cls, umid='', tracks=''):
            if h in seen or len(out) >= limit:
                return
            seen.add(h)
            out.append({'handle': h, 'name': name, 'cls': cls,
                        'umid': umid, 'tracks': tracks})

        for h, s in self._mobs.items():
            if ql in (s['name'] or '').lower() or ql in s['mobId'] or ql == h:
                add(h, s['name'] or s['cls'], s['cls'], s['mobId'], s['tracks'])
        hits = self._by_class.get(ql)
        if hits:
            for h in hits:
                obj = None
                try:
                    obj = self._obj(h)
                except Exception:
                    pass
                if obj is None:
                    continue
                s = self._mobs.get(h)
                add(h, self.label(obj) or _class_name(obj), _class_name(obj),
                    s['mobId'] if s else '', s['tracks'] if s else '')
        if ql in self._h2key:
            obj = self._obj(ql)
            if obj is not None:
                add(ql, self.label(obj) or _class_name(obj), _class_name(obj))
        return out

    # ------------------------------------------------------------ exports
    def subtree(self, lens, handle, max_depth=48, max_rows=250000):
        """Everything under `handle`, nested, as the lens draws it with
        every node open.  Built from the same `children()` the tree uses,
        so an export cannot disagree with the screen about what is under
        what.  Bounded, since a fully opened cross-linked graph is as big
        as the file lets it be."""
        budget = [max_rows]
        capped = [False]

        def props(h):
            obj = self._obj(h)
            if obj is None:
                return None
            out = OrderedDict()
            for p in obj.properties():
                if isinstance(p, (_StrongRef,) + _COLLECTIONS):
                    continue
                row = self._row(obj, p)
                out[row['n']] = row.get('full') or row['v']
            return out or None

        def build(entry, path, depth):
            budget[0] -= 1
            node = OrderedDict()
            for k in ('role', 'name', 'cls', 'value', 'note', 'umid', 'tracks', 'handle'):
                v = entry.get(k)
                if v:
                    node['class' if k == 'cls' else 'mobId' if k == 'umid' else k] = v
            if entry.get('follow'):
                node['reference'] = True
            h = entry.get('handle')
            if lens == 'content' and h and entry.get('kind') == 'object':
                pr = props(h)
                if pr:
                    node['properties'] = pr
            if not h or not entry.get('has'):
                return node
            if h in path:
                node['jump'] = True
                return node
            if depth >= max_depth or budget[0] <= 0:
                node['truncated'] = True
                capped[0] = True
                return node
            kids = []
            for c in self.children(lens, h):
                if budget[0] <= 0:
                    node['truncated'] = True
                    capped[0] = True
                    break
                kids.append(build(c, path | {h}, depth + 1))
            if kids:
                node['children'] = kids
            return node

        obj = self._obj(handle)
        root = {'handle': handle, 'has': True, 'kind': 'object'}
        if obj is not None:
            root.update(name=self.label(obj) or _class_name(obj), cls=_class_name(obj),
                        value=self.summary(obj))
            self._mob_cols(root)
        tree = build(root, frozenset(), 0)
        return {'tree': tree, 'capped': capped[0], 'rows': max_rows - budget[0]}

    def subtree_json(self, lens, handle):
        return json.dumps(self.subtree(lens, handle), default=unicode)

    def plain(self, handle, depth=0):
        """One object as plain data: AAF property names, decoded values, the
        class that declares each one.  A collection brings its items, one
        level down."""
        node = self.node(handle)
        if node is None:
            return None
        out = OrderedDict()
        out['handle'] = handle
        out['class'] = node.get('cls')
        if node.get('classId'):
            out['classId'] = node['classId']
        if node.get('label'):
            out['name'] = node['label']
        if node.get('path'):
            out['path'] = node['path']
        plist = []
        for g in node['groups']:
            if g.get('storage'):
                continue
            for row in g['rows']:
                e = OrderedDict()
                e['name'] = row['n']
                e['declaredBy'] = g['name']
                if row.get('pid'):
                    e['pid'] = row['pid']
                if row.get('t'):
                    e['type'] = row['t']
                e['value'] = row.get('full') or row.get('v')
                if row.get('note'):
                    e['note'] = row['note']
                if row.get('ref'):
                    e['reference'] = row['ref']
                if row.get('k') == 'list' and row.get('ref'):
                    e['items'] = [OrderedDict((k, v) for k, v in (
                        ('name', c['name']), ('class', c.get('cls')),
                        ('handle', c.get('handle')), ('label', c.get('value')),
                        ('key', c.get('note'))) if v)
                        for c in self._raw_children(row['ref'])]
                plist.append(e)
        out['properties'] = plist
        if node.get('mob'):
            out['mob'] = node['mob']
        refs = self._referrers.get(handle)
        if refs:
            out['referencedBy'] = refs[:1000]
        return out

    def plain_json(self, handles):
        hs = json.loads(handles)
        return json.dumps([self.plain(h) for h in hs], default=unicode)

    # ---------------------------------------------------------------- XML
    def dump_xml(self, handles=None):
        """The strong-reference tree under each handle (the Header when
        none is given), every property, as XML.

        Objects are elements named for their AAF class; properties are
        elements named for the property.  Weak references and MobIDs are
        annotated with what they resolve to rather than followed, so a
        definition or a master mob is written once and not once per clip
        that names it.  Streams are measured, never read: an export of a
        2 GB AAF with embedded essence is the size of its metadata."""
        if isinstance(handles, (str, unicode)):
            handles = json.loads(handles) if handles.startswith('[') else [handles]
        out = []
        w = out.append
        m = self.meta()
        w('<?xml version="1.0" encoding="UTF-8"?>\n')
        w('<aaf%s%s%s%s>\n' % (_attr('file', m.get('name')), _attr('creator', m.get('creator')),
                               _attr('pyaaf2', m.get('pyaaf2')),
                               _attr('exportedBy', 'AAFInspector')))
        roots = [h for h in (handles or []) if h] or [self.handle_of(self.f.header)]
        for h in roots:
            obj = self._obj(h)
            if obj is not None:
                self._xml_obj(obj, 1, w, set())
        w('</aaf>\n')
        return ''.join(out)

    def _xml_obj(self, obj, depth, w, path, tag=None):
        pad = '  ' * depth
        cls = _class_name(obj)
        name = tag if tag else (cls if _XML_NAME.match(cls) else 'object')
        h = self.handle_of(obj)
        extra = '' if name == cls else _attr('class', cls)
        mob = self._mobs.get(h)
        if mob:
            extra += _attr('mobKind', mob['kind'])
        if h in path:
            w('%s<%s%s%s cycle="true"/>\n' % (pad, name, _attr('id', h), extra))
            return
        w('%s<%s%s%s>\n' % (pad, name, _attr('id', h), extra))
        inner = path | {h}
        for p in obj.properties():
            self._xml_prop(obj, p, depth + 1, w, inner)
        w('%s</%s>\n' % (pad, name))

    def _xml_prop(self, obj, p, depth, w, path):
        pad = '  ' * depth
        pname = _prop_name(p)
        tag = pname if _XML_NAME.match(pname) else 'property'
        nattr = '' if tag == pname else _attr('name', pname)
        nattr += _attr('pid', '0x%04x' % p.pid)
        try:
            if isinstance(p, _StrongRef):
                child = p.value
                w('%s<%s%s>\n' % (pad, tag, nattr))
                if child is not None:
                    self._xml_obj(child, depth + 1, w, path)
                w('%s</%s>\n' % (pad, tag))
                return
            if isinstance(p, (_StrongVec, _StrongSet)):
                vals = self._strong_values(p)
                w('%s<%s%s%s>\n' % (pad, tag, nattr, _attr('count', len(vals))))
                for child in vals:
                    self._xml_obj(child, depth + 1, w, path)
                w('%s</%s>\n' % (pad, tag))
                return
            if _WeakArr and isinstance(p, _WeakArr):
                w('%s<%s%s%s>\n' % (pad, tag, nattr, _attr('count', len(p))))
                for t in p:
                    w('%s  <ref%s%s/>\n' % (pad, _attr('to', self.label(t)),
                                           _attr('id', self.handle_of(t))))
                w('%s</%s>\n' % (pad, tag))
                return
            if isinstance(p, _WeakRef):
                t = p.value
                key = getattr(p, 'ref', None)
                w('%s<%s%s%s%s%s/>\n' % (pad, tag, nattr, _attr('weakref', 'true'),
                                         _attr('to', self.label(t) if t is not None else ''),
                                         _attr('key', auid_text(key) if isinstance(key, AUID) else key)))
                return
            if isinstance(p, _Stream):
                e = p.value
                w('%s<%s%s%s%s/>\n' % (pad, tag, nattr, _attr('stream', getattr(p, 'stream_name', '')),
                                       _attr('size', e.byte_size if e is not None else 0)))
                return
            v = p.value
            kind, shown, full, note = pretty(v, _safe(lambda: p.typedef))
            text = full or shown
            if kind == 'bytes':
                text = ' '.join('%02x' % c for c in bytearray(v))
            ann = ''
            if isinstance(v, MobID) and pname in ('SourceID',):
                th = self._mob_by_urn.get(v.urn)
                if th:
                    ann = _attr('mob', th) + _attr('mobName', self._mobs[th]['name'])
            if isinstance(v, AUID):
                dn = self._def_name(v)
                if dn:
                    ann = _attr('def', dn)
            w('%s<%s%s%s%s>%s</%s>\n' % (pad, tag, nattr, _attr('type', _type_name(p)), ann,
                                       _xml_text(text), tag))
        except Exception as e:
            w('%s<%s%s error="%s"/>\n' % (pad, tag, nattr, _xml_text(unicode(e))))

    def close(self):
        try:
            self.f.manager.path_cache.clear()
            self.f.cfb.f.close()
        except Exception:
            pass
        self.f = None


_XML_NAME = re.compile(r'^[A-Za-z_][A-Za-z0-9_.-]*$')
_XML_BAD = re.compile('[\x00-\x08\x0b\x0c\x0e-\x1f]')


def _xml_text(text):
    s = unicode(text if text is not None else '')
    s = _XML_BAD.sub(lambda m: '\\x%02x' % ord(m.group(0)), s)
    return (s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
             .replace('"', '&quot;'))


def _attr(name, value):
    if value is None or value == '':
        return ''
    return ' %s="%s"' % (name, _xml_text(value))


def dumps(value):
    return json.dumps(value, default=unicode)
