ToolPcbWizard.py 18 KB

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