ToolPcbWizard.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 4/15/2019 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import RadioSet, FCComboBox, FCSpinner, FCButton, FCTable
  10. from PyQt5 import QtGui, QtWidgets, QtCore
  11. from PyQt5.QtCore import pyqtSignal
  12. import re
  13. import os
  14. from datetime import datetime
  15. from io import StringIO
  16. import gettext
  17. import FlatCAMTranslation as fcTranslate
  18. import builtins
  19. fcTranslate.apply_language('strings')
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. class PcbWizard(FlatCAMTool):
  23. file_loaded = pyqtSignal(str, str)
  24. toolName = _("PcbWizard Import Tool")
  25. def __init__(self, app):
  26. FlatCAMTool.__init__(self, app)
  27. self.app = app
  28. # Title
  29. title_label = QtWidgets.QLabel("%s" % _('Import 2-file Excellon'))
  30. title_label.setStyleSheet("""
  31. QLabel
  32. {
  33. font-size: 16px;
  34. font-weight: bold;
  35. }
  36. """)
  37. self.layout.addWidget(title_label)
  38. self.layout.addWidget(QtWidgets.QLabel(""))
  39. self.layout.addWidget(QtWidgets.QLabel("<b>%s:</b>" % _("Load files")))
  40. # Form Layout
  41. form_layout = QtWidgets.QFormLayout()
  42. self.layout.addLayout(form_layout)
  43. self.excellon_label = QtWidgets.QLabel('%s:' % _("Excellon file"))
  44. self.excellon_label.setToolTip(
  45. _("Load the Excellon file.\n"
  46. "Usually it has a .DRL extension")
  47. )
  48. self.excellon_brn = FCButton(_("Open"))
  49. form_layout.addRow(self.excellon_label, self.excellon_brn)
  50. self.inf_label = QtWidgets.QLabel('%s:' % _("INF file"))
  51. self.inf_label.setToolTip(
  52. _("Load the INF file.")
  53. )
  54. self.inf_btn = FCButton(_("Open"))
  55. form_layout.addRow(self.inf_label, self.inf_btn)
  56. self.tools_table = FCTable()
  57. self.layout.addWidget(self.tools_table)
  58. self.tools_table.setColumnCount(2)
  59. self.tools_table.setHorizontalHeaderLabels(['#Tool', _('Diameter')])
  60. self.tools_table.horizontalHeaderItem(0).setToolTip(
  61. _("Tool Number"))
  62. self.tools_table.horizontalHeaderItem(1).setToolTip(
  63. _("Tool diameter in file units."))
  64. # start with apertures table hidden
  65. self.tools_table.setVisible(False)
  66. self.layout.addWidget(QtWidgets.QLabel(""))
  67. self.layout.addWidget(QtWidgets.QLabel("<b>%s:</b>" % _("Excellon format")))
  68. # Form Layout
  69. form_layout1 = QtWidgets.QFormLayout()
  70. self.layout.addLayout(form_layout1)
  71. # Integral part of the coordinates
  72. self.int_entry = FCSpinner()
  73. self.int_entry.set_range(1, 10)
  74. self.int_label = QtWidgets.QLabel('%s:' % _("Int. digits"))
  75. self.int_label.setToolTip(
  76. _("The number of digits for the integral part of the coordinates.")
  77. )
  78. form_layout1.addRow(self.int_label, self.int_entry)
  79. # Fractional part of the coordinates
  80. self.frac_entry = FCSpinner()
  81. self.frac_entry.set_range(1, 10)
  82. self.frac_label = QtWidgets.QLabel('%s:' % _("Frac. digits"))
  83. self.frac_label.setToolTip(
  84. _("The number of digits for the fractional part of the coordinates.")
  85. )
  86. form_layout1.addRow(self.frac_label, self.frac_entry)
  87. # Zeros suppression for coordinates
  88. self.zeros_radio = RadioSet([{'label': _('LZ'), 'value': 'LZ'},
  89. {'label': _('TZ'), 'value': 'TZ'},
  90. {'label': _('No Suppression'), 'value': 'D'}])
  91. self.zeros_label = QtWidgets.QLabel('%s:' % _("Zeros supp."))
  92. self.zeros_label.setToolTip(
  93. _("The type of zeros suppression used.\n"
  94. "Can be of type:\n"
  95. "- LZ = leading zeros are kept\n"
  96. "- TZ = trailing zeros are kept\n"
  97. "- No Suppression = no zero suppression")
  98. )
  99. form_layout1.addRow(self.zeros_label, self.zeros_radio)
  100. # Units type
  101. self.units_radio = RadioSet([{'label': _('INCH'), 'value': 'INCH'},
  102. {'label': _('MM'), 'value': 'METRIC'}])
  103. self.units_label = QtWidgets.QLabel("<b>%s:</b>" % _('Units'))
  104. self.units_label.setToolTip(
  105. _("The type of units that the coordinates and tool\n"
  106. "diameters are using. Can be INCH or MM.")
  107. )
  108. form_layout1.addRow(self.units_label, self.units_radio)
  109. # Buttons
  110. self.import_button = QtWidgets.QPushButton(_("Import Excellon"))
  111. self.import_button.setToolTip(
  112. _("Import in FlatCAM an Excellon file\n"
  113. "that store it's information's in 2 files.\n"
  114. "One usually has .DRL extension while\n"
  115. "the other has .INF extension.")
  116. )
  117. self.layout.addWidget(self.import_button)
  118. self.layout.addStretch()
  119. self.excellon_loaded = False
  120. self.inf_loaded = False
  121. self.process_finished = False
  122. self.modified_excellon_file = ''
  123. # ## Signals
  124. self.excellon_brn.clicked.connect(self.on_load_excellon_click)
  125. self.inf_btn.clicked.connect(self.on_load_inf_click)
  126. self.import_button.clicked.connect(lambda: self.on_import_excellon(
  127. excellon_fileobj=self.modified_excellon_file))
  128. self.file_loaded.connect(self.on_file_loaded)
  129. self.units_radio.activated_custom.connect(self.on_units_change)
  130. self.units = 'INCH'
  131. self.zeros = 'LZ'
  132. self.integral = 2
  133. self.fractional = 4
  134. self.outname = 'file'
  135. self.exc_file_content = None
  136. self.tools_from_inf = {}
  137. def run(self, toggle=False):
  138. self.app.report_usage("PcbWizard Tool()")
  139. if toggle:
  140. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  141. if self.app.ui.splitter.sizes()[0] == 0:
  142. self.app.ui.splitter.setSizes([1, 1])
  143. else:
  144. try:
  145. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  146. # if tab is populated with the tool but it does not have the focus, focus on it
  147. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  148. # focus on Tool Tab
  149. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  150. else:
  151. self.app.ui.splitter.setSizes([0, 1])
  152. except AttributeError:
  153. pass
  154. else:
  155. if self.app.ui.splitter.sizes()[0] == 0:
  156. self.app.ui.splitter.setSizes([1, 1])
  157. FlatCAMTool.run(self)
  158. self.set_tool_ui()
  159. self.app.ui.notebook.setTabText(2, _("PCBWizard Tool"))
  160. def install(self, icon=None, separator=None, **kwargs):
  161. FlatCAMTool.install(self, icon, separator, **kwargs)
  162. def set_tool_ui(self):
  163. self.units = 'INCH'
  164. self.zeros = 'LZ'
  165. self.integral = 2
  166. self.fractional = 4
  167. self.outname = 'file'
  168. self.exc_file_content = None
  169. self.tools_from_inf = {}
  170. # ## Initialize form
  171. self.int_entry.set_value(self.integral)
  172. self.frac_entry.set_value(self.fractional)
  173. self.zeros_radio.set_value(self.zeros)
  174. self.units_radio.set_value(self.units)
  175. self.excellon_loaded = False
  176. self.inf_loaded = False
  177. self.process_finished = False
  178. self.modified_excellon_file = ''
  179. self.build_ui()
  180. def build_ui(self):
  181. sorted_tools = []
  182. if not self.tools_from_inf:
  183. self.tools_table.setVisible(False)
  184. else:
  185. sort = []
  186. for k, v in list(self.tools_from_inf.items()):
  187. sort.append(int(k))
  188. sorted_tools = sorted(sort)
  189. n = len(sorted_tools)
  190. self.tools_table.setRowCount(n)
  191. tool_row = 0
  192. for tool in sorted_tools:
  193. tool_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool))
  194. tool_id_item.setFlags(QtCore.Qt.ItemIsEnabled)
  195. self.tools_table.setItem(tool_row, 0, tool_id_item) # Tool name/id
  196. tool_dia_item = QtWidgets.QTableWidgetItem(str(self.tools_from_inf[tool]))
  197. tool_dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  198. self.tools_table.setItem(tool_row, 1, tool_dia_item)
  199. tool_row += 1
  200. self.tools_table.resizeColumnsToContents()
  201. self.tools_table.resizeRowsToContents()
  202. vertical_header = self.tools_table.verticalHeader()
  203. vertical_header.hide()
  204. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  205. horizontal_header = self.tools_table.horizontalHeader()
  206. # horizontal_header.setMinimumSectionSize(10)
  207. # horizontal_header.setDefaultSectionSize(70)
  208. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  209. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  210. self.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  211. self.tools_table.setSortingEnabled(False)
  212. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  213. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  214. def update_params(self):
  215. self.units = self.units_radio.get_value()
  216. self.zeros = self.zeros_radio.get_value()
  217. self.integral = self.int_entry.get_value()
  218. self.fractional = self.frac_entry.get_value()
  219. def on_units_change(self, val):
  220. if val == 'INCH':
  221. self.int_entry.set_value(2)
  222. self.frac_entry.set_value(4)
  223. else:
  224. self.int_entry.set_value(3)
  225. self.frac_entry.set_value(3)
  226. def on_load_excellon_click(self):
  227. """
  228. :return: None
  229. """
  230. self.app.log.debug("on_load_excellon_click()")
  231. _filter = "Excellon Files(*.DRL *.DRD *.TXT);;All Files (*.*)"
  232. try:
  233. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Load PcbWizard Excellon file"),
  234. directory=self.app.get_last_folder(),
  235. filter=_filter)
  236. except TypeError:
  237. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Load PcbWizard Excellon file"),
  238. filter=_filter)
  239. filename = str(filename)
  240. if filename == "":
  241. self.app.inform.emit(_("Open cancelled."))
  242. else:
  243. self.app.worker_task.emit({'fcn': self.load_excellon, 'params': [filename]})
  244. def on_load_inf_click(self):
  245. """
  246. :return: None
  247. """
  248. self.app.log.debug("on_load_inf_click()")
  249. _filter = "INF Files(*.INF);;All Files (*.*)"
  250. try:
  251. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Load PcbWizard INF file"),
  252. directory=self.app.get_last_folder(),
  253. filter=_filter)
  254. except TypeError:
  255. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Load PcbWizard INF file"),
  256. filter=_filter)
  257. filename = str(filename)
  258. if filename == "":
  259. self.app.inform.emit(_("Open cancelled."))
  260. else:
  261. self.app.worker_task.emit({'fcn': self.load_inf, 'params': [filename]})
  262. def load_inf(self, filename):
  263. self.app.log.debug("ToolPcbWizard.load_inf()")
  264. with open(filename, 'r') as inf_f:
  265. inf_file_content = inf_f.readlines()
  266. tool_re = re.compile(r'^T(\d+)\s+(\d*\.?\d+)$')
  267. format_re = re.compile(r'^(\d+)\.?(\d+)\s*format,\s*(inches|metric)?,\s*(absolute|incremental)?.*$')
  268. for eline in inf_file_content:
  269. # Cleanup lines
  270. eline = eline.strip(' \r\n')
  271. match = tool_re.search(eline)
  272. if match:
  273. tool = int(match.group(1))
  274. dia = float(match.group(2))
  275. # if dia < 0.1:
  276. # # most likely the file is in INCH
  277. # self.units_radio.set_value('INCH')
  278. self.tools_from_inf[tool] = dia
  279. continue
  280. match = format_re.search(eline)
  281. if match:
  282. self.integral = int(match.group(1))
  283. self.fractional = int(match.group(2))
  284. units = match.group(3)
  285. if units == 'inches':
  286. self.units = 'INCH'
  287. else:
  288. self.units = 'METRIC'
  289. self.units_radio.set_value(self.units)
  290. self.int_entry.set_value(self.integral)
  291. self.frac_entry.set_value(self.fractional)
  292. if not self.tools_from_inf:
  293. self.app.inform.emit('[ERROR] %s' %
  294. _("The INF file does not contain the tool table.\n"
  295. "Try to open the Excellon file from File -> Open -> Excellon\n"
  296. "and edit the drill diameters manually."))
  297. return "fail"
  298. self.file_loaded.emit('inf', filename)
  299. def load_excellon(self, filename):
  300. with open(filename, 'r') as exc_f:
  301. self.exc_file_content = exc_f.readlines()
  302. self.file_loaded.emit("excellon", filename)
  303. def on_file_loaded(self, signal, filename):
  304. self.build_ui()
  305. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  306. if signal == 'inf':
  307. self.inf_loaded = True
  308. self.tools_table.setVisible(True)
  309. self.app.inform.emit('[success] %s' %
  310. _("PcbWizard .INF file loaded."))
  311. elif signal == 'excellon':
  312. self.excellon_loaded = True
  313. self.outname = os.path.split(str(filename))[1]
  314. self.app.inform.emit('[success] %s' %
  315. _("Main PcbWizard Excellon file loaded."))
  316. if self.excellon_loaded and self.inf_loaded:
  317. self.update_params()
  318. excellon_string = ''
  319. for line in self.exc_file_content:
  320. excellon_string += line
  321. if 'M48' in line:
  322. header = ';EXCELLON RE-GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  323. (str(self.app.version), str(self.app.version_date))
  324. header += ';Created on : %s' % time_str + '\n'
  325. header += ';FILE_FORMAT={integral}:{fractional}\n'.format(integral=self.integral,
  326. fractional=self.fractional)
  327. header += '{units},{zeros}\n'.format(units=self.units, zeros=self.zeros)
  328. for k, v in self.tools_from_inf.items():
  329. header += 'T{tool}C{dia}\n'.format(tool=int(k), dia=float(v))
  330. excellon_string += header
  331. self.modified_excellon_file = StringIO(excellon_string)
  332. self.process_finished = True
  333. # Register recent file
  334. self.app.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  335. def on_import_excellon(self, signal=None, excellon_fileobj=None):
  336. self.app.log.debug("import_2files_excellon()")
  337. # How the object should be initialized
  338. def obj_init(excellon_obj, app_obj):
  339. # self.progress.emit(20)
  340. try:
  341. ret = excellon_obj.parse_file(file_obj=excellon_fileobj)
  342. if ret == "fail":
  343. app_obj.log.debug("Excellon parsing failed.")
  344. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  345. _("This is not Excellon file."))
  346. return "fail"
  347. except IOError:
  348. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  349. _("Cannot parse file"), self.outname))
  350. app_obj.log.debug("Could not import Excellon object.")
  351. app_obj.progress.emit(0)
  352. return "fail"
  353. except Exception as e:
  354. app_obj.log.debug("PcbWizard.on_import_excellon().obj_init() %s" % str(e))
  355. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  356. msg += app_obj.traceback.format_exc()
  357. app_obj.inform.emit(msg)
  358. return "fail"
  359. ret = excellon_obj.create_geometry()
  360. if ret == 'fail':
  361. app_obj.log.debug("Could not create geometry for Excellon object.")
  362. return "fail"
  363. app_obj.progress.emit(100)
  364. for tool in excellon_obj.tools:
  365. if excellon_obj.tools[tool]['solid_geometry']:
  366. return
  367. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  368. (_("No geometry found in file"), name))
  369. return "fail"
  370. if excellon_fileobj is not None and excellon_fileobj != '':
  371. if self.process_finished:
  372. with self.app.proc_container.new(_("Importing Excellon.")):
  373. # Object name
  374. name = self.outname
  375. ret_val = self.app.new_object("excellon", name, obj_init, autoselected=False)
  376. if ret_val == 'fail':
  377. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Import Excellon file failed.'))
  378. return
  379. # Register recent file
  380. self.app.file_opened.emit("excellon", name)
  381. # GUI feedback
  382. self.app.inform.emit('[success] %s: %s' %
  383. (_("Imported"), name))
  384. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  385. else:
  386. self.app.inform.emit('[WARNING_NOTCL] %s' %
  387. _('Excellon merging is in progress. Please wait...'))
  388. else:
  389. self.app.inform.emit('[ERROR_NOTCL] %s' %
  390. _('The imported Excellon file is None.'))