-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathpart_preferences.py
More file actions
279 lines (242 loc) · 10.6 KB
/
Copy pathpart_preferences.py
File metadata and controls
279 lines (242 loc) · 10.6 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
"""Manage reusable LCSC part preferences shared across projects."""
import csv
import logging
import sqlite3
from typing import TYPE_CHECKING
import wx # pylint: disable=import-error
import wx.dataview # pylint: disable=import-error
from .helpers import HighResWxSize, loadBitmapScaled
if TYPE_CHECKING:
from .mainwindow import JLCPCBTools
_CSV_HEADER = ["Footprint", "Part Value", "LCSC Part"]
class PartPreferencesDialog(wx.Dialog):
"""Dialog for managing preferred LCSC parts by footprint and value."""
def __init__(self, parent: "JLCPCBTools") -> None:
wx.Dialog.__init__(
self,
parent,
id=wx.ID_ANY,
title="Part preferences",
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
# ---------------------------------------------------------------------
# ---------------------------- 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)
# ---------------------------------------------------------------------
# ---------------------- Part preferences list ------------------------
# ---------------------------------------------------------------------
self.part_preferences_list = wx.dataview.DataViewListCtrl(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.DefaultSize,
style=wx.dataview.DV_MULTIPLE,
)
self.part_preferences_list.AppendTextColumn(
"Footprint",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(parent.scale_factor * 150),
align=wx.ALIGN_LEFT,
)
self.part_preferences_list.AppendTextColumn(
"Value",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(parent.scale_factor * 100),
align=wx.ALIGN_LEFT,
)
self.part_preferences_list.AppendTextColumn(
"LCSC Part",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(parent.scale_factor * 100),
align=wx.ALIGN_LEFT,
)
self.part_preferences_list.SetMinSize(
HighResWxSize(parent.window, wx.Size(600, 500))
)
self.part_preferences_list.Bind(
wx.dataview.EVT_DATAVIEW_SELECTION_CHANGED, self.on_part_preference_selected
)
table_sizer = wx.BoxSizer(wx.HORIZONTAL)
table_sizer.SetMinSize(HighResWxSize(parent.window, wx.Size(-1, 400)))
table_sizer.Add(self.part_preferences_list, 20, wx.ALL | wx.EXPAND, 5)
# ---------------------------------------------------------------------
# ------------------------ Right side toolbar -------------------------
# ---------------------------------------------------------------------
self.delete_button = wx.Button(
self,
wx.ID_ANY,
"Delete",
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.delete_button.Bind(wx.EVT_BUTTON, self.delete_selected_part_preferences)
self.delete_button.SetToolTip(
"Remove selected preferences without changing assignments on your boards."
)
self.import_button.Bind(wx.EVT_BUTTON, self.import_part_preferences_dialog)
self.export_button.Bind(wx.EVT_BUTTON, self.export_part_preferences_dialog)
self.delete_button.SetBitmap(
loadBitmapScaled(
"mdi-trash-can-outline.png",
self.parent.scale_factor,
)
)
self.delete_button.SetBitmapMargins((2, 0))
self.import_button.SetBitmap(
loadBitmapScaled(
"mdi-database-import-outline.png",
self.parent.scale_factor,
)
)
self.import_button.SetBitmapMargins((2, 0))
self.export_button.SetBitmap(
loadBitmapScaled(
"mdi-database-export-outline.png",
self.parent.scale_factor,
)
)
self.export_button.SetBitmapMargins((2, 0))
tool_sizer = wx.BoxSizer(wx.VERTICAL)
tool_sizer.Add(self.delete_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)
description = wx.StaticText(
self,
label="Preferred LCSC parts for matching values and footprints, shared across projects.",
)
description.Wrap(HighResWxSize(parent.window, wx.Size(650, -1)).width)
layout.Add(description, 0, wx.ALL | wx.EXPAND, 10)
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_part_preferences_list()
def quit_dialog(self, *_: object) -> None:
"""Close this dialog."""
self.Destroy()
self.EndModal(0)
def enable_toolbar_buttons(self, state: bool) -> None:
"""Control the state of all the buttons in toolbar on the right side."""
for b in [
self.delete_button,
]:
b.Enable(bool(state))
def populate_part_preferences_list(self) -> None:
"""Populate the list with all shared part preferences."""
self.part_preferences_list.DeleteAllItems()
for part_preference in self.parent.library.get_all_part_preferences():
self.part_preferences_list.AppendItem(
[str(field) for field in part_preference]
)
def delete_selected_part_preferences(self, *_: object) -> None:
"""Delete the selected part preferences from the shared database."""
for item in self.part_preferences_list.GetSelections():
row = self.part_preferences_list.ItemToRow(item)
if row == -1:
return
footprint = self.part_preferences_list.GetTextValue(row, 0)
value = self.part_preferences_list.GetTextValue(row, 1)
self.parent.library.delete_part_preference(footprint, value)
self.populate_part_preferences_list()
def on_part_preference_selected(self, *_: object) -> None:
"""Enable the toolbar buttons when a selection was made."""
if self.part_preferences_list.GetSelectedItemsCount() > 0:
self.enable_toolbar_buttons(True)
else:
self.enable_toolbar_buttons(False)
def import_part_preferences_dialog(self, *_: object) -> None:
"""Choose a CSV file containing part preferences to import."""
with wx.FileDialog(
self,
"Import part preferences CSV",
"",
"",
"CSV files (*.csv)|*.csv",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
) as part_preferences_dialog:
if part_preferences_dialog.ShowModal() == wx.ID_CANCEL:
return
path = part_preferences_dialog.GetPath()
self._import_part_preferences(path)
def export_part_preferences_dialog(self, *_: object) -> None:
"""Choose a CSV file to export shared part preferences to."""
with wx.FileDialog(
self,
"Export part preferences CSV",
"",
"part-preferences",
"CSV files (*.csv)|*.csv",
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
) as part_preferences_dialog:
if part_preferences_dialog.ShowModal() == wx.ID_CANCEL:
return
path = part_preferences_dialog.GetPath()
self._export_part_preferences(path)
def _import_part_preferences(self, path: str) -> None:
"""Parse the complete CSV before saving its valid preferences together."""
try:
with open(path, newline="", encoding="utf-8") as part_preferences_file:
rows = list(csv.reader(part_preferences_file, strict=True))
if (
not rows
or rows[0] != _CSV_HEADER
or any(len(row) != 3 for row in rows[1:])
):
raise csv.Error(
"Expected Footprint, Part Value, LCSC Part header and three columns per row"
)
changed = self.parent.library.save_part_preferences(
(footprint, value, lcsc) for footprint, value, lcsc in rows[1:]
)
except (OSError, UnicodeError, csv.Error, sqlite3.Error) as error:
self.logger.warning("Unable to import part preferences: %s", error)
return
if changed:
self.logger.info("Imported %d part preference(s).", changed)
self.populate_part_preferences_list()
def _export_part_preferences(self, path: str) -> None:
"""Export shared part preferences using the existing CSV format."""
with open(path, "w", newline="", encoding="utf-8") as part_preferences_file:
part_preferences_writer = csv.writer(
part_preferences_file, quotechar='"', quoting=csv.QUOTE_ALL
)
part_preferences_writer.writerow(_CSV_HEADER)
for part_preference in self.parent.library.get_all_part_preferences():
part_preferences_writer.writerow(
[part_preference[0], part_preference[1], part_preference[2]]
)