-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
panelize_ui.py
377 lines (324 loc) · 14.1 KB
/
panelize_ui.py
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
import click
import os
import csv
import io
import glob
import traceback
from kikit.panelize_ui_sections import *
PKG_BASE = os.path.dirname(__file__)
PRESETS = os.path.join(PKG_BASE, "resources/panelizePresets")
IS_CLICK_V8 = click.__version__.startswith("8.")
# We would like to support both, click v7 and v8 in order to maximize
# compatibility. However, since click v8.1 there is breaking change in the way
# shell completion works. This functions hides the differences and should allow
# us to use both. Pass to it as **addCompatibleCompletion(completionFunction)
def addCompatibleShellCompletion(completionFn):
if IS_CLICK_V8:
import click.shell_completion
def completion(*args, **kwargs):
return [click.shell_completion.CompletionItem(x) for x in completionFn(*args, **kwargs)]
return {"shell_complete": completionFn}
else:
return {"autocompletion": completionFn}
def splitStr(delimiter, escapeChar, s):
"""
Splits s based on delimiter that can be escaped via escapeChar
"""
# Let's use csv reader to implement this
reader = csv.reader(io.StringIO(s), delimiter=delimiter, escapechar=escapeChar)
# Unpack first line
for x in reader:
return x
class Section(click.ParamType):
"""
A CLI argument type for overriding section parameters. Basically a semicolon
separated list of `key: value` pairs. The first word might omit the key; in
that case "type" key is used.
"""
name = "parameter_list"
def convert(self, value, param, ctx):
if len(value.strip()) == 0:
self.fail(f"{value} is not a valid argument specification",
param, ctx)
try:
values = {}
for i, pair in enumerate(splitStr(";", "\\", value)):
if len(pair.strip()) == 0:
continue
s = pair.split(":", 1)
if i == 0 and len(s) == 1:
values["type"] = s[0].strip()
continue
key, value = s[0].strip(), s[1].strip()
values[key] = value
return values
except (TypeError, IndexError):
self.fail(f"'{pair}' is not a valid key: value pair",
param,
ctx)
class HookPlugin(click.ParamType):
"""
A CLI argument type for a HookPlugin. The format is <moduleName or
path>:<plugin name>:<arg>. The arg is optional.
"""
name = "<module>.<plugin>:[arg]"
def convert(self, value, param, ctx):
pieces = value.split(":", maxsplit=1)
specPieces = pieces[0].rsplit(".", maxsplit=1)
if len(specPieces) < 2:
self.fail(f"{value} is not a valid plugin specification")
module = specPieces[0]
pluginName = specPieces[1]
arg = "" if len(pieces) == 2 else pieces[1]
return (module, pluginName, arg)
def completePath(prefix, fileSuffix=""):
"""
This is rather hacky and far from ideal, however, until Click 8 we probably
cannot do much better.
"""
paths = []
for p in glob.glob(prefix + "*"):
if os.path.isdir(p):
paths.append(p + "/")
elif p.endswith(fileSuffix):
paths.append(p)
return paths
def pathCompletion(fileSuffix=""):
def f(ctx, args, incomplete):
return completePath(incomplete, fileSuffix)
return f
def completePreset(ctx, args, incomplete):
presets = [":" + x.replace(".json", "")
for x in os.listdir(PRESETS)
if x.endswith(".json") and (x.startswith(incomplete) or x.startswith(incomplete[1:]))]
if incomplete.startswith(":"):
return presets
return presets + completePath(incomplete, ".json")
def lastSectionPair(incomplete):
"""
Given an incomplete command text of a section, return the last (possibly
incomplete) key-value pair
"""
lastSection = incomplete.split(";")[-1]
x = [x.strip() for x in lastSection.split(":", 1)]
if len(x) == 1:
return x[0], ""
return x
def hasNoSectionPair(incomplete):
return ";" not in incomplete
def completeSection(section):
def fun(ctx, args, incomplete):
if incomplete.startswith("'"):
incomplete = incomplete[1:]
key, val = lastSectionPair(incomplete)
candidates = []
if hasNoSectionPair(incomplete):
candidates.extend([x for x in section["type"].vals if x.startswith(incomplete)])
if len(val) == 0:
trimmedIncomplete = incomplete.rsplit(";", 1)[0]
candidates.extend([trimmedIncomplete + x + ":"
for x in section.keys() if x.startswith(key)])
return candidates
return fun
@click.command()
@click.argument("input", type=click.Path(dir_okay=False),
**addCompatibleShellCompletion(pathCompletion(".kicad_pcb")))
@click.argument("output", type=click.Path(dir_okay=False),
**addCompatibleShellCompletion(pathCompletion(".kicad_pcb")))
@click.option("--preset", "-p", multiple=True,
help="A panelization preset file; use prefix ':' for built-in styles.",
**addCompatibleShellCompletion(completePreset))
@click.option("--plugin", multiple=True, type=HookPlugin(),
help="A hook plugin to use during the panelization",
**addCompatibleShellCompletion(completePreset))
@click.option("--layout", "-l", type=Section(),
help="Override layout settings.",
**addCompatibleShellCompletion(completeSection(LAYOUT_SECTION)))
@click.option("--source", "-s", type=Section(),
help="Override source settings.",
**addCompatibleShellCompletion(completeSection(SOURCE_SECTION)))
@click.option("--tabs", "-t", type=Section(),
help="Override tab settings.",
**addCompatibleShellCompletion(completeSection(TABS_SECTION)))
@click.option("--cuts", "-c", type=Section(),
help="Override cut settings.",
**addCompatibleShellCompletion(completeSection(CUTS_SECTION)))
@click.option("--framing", "-r", type=Section(),
help="Override framing settings.",
**addCompatibleShellCompletion(completeSection(FRAMING_SECTION)))
@click.option("--tooling", "-o", type=Section(),
help="Override tooling settings.",
**addCompatibleShellCompletion(completeSection(TOOLING_SECTION)))
@click.option("--fiducials", "-f", type=Section(),
help="Override fiducials settings.",
**addCompatibleShellCompletion(completeSection(FIDUCIALS_SECTION)))
@click.option("--text", "-t", type=Section(),
help="Override text settings.",
**addCompatibleShellCompletion(completeSection(TEXT_SECTION)))
@click.option("--text2", type=Section(),
help="Override text settings.",
**addCompatibleShellCompletion(completeSection(TEXT_SECTION)))
@click.option("--text3", type=Section(),
help="Override text settings.",
**addCompatibleShellCompletion(completeSection(TEXT_SECTION)))
@click.option("--text4", type=Section(),
help="Override text settings.",
**addCompatibleShellCompletion(completeSection(TEXT_SECTION)))
@click.option("--copperfill", "-u", type=Section(),
help="Override copper fill settings.",
**addCompatibleShellCompletion(completeSection(COPPERFILL_SECTION)))
@click.option("--page", "-P", type=Section(),
help="Override page settings.",
**addCompatibleShellCompletion(completeSection(POST_SECTION)))
@click.option("--post", "-z", type=Section(),
help="Override post processing settings.",
**addCompatibleShellCompletion(completeSection(POST_SECTION)))
@click.option("--debug", type=Section(),
help="Include debug traces or drawings in the panel.",
**addCompatibleShellCompletion(completeSection(DEBUG_SECTION)))
@click.option("--dump", "-d", type=click.Path(file_okay=True, dir_okay=False),
help="Dump constructured preset into a JSON file.")
def panelize(input, output, preset, plugin, layout, source, tabs, cuts, framing,
tooling, fiducials, text, text2, text3, text4, copperfill, page,
post, debug, dump):
"""
Panelize boards
"""
try:
# Hide the import in the function to make KiKit start faster
from kikit import panelize_ui_impl as ki
import sys
from kikit.common import fakeKiCADGui
app = fakeKiCADGui()
preset = ki.obtainPreset(preset,
layout=layout, source=source, tabs=tabs, cuts=cuts, framing=framing,
tooling=tooling, fiducials=fiducials, text=text,text2=text2,
text3=text3, text4=text4, copperfill=copperfill, page=page,
post=post, debug=debug)
doPanelization(input, output, preset, plugin)
if (dump):
with open(dump, "w", encoding="utf-8") as f:
f.write(ki.dumpPreset(preset))
except Exception as e:
import sys
from kikit.panelize import NonFatalErrors
if isinstance(e, NonFatalErrors):
sys.stderr.write(str(e) + "\n")
else:
sys.stderr.write("An error occurred: " + str(e) + "\n")
sys.stderr.write("No output files produced\n")
if isinstance(preset, dict) and preset["debug"]["trace"]:
traceback.print_exc(file=sys.stderr)
sys.exit(1)
def doPanelization(input, output, preset, plugins=[]):
"""
The panelization logic is separated into a separate function so we can
handle errors based on the context; e.g., CLI vs GUI
"""
from kikit import panelize_ui_impl as ki
from kikit.panelize import Panel, NonFatalErrors
from pcbnewTransition.transition import pcbnew
from pcbnewTransition.pcbnew import LoadBoard
from itertools import chain
if preset["debug"]["deterministic"]:
pcbnew.KIID.SeedGenerator(42)
if preset["debug"]["drawtabfail"]:
import kikit.substrate
kikit.substrate.TABFAIL_VISUAL = True
board = LoadBoard(input)
panel = Panel(output)
useHookPlugins = ki.loadHookPlugins(plugins, board, preset)
useHookPlugins(lambda x: x.prePanelSetup(panel))
# Register extra footprints for annotations
for tabFootprint in preset["tabs"]["tabfootprints"]:
panel.annotationReader.registerTab(tabFootprint.lib, tabFootprint.footprint)
panel.inheritDesignSettings(board)
panel.inheritProperties(board)
panel.inheritTitleBlock(board)
panel.inheritLayerNames(board)
useHookPlugins(lambda x: x.afterPanelSetup(panel))
sourceArea = ki.readSourceArea(preset["source"], board)
substrates, framingSubstrates, backboneCuts = \
ki.buildLayout(preset, panel, input, sourceArea)
useHookPlugins(lambda x: x.afterLayout(panel, substrates))
tabCuts = ki.buildTabs(preset, panel, substrates, framingSubstrates)
useHookPlugins(lambda x: x.afterTabs(panel, tabCuts, backboneCuts))
frameCuts = ki.buildFraming(preset, panel)
useHookPlugins(lambda x: x.afterFraming(panel, frameCuts))
ki.buildTooling(preset, panel)
ki.buildFiducials(preset, panel)
for textSection in ["text", "text2", "text3", "text4"]:
ki.buildText(preset[textSection], panel)
ki.buildPostprocessing(preset["post"], panel)
ki.makeTabCuts(preset, panel, tabCuts)
ki.makeOtherCuts(preset, panel, chain(backboneCuts, frameCuts))
useHookPlugins(lambda x: x.afterCuts(panel))
ki.buildCopperfill(preset["copperfill"], panel)
ki.setStackup(preset["source"], panel)
ki.setPageSize(preset["page"], panel, board)
ki.positionPanel(preset["page"], panel)
ki.runUserScript(preset["post"], panel)
useHookPlugins(lambda x: x.finish(panel))
ki.buildDebugAnnotation(preset["debug"], panel)
panel.save(reconstructArcs=preset["post"]["reconstructarcs"],
refillAllZones=preset["post"]["refillzones"],
edgeWidth=preset["post"]["edgewidth"])
if panel.hasErrors():
raise NonFatalErrors(panel.errors)
@click.command()
@click.argument("input", type=click.Path(dir_okay=False))
@click.argument("output", type=click.Path(dir_okay=False))
@click.option("--source", "-s", type=Section(),
help="Specify source settings.")
@click.option("--page", "-P", type=Section(),
help="Override page settings.",
**addCompatibleShellCompletion(completeSection(POST_SECTION)))
@click.option("--debug", type=Section(),
help="Include debug traces or drawings in the panel.")
@click.option("--keepAnnotations/--stripAnnotations", default=True,
help="Do not strip annotations" )
@click.option("--preserveArcs/--looseArcs", default=True,
help="Preserve arcs in the files" )
def separate(input, output, source, page, debug, keepannotations, preservearcs):
"""
Separate a single board out of a multi-board design. The separated board is
placed in the middle of the sheet.
You can specify the board via bounding box or annotation. See documentation
for further details on usage.
"""
try:
from kikit import panelize_ui_impl as ki
from kikit.panelize import Panel, NonFatalErrors
from kikit.units import mm
from pcbnewTransition import pcbnew
from pcbnewTransition.pcbnew import LoadBoard, VECTOR2I
from kikit.common import fakeKiCADGui
app = fakeKiCADGui()
preset = ki.obtainPreset([], validate=False, source=source, page=page, debug=debug)
if preset["debug"]["deterministic"]:
pcbnew.KIID.SeedGenerator(42)
board = LoadBoard(input)
sourceArea = ki.readSourceArea(preset["source"], board)
panel = Panel(output)
panel.inheritDesignSettings(board)
panel.inheritProperties(board)
panel.inheritTitleBlock(board)
panel.inheritLayerNames(board)
destination = VECTOR2I(150 * mm, 100 * mm)
panel.appendBoard(input, destination, sourceArea,
interpretAnnotations=(not keepannotations),
netRenamer=lambda i, x: x,
refRenamer=lambda i, x: x)
ki.setStackup(preset["source"], panel)
ki.setPageSize(preset["page"], panel, board)
ki.positionPanel(preset["page"], panel)
panel.save(reconstructArcs=preservearcs)
if panel.hasErrors():
raise NonFatalErrors(panel.errors)
except Exception as e:
import sys
sys.stderr.write("An error occurred: " + str(e) + "\n")
sys.stderr.write("No output files produced\n")
if isinstance(preset, dict) and preset["debug"]["trace"]:
traceback.print_exc(file=sys.stderr)
sys.exit(1)