-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
250 lines (198 loc) · 8.07 KB
/
main.py
File metadata and controls
250 lines (198 loc) · 8.07 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
from pysvg.filter import *
from pysvg.gradient import *
from pysvg.linking import *
from pysvg.script import *
from pysvg.shape import *
from pysvg.structure import *
from pysvg.style import *
from pysvg.text import *
from pysvg.builders import *
from pysvg.parser import parse
import json
import argparse
import os
from termcolor import cprint
import time
from deepmerge import always_merger
import helpers
# import png_renderer
import legend
import labels
def style_order_helper():
global style_order
style_order = []
for styl in styles['label']:
style_order.append(styl)
def order_chooser(elems, order):
if (order == "regular"):
return(elems)
elif (order == "reversed"):
return(reversed(elems))
else:
raise Exception("order needs to be 'regular' or 'reversed'")
def style_sort(k):
return (style_order.index(k['style']))
def styles_in_sheet_helper():
pass
def replace_variables(obj, variables):
if isinstance(obj, dict):
for key, value in obj.items():
obj[key] = replace_variables(value, variables)
return obj
elif isinstance(obj, list):
return [replace_variables(item, variables) for item in obj]
elif isinstance(obj, str) and obj.startswith("$"):
var_name = obj[1:]
if var_name in variables:
return variables[var_name]
return obj
def include_files_recursively(file, data, variables):
file_descriptor = open(file)
file_json = json.load(file_descriptor)
file_descriptor.close()
for item in file_json.get("variables", []):
always_merger.merge(variables, item)
file_json = replace_variables(file_json, variables)
always_merger.merge(data, file_json) #maybe after recursive ?
if ("includes" in file_json):
for include_file in file_json["includes"]:
include_files_recursively(include_file, data, variables)
def load_pins_file(filepath, svg):
board_data = {}
variables = {}
include_files_recursively(filepath, board_data, variables)
global legend_data
legend_data = board_data["legend"]
global license_data
license_data = []
if "license" in board_data:
license_data = board_data["license"]
global additional_data
additional_data = []
if "additional" in board_data:
additional_data = board_data["additional"]
filename = os.path.splitext(os.path.basename(filepath))[0]
board = G(**helpers.kwargs_helper([("id", filename)]))
for index, pin_group in enumerate(board_data["groups"]):
group_name = filename + "_" + str(index) + "_" + pin_group["name"]
units = "px"
if ("units" in pin_group["origin"]):
units = pin_group["origin"]["units"]
x = helpers.units_to_pixels(pin_group["origin"]["x"], units)
y = helpers.units_to_pixels(pin_group["origin"]["y"], units)
group = G(**helpers.kwargs_helper([("id", group_name), ("transform", "translate(" + str(x) + ", " + str(y) + ")")]))
#adding all the syles encountered in a list for the legend excluding the omited categories
for pind in pin_group["pins"]:
for func in pind["functions"]:
if ("categories" in func) and any(check in func["categories"] for check in omit_categories):
pass
elif (func["style"] not in styles_in_sheets):
styles_in_sheets.append(func["style"])
#choosing the order (from top to bottom aka regular or from bottom to top aka reversed)
order="regular"
if ("order" in pin_group):
order = pin_group["order"]
#sort the pins with their style
for pind in pin_group["pins"]:
pin_functions = pind["functions"]
pin_functions.sort(key=style_sort) #sort the label within pin with the order of the styles in the style.json
#make the pin
y_pin_origin = 0
group_list = order_chooser(pin_group["pins"], order)
number_pins_in_group = len(group_list)
for pin_number_in_group, b in enumerate(group_list):
#print(order_chooser(pin_group["pins"], order))
labels.pin_maker(b, pin_number_in_group, number_pins_in_group, group, 0, y_pin_origin, pin_group["side"], pin_group, styles, omit_styles, omit_categories)
spacing = helpers.inch_to_pixels(0.1)
if ("spacing" in pin_group):
spacing = pin_group["spacing"]
y_pin_origin = y_pin_origin + helpers.mm_to_pixels(spacing)
board.addElement(group)
svg.addElement(board)
# def categories_helper(filepath_array):
# for (filepath in filepath_array):
# f = open(filepath)
# board_data = json.load(f)
# f.close()
# for group in board_data["groups"]:
# for f in pin_data['functions']:
if __name__ == '__main__':
start = time.time()
global styles #all the styles in the json style file
global categories #all the categories in the json pin file
global omit_categories
global sheet_name
global styles_in_sheets
styles_in_sheets = []
# A4 paper = 210 x 297 mm
all_args = argparse.ArgumentParser()
all_args.add_argument('-p', "--pins", action='append', required=True, help="pins.json file(s)")
all_args.add_argument("-s", "--style", required=False, help="style.json file")
all_args.add_argument('-os', "--omit_styles", action='append', required=False, help="prevent plotting of a style")
all_args.add_argument('-oc', "--omit_categories", action='append', required=False, help="prevent plotting of a category")
all_args.add_argument("-l", "--legend", action='store_true', required=False, help="plotting the legend")
all_args.add_argument("-w", "--show", action='store_true', required=False, help="show a preview png file (not 100% accurate).")
all_args.add_argument('-i', "--inkscape", action='store_true', required=False, help="open inkscape")
all_args.add_argument("-o", "--output", required=False, help="name of the output file (pinout.svg is the default value)")
all_args.add_argument("-f", "--font", required=False, help="include a font file into the output svg")
all_args.add_argument("-ps", "--paper_size", required=False, help="specify the page size ('A3', 'A4', 'A5')")
all_args.add_argument("-po", "--paper_orientation", required=False, help="specify the page orientation ('Portraitt', 'Landscape')")
args = vars(all_args.parse_args())
#print(args)
style_file = 'styles.json'
if (args['style']):
style_file = args['style']
fstyles = open(style_file)
styles = json.load(fstyles)
fstyles.close()
omit_categories = []
omit_styles = []
# omit_styles = ["portPin", "default", "led", "timer", "adc", "dac", "i2c", "spi", "audio", "control", "jtag", "usb", "rtc"] #["timer"]
if (args['paper_size']):
paper_size = str(args['paper_size'])
else:
paper_size = "A4"
if (args['paper_orientation']):
paper_orientation = str(args['paper_orientation'])
else:
paper_orientation = "Portrait"
cprint("Page size is " + paper_size + " | orientation " + paper_orientation, "blue")
page_size = helpers.paper_size(paper_size, paper_orientation)
s = Svg(0, 0, page_size["px"][0], page_size["px"][1])
#test = parse("licenses/by-nc.svg")
if (args['omit_styles']):
for omit_styles_arg in args['omit_styles']:
if (omit_styles_arg not in styles['label']):
cprint("Warning: '" + omit_styles_arg + "' is not present in the style file. skipping", "yellow")
else:
omit_styles.append(omit_styles_arg)
if (args['omit_categories']):
for omit_categories_arg in args['omit_categories']:
omit_categories.append(omit_categories_arg)
#TODO: check if the category exist
style_order_helper()
for pin_file in args['pins']:
load_pins_file(pin_file, s)
if (args['legend']):
legend.legend_maker(s, styles, omit_styles, omit_categories, legend_data, styles_in_sheets, page_size)
output_file = "pinout.svg"
if (args['output']):
output_file = str(args['output'])
helpers.include_additional(s, additional_data, page_size)
helpers.include_license(s, license_data, page_size)
s.save(output_file)
end = time.time()
cprint("Done in %.3f"%(end - start) + "s ! Happy pin making :)", "green")
if (args['show']):
cprint("Opening the rendered png file ...", "blue")
png_renderer.show_svg(output_file, s.get_width(), s.get_height())
if (args['inkscape']):
if (helpers.is_tool("inkscape")):
cprint("Opening inkscape ...", "blue")
os.system("inkscape " + output_file + " 2> /dev/null &") #quiet please
else:
helpers.inkscape_not_here_helper()
if (args['font']):
font_file = str(args['font'])
cprint("including the font " + font_file, "blue")
helpers.include_font_file(font_file, output_file)