This repository has been archived by the owner on Sep 10, 2023. It is now read-only.
forked from Bouni/kicad-jlcpcb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotations.py
414 lines (369 loc) · 15.4 KB
/
rotations.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
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
import csv
import logging
import os
import requests
import wx
from .events import (
MessageEvent,
PopulateFootprintListEvent,
ResetGaugeEvent,
UpdateGaugeEvent,
)
from .helpers import PLUGIN_PATH, HighResWxSize, loadBitmapScaled
class RotationManagerDialog(wx.Dialog):
def __init__(self, parent, footprint):
wx.Dialog.__init__(
self,
parent,
id=wx.ID_ANY,
title="Rotations Manager",
pos=wx.DefaultPosition,
size=HighResWxSize(parent.window, wx.Size(800, 800)),
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX,
)
self.logger = logging.getLogger(__name__)
self.parent = parent
self.selection_regex = None
self.selection_correction = None
self.import_legacy_corrections()
# ---------------------------------------------------------------------
# ---------------------------- Hotkeys --------------------------------
# ---------------------------------------------------------------------
quitid = wx.NewId()
self.Bind(wx.EVT_MENU, self.quit_dialog, id=quitid)
entries = [wx.AcceleratorEntry(), wx.AcceleratorEntry(), wx.AcceleratorEntry()]
entries[0].Set(wx.ACCEL_CTRL, ord("W"), quitid)
entries[1].Set(wx.ACCEL_CTRL, ord("Q"), quitid)
entries[2].Set(wx.ACCEL_SHIFT, wx.WXK_ESCAPE, quitid)
accel = wx.AcceleratorTable(entries)
self.SetAcceleratorTable(accel)
# ---------------------------------------------------------------------
# ------------------------- Add/Edit inputs ---------------------------
# ---------------------------------------------------------------------
regex_label = wx.StaticText(
self,
wx.ID_ANY,
"Regex",
size=HighResWxSize(parent.window, wx.Size(150, 15)),
)
self.regex = wx.TextCtrl(
self,
wx.ID_ANY,
footprint,
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(200, 24)),
)
sizer_left = wx.BoxSizer(wx.VERTICAL)
sizer_left.Add(regex_label, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
sizer_left.Add(
self.regex,
0,
wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
5,
)
correction_label = wx.StaticText(
self,
wx.ID_ANY,
"Correction",
size=HighResWxSize(parent.window, wx.Size(150, 15)),
)
self.correction = wx.TextCtrl(
self,
wx.ID_ANY,
"",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(200, 24)),
)
sizer_right = wx.BoxSizer(wx.VERTICAL)
sizer_right.Add(correction_label, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
sizer_right.Add(
self.correction,
0,
wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
5,
)
self.regex.Bind(wx.EVT_TEXT, self.on_textfield_change)
self.correction.Bind(wx.EVT_TEXT, self.on_textfield_change)
add_edit_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, self, "Add / Edit")
add_edit_sizer.Add(sizer_left, 0, wx.RIGHT, 20)
add_edit_sizer.Add(sizer_right, 0, wx.RIGHT, 20)
# ---------------------------------------------------------------------
# ------------------------- Rotations list ----------------------------
# ---------------------------------------------------------------------
self.rotations_list = wx.dataview.DataViewListCtrl(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.DefaultSize,
style=wx.dataview.DV_SINGLE,
)
regex = self.rotations_list.AppendTextColumn(
"Regex",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(parent.scale_factor * 480),
align=wx.ALIGN_LEFT,
)
rotation = self.rotations_list.AppendTextColumn(
"Correction",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(parent.scale_factor * 100),
align=wx.ALIGN_LEFT,
)
self.rotations_list.SetMinSize(HighResWxSize(parent.window, wx.Size(600, 500)))
self.rotations_list.Bind(
wx.dataview.EVT_DATAVIEW_SELECTION_CHANGED, self.on_correction_selected
)
table_sizer = wx.BoxSizer(wx.HORIZONTAL)
table_sizer.SetMinSize(HighResWxSize(parent.window, wx.Size(-1, 400)))
table_sizer.Add(self.rotations_list, 20, wx.ALL | wx.EXPAND, 5)
# ---------------------------------------------------------------------
# ------------------------ Right side toolbar -------------------------
# ---------------------------------------------------------------------
self.save_button = wx.Button(
self,
wx.ID_ANY,
"Save",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(150, -1)),
0,
)
self.delete_button = wx.Button(
self,
wx.ID_ANY,
"Delete",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(150, -1)),
0,
)
self.update_button = wx.Button(
self,
wx.ID_ANY,
"Update",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(150, -1)),
0,
)
self.import_button = wx.Button(
self,
wx.ID_ANY,
"Import",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(150, -1)),
0,
)
self.export_button = wx.Button(
self,
wx.ID_ANY,
"Export",
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(150, -1)),
0,
)
self.save_button.Bind(wx.EVT_BUTTON, self.save_correction)
self.delete_button.Bind(wx.EVT_BUTTON, self.delete_correction)
self.update_button.Bind(wx.EVT_BUTTON, self.download_correction_data)
self.import_button.Bind(wx.EVT_BUTTON, self.import_corrections_dialog)
self.export_button.Bind(wx.EVT_BUTTON, self.export_corrections_dialog)
self.save_button.SetBitmap(
loadBitmapScaled(
"mdi-content-save-outline.png",
self.parent.scale_factor,
self.parent.KicadBuildVersion,
)
)
self.save_button.SetBitmapMargins((2, 0))
self.delete_button.SetBitmap(
loadBitmapScaled(
"mdi-trash-can-outline.png",
self.parent.scale_factor,
self.parent.KicadBuildVersion,
)
)
self.delete_button.SetBitmapMargins((2, 0))
self.update_button.SetBitmap(
loadBitmapScaled(
"mdi-cloud-download-outline.png",
self.parent.scale_factor,
self.parent.KicadBuildVersion,
)
)
self.update_button.SetBitmapMargins((2, 0))
self.import_button.SetBitmap(
loadBitmapScaled(
"mdi-database-import-outline.png",
self.parent.scale_factor,
self.parent.KicadBuildVersion,
)
)
self.import_button.SetBitmapMargins((2, 0))
self.export_button.SetBitmap(
loadBitmapScaled(
"mdi-database-export-outline.png",
self.parent.scale_factor,
self.parent.KicadBuildVersion,
)
)
self.export_button.SetBitmapMargins((2, 0))
tool_sizer = wx.BoxSizer(wx.VERTICAL)
tool_sizer.Add(self.save_button, 0, wx.ALL, 5)
tool_sizer.Add(self.delete_button, 0, wx.ALL, 5)
tool_sizer.Add(self.update_button, 0, wx.ALL, 5)
tool_sizer.Add(self.import_button, 0, wx.ALL, 5)
tool_sizer.Add(self.export_button, 0, wx.ALL, 5)
table_sizer.Add(tool_sizer, 3, wx.EXPAND, 5)
# ---------------------------------------------------------------------
# ------------------------------ Sizers ------------------------------
# ---------------------------------------------------------------------
layout = wx.BoxSizer(wx.VERTICAL)
layout.Add(add_edit_sizer, 1, wx.ALL | wx.EXPAND, 5)
layout.Add(table_sizer, 20, wx.ALL | wx.EXPAND, 5)
self.SetSizer(layout)
self.Layout()
self.Centre(wx.BOTH)
self.enable_toolbar_buttons(False)
self.populate_rotations_list()
def quit_dialog(self, e):
self.Destroy()
self.EndModal(0)
def enable_toolbar_buttons(self, state):
"""Control the state of all the buttons in toolbar on the right side"""
for b in [
self.save_button,
self.delete_button,
]:
b.Enable(bool(state))
def populate_rotations_list(self):
"""Populate the list with the result of the search."""
self.rotations_list.DeleteAllItems()
for corrections in self.parent.library.get_all_correction_data():
self.rotations_list.AppendItem([str(c) for c in corrections])
def save_correction(self, e):
"""Add/Update a correction in the database."""
regex = self.regex.GetValue()
correction = self.correction.GetValue()
if regex == self.selection_regex:
self.parent.library.update_correction_data(regex, correction)
self.selection_regex = None
elif self.selection_regex == None:
self.parent.library.insert_correction_data(regex, correction)
else:
self.parent.library.delete_correction_data(self.selection_regex)
self.parent.library.insert_correction_data(regex, correction)
self.selection_regex = None
self.populate_rotations_list()
wx.PostEvent(self.parent, PopulateFootprintListEvent())
def delete_correction(self, e):
"""Delete a correction from the database."""
item = self.rotations_list.GetSelection()
row = self.rotations_list.ItemToRow(item)
if row == -1:
return
regex = self.rotations_list.GetTextValue(row, 0)
self.parent.library.delete_correction_data(regex)
self.populate_rotations_list()
wx.PostEvent(self.parent, PopulateFootprintListEvent())
def on_correction_selected(self, e):
"""Enable the toolbar buttons when a selection was made."""
if self.rotations_list.GetSelectedItemsCount() > 0:
self.enable_toolbar_buttons(True)
item = self.rotations_list.GetSelection()
row = self.rotations_list.ItemToRow(item)
if row == -1:
return
self.selection_regex = self.rotations_list.GetTextValue(row, 0)
self.selection_correction = self.rotations_list.GetTextValue(row, 1)
self.regex.SetValue(self.selection_regex)
self.correction.SetValue(self.selection_correction)
else:
self.selection_regex = None
self.enable_toolbar_buttons(False)
def on_textfield_change(self, e):
"""Check if the Add button should be activated."""
if self.regex.GetValue() and self.correction.GetValue():
self.enable_toolbar_buttons(True)
else:
self.enable_toolbar_buttons(False)
def download_correction_data(self, e):
"""Fetch the latest rotation correction table from Matthew Lai's JLCKicadTool repo"""
self.parent.library.create_rotation_table()
try:
r = requests.get(
"https://raw.githubusercontent.com/matthewlai/JLCKicadTools/master/jlc_kicad_tools/cpl_rotations_db.csv"
)
corrections = csv.reader(r.text.splitlines(), delimiter=",", quotechar='"')
next(corrections)
for row in corrections:
if not self.parent.library.get_correction_data(row[0]):
self.parent.library.insert_correction_data(row[0], row[1])
else:
self.logger.info(
f"Correction '{row[0]}' exists already in database with correction value {row[1]}. Leaving this one out."
)
except Exception as e:
self.logger.debug(e)
self.populate_rotations_list()
wx.PostEvent(self.parent, PopulateFootprintListEvent())
def import_legacy_corrections(self):
"""Check if corrections in CSV format are found and import them into the database."""
csv_file = os.path.join(PLUGIN_PATH, "corrections", "cpl_rotations_db.csv")
if os.path.isfile(csv_file):
self._import_corrections(csv_file)
os.rename(csv_file, f"{csv_file}.backup")
def import_corrections_dialog(self, e=None):
"""Dialog to import correctios from a CSV file."""
with wx.FileDialog(
self,
"Import",
"",
"",
"CSV files (*.csv)|*.csv",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
) as importFileDialog:
if importFileDialog.ShowModal() == wx.ID_CANCEL:
return
path = importFileDialog.GetPath()
self._import_corrections(path)
def export_corrections_dialog(self, e=None):
"""Dialog to export correctios to a CSV file."""
with wx.FileDialog(
self,
"Export",
"",
"",
"CSV files (*.csv)|*.csv",
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
) as exportFileDialog:
if exportFileDialog.ShowModal() == wx.ID_CANCEL:
return
path = exportFileDialog.GetPath()
self._export_corrections(path)
def _import_corrections(self, path):
"""corrections import logic"""
if os.path.isfile(path):
with open(path) as f:
csvreader = csv.DictReader(f, fieldnames=("regex", "correction"))
next(csvreader)
for row in csvreader:
if self.parent.library.get_correction_data(row["regex"]):
self.parent.library.update_correction_data(
row["regex"], row["correction"]
)
self.logger.info(
f"Correction '{row['regex']}' exists already in database with correction value {row['correction']}. Overwrite it with local values from CSV."
)
else:
self.parent.library.insert_correction_data(
row["regex"], row["correction"]
)
self.logger.info(
f"Correction '{row['regex']}' with correction value {row['correction']} is added to the database from local CSV."
)
self.populate_rotations_list()
wx.PostEvent(self.parent, PopulateFootprintListEvent())
def _export_corrections(self, path):
"""corrections export logic"""
with open(path, "w", newline="") as f:
csvwriter = csv.writer(f, quotechar='"', quoting=csv.QUOTE_ALL)
csvwriter.writerow(["Footprint pattern", "Correction"])
for c in self.parent.library.get_all_correction_data():
csvwriter.writerow([c[0], c[1]])