-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathpatch_printer.py
More file actions
570 lines (450 loc) · 18.7 KB
/
patch_printer.py
File metadata and controls
570 lines (450 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
"""Module that decodes a Max patcher dict into a textual representation that can then be diffed."""
from known_objects import known_objects
from default_patcher import default_patcher
from object_aliases import object_aliases
from typing import Any
def print_patcher(patcher_dict: dict, summarize: bool = True) -> dict | str:
"""Print a summary of a patcher dict.
Note that the script should only format properties it knows about or is actively set to skip.
Unknown or unexpected data should always be printed as raw json, so that the summary never discards valuable information.
The only exception is the patcher (not presentation) rectangle of objects.
The execution order in case of multiple connections from a single outlet is covered by the line order summaries.
"""
if summarize:
known_objects_map = {}
for box_obj in known_objects["boxes"]:
box = box_obj["box"] # type: ignore
name = get_box_text(box)
known_objects_map[name] = box
display_text = print_top_patcher_summary(patcher_dict)
display_text += print_patcher_summary_recursive(patcher_dict, known_objects_map)
return display_text
else:
import json
return json.dumps(patcher_dict, indent=4, sort_keys=True)
def print_top_patcher_summary(patcher_dict: dict) -> str:
patcher = patcher_dict["patcher"]
summary_string = ""
if "parameters" in patcher:
summary_string += get_parameters_string_block(patcher)
if "dependency_cache" in patcher:
summary_string += get_dependency_cache_string_block(patcher["dependency_cache"])
if "project" in patcher:
summary_string += get_project_string_block(patcher["project"])
if "styles" in patcher:
summary_string += get_styles_string_block(patcher["styles"])
if summary_string != "":
return f"{summary_string}\n"
else:
return ""
def print_patcher_summary_recursive(
patcher_dict: dict, known_objects_map: dict, indent: int = 0
) -> str:
"""Recursively print a summary of a patcher dict."""
if (
"patcher" not in patcher_dict
or "boxes" not in patcher_dict["patcher"]
or "lines" not in patcher_dict["patcher"]
):
return ""
summary_string = create_indented_text("----------- patcher -----------\n", indent)
patcher = patcher_dict["patcher"]
#### patcher ####
skip_patcher_properties = [
"boxes", # iterated over later
"lines", # iterated over later
"parameters", # treated separately
"dependency_cache", # treated separately
"project", # treated separately
"styles", # treated separately
"originid", # invalid Max 9 property
]
properties = get_properties_to_print(
patcher, default_patcher, skip_patcher_properties
)
display_text = ""
for key, value in properties.items():
if key == "appversion":
display_text += get_appversion_string_short(value)
continue
display_text = concat(display_text, f"{key}: {get_property_string(value)}")
if display_text != "":
summary_string += create_indented_text(f"{display_text}\n", indent)
#### objects ####
if not patcher["boxes"]:
return ""
summary_string += create_indented_text("----------- objects -----------\n", indent)
# every entry of "boxes" has a single item "box"
boxes = list(map(lambda val: val["box"], patcher["boxes"]))
skip_box_properties = [
"maxclass", # used in box name
"text", # shown in box name
"id", # used only for lines
"patching_rect", # not relevant for patch diffing (event ordering is shown with "order" property")
"numinlets", # cached from inlet objects
"numoutlets", # cached from outlet objects
"outlettype", # cached from outlet objects
"patcher", # treated separately
"locked_bgcolor", # duplicate from patcher properties
"editing_bgcolor", # duplicate from patcher properties
"color", # duplicate from patcher properties
]
ids_to_names = {}
for box in boxes:
box_text = get_box_text(box)
ids_to_names[box["id"]] = box_text
display_text = ""
object_name = box_text.split()[0]
if object_name not in known_objects_map and object_name in object_aliases:
object_name = object_aliases[object_name]
default_box = {}
if object_name in known_objects_map:
default_box = known_objects_map[object_name]
properties = get_properties_to_print(box, default_box, skip_box_properties)
for key, value in properties.items():
if key == "code":
display_text += get_code_string_block(value, indent + 1)
continue
display_text = concat(display_text, f"{key}: {get_property_string(value)}")
summary_string += create_indented_text(f"[{box_text}] {display_text}\n", indent)
if "patcher" in box:
summary_string += print_patcher_summary_recursive(
box, known_objects_map, indent + 1
)
#### patch cords ####
skip_line_properties = [
"midpoints", # not relevant for patch diffing (event ordering is captured with "order" property")
]
if len(patcher["lines"]) == 0:
return summary_string
summary_string += create_indented_text(
"----------- patch cords -----------\n", indent
)
for line in patcher_dict["patcher"]["lines"]:
from_name = ""
from_outlet = ""
to_name = ""
to_inlet = ""
more_info = ""
for key, val in line.items():
if key == "patchline":
for key2, val2 in val.items():
if key2 in skip_line_properties:
continue
if key2 == "source":
from_name = f"[{ids_to_names[val2[0]]}]"
from_outlet = f"({val2[1]})"
elif key2 == "destination":
to_name = f"[{ids_to_names[val2[0]]}]"
to_inlet = f"({val2[1]})"
else:
more_info = concat(more_info, f"{key2}: {val2}")
else:
more_info = concat(more_info, f"{key}: {value}")
display_text = f"{from_name} {from_outlet} => {to_inlet} {to_name}"
if more_info != "":
display_text += f" | {more_info}"
summary_string += create_indented_text(f"{display_text}\n", indent)
# We don't try to vertically align the sources and destinations of the lines,
# even though that might make this more readable; a change in the maximum
# source object length would affect all other printed lines
return summary_string
def get_box_text(box: dict) -> str:
"""Extract the text in a box in a Max patch.
A box is otherwise known as an "object".
"""
objecttype = box["maxclass"]
boxtext = objecttype
if objecttype == "newobj":
if "text" in box:
boxtext = box["text"]
else:
boxtext = "- empty -"
elif "text" in box:
boxtext = f"{objecttype} {box['text']}"
if objecttype == "bpatcher" and "name" in box:
boxtext = f"{boxtext} {box['name']}"
return boxtext
def get_object_names_from_ids_recursive(
id_hierarchy: list, boxes_parent: list, indent: int = 0
):
"""Translates an object id hierarchy string in the form of "obj-n::obj-m:: etc" to a string
in the form of "<objectname1>/<objectname2/ etc", replacing the object ids with the textual
representation of these objects.
If an object id cannot be found in the patch, for instance because it refers to an object
inside an abstraction, the object id is used instead.
"""
# every entry of "boxes_parent" has a single item "box"
boxes = list(map(lambda val: val["box"], boxes_parent))
id_to_check = id_hierarchy[0] if isinstance(id_hierarchy, list) else id_hierarchy
name = ""
for box in boxes:
if "id" in box:
if id_to_check == box["id"]:
name = get_box_text(box)
if "embed" in box and box["embed"] == 1:
name += " <embedded>"
name = f"[{name}]"
if isinstance(id_hierarchy, list) and len(id_hierarchy) > 1:
id_hierarchy.pop(0)
if "patcher" in box:
subpatcher_boxes = box["patcher"]["boxes"]
name += f"/{get_object_names_from_ids_recursive(id_hierarchy, subpatcher_boxes, indent + 1)}"
else:
for id_level in id_hierarchy:
name += f"/[{id_level}]"
if name == "":
name = f"[{id_to_check}]"
return name
def get_properties_to_print(
box_or_patcher: dict, default: dict, skip_properties: list[str]
) -> dict:
"""Get the properties of a box or patcher that should be printed."""
properties = {}
for key, value in box_or_patcher.items():
if key in skip_properties:
continue
if key == "name" and box_or_patcher.get("maxclass") == "bpatcher":
continue # special case: bpatcher name is already in the box text
if key in default and default[key] == value:
continue
if value == "":
# TODO: are we sure there are no properties that have default values of some string but can be set to an empty string?
continue
if key == "saved_attribute_attributes":
# We take the attributes out or saved_attribute_attributes and present them as properties
attributes = get_saved_attribute_attributes(value)
attributes_to_print = get_properties_to_print(
attributes, default, skip_properties
)
for new_key, new_value in attributes_to_print.items():
properties[new_key] = (
new_value # this may overwrite existing value-based colors. This is ok, we want dynamic color values instead.
)
continue
if key == "saved_object_attributes":
# We take the attributes out or saved_object_attributes and present them as properties
attributes = get_saved_object_attributes(value)
attributes_to_print = get_properties_to_print(
attributes, default, skip_properties
)
for new_key, new_value in attributes_to_print.items():
properties[new_key] = new_value
continue
if key not in properties:
# Don't overwrite existing dynamic colors
properties[key] = value
return properties
def get_property_string(value: str | list) -> str:
"""Produce a string representation of a property value."""
if isinstance(value, list):
property_string = ""
for item in value:
if property_string != "":
property_string += ", "
if isinstance(item, float):
if item.is_integer():
property_string += f"{item:.0f}"
else:
property_string += f"{item:.2f}"
else:
property_string += str(item)
return f"[{property_string}]"
return str(value)
def get_code_string_block(value, indent_amount):
"""Produce a string representing code in a patcher."""
return f"\n{indent(value, indent_amount)}"
def get_saved_attribute_attributes(value: dict) -> dict:
"""Produce a string representing saved attribute attributes in a patcher."""
result = {}
for attrkey, attrvalue in value.items():
if attrvalue == "":
continue
if attrkey == "valueof":
# Handle parameter info. TODO: are there usages of valueof other than for parameter info?
result["parameter"] = f"<{get_object_parameter_string(attrvalue)}>"
continue
# Handle dynamic colors
if "expression" in attrvalue:
if attrvalue["expression"] == "":
continue
if attrvalue["expression"].startswith("themecolor."):
result[attrkey] = attrvalue["expression"].split(".")[1]
continue
result[attrkey] = attrvalue
return result
def get_saved_object_attributes(value: dict) -> dict:
"""Produce a string representing saved object attributes in a patcher."""
result = {}
for attrkey, attrvalue in value.items():
if attrvalue == "":
continue
result[attrkey] = attrvalue
return result
def get_parameters_string_block(patcher: dict) -> str:
"""Produce a string that lists overridden parameters in a patcher.
Non-overridden parameter attributes are already shown with the parameter objects.
"""
parameters = patcher["parameters"]
parameters_string = ""
for bankindex, bank in parameters.items():
if bankindex in ["parameter_overrides", "parameterbanks"]:
continue
parsed_key = bankindex
if bankindex.startswith("obj"):
id_tokens = bankindex.split("::")
parsed_key = get_object_names_from_ids_recursive(id_tokens, patcher["boxes"])
parameters_string += f"\t{parsed_key}: {bank}"
if (
"parameter_overrides" in parameters
and bankindex in parameters["parameter_overrides"]
):
override = parameters["parameter_overrides"][bankindex]
override_print = [
override.get("parameter_longname", "-"),
override.get("parameter_shortname", "-"),
str(override.get("parameter_linknames", "-")),
]
for key, value in override.items():
if key in [
"parameter_longname",
"parameter_shortname",
"parameter_linknames",
]:
continue
override_print.append(f"{key}: {value}")
parameters_string += f" > override > {str(override_print)}"
parameters_string += "\n"
if "parameterbanks" in parameters:
parameters_string += "banks:\n"
for bankindex, bank in parameters["parameterbanks"].items():
for key, value in bank.items():
parameters_string += "\t"
if key == "index":
parameters_string += f"{value}:"
elif key == "name":
parameters_string += f"({value})" if value != "" else ""
elif key == "parameters":
parameters_string += f"encoders: {bank['parameters']}"
elif key == "buttons":
parameters_string += f"buttons: {bank['buttons']}"
else:
parameters_string += f"{value}"
parameters_string += "\n"
return f"parameters:\n{parameters_string}"
def get_dependency_cache_string_block(dependency_cache: list):
"""Produce a string representing a dependency cache in a patcher."""
if len(dependency_cache) < 0:
return ""
dependency_cache_string = ""
for dependency in dependency_cache:
dependency_cache_string += f"\t{dependency}\n"
return (
f"dependency_cache:\n{dependency_cache_string}\n"
if dependency_cache_string != ""
else ""
)
def get_appversion_string_short(appversion: dict):
"""Produce a string representing an appversion in a patcher."""
return f"appversion: {appversion['major']}.{appversion['minor']}.{appversion['revision']}-{appversion['architecture']}-{appversion['modernui']}"
def get_project_string_block(project: dict):
"""Produce a string representing a project in a patcher."""
project_string = ""
for key, value in project.items():
if key != "contents":
project_string = concat(
project_string, f"{key}: {get_property_string(value)}"
)
if "contents" in project:
contents_string = ""
for key2, value2 in project["contents"].items():
key3_string = ""
for key3 in value2:
key3_string += f"\n\t\t\t{key3}"
if key3_string != "":
contents_string += f"\n\t\t{key2}:{key3_string}"
if contents_string != "":
project_string += f"\n\tcontents:{contents_string}"
return f"project:\n\t{project_string}\n"
def get_styles_string_block(styles: Any) -> str:
"""Produce a string representing styles in a patcher."""
styles_string = ""
if len(styles) <= 0:
return styles_string
for style in styles:
styles_string += f"\t{style}\n"
return f"styles:\n{styles_string}\n"
def get_object_parameter_string(parameter: dict) -> str:
"""Produce a string representing an object parameter."""
parameter_string = ""
for key, value in parameter.items():
key_text = key[len("parameter_") :] if key.startswith("parameter_") else key
parameter_string = concat(
parameter_string, f"{key_text}: {get_property_string(value)}"
)
return parameter_string
def concat(a: str, b: str) -> str:
"""Concatenate two strings with a separator if both are non-empty."""
sep = " | "
return sep.join(filter(None, [a, b]))
def create_indented_text(text: str, indent_amount: int = 0) -> str:
"""Indent a string with a given indentation amount."""
return "\t" * indent_amount + text
def indent(text: str, amount: int, ch: str = "\t"):
"""Indent a string with a given indentation amount and character.
It will also split the lines of the string and indent each line.
"""
padding = amount * ch
return "".join(padding + line for line in text.splitlines(True))
color_properties = [
"slidercolor",
"bgcolor",
"bordercolor",
"bordercolor2",
"bgstepcolor",
"tricolor",
"tribordercolor",
"panelcolor",
"hltcolor",
"needlecolor",
"activeneedlecolor",
"circlecolor",
"activetricolor",
"tricolor2",
"activebgcolor",
"bgrulercolor",
"bgfillcolor",
"blinkcolor",
"bgoncolor",
"stepcolor",
"modulationcolor",
"circleoncolor",
"fgdialcolor",
"activefgdialcolor",
"dialcolor",
"focusbordercolor",
"locked_bgcolor",
"editing_bgcolor",
"bgstepcolor2",
"bgunitcolor",
"lcdbgcolor",
"lcdcolor",
"inactivelcdcolor",
"linecolor",
"activetricolor2",
"activeslidercolor",
"directioncolor",
"textcolor",
"activetextcolor",
"textovercolor",
"inactivetextoffcolor",
"textoffcolor",
"trioncolor",
"arrowcolor",
"textoncolor",
"activetextoncolor",
"hlttextcolor",
"labeltextcolor",
"inactivetextoncolor",
"activebgoncolor",
]