l1vmet3s.av

libraryCTRL

Posa al dia els mòduls d'un projecte i n'hi afegeix de nous: et diu què canvia, conserva cables i ajustos i sempre pots tornar enrere.Pone al día los módulos de un proyecto y le añade otros nuevos: te dice qué cambia, conserva cables y ajustes y siempre puedes volver atrás.Brings a project's modules up to date and adds new ones: it tells you what changes, keeps cables and settings, and you can always go back.

v1.0.034 controlscontrolescontrols20 operadorsoperadoresoperators2105 línies de codilíneas de códigolines of code52 KB
libraryCTRL
  • sense entradessin entradasno inputs
libraryCTRL
  • out1CHOPstate

UsarUsarUse

Prova aixòPrueba estoTry this

En un projecte antic, prem Check Now i llegeix What's New d'un mòdul abans de fer Update This One. Després prova Restore Previous Version.En un proyecto antiguo, pulsa Check Now y lee What's New de un módulo antes de darle a Update This One. Después prueba Restore Previous Version.In an old project, press Check Now and read a module's What's New before Update This One. Then try Restore Previous Version.

Aquesta part és en castellà.This part is in Spanish.

  1. Arrastrar tox/CTRL/libraryCTRL.tox a cualquier sitio del proyecto.
  2. CHECK NOW. En la lista: flúor = versión nueva que conserva todo; ámbar = pierde algo o es un cambio grande; gris = al día.
  3. Pulsar una fila para leer qué cambia. UPDATE para ese, UPDATE ALL para todos los que no pierden nada.
  4. Si no convence, GO BACK TO en la misma ficha.
  5. Guardar el proyecto cuando esté bien: hasta entonces, el .toe del disco sigue con los módulos viejos.
  6. LIBRARY: la librería por categorías. ADD pone el módulo en la red que estás mirando.
  7. Página Palette → Update My Palette: la librería, ordenada, en la paleta de TouchDesigner.

Al sacar una versión de un módulo (mantenedores): si estrena opciones que salen encendidas, apuntar en docs/web/library.json → neutral el valor que deja la imagen como estaba; si hay que avisar de algo, en care; si cambia de nombre, en was; si guarda algo que no es un parámetro, en keep. Después, python3 tools/build_docs.py rehace catalog.json. Al añadir un módulo nuevo, python3 tools/link_palette.py lo enlaza en la paleta de este ordenador.

Export: COMP vacío en test_box → build1 → build2 → build3 → build4 → en otra llamada, build5 + guardar en tox/CTRL/ → tools/sign_tox.py → cargar en frío.

Límites: lo cambiado a mano dentro de un módulo no pasa al nuevo (está en la copia); no se actualiza a sí mismo; no mira dentro de los módulos de la librería ni en otros .toe.

Va bé ambVa bien conGoes well with

ParàmetresParámetrosParameters

El panell real del mòdul amb els seus valors per defecte. Prem una fila per saber què fa; les notes són en castellà.El panel real del módulo con sus valores por defecto. Pulsa una fila para saber qué hace.The module's real panel with its default values. Press a row to see what it does; notes are in Spanish.

EntendreEntenderUnderstand

Carrega la versió nova aturada, hi passa tot el que havies tocat, desa la vella al disc i només llavors les canvia. No mira ni es connecta enlloc si no l'hi demanes.Carga la versión nueva parada, le pasa todo lo que habías tocado, guarda la vieja en el disco y solo entonces las cambia. No mira ni se conecta a nada si no se lo pides.It loads the new version while it's stopped, hands it everything you had touched, saves the old one to disk, and only then swaps them. It never checks or connects unless you ask.

Les idees que hi ha a sotaLas ideas que hay debajoThe ideas underneath

Per dinsPor dentroInside

Aquesta part és en castellà.This part is in Spanish.

El recorrido de la señal esquema en texto
list_exec (Parameter Execute, pars propios) ─┐
tile_click (Panel Execute, clics del panel) ─┼→ util ── toda la lógica; nada por frame
start (Execute, onStart / onCreate) ─────────┘    │
                                                  ├→ stage (Base COMP con el cooking apagado): aquí se carga el .tox nuevo
                                                  ├→ items (Table: un módulo del proyecto por fila)
                                                  ├→ report (Text: lo que pasó en la última actualización)
                                                  ├→ state (Constant) → null_out → out1
                                                  └→ panel:
   tile_size, tile_data (Script TOP: las cajas) ─┐
   tile_spec (Table) → tile_txt (Text TOP) ──────┴→ tile_glsl → null_tile → tile (Container) ← win (Window COMP)

Fuera del módulo, y solo cuando se pide: los módulos del proyecto que se cambian, la copia en Documentos, lo bajado de la web y la carpeta l1vmet3s de la paleta.

Operador a operador configuración clave
OperadorConfiguración clave
utilTodo el Python. build1 lo escribe entero; build2, build3 y build4 reponen cada uno su sección, en su sitio
list_execParameter Execute sobre .., solo pars propios: on_change y on_pulse
startExecute con onStart y onCreate. Nada por frame
stageBase COMP con allowCooking = False: el .tox nuevo se carga aquí y no arranca nada (ni cámaras, ni red, ni procesos)
itemspath module cat from to state lost losttext skip: la lista de PROJECT
reportTexto largo del último cambio
state → null_out → out1Constant que solo se escribe al cambiar
tile_size, tile_dataNº de cajas y sus rectángulos, colores y tipo en una textura N × 3 (Script TOP, rgba32f)
tile_spec → tile_txtTodos los textos del panel en un solo Text TOP (Arial Bold, Spec DAT)
tile_glsl → null_tile → tileDibuja las cajas y colorea el texto por zonas; Container de 680 × 684, también el visor del nodo
tile_clickPanel Execute (lselect): busca la caja pulsada y hace lo suyo
winWindow COMP; winop solo mientras está abierta; cursorvisible = alwaysvisible; Esc cierra

De dónde sale la información

  • catalog.json (raíz de la librería; lo escribe tools/build_docs.py): por módulo, versión, archivo, tamaño y sha256, qué hace y las novedades en tres idiomas.
  • docs/web/library.json (a mano; build_docs.py lo mete en el catálogo): lo que una versión nueva necesita para entrar bien en un proyecto que ya existe.
ClavePara qué
wasNombres anteriores de un módulo (composeMIX era composeFX)
keepLo que no son parámetros y tiene que pasar: DATs y entradas del storage (el banco de sceneCTRL…)
stopEl pulso que hay que dar al viejo antes de cambiarlo (el detector de faceTrackGEN)
careAvisos por versión, en tres idiomas
neutralEl valor que deja como estaba cada opción que estrena una versión: el .tox sale con un ejemplo encendido

TallerTallerWorkshop

El codiEl códigoThe code

util python · 1999 línieslíneaslines
# libraryCTRL util — fase 1: catálogo, módulos del proyecto, actualizar, informe y volver atrás. Todo por pulso.
import hashlib, json, os, re, time

STATE = {}                                       # por ruta del COMP: catálogo, filas, cola, fichas de cada .tox
HEAD = ['path', 'module', 'cat', 'from', 'to', 'state', 'lost', 'losttext', 'skip']
NL = chr(10)
ARROW = ' ' + chr(8594) + ' '


def state(comp):
	return STATE.setdefault(comp.path, {})


def say(comp, msg, name='Status'):
	p = comp.par[name]
	if p.eval() != msg:
		p.val = msg


def out(comp, **kw):
	st = comp.op('state')
	for i, n in enumerate(('modules', 'outdated', 'busy')):
		if n in kw and st.par['const%dvalue' % i].eval() != kw[n]:
			st.par['const%dvalue' % i].val = kw[n]


def locked(comp):
	if ui.performMode:
		say(comp, 'Not in Perform Mode')
		return True
	if state(comp).get('busy'):
		say(comp, 'Still working, wait')
		return True
	return False


# ---- la librería: una carpeta con catalog.json y tox/<CAT>/
def documents():
	return os.path.dirname(os.path.dirname(app.userPaletteFolder))


def library(comp):
	"""Carpeta de la librería. Vacía: la de la paleta (l1vmet3s dentro de ella, o el sitio al que apuntan sus enlaces)."""
	f = comp.par.Folder.eval()
	if f:
		try:
			f = tdu.expandPath(f)
		except Exception:
			pass
		tries = [f, os.path.dirname(f.rstrip('/'))]
	else:
		pal = app.userPaletteFolder
		tries = [os.path.join(pal, 'l1vmet3s'), os.path.dirname(os.path.dirname(os.path.realpath(os.path.join(pal, 'CTRL'))))]
	for t in tries:
		if os.path.isfile(os.path.join(t, 'catalog.json')):
			return t.replace(chr(92), '/')
	return None


def load_catalog(comp):
	s = state(comp)
	root = library(comp)
	s['root'], s['cat'], s['was'] = root, {}, {}
	if root is None:
		return False
	with open(root + '/catalog.json', encoding='utf-8') as f:
		d = json.load(f)
	for m in d['modules']:
		s['cat'][m['name']] = m
		for w in m.get('was', ()):
			s['was'][w] = m['name']
	return True


def fetch(comp, m):
	"""Ruta del .tox comprobado con su sha256, o un texto con el problema."""
	f = state(comp)['root'] + '/' + m['file']
	if not os.path.isfile(f):
		return None, 'file missing: ' + m['file']
	with open(f, 'rb') as h:
		if hashlib.sha256(h.read()).hexdigest() != m['sha256']:
			return None, m['name'] + ': the file does not match the catalog'
	return f, ''


def clear(box):
	for c in list(box.children):
		c.destroy()


def load(comp, f):
	"""Carga un .tox sin que arranque nada: stage tiene el cooking apagado."""
	box = comp.op('stage')
	box.allowCooking = False
	clear(box)
	return box.loadTox(f)


# ---- los módulos del proyecto
def vtuple(v):
	return tuple(int(x) for x in re.findall('[0-9]+', v)[:3])


def identity(comp, o):
	"""(nombre en el catálogo, versión) o None. Sin página About, solo los FX sueltos antiguos, por su nombre."""
	s = state(comp)
	p = getattr(o.par, 'Module', None)
	if p is not None and p.readOnly and getattr(o.par, 'Version', None) is not None:
		w = re.match('[A-Za-z0-9]*', str(p.eval())).group(0)
		n = s['was'].get(w, w)
		return (n, str(o.par.Version.eval()), n != w) if n in s['cat'] else None
	n = re.sub('[0-9]+$', '', o.name)
	if p is None and n in s['cat'] and o.customPages and s['cat'][n]['cat'] == 'FX' and getattr(o.par, 'Bypass', None) is not None:
		return n, '', False
	return None


def walk(comp):
	"""Todos los módulos del proyecto, sin entrar dentro de ellos, de las interfaces de TD ni de los clones."""
	found, todo = [], [c for c in op('/').children if c.isCOMP and c.name not in ('ui', 'sys', 'local', 'perform')]
	while todo:
		o = todo.pop(0)
		if o == comp:
			continue
		k = identity(comp, o)
		if k:
			found.append((o,) + k)
		elif 'libraryCTRL' not in o.tags:
			todo += [c for c in o.children if c.isCOMP]
	return found


def pages(c):
	return [p for p in c.customPars if p.page is not None and p.page.name != 'About']


def spec(comp, m):
	"""Ficha del .tox nuevo (tipo, menú y secuencia de cada parámetro y sus entradas), para avisar antes de cambiar nada."""
	c = state(comp).setdefault('specs', {})
	if m['sha256'] not in c:
		f, why = fetch(comp, m)
		if f is None:
			return None, why
		o = load(comp, f)
		c[m['sha256']] = {'pars': {p.name: (p.style, list(p.menuNames) if p.style == 'Menu' else None) for p in pages(o)},
						  'seqs': [q.name for q in seqs(o)],
						  'ins': [k.inOP.name if k.inOP else '' for k in o.inputConnectors],
						  'outs': [k.outOP.name if k.outOP else '' for k in o.outputConnectors]}
		o.destroy()
	return c[m['sha256']], ''


def seqs(o):
	d = {}
	for p in pages(o):
		if p.sequence is not None:
			d[p.sequence.name] = p.sequence
	return list(d.values())


def touched(p):
	"""¿Lo ha movido alguien? (por expresión, bind o export, o un valor distinto del de fábrica)"""
	if p.isOP and p.mode == ParMode.CONSTANT:
		return bool(p.val)                       # vacío se lee None y de fábrica es ''
	return p.mode != ParMode.CONSTANT or p.eval() != p.default


def matters(p):
	"""¿Se nota si no pasa? Lo tocado, y lo que el audio está moviendo aunque siga con su valor de fábrica (To…, Level…)."""
	if touched(p):
		return True
	a = getattr(p.owner.par, 'Audio', None)
	return bool(p.name.startswith(('To', 'Level')) and p.isNumber and p.eval() and a is not None and a.eval())


def old_audio(p, names):
	"""Nombres de antes del audio común: Band → Hit Band y la fuente Audio Level de Modulate → su banda. (parámetro, valor) o None."""
	band = {'kick': 'low', 'full': 'full'}
	b = getattr(p.owner.par, 'Audioband', None)
	if p.name == 'Audioband' and 'Hitband' in names and p.eval() in band:
		return 'Hitband', band[p.eval()]
	if re.match('M[0-9]src$', p.name) and p.eval() == 'level' and p.name in names:
		return p.name, band.get(b.eval() if b is not None else 'kick', 'low')
	return None


def neutral(old, new, m):
	"""Lo que estrena la versión nueva, en el valor que deja la imagen como estaba (el .tox sale con un ejemplo puesto)."""
	d = {p.name: 'off' for p in pages(new) if re.match('M[0-9]src$', p.name)}
	d.update(m.get('neutral', {}) if m else {})
	r = {}
	for n, v in d.items():
		if getattr(new.par, n, None) is None or getattr(old.par, n, None) is not None:
			continue
		if isinstance(v, dict):
			q = getattr(old.par, v['from'], None)
			if q is None:
				continue
			v = min(v.get('max', 1e9), max(v.get('min', -1e9), q.eval() * v['mul']))
			if new.par[n].style == 'Int':
				v = int(v + 1e-6)
		r[n] = v
	return r


def menu_ok(v, new, old):
	"""La opción existe, o el menú es de los que el módulo rellena solo (el nuevo trae un trozo del viejo)."""
	return v in new or (set(new) < set(old) and v in old)


def kind_ok(p, style):
	return p.style == style or (p.style in ('Str', 'StrMenu', 'File', 'Folder') and style in ('Str', 'StrMenu', 'File', 'Folder')) or \
		(p.style in ('Float', 'Int') and style in ('Float', 'Int'))


def text_of(p):
	if p.mode == ParMode.EXPRESSION:
		return p.expr
	if p.mode == ParMode.BIND:
		return 'bind ' + p.bindExpr
	v = p.eval()
	return ('%.4g' % v) if isinstance(v, float) else str(v)


def losses(o, sp):
	"""Lo que no pasa a la versión nueva: solo lo que se ha tocado."""
	out_, base = [], lambda p: re.sub('[0-9]+', '0', p.name, count=1)
	for p in pages(o):
		if p.style in ('Pulse', 'Momentary', 'Header', 'Sequence') or p.readOnly or not matters(p) or old_audio(p, sp['pars']):
			continue
		n = p.name if p.name in sp['pars'] or p.sequence is None else base(p)
		q = sp['pars'].get(n)
		if q is None or not kind_ok(p, q[0]):
			out_.append('%s = %s' % (p.label, text_of(p)))
		elif p.style == 'Menu' and p.mode == ParMode.CONSTANT and q[1] is not None and not menu_ok(p.eval(), q[1], p.menuNames):
			out_.append('%s = %s' % (p.label, text_of(p)))
	for k, ic in enumerate(o.inputConnectors):
		if ic.connections and end(ic, 'inOP', k, sp['ins']) is None:
			out_.append('cable into input %d' % (k + 1))
	for k, oc in enumerate(o.outputConnectors):
		if oc.connections and end(oc, 'outOP', k, sp['outs']) is None:
			out_.append('cable from output %d' % (k + 1))
	return out_


def end(conn, attr, k, names):
	"""Índice del conector equivalente: por el nombre del In / Out de dentro; si no, el mismo sitio."""
	o = getattr(conn, attr)
	if o is not None and o.name in names:
		return names.index(o.name)
	return k if k < len(names) and not (o is not None and names[k]) else None


def skips(comp):
	return set(comp.fetch('lb_skip', [], search=False))


def check(comp):
	"""Lee el catálogo, mira el proyecto y rellena items, el menú y el estado."""
	s = state(comp)
	t = comp.op('items')
	try:
		ok = load_catalog(comp)
	except Exception as e:
		ok = False
		say(comp, 'catalog.json cannot be read: %s' % e)
	if not ok:
		t.clear()
		t.appendRow(HEAD)
		if s.get('root') is None:
			say(comp, 'No library found: choose the folder that has catalog.json')
		fill_menu(comp)
		out(comp, modules=0, outdated=0)
		return
	rows, bad, sk = [], [], skips(comp)
	for o, n, v, renamed in walk(comp):
		m = s['cat'][n]
		a, b = vtuple(v), vtuple(m['version'])
		st, lost = 'ok', []
		if not a:
			st = 'unknown'
		elif a > b:
			st = 'newer'
		elif a < b:
			st = 'update' if a[0] == b[0] and not renamed else 'major'
		if st in ('update', 'major', 'unknown'):
			sp, why = spec(comp, m)
			if sp is None:
				st = 'blocked'
				bad.append(why)
			else:
				lost = losses(o, sp)
		rows.append([o.path, n, m['cat'], v, m['version'], st, len(lost), ' · '.join(lost), int(o.path in sk)])
	rank = {'update': 0, 'major': 1, 'unknown': 1, 'blocked': 2, 'newer': 3, 'ok': 4}
	rows.sort(key=lambda r: (rank[r[5]], r[0].lower()))
	t.clear()
	t.appendRow(HEAD)
	for r in rows:
		t.appendRow(r)
	clear(comp.op('stage'))
	old = sum(r[5] in ('update', 'major', 'unknown') for r in rows)
	fill_menu(comp)
	out(comp, modules=len(rows), outdated=old)
	say(comp, '%d modules, %s' % (len(rows), 'all up to date' if not old else '%d with a newer version' % old) +
		(' · ' + bad[0] if bad else ''))


def rows(comp):
	t = comp.op('items')
	return [dict(zip(HEAD, [c.val for c in t.row(i)])) for i in range(1, t.numRows)]


def row(comp, path=None):
	path = path or comp.par.Pick.eval()
	return next((r for r in rows(comp) if r['path'] == path), None)


def short(comp, path):
	base = comp.parent().path.rstrip('/') + '/'
	return path[len(base):] if path.startswith(base) else path


def fill_menu(comp):
	p, rr = comp.par.Pick, rows(comp)
	names = [r['path'] for r in rr] or ['none']
	labels = []
	for r in rr:
		l = short(comp, r['path'])
		if r['state'] in ('update', 'major', 'unknown', 'blocked'):
			l += '   %s%s%s' % (r['from'] or '?', ARROW, r['to'])
			if int(r['lost']):
				l += '   (%s lost)' % r['lost']
		elif r['state'] == 'newer':
			l += '   %s, newer than the library' % r['from']
		labels.append(l)
	cur = p.eval()
	p.menuNames, p.menuLabels = names, labels or ['Press Check Now']
	p.val = cur if cur in names else names[0]
	show(comp)


def show(comp):
	"""La ficha del módulo elegido."""
	s, r = state(comp), row(comp)
	m = s.get('cat', {}).get(r['module']) if r else None
	la = comp.par.Language.eval()
	ch = ''
	if r:
		ch = r['from'] or 'before versions'
		if r['state'] in ('update', 'major', 'unknown', 'blocked'):
			ch += ARROW + r['to']
		else:
			ch += ' · up to date' if r['state'] == 'ok' else ' · newer than the library (%s)' % r['to']
		if r['state'] in ('major', 'unknown'):
			ch += ' · big change: only one by one'
	say(comp, ch, 'Change')
	late = bool(r) and r['state'] in ('update', 'major', 'unknown')
	say(comp, m.get('news', {}).get(la, '').replace('`', '') if m and late else '', 'News')
	nt = m.get('note', {}).get(la, '') if m and late else ''
	care = m.get('care') if m and late else None
	if care and vtuple(r['from']) < vtuple(care['before']):
		nt = care[la] + (' ' + nt if nt else '')
	say(comp, nt.replace('`', ''), 'Note')
	say(comp, r['losttext'] if r else '', 'Lost')
	v = bool(r) and r['skip'] == '1'
	if comp.par.Skip.eval() != v:
		comp.par.Skip.val = v


def set_skip(comp, on):
	r = row(comp)
	if r is None or (r['skip'] == '1') == on:
		return
	sk = skips(comp)
	(sk.add if on else sk.discard)(r['path'])
	comp.store('lb_skip', sorted(sk))
	t = comp.op('items')
	for i in range(1, t.numRows):
		if t[i, 'path'].val == r['path']:
			t[i, 'skip'] = int(on)


# ---- pasar lo de uno a otro
def raw(p, base):
	v = p.val
	if isinstance(v, td.OP):
		return base.relativePath(v)
	return v


def transfer(old, new, m):
	"""Valores, expresiones, binds, secuencias y lo que el módulo guarda aparte. Devuelve (lo que debe quedar, lo perdido)."""
	want, lost = {}, []
	names = set(p.name for p in pages(new))
	for n, v in neutral(old, new, m).items():
		new.par[n].val = v
		want[n] = (ParMode.CONSTANT, new.par[n].eval(), '')
	nseq = {q.name: q for q in seqs(new)}
	for q in seqs(old):
		if q.name in nseq and nseq[q.name].numBlocks != q.numBlocks:
			nseq[q.name].numBlocks = q.numBlocks
	for p in pages(old):
		if p.style in ('Pulse', 'Momentary', 'Header', 'Sequence'):
			continue
		ro = p.readOnly
		if ro and p.mode != ParMode.CONSTANT:
			continue                             # lecturas del propio módulo
		al = None if ro else old_audio(p, names)
		if al:
			new.par[al[0]].val = al[1]
			want[al[0]] = (ParMode.CONSTANT, al[1], '')
			continue
		q = getattr(new.par, p.name, None)
		if q is None or not kind_ok(p, q.style) or q.readOnly != ro:
			if not ro and matters(p):
				lost.append('%s = %s' % (p.label, text_of(p)))
			continue
		try:
			if ro:
				q.readOnly = False
				q.val = raw(p, old.parent())
				q.readOnly = True
				continue
			if p.style == 'Menu' and p.eval() not in q.menuNames:
				if p.mode == ParMode.CONSTANT and not menu_ok(p.eval(), q.menuNames, p.menuNames):
					if touched(p):
						lost.append('%s = %s' % (p.label, text_of(p)))
					continue
				q.menuNames, q.menuLabels = p.menuNames, p.menuLabels
			v = p.eval() if p.style == 'Menu' else raw(p, old.parent())
			if p.mode != ParMode.EXPORT:
				q.val = v
			if p.mode == ParMode.EXPRESSION:
				q.expr = p.expr
				q.mode = ParMode.EXPRESSION
			elif p.mode == ParMode.BIND:
				q.bindExpr = p.bindExpr
				q.mode = ParMode.BIND
			want[p.name] = (p.mode, v, p.expr if p.mode == ParMode.EXPRESSION else p.bindExpr if p.mode == ParMode.BIND else '')
		except Exception as e:
			lost.append('%s = %s (%s)' % (p.label, text_of(p), e))
	k = m.get('keep', {}) if m else {}
	for n in k.get('dats', ()):
		if old.op(n) is not None and new.op(n) is not None:
			new.op(n).text = old.op(n).text
	for n in k.get('storage', ()):
		if n in old.storage:
			new.store(n, old.storage[n])
	for n in ('parentshortcut', 'opshortcut'):
		a, b = getattr(old.par, n, None), getattr(new.par, n, None)
		if a is not None and b is not None and a.eval() and a.eval() != b.eval():
			b.val = a.eval()
	return want, lost


def rewire(old, new):
	"""Los cables, conectando el nuevo sobre el sitio del viejo: borrar antes el viejo corre las entradas de un Composite."""
	lost = []
	ins = [k.inOP.name if k.inOP else '' for k in new.inputConnectors]
	outs = [k.outOP.name if k.outOP else '' for k in new.outputConnectors]
	for k, ic in enumerate(old.inputConnectors):
		for src in list(ic.connections):
			i = end(ic, 'inOP', k, ins)
			try:
				new.inputConnectors[i].connect(new.outputConnectors[src.index] if src.owner == old else src)
			except Exception:
				lost.append('cable from %s' % src.owner.name)
	for k, oc in enumerate(old.outputConnectors):
		for dst in list(oc.connections):
			if dst.owner in (old, new):
				continue
			i = end(oc, 'outOP', k, outs)
			try:
				dst.connect(new.outputConnectors[i])
			except Exception:
				lost.append('cable into %s' % dst.owner.name)
	return lost


# ---- copias de seguridad
def backups(comp):
	f = comp.par.Backupfolder.eval()
	return (f or os.path.join(documents(), 'l1vmet3s_av', 'libraryCTRL', 'backups')).replace(chr(92), '/')


def project_name():
	return re.sub('([.][0-9]+)?[.]toe$', '', project.name)


def read_index(comp):
	f = backups(comp) + '/index.json'
	try:
		with open(f, encoding='utf-8') as h:
			return json.load(h)
	except FileNotFoundError:
		return []


def write_index(comp, d):
	f = backups(comp) + '/index.json'
	with open(f + '.tmp', 'w', encoding='utf-8') as h:
		json.dump(d, h, ensure_ascii=False, indent=1)
	os.replace(f + '.tmp', f)


def copies(comp, path):
	return [e for e in read_index(comp) if e['project'] == project_name() and e['path'] == path and os.path.isfile(backups(comp) + '/' + e['file'])]


def backup(comp, o, name, ver):
	root, pj = backups(comp), project_name()
	safe = re.sub('[^A-Za-z0-9_-]+', '_', pj)
	os.makedirs(root + '/' + safe, exist_ok=True)
	idx = read_index(comp)
	stem = '%s/%s_%s_%s' % (safe, re.sub('[^A-Za-z0-9_-]+', '_', o.path.strip('/')), ver or '0', time.strftime('%Y%m%d_%H%M%S'))
	f, k = stem + '.tox', 1
	while os.path.exists(root + '/' + f):
		k += 1
		f = '%s_%d.tox' % (stem, k)
	o.save(root + '/' + f)
	if not os.path.isfile(root + '/' + f):
		raise IOError('the backup was not written')
	idx.append({'project': pj, 'path': o.path, 'module': name, 'version': ver, 'file': f, 'time': time.strftime('%Y-%m-%d %H:%M:%S')})
	mine = [e for e in idx if e['project'] == pj and e['path'] == o.path]
	for e in mine[:-max(1, int(comp.par.Keep.eval()))]:
		idx.remove(e)
		if os.path.isfile(root + '/' + e['file']):
			os.remove(root + '/' + e['file'])
	write_index(comp, idx)


# ---- el cambio
LOOK = ('nodeX', 'nodeY', 'nodeWidth', 'nodeHeight', 'color', 'comment', 'viewer')


def replace(comp, path, f, m, ver, keepvals=True):
	"""Cambia el módulo de path por el del archivo f. Devuelve un dict con lo que hay que repasar después."""
	old = op(path)
	box = old.parent()
	new = load(comp, f)
	want, lost = transfer(old, new, m) if keepvals else ({}, [])
	backup(comp, old, m['name'], ver)
	name, look, tags, cook = old.name, {k: getattr(old, k) for k in LOOK}, set(old.tags), old.allowCooking
	sel = old.selected
	stop = m.get('stop')
	if stop and hasattr(old, stop):
		try:
			getattr(old, stop)()
		except Exception as e:
			print('libraryCTRL: %s de %s: %s' % (stop, name, e))
	docked = list(old.docked)
	for d in docked:
		d.dock = None                            # si no, se irían con el viejo
	new.name = name
	old.name = name + '_libold'
	c = None
	try:
		c = box.copy(new, name=name)             # aquí arranca: ya con sus valores y su nombre
		lost += rewire(old, c)
	except Exception:
		if c is not None:
			c.destroy()
		old.name = name
		for d in docked:
			d.dock = old
		raise
	old.destroy()
	clear(comp.op('stage'))
	for k, v in look.items():
		try:
			setattr(c, k, v)
		except Exception as e:
			print('libraryCTRL: %s.%s: %s' % (name, k, e))
	for t in tags:
		c.tags.add(t)
	for d in docked:
		d.dock = c
	c.selected = sel
	c.allowCooking = True
	return {'path': path, 'want': want, 'lost': lost, 'cook': cook, 'cat': m['cat'], 'new': c.id}


def pool(o):
	"""Parameter Execute del módulo que vigilan sus propios parámetros."""
	r = []
	for d in o.findChildren(type=parameterexecuteDAT, depth=1):
		if d.par.active.eval() and d.par.valuechange.eval():
			w = d.par.op.eval()
			if w == o or (isinstance(w, (list, tuple)) and o in w):
				r.append(d)
	return r


def poke(job):
	"""Los valores llegaron con el módulo parado: se le avisa de cada uno como si se hubiera movido a mano. Hay módulos que
	guardan tablas o texturas calculadas a partir de sus parámetros. Los CTRL y XPORT lo hacen solos al cargarse."""
	o = op(job['path'])
	if o is None or job['cat'] in ('CTRL', 'XPORT'):
		return
	ch = [n for n, w in job['want'].items() if getattr(o.par, n, None) is not None and (w[0] != ParMode.CONSTANT or o.par[n].eval() != o.par[n].default)]
	for d in pool(o):
		pat = d.par.pars.eval()
		t = d.text
		i = t.find('def onValueChange')
		j = t.find('def ', i + 5)
		one = re.findall("op[(]'util'[)][.]module[.]([a-z_]+)[(]parent[(][)][)]", t[i:j if j > 0 else len(t)])
		try:
			if len(one) == 1 and pat.strip() == '*':
				getattr(o.op('util').module, one[0])(o)
				continue
			for n in tdu.match(pat, ch):
				d.module.onValueChange(o.par[n], o.par[n].default)
		except Exception as e:
			print('libraryCTRL: %s de %s: %s' % (d.name, o.name, e))


def differs(p, w):
	if p.mode != w[0]:
		return True
	if w[0] == ParMode.EXPRESSION:
		return p.expr != w[2]
	if w[0] == ParMode.BIND:
		return p.bindExpr != w[2]
	if w[0] != ParMode.CONSTANT:
		return False
	a, b = p.eval() if p.style == 'Menu' else raw(p, p.owner.parent()), w[1]
	if isinstance(b, float) or isinstance(a, float):
		return abs(float(a) - float(b)) > 1e-6 * max(1.0, abs(float(b)))
	return a != b


def settle(job, fix=True):
	"""Repaso: un módulo puede tocar sus propios pars al avisarle de otro (Modulate: Target → Min / Max)."""
	o, bad = op(job['path']), []
	if o is None:
		return ['?']
	for n, w in job['want'].items():
		p = getattr(o.par, n, None)
		if p is None or not differs(p, w):
			continue
		if not fix:
			bad.append('%s = %s' % (p.label, w[2] or w[1]))
			continue
		try:
			if w[0] == ParMode.EXPRESSION:
				p.expr = w[2]
				p.mode = w[0]
			elif w[0] == ParMode.BIND:
				p.bindExpr = w[2]
				p.mode = w[0]
			elif w[0] == ParMode.CONSTANT:
				p.val = w[1]
		except Exception as e:
			print('libraryCTRL: %s: %s' % (n, e))
	return bad


# ---- la cola: un módulo detrás de otro, con unos frames para que cada uno se asiente
def recording(comp):
	for r in rows(comp):
		if r['module'] == 'recXPORT' and op(r['path']) is not None:
			c = op(r['path']).op('out2')
			if c is not None and c['recording'] is not None and c['recording'].eval() > 0:
				return True
	return False


def learn_off(comp):
	"""Un midiCTRL o un consoleCTRL con Learn encendido aprendería de la propia actualización."""
	l = []
	for r in rows(comp):
		o = op(r['path'])
		p = getattr(o.par, 'Learn', None) if o is not None else None
		if p is not None and p.style == 'Toggle' and p.mode == ParMode.CONSTANT and p.eval():
			p.val = False
			l.append(r['path'])
	return l


def start(comp, jobs):
	"""jobs: [(ruta, 'update' o archivo de una copia)]"""
	s = state(comp)
	if not jobs:
		return
	if recording(comp):
		say(comp, 'recXPORT is recording: stop it first')
		return
	s['busy'], s['queue'], s['done'], s['log'] = True, list(jobs), 0, []
	s['total'] = len(jobs)
	s['learn'] = learn_off(comp)
	out(comp, busy=1)
	say(comp, 'Updating 1 / %d' % len(jobs))
	later(comp, 'step', 3 if s['learn'] else 1)


def later(comp, fn, frames):
	run("args[0].valid and getattr(args[0].op('util').module, args[1])(args[0])", comp, fn, delayRef=op.TDResources, delayFrames=frames)


def step(comp):
	s = state(comp)
	if not s.get('queue'):
		return finish(comp)
	path, what = s['queue'].pop(0)
	r = row(comp, path)
	s['job'] = None
	say(comp, 'Updating %d / %d: %s' % (s['total'] - len(s['queue']), s['total'], short(comp, path)))
	try:
		if r is None or op(path) is None:
			raise IOError('it is no longer there')
		m = s['cat'][r['module']]
		if ui.performMode:
			raise IOError('not in Perform Mode')
		k = identity(comp, op(path))
		if not k or k[0] != r['module']:
			raise IOError('it is not the same module any more: press Check Now')
		if what == 'update':
			f, why = fetch(comp, m)
			if f is None:
				raise IOError(why)
			j = replace(comp, path, f, m, k[1])
		else:
			j = replace(comp, path, what['file'], m, k[1], False)
		j['from'], j['to'] = k[1] or '?', str(op(path).par.Version.eval()) if getattr(op(path).par, 'Version', None) is not None else '?'
		s['job'] = j
	except Exception as e:
		s['log'].append({'path': path, 'error': str(e)})
		clear(comp.op('stage'))
		return later(comp, 'step', 1)
	later(comp, 'do_poke', 4)


def do_poke(comp):
	j = state(comp)['job']
	if j['want']:
		poke(j)
	for k in (3, 6, 10):
		later(comp, 'do_settle', k)
	later(comp, 'do_close', 14)


def do_settle(comp):
	settle(state(comp)['job'])


def alive(o):
	"""Errores de verdad: los que quedan al volver a procesar lo que se quejó mientras se cargaba."""
	for p in o.customPars:
		if p.readOnly and p.mode == ParMode.EXPRESSION:
			try:
				p.eval()
			except Exception:
				pass
	if o.errors(recurse=True):
		o.clearScriptErrors(recurse=True)
		for c in o.findChildren(key=lambda c: bool(c.errors())):
			c.cook(force=True)
	return o.errors(recurse=True)


def do_close(comp):
	s = state(comp)
	j = s['job']
	j['lost'] += settle(j, fix=False)
	o = op(j['path'])
	if o is not None:
		e = alive(o)
		o.allowCooking = j['cook']
		j['errors'] = e.strip().split(NL)[0][:200] if e else ''
	s['log'].append(j)
	step(comp)


def finish(comp):
	s = state(comp)
	for p in s.get('learn', ()):
		if op(p) is not None:
			op(p).par.Learn.val = True
	log = s['log']
	lines = [time.strftime('%Y-%m-%d %H:%M')]
	good = [j for j in log if 'error' not in j]
	for j in log:
		if 'error' in j:
			lines.append('%s  NOT CHANGED: %s' % (short(comp, j['path']), j['error']))
			continue
		lines.append('%s  %s%s%s  %s' % (short(comp, j['path']), j['from'], ARROW, j['to'], 'nothing lost' if not j['lost'] else 'not carried over:'))
		lines += ['    ' + x for x in j['lost']]
		if j['errors']:
			lines.append('    error: ' + j['errors'])
	comp.op('report').text = NL.join(lines)
	n = sum(len(j['lost']) for j in good)
	s['busy'] = False
	s['job'] = None
	out(comp, busy=0)
	check(comp)
	msg = '%d changed' % len(good)
	if len(good) < len(log):
		msg += ', %d not changed' % (len(log) - len(good))
	msg += ', nothing lost' if not n else ', %d setting%s not carried over' % (n, '' if n == 1 else 's')
	if any(j['errors'] for j in good):
		msg += ', with errors'
	say(comp, msg + ' (details in the report DAT)', 'Report')


# ---- los pulsos
def on_update(comp):
	s, r = state(comp), row(comp)
	if r is None or 'cat' not in s:
		say(comp, 'Press Check Now first')
		return
	if r['state'] not in ('update', 'major', 'unknown'):
		say(comp, short(comp, r['path']) + ': nothing to update')
		return
	if int(r['lost']) or r['state'] != 'update':
		a = s.get('armed')
		if not a or a[0] != r['path'] or time.time() - a[1] > 10:
			s['armed'] = (r['path'], time.time())
			say(comp, ('%s setting%s will be lost' % (r['lost'], '' if r['lost'] == '1' else 's') if int(r['lost']) else 'Big change') + ': press Update again within 10 s')
			return
	s['armed'] = None
	start(comp, [(r['path'], 'update')])


def takes(comp):
	"""Lo que cogería Update All: (los anticuados, los que de verdad cambiaría)"""
	lossy = comp.par.Allwhat.eval() == 'lossy'
	late = [r for r in rows(comp) if r['state'] == 'update' and r['skip'] != '1']
	return late, [(r['path'], 'update') for r in late if lossy or not int(r['lost'])]


def on_update_all(comp):
	if 'cat' not in state(comp):
		say(comp, 'Press Check Now first')
		return
	late, jobs = takes(comp)
	if not jobs:
		say(comp, 'Nothing to update' if not late else '%d would lose settings: one by one, or Update All Takes' % len(late))
		return
	start(comp, jobs)


def on_restore(comp):
	s, r = state(comp), row(comp)
	if r is None or 'cat' not in s:
		say(comp, 'Press Check Now first')
		return
	c = copies(comp, r['path'])
	if not c:
		say(comp, short(comp, r['path']) + ': no previous version saved')
		return
	start(comp, [(r['path'], {'file': backups(comp) + '/' + c[-1]['file']})])


def on_change(comp, par, prev):
	if par.name == 'Pick' or par.name == 'Language':
		a = state(comp).get('armed')
		if a and a[0] != comp.par.Pick.eval():
			state(comp)['armed'] = None
		show(comp)
	elif par.name == 'Skip':
		set_skip(comp, bool(par.eval()))


def on_pulse(comp, par):
	if par.name == 'Openbackups':
		os.makedirs(backups(comp), exist_ok=True)
		ui.viewFile(backups(comp))
	elif par.name in ('Check', 'Update', 'Updateall', 'Restore'):
		if not locked(comp):
			{'Check': check, 'Update': on_update, 'Updateall': on_update_all, 'Restore': on_restore}[par.name](comp)


def on_start(comp):
	"""Al abrir el proyecto o soltar el .tox: en blanco. No mira nada hasta que se pulsa Check Now."""
	STATE.pop(comp.path, None)
	t = comp.op('items')
	t.clear()
	t.appendRow(HEAD)
	clear(comp.op('stage'))
	fill_menu(comp)
	out(comp, modules=0, outdated=0, busy=0)
	say(comp, 'Press Check Now')


# ---- build2: panel ----
import numpy as np

# ---- maqueta (px, y hacia abajo): alto fijo, para que la ventana no cambie de tamaño
TW, NROW, ROWH = 680, 9, 32
Y_TOOL, Y_ROWS = 44, 92
Y_DET = Y_ROWS + NROW * ROWH + 8
NLINE, LINEH = 8, 20
Y_BTN = Y_DET + 40 + NLINE * LINEH + 16
Y_FOOT = Y_BTN + 40
TH = Y_FOOT + 40
PAD, TXTX = 14, 124
C_BG, C_ROW, C_SEL = (0.025, 0.025, 0.025), (0.07, 0.07, 0.07), (0.17, 0.17, 0.16)
C_BTN, C_LINE, C_OFF = (0.19, 0.19, 0.18), (0.24, 0.24, 0.23), (0.35, 0.35, 0.34)
C_ACC, C_INK = (0.863, 1.0, 0.18), (0.025, 0.025, 0.025)      # flúor de la casa (#dcff2e)
C_TXT, C_DIM = (0.93, 0.93, 0.9), (0.56, 0.56, 0.53)
C_AMB, C_ERR = (1.0, 0.68, 0.0), (1.0, 0.4, 0.33)
LATE = ('update', 'major', 'unknown')
DOTS = chr(8230)
TAB = chr(9)
SURE = 10                                        # segundos para la segunda pulsación


def text_w(comp, t):
	c = state(comp).setdefault('tw', {})
	if t not in c:
		if len(c) > 4000:
			c.clear()
		c[t] = float(comp.op('tile_txt').evalTextSize(t)[0]) if t else 0.0
	return c[t]


def cut(comp, t, w):
	if text_w(comp, t) <= w:
		return t
	while len(t) > 1 and text_w(comp, t + DOTS) > w:
		t = t[:-1]
	return t.rstrip() + DOTS


def wrap(comp, t, w, n):
	"""Parte un texto en n líneas como mucho; lo que no cabe acaba en puntos suspensivos."""
	r, cur = [], ''
	for word in t.split():
		k = (cur + ' ' + word).strip()
		if cur and text_w(comp, k) > w:
			r.append(cur)
			cur = word
		else:
			cur = k
	if cur:
		r.append(cur)
	if len(r) > n:
		r = r[:n - 1] + [' '.join(r[n - 1:])]
	return [cut(comp, x, w) for x in r]


def armed(comp, what):
	a = state(comp).get('armed')
	return bool(a) and a[0] == what and time.time() - a[1] <= SURE


# ---- dibujar: se pide al cambiar algo y se hace una vez, en el frame siguiente
def redraw(comp, ms=0):
	s = state(comp)
	if ms:
		run("args[0].valid and args[0].op('util').module.redraw(args[0])", comp, delayRef=op.TDResources, delayMilliSeconds=ms)
	elif not s.get('drawing'):
		s['drawing'] = True
		run("args[0].valid and args[0].op('util').module.tile_draw(args[0])", comp, delayRef=op.TDResources, delayFrames=1)


def pages_bar(comp, n, pg, kind, label, button):
	"""< 1 / 3 > arriba a la derecha. Devuelve la página que toca."""
	k = max(1, -(-n // NROW))
	pg = max(0, min(pg, k - 1))
	if k > 1:
		y = Y_TOOL + 9
		button(TW - PAD - 116, y, 30, 30, '<', kind, pg - 1, on=pg > 0)
		t = '%d / %d' % (pg + 1, k)
		label(TW - PAD - 58 - text_w(comp, t) / 2, y + 15, t, C_DIM)
		button(TW - PAD - 30, y, 30, 30, '>', kind, pg + 1, on=pg < k - 1)
	return pg


def details(comp, parts, rect, label):
	"""La ficha: (título, texto, tinta, líneas como mucho)"""
	y, left = Y_DET + 48, NLINE
	for h, t, ink, n in parts:
		ls = wrap(comp, t.replace('`', ''), TW - PAD - TXTX - 8, min(n, left)) if t and left > 0 else []
		for i, l in enumerate(ls):
			if i == 0:
				label(PAD, y, h, C_DIM)
			label(TXTX + 8, y, l, ink)
			y += LINEH
		left -= len(ls)
		if ls:
			y += 4


def project_view(comp, s, busy, rect, label, button, hits):
	rr, y = rows(comp), Y_TOOL + 9
	# botones de todo el proyecto
	button(PAD, y, 122, 30, 'CHECK NOW', 'check', on=not busy, fill=C_BTN if rr else C_ACC, ink=C_TXT if rr else C_INK)
	if rr:
		_, jobs = takes(comp)
		if armed(comp, 'all'):
			button(PAD + 130, y, 176, 30, 'SURE? PRESS AGAIN', 'all', fill=C_AMB, ink=C_INK, on=not busy)
		else:
			button(PAD + 130, y, 176, 30, 'UPDATE ALL (%d)' % len(jobs), 'all', on=bool(jobs) and not busy, fill=C_ACC, ink=C_INK)
		lossy = comp.par.Allwhat.eval() == 'lossy'
		x = PAD + 318
		rect(x, y + 8, x + 14, y + 22, C_DIM)
		rect(x + 2, y + 10, x + 12, y + 20, C_ACC if lossy else C_BG)
		w = label(x + 22, y + 15, 'even if settings are lost', C_TXT if lossy else C_DIM)
		hits.append((x - 4, y, x + 26 + w, y + 30, 'lossy', 0))
	pg = s['page'] = pages_bar(comp, len(rr), s.get('page', 0), 'page', label, button)
	# módulos
	pick = comp.par.Pick.eval()
	if not rr:
		label(PAD, Y_ROWS + 24, 'CHECK NOW looks for modules of the library in this project.', C_TXT)
		label(PAD, Y_ROWS + 48, 'Nothing changes until you press UPDATE.', C_DIM)
	for j, r in enumerate(rr[pg * NROW:(pg + 1) * NROW]):
		ya = Y_ROWS + j * ROWH
		yc, yb = ya + ROWH / 2 - 1, ya + ROWH - 2
		sel = r['path'] == pick
		rect(PAD, ya, TW - PAD, yb, C_SEL if sel else C_ROW)
		if sel:
			rect(PAD, ya, PAD + 3, yb, C_TXT)
		hits.append((PAD, ya, TW - PAD, yb, 'row', r['path']))
		big = r['state'] in ('major', 'unknown')
		led = C_ACC if r['state'] == 'update' else C_AMB if big else C_ERR if r['state'] == 'blocked' else C_OFF
		rect(PAD + 12, yc - 5, PAD + 22, yc + 5, led)
		old = r['state'] in LATE
		label(PAD + 34, yc, cut(comp, short(comp, r['path']), 220), C_TXT if old or sel else C_DIM)
		x = PAD + 266
		if old or r['state'] == 'blocked':
			w = label(x, yc, (r['from'] or '?') + ARROW, C_DIM)
			label(x + w + text_w(comp, ' '), yc, r['to'], led)
		else:
			label(x, yc, r['from'], C_DIM)
		note = 'out of Update All' if r['skip'] == '1' else '%s lost' % r['lost'] if old and int(r['lost']) else 'big change' if big else \
			'file problem' if r['state'] == 'blocked' else 'newer than the library' if r['state'] == 'newer' else ''
		label(TW - PAD - 104, yc, note, C_DIM if r['skip'] == '1' or r['state'] == 'newer' else C_AMB, right=True)
		if old:
			sure = armed(comp, r['path'])
			button(TW - PAD - 94, ya + 3, 90, ROWH - 8, 'SURE?' if sure else 'UPDATE', 'update', r['path'], on=not busy,
				fill=C_AMB if sure else C_LINE if not sel else C_OFF, ink=C_INK if sure else C_TXT)
	# ficha del elegido
	rect(0, Y_DET, TW, Y_DET + 1, C_LINE)
	r = row(comp)
	if r:
		w = label(PAD, Y_DET + 20, cut(comp, short(comp, r['path']), 300), C_TXT)
		what = r['module'] + '   ' if short(comp, r['path']) != r['module'] else ''
		label(PAD + w + 16, Y_DET + 20, cut(comp, what + comp.par.Change.eval(), TW - 2 * PAD - w - 16), C_DIM)
		parts = [('WILL BE LOST', comp.par.Lost.eval() if r['state'] in LATE else '', C_AMB, 3),
				 ('KEEP IN MIND', comp.par.Note.eval(), C_TXT, 3), ("WHAT'S NEW", comp.par.News.eval(), C_TXT, 3)]
		k = s.get('last', {}).get(r['path'])
		if k:
			parts.insert(0, ('LAST CHANGE', k[0], k[1], 3))
		details(comp, parts, rect, label)
		old = r['state'] in LATE
		if old:
			sure = armed(comp, r['path'])
			t = 'UPDATE TO ' + r['to']
			if sure:
				t = 'SURE? PRESS AGAIN'
			button(PAD, Y_BTN, 190, 30, t, 'update', r['path'], on=not busy, fill=C_AMB if sure else C_ACC, ink=C_INK)
		x = PAD + (198 if old else 0)
		c = copies(comp, r['path'])
		if c:
			button(x, Y_BTN, 190, 30, 'GO BACK TO ' + (c[-1]['version'] or 'THE OLD ONE'), 'restore', r['path'], on=not busy)
			x += 198
		if old or r['skip'] == '1':
			on = r['skip'] == '1'
			rect(x + 6, Y_BTN + 8, x + 20, Y_BTN + 22, C_DIM)
			rect(x + 8, Y_BTN + 10, x + 18, Y_BTN + 20, C_ACC if on else C_BG)
			w = label(x + 28, Y_BTN + 15, 'out of Update All', C_TXT if on else C_DIM)
			hits.append((x, Y_BTN, x + 32 + w, Y_BTN + 30, 'skip', r['path']))


VIEWS = {'project': project_view}                # las fases siguientes añaden la suya
TABS = [('project', 'PROJECT')]


def foot_tag(comp):
	return ''                                    # la fase 4 dice de dónde sale la lista


def tile_draw(comp):
	s = state(comp)
	s['drawing'] = False
	rects, texts, hits = [], [], []
	busy = bool(s.get('busy'))

	def rect(x0, y0, x1, y1, fill=None, ink=None):
		rects.append((x0, y0, x1, y1, fill, ink))

	def label(x, yc, t, ink=C_TXT, right=False):
		if not t:
			return 0
		w = text_w(comp, t)
		x0 = round(x - w if right else x)
		texts.append((x0, TH - round(yc) - 5, t))
		rect(x0 - 1, yc - 11, x0 + w + 2, yc + 10, None, ink)
		return w

	def button(x0, y0, w, h, t, kind, arg=0, on=True, fill=C_BTN, ink=C_TXT):
		"""on False = apagado: se ve, pero no responde."""
		rect(x0, y0, x0 + w, y0 + h, fill if on else C_ROW)
		label(x0 + (w - text_w(comp, t)) / 2, y0 + h / 2, t, ink if on else C_OFF)
		if on:
			hits.append((x0, y0, x0 + w, y0 + h, kind, arg))

	rr = rows(comp)
	late = [r for r in rr if r['state'] in LATE]
	rect(0, 0, TW, TH, C_BG)
	# cabecera
	view = s.get('view', 'project')
	if len(TABS) > 1:
		for i, (k, t) in enumerate(TABS):
			on = k == view
			button(PAD + i * 90, 8, 86, 28, t, 'tab', k, fill=C_TXT if on else C_BTN, ink=C_INK if on else C_TXT)
	else:
		label(PAD, 22, 'libraryCTRL', C_DIM)
	hx = PAD + 90 * len(TABS) + 12 if len(TABS) > 1 else TXTX
	st, ink = comp.par.Status.eval(), C_TXT
	if busy:
		ink = C_AMB
	elif rr:
		st, ink = ('%d of %d have a newer version' % (len(late), len(rr)), C_ACC) if late else ('%d modules, all up to date' % len(rr), C_TXT)
		if any(r['state'] == 'blocked' for r in rr):
			st, ink = '%d of %d with a file problem' % (sum(r['state'] == 'blocked' for r in rr), len(rr)), C_ERR
	elif view != 'project' and s.get('cat'):
		st = '%d modules in the library' % len(s['cat'])
	win = comp.op('win').isOpen
	button(TW - PAD - 130, 8, 130, 28, 'CLOSE WINDOW' if win else 'OPEN WINDOW', 'window')
	label(hx, 22, cut(comp, st, TW - PAD - 142 - hx), ink)
	if busy:
		done = (s.get('total', 1) - len(s.get('queue', ()))) / max(1, s.get('total', 1))
		rect(0, Y_TOOL - 3, TW * done, Y_TOOL, C_AMB)
	else:
		rect(0, Y_TOOL - 1, TW, Y_TOOL, C_LINE)
	VIEWS[view](comp, s, busy, rect, label, button, hits)
	rect(0, Y_FOOT, TW, Y_FOOT + 1, C_LINE)
	t = comp.par.Report.eval().replace(' (details in the report DAT)', '')
	fw = TW - 2 * PAD - label(TW - PAD, Y_FOOT + 20, foot_tag(comp), C_OFF, right=True) - 12
	if not busy and s.get('warn'):
		label(PAD, Y_FOOT + 20, cut(comp, s['warn'], fw), C_AMB)
	elif t:
		label(PAD, Y_FOOT + 20, cut(comp, 'Last: ' + t, fw), C_ERR if 'error' in t or 'not changed' in t else C_DIM)
	else:
		label(PAD, Y_FOOT + 20, 'The old version is always saved before a change.' if view == 'project' else 'ADD puts a new one in the network you are looking at.', C_DIM)

	# escribir solo lo que cambia
	s['hits'] = hits
	tx = NL.join(['x' + TAB + 'y' + TAB + 'text'] + ['%d%s%d%s%s' % (x, TAB, y, TAB, t.replace(TAB, ' ')) for x, y, t in texts])
	d = comp.op('tile_spec')
	if s.get('ttext') != tx:
		s['ttext'] = d.text = tx
	arr = np.zeros((3, len(rects), 4), dtype=np.float32)
	for i, (x0, y0, x1, y1, fill, ink) in enumerate(rects):
		arr[0, i] = (x0, y0, x1, y1)
		if fill is not None:
			arr[1, i] = fill + (1.0,)
		if ink is not None:
			arr[2, i] = ink + (1.0,)
	old = s.get('tarr')
	if old is None or old.shape != arr.shape or not np.array_equal(old, arr):
		s['tarr'] = arr
		ts = comp.op('tile_size')
		ts.par.const0value = len(rects)
		ts.par.const1value = (ts.par.const1value.eval() + 1) % 100000


def tile_array(comp):
	a = state(comp).get('tarr')
	return a if a is not None else np.zeros((3, 1, 4), dtype=np.float32)


# ---- clics
def tile_click(comp, u, v):
	s = state(comp)
	x, y = u * TW, (1.0 - v) * TH
	for x0, y0, x1, y1, kind, arg in reversed(s.get('hits', [])):     # el último dibujado manda (UPDATE va sobre su fila)
		if x0 <= x < x1 and y0 <= y < y1:
			return do_click(comp, kind, arg)


def do_click(comp, kind, arg):
	s = state(comp)
	s['warn'] = ''
	redraw(comp)
	if kind == 'window':
		return close_window(comp) if comp.op('win').isOpen else open_window(comp)
	if kind == 'page':
		s['page'] = arg
		return
	if kind == 'row':
		comp.par.Pick.val = arg
		return
	if kind == 'lossy':
		comp.par.Allwhat.val = 'safe' if comp.par.Allwhat.eval() == 'lossy' else 'lossy'
		return
	if kind == 'skip':
		comp.par.Skip.val = not comp.par.Skip.eval()
		return
	if locked(comp):
		if ui.performMode:
			s['warn'] = 'Not in Perform Mode'
		return
	if kind == 'check':
		check(comp)
	elif kind == 'all':
		if armed(comp, 'all'):
			s['armed'] = None
			on_update_all(comp)
		else:
			s['armed'] = ('all', time.time())
			redraw(comp, SURE * 1000 + 300)
	else:
		comp.par.Pick.val = arg
		show(comp)
		if kind == 'update':
			on_update(comp)
			if s.get('armed'):
				redraw(comp, SURE * 1000 + 300)
		else:
			on_restore(comp)


# ---- ventana: el panel solo está enganchado a ella mientras está abierta (si no, le quita el ratón al nodo)
def open_window(comp):
	w = comp.op('win')
	w.par.winop = 'tile'
	run("args[0].valid and args[0].par.winopen.pulse()", w, delayRef=op.TDResources, delayFrames=2)
	run("args[0].valid and args[0].op('util').module.watch_window(args[0])", comp, delayRef=op.TDResources, delayFrames=20)


def close_window(comp):
	w = comp.op('win')
	if w.isOpen:
		w.par.winclose.pulse()
	run("args[0].valid and setattr(args[0].par, 'winop', '')", w, delayRef=op.TDResources, delayFrames=2)
	redraw(comp)
	run("args[0].valid and args[0].op('util').module.redraw(args[0])", comp, delayRef=op.TDResources, delayFrames=6)


def watch_window(comp, was=False):
	"""Solo mientras está abierta: dos veces por segundo mira si la han cerrado con Esc o con la X."""
	if not comp.op('win').isOpen:
		return close_window(comp)
	if not was:
		redraw(comp)
	run("args[0].valid and args[0].op('util').module.watch_window(args[0], True)", comp, delayRef=op.TDResources, delayFrames=30)


# ---- enganches con la fase 1: todo lo que cambia algo pasa por aquí
_say_b1, _set_skip_b1, _on_change_b1, _on_pulse_b1, _on_start_b1, _finish_b1, _check_b1 = \
	say, set_skip, on_change, on_pulse, on_start, finish, check


def say(comp, msg, name='Status'):
	_say_b1(comp, msg, name)
	redraw(comp)


def set_skip(comp, on):
	_set_skip_b1(comp, on)
	redraw(comp)


def check(comp):
	_check_b1(comp)
	rr = rows(comp)
	if rr and rr[0]['state'] in LATE and (row(comp) or {}).get('state') not in LATE and not state(comp).get('keep_pick'):
		comp.par.Pick.val = rr[0]['path']            # lo primero que se ve es lo que hay por actualizar
		show(comp)
	redraw(comp)


def on_change(comp, par, prev):
	_on_change_b1(comp, par, prev)
	if par.name == 'Pick':
		i = next((i for i, r in enumerate(rows(comp)) if r['path'] == par.eval()), None)
		if i is not None:
			state(comp)['page'] = i // NROW
	redraw(comp)


def on_pulse(comp, par):
	if par.name == 'Openwindow':
		return open_window(comp) if not comp.op('win').isOpen else close_window(comp)
	_on_pulse_b1(comp, par)
	redraw(comp)


def finish(comp):
	s = state(comp)
	last = s.setdefault('last', {})
	for j in s['log']:
		if 'error' in j:
			last[j['path']] = ('Not changed: ' + j['error'], C_ERR)
		else:
			t = j['from'] + ARROW + j['to'] + ', '
			if j['errors']:
				last[j['path']] = (t + 'with an error: ' + j['errors'], C_ERR)
			else:
				last[j['path']] = (t + ('nothing lost' if not j['lost'] else 'not carried over: ' + ', '.join(j['lost'])), C_AMB if j['lost'] else C_ACC)
	s['keep_pick'] = True                            # tras actualizar se queda en el que se ha cambiado
	_finish_b1(comp)
	s['keep_pick'] = False


def on_start(comp):
	w = comp.op('win')
	if w is not None:
		if w.isOpen:
			w.par.winclose.pulse()                   # TD reabre al cargar las ventanas que se guardaron abiertas
		w.par.winop = ''
	_on_start_b1(comp)
	if comp.op('tile_spec') is not None:
		redraw(comp)


# ---- build3: librería ----
# ---- vista de la librería: el catálogo por categorías y ADD
CATS = ('all', 'GEN', 'FX', '3D', 'MIX', 'CTRL', 'OUT', 'XPORT')
C_CAT = {'GEN': C_ACC, '3D': C_ACC, 'FX': (1.0, 0.36, 0.96), 'MIX': (1.0, 0.36, 0.96), 'CTRL': (0.18, 0.95, 1.0),
		 'OUT': (1.0, 0.6, 0.18), 'XPORT': (1.0, 0.6, 0.18)}     # los colores de la web: hacer, transformar, controlar, sacar


def lib_open(comp):
	"""Lee el catálogo si aún no está y cuenta lo que ya hay en el proyecto."""
	s = state(comp)
	if not s.get('cat'):
		try:
			if not load_catalog(comp):
				s['warn'] = 'No library found: choose the folder that has catalog.json'
		except Exception as e:
			s['warn'] = 'catalog.json cannot be read: %s' % e
	count_here(comp)
	lib_menu(comp)


def count_here(comp):
	d = {}
	if state(comp).get('cat'):
		for o, n, v, ren in walk(comp):
			d.setdefault(n, []).append(short(comp, o.path) + (' ' + v if v else ''))
	state(comp)['here'] = d


def lib_list(comp):
	c = comp.par.Category.eval()
	r = [m for m in state(comp).get('cat', {}).values() if c in ('all', m['cat'])]
	return sorted(r, key=lambda m: m['name'].lower())


def lib_menu(comp):
	p = comp.par.Addmodule
	names = [m['name'] for m in lib_list(comp)] or ['none']
	if list(p.menuNames) != names:
		cur = p.eval()
		p.menuNames, p.menuLabels = names, names if names != ['none'] else ['Press Check Now']
		p.val = cur if cur in names else names[0]
	lib_show(comp)


def lib_show(comp):
	m = state(comp).get('cat', {}).get(comp.par.Addmodule.eval())
	say(comp, m['what'].get(comp.par.Language.eval(), '').replace('`', '') if m else '', 'What')


def network(comp):
	"""La red que se está mirando. Nunca dentro de un módulo ni de las carpetas de TD: entonces, la de fuera."""
	pane = next((p for p in [ui.panes.current] + list(ui.panes) if p is not None and p.type == PaneType.NETWORKEDITOR), None)
	o = pane.owner if pane is not None else None
	if o is None or o.path == '/' or o.path.split('/')[1] in ('ui', 'sys', 'local', 'perform'):
		return comp.parent(), None
	box, a = o, o
	while a is not None and a.path != '/':
		if a == comp or identity(comp, a):
			box = a.parent()
		a = a.parent()
	return box, pane if box == o else None


def free_spot(box, new, x, y):
	"""El hueco libre más cercano a (x, y)."""
	w, h, m = new.nodeWidth, new.nodeHeight, 25
	busy = [(c.nodeX - m, c.nodeY - m, c.nodeX + c.nodeWidth + m, c.nodeY + c.nodeHeight + m) for c in box.children if c is not new and c != new]
	x, y = round((x - w / 2) / 25) * 25, round((y - h / 2) / 25) * 25
	for d in range(0, 200):
		ring = [(i, j) for i in range(-d, d + 1) for j in range(-d, d + 1) if max(abs(i), abs(j)) == d]
		for i, j in sorted(ring, key=lambda q: (q[0] ** 2 + q[1] ** 2, -q[0], q[1])):
			a, b = x + i * 50, y + j * 50
			if not any(a < q[2] and a + w > q[0] and b < q[3] and b + h > q[1] for q in busy):
				return a, b
	return x, y


def add(comp, name):
	"""Pone un módulo nuevo, tal como sale de la librería, en la red que está abierta."""
	s = state(comp)
	s['warn'] = ''
	m = s.get('cat', {}).get(name)
	if m is None:
		s['warn'] = 'Press Check Now first'
		return None
	try:
		f, why = fetch(comp, m)
		if f is None:
			raise IOError(why)
		box, pane = network(comp)
		n, k = name, 0
		while box.op(n) is not None:
			k += 1
			n = name + str(k)
		src = load(comp, f)
		ui.undo.startBlock('Add ' + n)
		try:
			c = box.copy(src, name=n)                # aquí arranca
			x, y = (pane.x, pane.y) if pane is not None else (comp.nodeX + comp.nodeWidth + 100, comp.nodeY + comp.nodeHeight / 2)
			c.nodeX, c.nodeY = free_spot(box, c, x, y)
			for q in list(box.selectedChildren):
				q.selected = False
			c.selected = c.current = True
		finally:
			ui.undo.endBlock()
		clear(comp.op('stage'))
	except Exception as e:
		clear(comp.op('stage'))
		s['warn'] = 'Not added: %s' % e
		return None
	run("args[0].valid and args[1].valid and args[0].op('util').module.alive(args[1])", comp, c, delayRef=op.TDResources, delayFrames=10)     # quejas de mientras se cargaba
	if rows(comp):
		s['keep_pick'] = True
		check(comp)                                  # la otra vista ya lo cuenta
		s['keep_pick'] = False
	count_here(comp)
	say(comp, '%s %s added to %s' % (n, m['version'], box.path), 'Report')
	redraw(comp)
	return c


def library_view(comp, s, busy, rect, label, button, hits):
	y, x = Y_TOOL + 9, PAD
	cat = comp.par.Category.eval()
	for c in CATS:
		t = c.upper()
		w = round(text_w(comp, t)) + 18
		on = c == cat
		button(x, y, w, 30, t, 'lcat', c, fill=C_CAT.get(c, C_TXT) if on else C_BTN, ink=C_INK if on else C_TXT)
		x += w + 5
	ml = lib_list(comp)
	s['lpage'] = pages_bar(comp, len(ml), s.get('lpage', 0), 'lpage', label, button)
	pick = comp.par.Addmodule.eval()
	here = s.get('here', {})
	if not ml:
		label(PAD, Y_ROWS + 24, 'No library found.', C_TXT)
		label(PAD, Y_ROWS + 48, 'Choose its folder (the one with catalog.json) on the Library page.', C_DIM)
	la = comp.par.Language.eval()
	for j, m in enumerate(ml[s['lpage'] * NROW:(s['lpage'] + 1) * NROW]):
		ya = Y_ROWS + j * ROWH
		yc, yb = ya + ROWH / 2 - 1, ya + ROWH - 2
		n, sel = m['name'], m['name'] == pick
		rect(PAD, ya, TW - PAD, yb, C_SEL if sel else C_ROW)
		if sel:
			rect(PAD, ya, PAD + 3, yb, C_TXT)
		hits.append((PAD, ya, TW - PAD, yb, 'lrow', n))
		rect(PAD + 12, yc - 5, PAD + 22, yc + 5, C_CAT[m['cat']])
		label(PAD + 34, yc, n, C_TXT)
		q = len(here.get(n, ()))
		wq = label(TW - PAD - 78, yc, '%d here' % q, C_DIM, right=True) + 14 if q else 0
		label(PAD + 170, yc, cut(comp, m['what'].get(la, '').replace('`', ''), TW - 2 * PAD - 170 - 80 - wq), C_TXT if sel else C_DIM)
		button(TW - PAD - 68, ya + 3, 64, ROWH - 8, 'ADD', 'add', n, on=not busy, fill=C_OFF if sel else C_LINE)
	rect(0, Y_DET, TW, Y_DET + 1, C_LINE)
	m = s.get('cat', {}).get(pick)
	if m:
		w = label(PAD, Y_DET + 20, m['name'], C_TXT)
		label(PAD + w + 16, Y_DET + 20, m['cat'], C_CAT[m['cat']])
		label(PAD + w + 16 + text_w(comp, m['cat']) + 16, Y_DET + 20, m['version'] + '   ' + m.get('date', ''), C_DIM)
		details(comp, [('WHAT IT DOES', m['what'].get(la, ''), C_TXT, 3), ('IN PROJECT', ', '.join(here.get(pick, ())), C_DIM, 1),
					   ("WHAT'S NEW", m.get('news', {}).get(la, ''), C_DIM, 3)], rect, label)
		button(PAD, Y_BTN, 270, 30, 'ADD TO THE OPEN NETWORK', 'add', pick, on=not busy, fill=C_ACC, ink=C_INK)


VIEWS['library'] = library_view
if ('library', 'LIBRARY') not in TABS:
	TABS.append(('library', 'LIBRARY'))


_do_click_b2, _on_change_b2, _on_pulse_b2, _on_start_b2, _check_b2 = do_click, on_change, on_pulse, on_start, check


def do_click(comp, kind, arg):
	s = state(comp)
	if kind not in ('tab', 'lcat', 'lpage', 'lrow', 'add'):
		return _do_click_b2(comp, kind, arg)
	s['warn'] = ''
	redraw(comp)
	if kind == 'tab':
		s['view'] = arg
		s['armed'] = None
		if arg == 'library':
			lib_open(comp)
	elif kind == 'lpage':
		s['lpage'] = arg
	elif kind == 'lcat':
		s['lpage'] = 0
		comp.par.Category.val = arg
		lib_menu(comp)
	elif kind == 'lrow':
		comp.par.Addmodule.val = arg
		lib_show(comp)
	elif kind == 'add':
		comp.par.Addmodule.val = arg
		lib_show(comp)
		if not locked(comp):
			add(comp, arg)
		elif ui.performMode:
			s['warn'] = 'Not in Perform Mode'


def on_change(comp, par, prev):
	_on_change_b2(comp, par, prev)
	if par.name == 'Category':
		lib_menu(comp)
	elif par.name in ('Addmodule', 'Language'):
		lib_show(comp)


def on_pulse(comp, par):
	if par.name == 'Add':
		if not locked(comp):
			add(comp, comp.par.Addmodule.eval())
			redraw(comp)
		return
	_on_pulse_b2(comp, par)


def check(comp):
	_check_b2(comp)
	count_here(comp)
	lib_menu(comp)


def on_start(comp):
	_on_start_b2(comp)
	lib_menu(comp)


# ---- build4: web y paleta ----
# ---- dos orígenes: una carpeta o la web. La web se guarda en una carpeta con la misma forma; lo demás no nota la diferencia
import shutil, ssl, threading, time, urllib.error, urllib.request

AGENT = {'User-Agent': 'libraryCTRL'}
FILE_OK = re.compile('tox/[A-Za-z0-9]+/[A-Za-z0-9_]+[.]tox')
PACK = 'l1vmet3s'                                # carpeta dentro de la paleta


def palette():
	return app.userPaletteFolder.replace(chr(92), '/')


def linked():
	"""¿La paleta ya es la librería (enlaces de carpeta)? El ordenador donde se hacen los módulos."""
	p = palette()
	return os.path.isdir(p + '/CTRL') and os.path.normcase(os.path.realpath(p + '/CTRL')) != os.path.normcase(os.path.join(os.path.realpath(p), 'CTRL'))


def source(comp):
	v = comp.par.Source.eval()
	return v if v != 'auto' else 'local' if comp.par.Folder.eval() or linked() else 'web'


def address(comp):
	a = comp.par.Webaddress.eval().strip()
	if not re.match('https://[^/]+|http://(localhost|127[.]0[.]0[.]1)(:|/|$)', a):
		return None
	return a.rstrip('/') + '/'


def web_root(comp):
	return (documents() + '/l1vmet3s_av/libraryCTRL/web/' + re.sub('[^A-Za-z0-9.-]+', '_', (address(comp) or 'none').split('//')[-1].strip('/'))).replace(chr(92), '/')


_library_b1, _fetch_b1 = library, fetch


def library(comp):
	if source(comp) == 'local':
		return _library_b1(comp)
	r = web_root(comp)
	return r if os.path.isfile(r + '/catalog.json') else None


def fetch(comp, m):
	f, why = _fetch_b1(comp, m)
	if f is None and source(comp) == 'web':
		why = state(comp).get('neterrs', {}).get(m['name']) or state(comp).get('neterr') or m['name'] + ': not downloaded yet, press CHECK NOW'
	return f, why


def have(comp, m):
	return _fetch_b1(comp, m)[0] is not None


# ---- descargas: en un hilo que no toca nada de TouchDesigner
def good_catalog(b):
	d = json.loads(b.decode('utf-8'))
	for m in d['modules']:
		if not (FILE_OK.fullmatch(m['file']) and re.fullmatch('[0-9a-f]{64}', m['sha256']) and re.fullmatch('[A-Za-z0-9_]+', m['name']) and m['cat'] and m['version']):
			raise ValueError('wrong entry in the list')
	return True


def trust():
	"""Control de certificados completo, con las raíces que trae TouchDesigner (certifi) y las de Windows que no han caducado: el
	contexto por defecto carga también las caducadas y rechaza webs buenas (una copia vieja de ISRG Root X2, en la de la librería)."""
	c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
	try:
		import certifi
		c.load_verify_locations(certifi.where())
	except (ImportError, OSError):
		pass
	if not hasattr(ssl, 'enum_certificates'):
		c.set_default_verify_paths()
		return c
	for der, kind, use in ssl.enum_certificates('ROOT'):
		if kind != 'x509_asn' or not (use is True or '1.3.6.1.5.5.7.3.1' in use):
			continue
		try:
			one = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
			one.load_verify_locations(cadata=der)
			if all(ssl.cert_time_to_seconds(x['notAfter']) > time.time() for x in one.get_ca_certs()):
				c.load_verify_locations(cadata=der)
		except ssl.SSLError:
			pass
	return c


def worker(job):
	ctx = trust()
	for url, dst, name, size, sha in job['items']:
		if job['stop']:
			break
		try:
			with urllib.request.urlopen(urllib.request.Request(url, headers=AGENT), timeout=15, context=ctx) as r:
				b = r.read(size + 1)
			if len(b) > size:
				raise ValueError('bigger than it should be')
			if sha is None:
				good_catalog(b)
			elif hashlib.sha256(b).hexdigest() != sha:
				raise ValueError('it does not match the list yet, try again later')
			os.makedirs(os.path.dirname(dst), exist_ok=True)
			with open(dst + '.tmp', 'wb') as h:
				h.write(b)
			os.replace(dst + '.tmp', dst)
		except urllib.error.HTTPError as e:
			job['errs'][name] = '%s: the web answers %d' % (name, e.code)
		except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
			bad = isinstance(getattr(e, 'reason', None), ssl.SSLError)
			job['err'] = 'The certificate of the web is not valid on this computer' if bad else 'No connection with the web'
			break
		except Exception as e:
			job['errs'][name] = '%s: %s' % (name, e)
		job['done'] += 1


def download(comp, items, then, *args):
	s = state(comp)
	s['neterr'], s['neterrs'] = '', {}
	if not items:
		return then(comp, *args)
	job = {'items': items, 'done': 0, 'err': '', 'errs': {}, 'was': comp.par.Status.eval(), 'stop': False, 'then': then, 'args': args}
	s['busy'], s['net'] = True, job
	out(comp, busy=1)
	job['thread'] = threading.Thread(target=worker, args=(job,), daemon=True)
	job['thread'].start()
	poll_net(comp)


def poll_net(comp):
	s = state(comp)
	job = s.get('net')
	if not job:
		return
	n = len(job['items'])
	if job['thread'].is_alive():
		s['total'], s['queue'] = n, [0] * (n - job['done'])     # la barra de arriba
		say(comp, 'Connecting' + DOTS if job['items'][0][4] is None else 'Downloading %d / %d' % (min(n, job['done'] + 1), n))
		redraw(comp)
		return run("args[0].valid and args[0].op('util').module.poll_net(args[0])", comp, delayMilliSeconds=100, delayRef=op.TDResources)
	s['net'], s['busy'], s['queue'] = None, False, []
	s['neterr'], s['neterrs'] = job['err'] or next(iter(job['errs'].values()), ''), job['errs']
	say(comp, job['was'])
	out(comp, busy=0)
	job['then'](comp, *job['args'])
	redraw(comp)


def items_of(comp, mods):
	a, r = address(comp), web_root(comp)
	return [(a + m['file'], r + '/' + m['file'], m['name'], int(m['size']), m['sha256']) for m in mods if not have(comp, m)]


# ---- CHECK NOW
def check_now(comp):
	s = state(comp)
	s['warn'] = ''
	if source(comp) == 'local':
		check(comp)
		return own_news(comp)
	a = address(comp)
	if a is None:
		s['warn'] = 'The Web Address has to start with https://'
		say(comp, s['warn'])
		return redraw(comp)
	download(comp, [(a + 'catalog.json', web_root(comp) + '/catalog.json', 'catalog.json', 8000000, None)], got_list)


def got_list(comp):
	s = state(comp)
	err = s['neterr']
	if library(comp) is None:
		s['warn'] = err or 'No list on that web'
		return say(comp, s['warn'])
	if err:
		err += ': using the list of ' + list_date(comp)
	else:
		os.utime(web_root(comp) + '/catalog.json')
	try:
		load_catalog(comp)
	except Exception as e:
		s['warn'] = 'catalog.json cannot be read: %s' % e
		return say(comp, s['warn'])
	late = {n: s['cat'][n] for o, n, v, ren in walk(comp) if vtuple(v) < vtuple(s['cat'][n]['version'])}
	if s['neterr']:
		return got_files(comp, err)                  # sin conexión: con lo que haya
	download(comp, items_of(comp, late.values()), got_files, err)


def got_files(comp, err):
	s = state(comp)
	e2 = s['neterr']
	check(comp)
	s['warn'] = err or e2
	if not s['warn']:
		own_news(comp)
	redraw(comp)


def own_news(comp):
	m = state(comp).get('cat', {}).get('libraryCTRL')
	if m and vtuple(m['version']) > vtuple(comp.par.Version.eval()):
		state(comp)['warn'] = 'Newer libraryCTRL (%s) in LIBRARY: add it, delete this one' % m['version']
		redraw(comp)


def list_date(comp):
	r = library(comp)
	return time.strftime('%Y-%m-%d', time.localtime(os.path.getmtime(r + '/catalog.json'))) if r else ''


def foot_tag(comp):
	if not state(comp).get('cat'):
		return ''
	return 'from the web, ' + list_date(comp) if source(comp) == 'web' else 'from a folder'


# ---- actualizar y añadir: lo que falte se baja antes
_start_b1, _add_b3, _lib_open_b3 = start, add, lib_open


def start(comp, jobs):
	s = state(comp)
	if source(comp) == 'local' or not s.get('cat'):
		return _start_b1(comp, jobs)
	mods = {r['module']: s['cat'][r['module']] for p, w in jobs if w == 'update' for r in [row(comp, p)] if r}
	download(comp, items_of(comp, mods.values()), _start_b1, jobs)


def add(comp, name):
	s = state(comp)
	m = s.get('cat', {}).get(name)
	if m is None or source(comp) == 'local':
		return _add_b3(comp, name)
	return download(comp, items_of(comp, [m]), _add_b3, name)


# ---- la paleta de quien usa la librería: Palette/l1vmet3s/<CAT>, solo lo que es de la librería
def pal_have(comp):
	"""Lo que puso libraryCTRL en la paleta: {nombre: ficha}"""
	try:
		with open(palette() + '/' + PACK + '/catalog.json', encoding='utf-8') as f:
			return {m['name']: m for m in json.load(f)['modules']}
	except (OSError, ValueError, KeyError):
		return {}


def pal_todo(comp):
	old, cat = pal_have(comp), state(comp).get('cat', {})
	return [m for n, m in cat.items() if n not in old or old[n]['sha256'] != m['sha256'] or old[n]['file'] != m['file']
			or not os.path.isfile(pal_path(m))], [m for n, m in old.items() if n not in cat]


def pal_path(m):
	return palette() + '/' + PACK + '/' + m['file'][4:]


def pal_info(comp):
	s = state(comp)
	if linked():
		t, k = 'Your palette is linked to the library', 'linked'
	elif not s.get('cat'):
		t, k = 'Press Check Now', 'none'
	else:
		new, gone = pal_todo(comp)
		if not pal_have(comp):
			t, k = 'Not in your palette yet', 'new'
		elif new or gone:
			t, k = '%d to update in your palette' % (len(new) + len(gone)), 'late'
		else:
			t, k = 'Your palette is up to date', 'ok'
	s['pal'] = k
	say(comp, t, 'Paletteinfo')


def pal_update(comp):
	s = state(comp)
	s['warn'] = ''
	pal_info(comp)
	if s['pal'] in ('linked', 'ok'):
		return say(comp, comp.par.Paletteinfo.eval(), 'Report')
	if s['pal'] == 'none':
		s['warn'] = 'Press CHECK NOW first'
		return
	new = pal_todo(comp)[0]
	if source(comp) == 'local':
		return pal_write(comp)
	download(comp, items_of(comp, new), pal_write)


def sha_of(f):
	with open(f, 'rb') as h:
		return hashlib.sha256(h.read()).hexdigest()


def pal_write(comp):
	s = state(comp)
	old, root = pal_have(comp), palette() + '/' + PACK
	new, gone = pal_todo(comp)
	safe = backups(comp) + '/palette_' + time.strftime('%Y%m%d_%H%M%S')
	done, kept, bad = 0, 0, []

	def aside(f, m):
		"""Lo que ha guardado encima el usuario no se pierde: va a la carpeta de copias."""
		if not os.path.isfile(f) or (m is not None and sha_of(f) in (m['sha256'], old.get(m['name'], {}).get('sha256'))):
			return 0
		d = safe + '/' + f[len(root) + 1:]
		os.makedirs(os.path.dirname(d), exist_ok=True)
		shutil.copy2(f, d)
		return 1
	try:
		for m in new:
			f, why = fetch(comp, m)
			if f is None:
				bad.append(why)
				continue
			d = pal_path(m)
			kept += aside(d, m)
			os.makedirs(os.path.dirname(d), exist_ok=True)
			shutil.copyfile(f, d + '.tmp')
			os.replace(d + '.tmp', d)
			o = old.get(m['name'])
			if o and o['file'] != m['file']:
				gone.append(o)
			old[m['name']] = m
			done += 1
		for m in gone:                               # ya no está en la librería (o ha cambiado de categoría)
			d = pal_path(m)
			kept += aside(d, m)
			if os.path.isfile(d):
				os.remove(d)
			if old.get(m['name']) is m:
				del old[m['name']]
		os.makedirs(root, exist_ok=True)
		with open(root + '/catalog.json.tmp', 'w', encoding='utf-8') as h:
			json.dump({'modules': list(old.values())}, h, ensure_ascii=False, indent=1)
		os.replace(root + '/catalog.json.tmp', root + '/catalog.json')
		pal_list()
	except Exception as e:
		bad.append(str(e))
	pal_info(comp)
	say(comp, '%d module%s put in your palette (My Components / %s)' % (done, '' if done == 1 else 's', PACK) + (', %d of yours saved in Backups' % kept if kept else ''), 'Report')
	if bad:
		s['warn'] = 'Palette: ' + bad[0] + (' (and %d more)' % (len(bad) - 1) if len(bad) > 1 else '')
	redraw(comp)


def pal_list():
	"""La lista que enseña el Palette Browser es un archivo: se pone al día nuestra carpeta y no se toca lo demás."""
	p = palette()

	def tree(d, i):
		k = [x for x in sorted(os.listdir(d), key=str.lower) if os.path.isdir(d + '/' + x) or x.endswith('.tox')]
		r = {'name': os.path.basename(d), 'path': d[len(p):].replace('/', chr(92)), 'id': i, 'type': 'directory', 'children': []}
		for n, x in enumerate(k):
			q, j = d + '/' + x, '%s.%d' % (i, n + 1)
			r['children'].append(tree(q, j) if os.path.isdir(q) else {'name': x, 'path': q[len(p):].replace('/', chr(92)), 'id': j, 'type': 'file'})
		return r
	f = p + '/paletteData.json'
	try:
		with open(f, encoding='utf-8') as h:
			d = json.load(h)
		ch = d['children']
	except (OSError, ValueError, KeyError):
		d = {'id': '2', 'localRoot': 'app.userPaletteFolder', 'name': 'My Components', 'palette': 'My Components', 'path': 'app.userPaletteFolder', 'type': 'directory'}
		ch = [c for c in tree(p, '2')['children'] if c['name'] != PACK]
	mine = next((c for c in ch if c['name'] == PACK), None)
	i = mine['id'] if mine else '2.%d' % (1 + max([int(c['id'].split('.')[-1]) for c in ch] or [0]))
	ch = [c for c in ch if c is not mine] + [tree(p + '/' + PACK, i)]
	d['children'] = sorted(ch, key=lambda c: int(c['id'].split('.')[-1]))
	t = json.dumps(d, sort_keys=True, indent=4)
	with open(f + '.tmp', 'w', encoding='utf-8') as h:
		h.write(t)
	os.replace(f + '.tmp', f)
	live = op('/ui/dialogs/palette/palette/cusPalette')
	if live is not None and p == app.userPaletteFolder.replace(chr(92), '/'):
		live.text = t                                # el Palette Browser abierto la enseña ya


# ---- panel
_library_view_b3 = VIEWS['library']


def library_view4(comp, s, busy, rect, label, button, hits):
	if not s.get('cat'):
		web = source(comp) == 'web'
		label(PAD, Y_ROWS + 24, 'Downloads the list, and the new version of the modules in this project.' if web else 'No library found.', C_TXT)
		label(PAD, Y_ROWS + 48, cut(comp, comp.par.Webaddress.eval(), TW - 2 * PAD) if web else
			'Choose its folder (the one with catalog.json) or Source = Web on the Library page.', C_DIM)
		if web:
			button(PAD, Y_TOOL + 9, 150, 30, 'GET THE LIST', 'check', on=not busy, fill=C_ACC, ink=C_INK)
		return
	_library_view_b3(comp, s, busy, rect, label, button, hits)
	k, x = s.get('pal', 'none'), PAD + 278
	if k in ('linked', 'ok'):
		label(x + 10, Y_BTN + 15, comp.par.Paletteinfo.eval(), C_DIM)
	else:
		button(x, Y_BTN, 270, 30, 'PUT THEM ALL IN MY PALETTE' if k == 'new' else 'UPDATE MY PALETTE', 'palette', on=not busy)


VIEWS['library'] = library_view4

_do_click_b3, _on_change_b3, _on_pulse_b3, _check_b3, _on_start_b3 = do_click, on_change, on_pulse, check, on_start


def lib_open(comp):
	s = state(comp)
	if s.get('cat') or library(comp) is not None:
		_lib_open_b3(comp)
		pal_info(comp)


def do_click(comp, kind, arg):
	if kind not in ('check', 'palette'):
		return _do_click_b3(comp, kind, arg)
	redraw(comp)
	if locked(comp):
		if ui.performMode:
			state(comp)['warn'] = 'Not in Perform Mode'
	elif kind == 'check':
		check_now(comp)
	else:
		pal_update(comp)


def on_change(comp, par, prev):
	_on_change_b3(comp, par, prev)
	if par.name in ('Source', 'Folder', 'Webaddress'):
		s = state(comp)
		if s.get('busy'):
			return
		s['cat'], s['armed'], s['warn'] = {}, None, ''       # otra librería: hay que volver a mirar
		t = comp.op('items')
		t.clear()
		t.appendRow(HEAD)
		fill_menu(comp)
		lib_menu(comp)
		pal_info(comp)
		out(comp, modules=0, outdated=0)
		say(comp, 'Press Check Now')


def on_pulse(comp, par):
	if par.name in ('Check', 'Updatepalette'):
		if not locked(comp):
			check_now(comp) if par.name == 'Check' else pal_update(comp)
		return redraw(comp)
	_on_pulse_b3(comp, par)


def check(comp):
	_check_b3(comp)
	pal_info(comp)


def on_start(comp):
	_on_start_b3(comp)
	pal_info(comp)
start python · 30 línieslíneaslines
# start: al abrir el proyecto o soltar el .tox. Nada por frame.
def onStart():
	op('util').module.on_start(me.parent())
	return

def onCreate():
	op('util').module.on_start(me.parent())
	return

def onExit():
	return

def onFrameStart(frame):
	return

def onFrameEnd(frame):
	return

def onPlayStateChange(state):
	return

def onDeviceChange():
	return

def onProjectPreSave():
	return

def onProjectPostSave():
	return
list_exec python · 21 línieslíneaslines
# list_exec: pars del propio libraryCTRL → util
def onValueChange(par, prev):
	op('util').module.on_change(me.parent(), par, prev)
	return

def onPulse(par):
	op('util').module.on_pulse(me.parent(), par)
	return

def onExpressionChange(par, val, prev):
	return

def onExportChange(par, val, prev):
	return

def onEnableChange(par, val, prev):
	return

def onModeChange(par, val, prev):
	return
tile_click python · 18 línieslíneaslines
# tile_click: un clic en el panel
def onOffToOn(panelValue):
	t = me.parent().op('tile')
	op('util').module.tile_click(me.parent(), float(t.panel.u), float(t.panel.v))
	return

def whileOn(panelValue):
	return

def onOnToOff(panelValue):
	return

def whileOff(panelValue):
	return

def onValueChange(panelValue, prev):
	return
tile_shader glsl · 25 línieslíneaslines
// libraryCTRL: tile. Entrada 0 = rects (N x 3: fila 0 caja x0 y0 x1 y1 en px con y hacia abajo, fila 1 relleno,
// fila 2 tinta del texto; alfa 0 = no cambia), entrada 1 = textos en blanco (Text TOP). El último rect manda.
uniform vec4 uN;    // x: nº de rects
out vec4 fragColor;
void main() {
	vec2 R = uTDOutputInfo.res.zw;
	vec2 p = vUV.st * R;
	float yd = R.y - p.y;
	vec3 c = vec3(0.07);
	vec3 ink = vec3(0.92);
	int n = int(uN.x + 0.5);
	for (int i = 0; i < n; i++) {
		vec4 r = texelFetch(sTD2DInputs[0], ivec2(i, 0), 0);
		if (p.x >= r.x && p.x < r.z && yd >= r.y && yd < r.w) {
			vec4 f = texelFetch(sTD2DInputs[0], ivec2(i, 1), 0);
			vec4 k = texelFetch(sTD2DInputs[0], ivec2(i, 2), 0);
			if (f.a > 0.0) c = f.rgb;
			if (k.a > 0.0) ink = k.rgb;
		}
	}
	vec4 t = texture(sTD2DInputs[1], vUV.st);
	c = mix(c, ink, t.a);
	fragColor = TDOutputSwizzle(vec4(c, 1.0));
}
tile_data_callbacks python · 12 línieslíneaslines
# libraryCTRL: rects del tile (util.tile_array) a la textura; solo cocina cuando cambia tile_size (tick)
def onSetupParameters(scriptOp):
	return

def onPulse(par):
	return

def onCook(scriptOp):
	scriptOp.parent().op('tile_size')['tick'].eval()
	scriptOp.copyNumpyArray(scriptOp.parent().op('util').module.tile_array(scriptOp.parent()))
	return

Aquesta part és en castellà.This part is in Spanish.

Decisiones de diseño
  • Cambiar el componente entero, no parchear por dentro. Lo que hubiera modificado a mano dentro de un módulo no pasa al nuevo; queda en la copia.
  • Solo pasa lo que has tocado. Un valor que sigue en el default viejo toma el default nuevo, salvo en las opciones que la versión nueva estrena: esas entran en su valor neutro para que la imagen no cambie sola.
  • Nada automático. Ni comprueba al abrir el proyecto ni se conecta por su cuenta. En un directo, lo último que hace falta es un módulo que decide. En Perform, o mientras recXPORT graba, se niega a cambiar nada.
  • Siempre hay vuelta atrás: la copia se guarda antes de tocar y Restore la vuelve a poner por el mismo camino.
  • Segunda pulsación solo cuando hay algo que perder (ajustes que no pasan, cambio de número mayor o de nombre). Pedirla siempre enseña a pulsar dos veces sin leer.
  • Update All no hace los cambios grandes: esos hay que mirarlos de uno en uno.
  • La web se guarda en disco con la misma forma que la librería local. Todo lo demás lee de una carpeta y no sabe de dónde vino.
  • No se actualiza a sí mismo: avisa de que hay uno más nuevo; se añade el nuevo y se borra el viejo.
  • El panel no tiene scroll: nueve filas por página y un alto fijo, para que los botones no se muevan de sitio.
Lo que falló y cómo se arregló
SíntomaCausaSolución
Con la web ya publicada, «No connection with the web»; el navegador la abríaWindows guarda una raíz caducada (ISRG Root X2) y Python la elige antes que la buenatrust(): las raíces de certifi y las de Windows sin caducar, con la comprobación completa (checklist #578)
Al actualizar un módulo conectado a un Composite, las capas cambiaban de ordenBorrar el viejo antes de cablear: las entradas múltiples se correnConectar el nuevo sobre la entrada del viejo y borrar el viejo después
El módulo nuevo arrancaba con los valores del .tox y después cambiabaonCreate salta en la misma llamada que lo creaCargarlo en stage (sin cooking), pasarle los valores y copiarlo ya completo a su red
typeGEN, stackFX… salían con los valores buenos y la imagen del ejemploCon el módulo parado sus Parameter Execute no se enteran de lo escritopoke (volver a avisar) y settle (repasar los valores) unos frames después
typeGEN 1.1 → 1.2 llenaba la pantalla de líneasEl .tox nuevo trae encendidas opciones que la versión vieja no teníaTabla neutral en library.json
«Audio CHOP» aparecía como ajuste perdido sin haberlo tocadoUn par OP vacío no es igual a su default al compararlostouched trata aparte los pars OP
loopFX y stackFX informaban de un error que ya no estabaErrores del instante de cargar, que se quedan apuntadosalive: limpiar errores, recocinar los operadores que se quejaban y mirar otra vez antes de informar
El ratón desaparecía encima de la ventanacursorvisible = 'always' no existe y el menú cayó a nocursor en silencioalwaysvisible, y los builds comprueban los valores de menú
Re-ejecutar build2 rompía el móduloPonía su sección detrás de la de build3, que la amplíaCada build repone su sección en el sitio donde estaba
Con el timeline parado, la descarga no terminaba nuncarun(delayFrames) cuenta frames del timelinerun(delayMilliSeconds, delayRef=op.TDResources)
El fallo de una descarga salía en todos los módulosUn solo mensaje de error comúnErrores por módulo
Cuánto cuesta
QuéMedido
En reposo0 operadores cocinando, 0 Python por frame
Check Now con carpeta local~1 s (la primera vez lee la ficha de los que tienen versión nueva)
Cambiar un módulo~0,2 s, más 14–30 frames de repaso
89 actualizaciones seguidas68 s
Añadir un módulode casi nada a ~2 s (city3D y gradientGEN, los más pesados)
Descargando42–45 ms el frame más largo; la librería entera pesa 2,6 MB

Cambiar módulos da tirones: es trabajo de preparación, no de directo.

Comprobado: 89 versiones de tox/Old actualizadas sin errores ni cables perdidos, con la imagen igual que la vieja (menos analogFX 1.1, cuya parte de impresión pasó a printFX: avisa); Restore ida y vuelta con 0 diferencias (gridGEN, y ledOUT con 4 tiras y 238 ajustes); los 55 módulos del catálogo añadidos seguidos sin solaparse. Un archivo alterado no se carga. Un módulo dormido sigue dormido y el Learn de midiCTRL / consoleCTRL se apaga durante el cambio y vuelve a como estaba.

Sin probar: actualizar faceTrackGEN, setupCTRL, videoinGEN, beatsyncCTRL, pulsesyncCTRL y consoleCTRL (abren hardware, red o procesos). La descarga contra la web publicada (llumetes.pages.dev) está probada: buscar, actualizar y añadir.