ToolPanelize.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/2019 #
  6. # MIT Licence #
  7. ############################################################
  8. from FlatCAMTool import FlatCAMTool
  9. from copy import copy, deepcopy
  10. from ObjectCollection import *
  11. import time
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. fcTranslate.apply_language('ToolPanelize')
  15. class Panelize(FlatCAMTool):
  16. toolName = _("Panelize PCB")
  17. def __init__(self, app):
  18. super(Panelize, self).__init__(self)
  19. self.app = app
  20. ## Title
  21. title_label = QtWidgets.QLabel("%s" % self.toolName)
  22. title_label.setStyleSheet("""
  23. QLabel
  24. {
  25. font-size: 16px;
  26. font-weight: bold;
  27. }
  28. """)
  29. self.layout.addWidget(title_label)
  30. ## Form Layout
  31. form_layout = QtWidgets.QFormLayout()
  32. self.layout.addLayout(form_layout)
  33. ## Type of object to be panelized
  34. self.type_obj_combo = QtWidgets.QComboBox()
  35. self.type_obj_combo.addItem("Gerber")
  36. self.type_obj_combo.addItem("Excellon")
  37. self.type_obj_combo.addItem("Geometry")
  38. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  39. self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  40. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  41. self.type_obj_combo_label = QtWidgets.QLabel(_("Object Type:"))
  42. self.type_obj_combo_label.setToolTip(
  43. _("Specify the type of object to be panelized\n"
  44. "It can be of type: Gerber, Excellon or Geometry.\n"
  45. "The selection here decide the type of objects that will be\n"
  46. "in the Object combobox.")
  47. )
  48. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  49. ## Object to be panelized
  50. self.object_combo = QtWidgets.QComboBox()
  51. self.object_combo.setModel(self.app.collection)
  52. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  53. self.object_combo.setCurrentIndex(1)
  54. self.object_label = QtWidgets.QLabel(_("Object:"))
  55. self.object_label.setToolTip(
  56. _("Object to be panelized. This means that it will\n"
  57. "be duplicated in an array of rows and columns.")
  58. )
  59. form_layout.addRow(self.object_label, self.object_combo)
  60. ## Type of Box Object to be used as an envelope for panelization
  61. self.type_box_combo = QtWidgets.QComboBox()
  62. self.type_box_combo.addItem("Gerber")
  63. self.type_box_combo.addItem("Excellon")
  64. self.type_box_combo.addItem("Geometry")
  65. # we get rid of item1 ("Excellon") as it is not suitable for use as a "box" for panelizing
  66. self.type_box_combo.view().setRowHidden(1, True)
  67. self.type_box_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  68. self.type_box_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  69. self.type_box_combo_label = QtWidgets.QLabel(_("Box Type:"))
  70. self.type_box_combo_label.setToolTip(
  71. _("Specify the type of object to be used as an container for\n"
  72. "panelization. It can be: Gerber or Geometry type.\n"
  73. "The selection here decide the type of objects that will be\n"
  74. "in the Box Object combobox.")
  75. )
  76. form_layout.addRow(self.type_box_combo_label, self.type_box_combo)
  77. ## Box
  78. self.box_combo = QtWidgets.QComboBox()
  79. self.box_combo.setModel(self.app.collection)
  80. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  81. self.box_combo.setCurrentIndex(1)
  82. self.box_combo_label = QtWidgets.QLabel(_("Box Object:"))
  83. self.box_combo_label.setToolTip(
  84. _("The actual object that is used a container for the\n "
  85. "selected object that is to be panelized.")
  86. )
  87. form_layout.addRow(self.box_combo_label, self.box_combo)
  88. ## Spacing Columns
  89. self.spacing_columns = FCEntry()
  90. self.spacing_columns_label = QtWidgets.QLabel(_("Spacing cols:"))
  91. self.spacing_columns_label.setToolTip(
  92. _("Spacing between columns of the desired panel.\n"
  93. "In current units.")
  94. )
  95. form_layout.addRow(self.spacing_columns_label, self.spacing_columns)
  96. ## Spacing Rows
  97. self.spacing_rows = FCEntry()
  98. self.spacing_rows_label = QtWidgets.QLabel(_("Spacing rows:"))
  99. self.spacing_rows_label.setToolTip(
  100. _("Spacing between rows of the desired panel.\n"
  101. "In current units.")
  102. )
  103. form_layout.addRow(self.spacing_rows_label, self.spacing_rows)
  104. ## Columns
  105. self.columns = FCEntry()
  106. self.columns_label = QtWidgets.QLabel(_("Columns:"))
  107. self.columns_label.setToolTip(
  108. _("Number of columns of the desired panel")
  109. )
  110. form_layout.addRow(self.columns_label, self.columns)
  111. ## Rows
  112. self.rows = FCEntry()
  113. self.rows_label = QtWidgets.QLabel(_("Rows:"))
  114. self.rows_label.setToolTip(
  115. _("Number of rows of the desired panel")
  116. )
  117. form_layout.addRow(self.rows_label, self.rows)
  118. ## Type of resulting Panel object
  119. self.panel_type_radio = RadioSet([{'label': 'Gerber', 'value': 'gerber'},
  120. {'label': 'Geometry', 'value': 'geometry'}])
  121. self.panel_type_label = QtWidgets.QLabel(_("Panel Type:"))
  122. self.panel_type_label.setToolTip(
  123. _("Choose the type of object for the panel object:\n"
  124. "- Geometry\n"
  125. "- Gerber")
  126. )
  127. form_layout.addRow(self.panel_type_label)
  128. form_layout.addRow(self.panel_type_radio)
  129. ## Constrains
  130. self.constrain_cb = FCCheckBox(_("Constrain panel within:"))
  131. self.constrain_cb.setToolTip(
  132. _("Area define by DX and DY within to constrain the panel.\n"
  133. "DX and DY values are in current units.\n"
  134. "Regardless of how many columns and rows are desired,\n"
  135. "the final panel will have as many columns and rows as\n"
  136. "they fit completely within selected area.")
  137. )
  138. form_layout.addRow(self.constrain_cb)
  139. self.x_width_entry = FCEntry()
  140. self.x_width_lbl = QtWidgets.QLabel(_("Width (DX):"))
  141. self.x_width_lbl.setToolTip(
  142. _("The width (DX) within which the panel must fit.\n"
  143. "In current units.")
  144. )
  145. form_layout.addRow(self.x_width_lbl, self.x_width_entry)
  146. self.y_height_entry = FCEntry()
  147. self.y_height_lbl = QtWidgets.QLabel(_("Height (DY):"))
  148. self.y_height_lbl.setToolTip(
  149. _("The height (DY)within which the panel must fit.\n"
  150. "In current units.")
  151. )
  152. form_layout.addRow(self.y_height_lbl, self.y_height_entry)
  153. self.constrain_sel = OptionalInputSection(
  154. self.constrain_cb, [self.x_width_lbl, self.x_width_entry, self.y_height_lbl, self.y_height_entry])
  155. ## Buttons
  156. hlay_2 = QtWidgets.QHBoxLayout()
  157. self.layout.addLayout(hlay_2)
  158. hlay_2.addStretch()
  159. self.panelize_object_button = QtWidgets.QPushButton(_("Panelize Object"))
  160. self.panelize_object_button.setToolTip(
  161. _("Panelize the specified object around the specified box.\n"
  162. "In other words it creates multiple copies of the source object,\n"
  163. "arranged in a 2D array of rows and columns.")
  164. )
  165. hlay_2.addWidget(self.panelize_object_button)
  166. self.layout.addStretch()
  167. ## Signals
  168. self.panelize_object_button.clicked.connect(self.on_panelize)
  169. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  170. self.type_box_combo.currentIndexChanged.connect(self.on_type_box_index_changed)
  171. # list to hold the temporary objects
  172. self.objs = []
  173. # final name for the panel object
  174. self.outname = ""
  175. # flag to signal the constrain was activated
  176. self.constrain_flag = False
  177. def run(self, toggle=False):
  178. self.app.report_usage("ToolPanelize()")
  179. if toggle:
  180. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  181. if self.app.ui.splitter.sizes()[0] == 0:
  182. self.app.ui.splitter.setSizes([1, 1])
  183. else:
  184. try:
  185. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  186. self.app.ui.splitter.setSizes([0, 1])
  187. except AttributeError:
  188. pass
  189. FlatCAMTool.run(self)
  190. self.set_tool_ui()
  191. self.app.ui.notebook.setTabText(2, "Panel. Tool")
  192. def install(self, icon=None, separator=None, **kwargs):
  193. FlatCAMTool.install(self, icon, separator, shortcut='ALT+Z', **kwargs)
  194. def set_tool_ui(self):
  195. self.reset_fields()
  196. sp_c = self.app.defaults["tools_panelize_spacing_columns"] if \
  197. self.app.defaults["tools_panelize_spacing_columns"] else 0.0
  198. self.spacing_columns.set_value(float(sp_c))
  199. sp_r = self.app.defaults["tools_panelize_spacing_rows"] if \
  200. self.app.defaults["tools_panelize_spacing_rows"] else 0.0
  201. self.spacing_rows.set_value(float(sp_r))
  202. rr = self.app.defaults["tools_panelize_rows"] if \
  203. self.app.defaults["tools_panelize_rows"] else 0.0
  204. self.rows.set_value(int(rr))
  205. cc = self.app.defaults["tools_panelize_columns"] if \
  206. self.app.defaults["tools_panelize_columns"] else 0.0
  207. self.columns.set_value(int(cc))
  208. c_cb = self.app.defaults["tools_panelize_constrain"] if \
  209. self.app.defaults["tools_panelize_constrain"] else False
  210. self.constrain_cb.set_value(c_cb)
  211. x_w = self.app.defaults["tools_panelize_constrainx"] if \
  212. self.app.defaults["tools_panelize_constrainx"] else 0.0
  213. self.x_width_entry.set_value(float(x_w))
  214. y_w = self.app.defaults["tools_panelize_constrainy"] if \
  215. self.app.defaults["tools_panelize_constrainy"] else 0.0
  216. self.y_height_entry.set_value(float(y_w))
  217. panel_type = self.app.defaults["tools_panelize_panel_type"] if \
  218. self.app.defaults["tools_panelize_panel_type"] else 'gerber'
  219. self.panel_type_radio.set_value(panel_type)
  220. def on_type_obj_index_changed(self):
  221. obj_type = self.type_obj_combo.currentIndex()
  222. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  223. self.object_combo.setCurrentIndex(0)
  224. def on_type_box_index_changed(self):
  225. obj_type = self.type_box_combo.currentIndex()
  226. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  227. self.box_combo.setCurrentIndex(0)
  228. def on_panelize(self):
  229. name = self.object_combo.currentText()
  230. # Get source object.
  231. try:
  232. obj = self.app.collection.get_by_name(str(name))
  233. except:
  234. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % name)
  235. return "Could not retrieve object: %s" % name
  236. panel_obj = obj
  237. if panel_obj is None:
  238. self.app.inform.emit(_("[ERROR_NOTCL]Object not found: %s") % panel_obj)
  239. return "Object not found: %s" % panel_obj
  240. boxname = self.box_combo.currentText()
  241. try:
  242. box = self.app.collection.get_by_name(boxname)
  243. except:
  244. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % boxname)
  245. return "Could not retrieve object: %s" % boxname
  246. if box is None:
  247. self.app.inform.emit(_("[WARNING]No object Box. Using instead %s") % panel_obj)
  248. box = panel_obj
  249. self.outname = name + '_panelized'
  250. try:
  251. spacing_columns = float(self.spacing_columns.get_value())
  252. except ValueError:
  253. # try to convert comma to decimal point. if it's still not working error message and return
  254. try:
  255. spacing_columns = float(self.spacing_columns.get_value().replace(',', '.'))
  256. except ValueError:
  257. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  258. "use a number."))
  259. return
  260. spacing_columns = spacing_columns if spacing_columns is not None else 0
  261. try:
  262. spacing_rows = float(self.spacing_rows.get_value())
  263. except ValueError:
  264. # try to convert comma to decimal point. if it's still not working error message and return
  265. try:
  266. spacing_rows = float(self.spacing_rows.get_value().replace(',', '.'))
  267. except ValueError:
  268. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  269. "use a number."))
  270. return
  271. spacing_rows = spacing_rows if spacing_rows is not None else 0
  272. try:
  273. rows = int(self.rows.get_value())
  274. except ValueError:
  275. # try to convert comma to decimal point. if it's still not working error message and return
  276. try:
  277. rows = float(self.rows.get_value().replace(',', '.'))
  278. rows = int(rows)
  279. except ValueError:
  280. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  281. "use a number."))
  282. return
  283. rows = rows if rows is not None else 1
  284. try:
  285. columns = int(self.columns.get_value())
  286. except ValueError:
  287. # try to convert comma to decimal point. if it's still not working error message and return
  288. try:
  289. columns = float(self.columns.get_value().replace(',', '.'))
  290. columns = int(columns)
  291. except ValueError:
  292. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  293. "use a number."))
  294. return
  295. columns = columns if columns is not None else 1
  296. try:
  297. constrain_dx = float(self.x_width_entry.get_value())
  298. except ValueError:
  299. # try to convert comma to decimal point. if it's still not working error message and return
  300. try:
  301. constrain_dx = float(self.x_width_entry.get_value().replace(',', '.'))
  302. except ValueError:
  303. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  304. "use a number."))
  305. return
  306. try:
  307. constrain_dy = float(self.y_height_entry.get_value())
  308. except ValueError:
  309. # try to convert comma to decimal point. if it's still not working error message and return
  310. try:
  311. constrain_dy = float(self.y_height_entry.get_value().replace(',', '.'))
  312. except ValueError:
  313. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  314. "use a number."))
  315. return
  316. panel_type = str(self.panel_type_radio.get_value())
  317. if 0 in {columns, rows}:
  318. self.app.inform.emit(_("[ERROR_NOTCL]Columns or Rows are zero value. Change them to a positive integer."))
  319. return "Columns or Rows are zero value. Change them to a positive integer."
  320. xmin, ymin, xmax, ymax = box.bounds()
  321. lenghtx = xmax - xmin + spacing_columns
  322. lenghty = ymax - ymin + spacing_rows
  323. # check if constrain within an area is desired
  324. if self.constrain_cb.isChecked():
  325. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  326. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  327. # adjust the number of columns and/or rows so the panel will fit within the panel constraint area
  328. if (panel_lengthx > constrain_dx) or (panel_lengthy > constrain_dy):
  329. self.constrain_flag = True
  330. while panel_lengthx > constrain_dx:
  331. columns -= 1
  332. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  333. while panel_lengthy > constrain_dy:
  334. rows -= 1
  335. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  336. def panelize_2():
  337. if panel_obj is not None:
  338. self.app.inform.emit(_("Generating panel ... Please wait."))
  339. self.app.progress.emit(0)
  340. def job_init_excellon(obj_fin, app_obj):
  341. currenty = 0.0
  342. self.app.progress.emit(10)
  343. obj_fin.tools = panel_obj.tools.copy()
  344. obj_fin.drills = []
  345. obj_fin.slots = []
  346. obj_fin.solid_geometry = []
  347. for option in panel_obj.options:
  348. if option is not 'name':
  349. try:
  350. obj_fin.options[option] = panel_obj.options[option]
  351. except:
  352. log.warning("Failed to copy option.", option)
  353. for row in range(rows):
  354. currentx = 0.0
  355. for col in range(columns):
  356. if panel_obj.drills:
  357. for tool_dict in panel_obj.drills:
  358. point_offseted = affinity.translate(tool_dict['point'], currentx, currenty)
  359. obj_fin.drills.append(
  360. {
  361. "point": point_offseted,
  362. "tool": tool_dict['tool']
  363. }
  364. )
  365. if panel_obj.slots:
  366. for tool_dict in panel_obj.slots:
  367. start_offseted = affinity.translate(tool_dict['start'], currentx, currenty)
  368. stop_offseted = affinity.translate(tool_dict['stop'], currentx, currenty)
  369. obj_fin.slots.append(
  370. {
  371. "start": start_offseted,
  372. "stop": stop_offseted,
  373. "tool": tool_dict['tool']
  374. }
  375. )
  376. currentx += lenghtx
  377. currenty += lenghty
  378. obj_fin.create_geometry()
  379. obj_fin.zeros = panel_obj.zeros
  380. obj_fin.units = panel_obj.units
  381. def job_init_geometry(obj_fin, app_obj):
  382. currentx = 0.0
  383. currenty = 0.0
  384. def translate_recursion(geom):
  385. if type(geom) == list:
  386. geoms = list()
  387. for local_geom in geom:
  388. geoms.append(translate_recursion(local_geom))
  389. return geoms
  390. else:
  391. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  392. obj_fin.solid_geometry = []
  393. if isinstance(panel_obj, FlatCAMGeometry):
  394. obj_fin.multigeo = panel_obj.multigeo
  395. obj_fin.tools = deepcopy(panel_obj.tools)
  396. if panel_obj.multigeo is True:
  397. for tool in panel_obj.tools:
  398. obj_fin.tools[tool]['solid_geometry'][:] = []
  399. self.app.progress.emit(0)
  400. for row in range(rows):
  401. currentx = 0.0
  402. for col in range(columns):
  403. if isinstance(panel_obj, FlatCAMGeometry):
  404. if panel_obj.multigeo is True:
  405. for tool in panel_obj.tools:
  406. obj_fin.tools[tool]['solid_geometry'].append(translate_recursion(
  407. panel_obj.tools[tool]['solid_geometry'])
  408. )
  409. else:
  410. obj_fin.solid_geometry.append(
  411. translate_recursion(panel_obj.solid_geometry)
  412. )
  413. else:
  414. obj_fin.solid_geometry.append(
  415. translate_recursion(panel_obj.solid_geometry)
  416. )
  417. currentx += lenghtx
  418. currenty += lenghty
  419. if isinstance(panel_obj, FlatCAMExcellon):
  420. self.app.progress.emit(50)
  421. self.app.new_object("excellon", self.outname, job_init_excellon, plot=True, autoselected=True)
  422. else:
  423. self.app.progress.emit(50)
  424. self.app.new_object(panel_type, self.outname, job_init_geometry,
  425. plot=True, autoselected=True)
  426. if self.constrain_flag is False:
  427. self.app.inform.emit(_("[success]Panel done..."))
  428. else:
  429. self.constrain_flag = False
  430. self.app.inform.emit(_("[WARNING] Too big for the constrain area. Final panel has %s columns and %s rows") %
  431. (columns, rows))
  432. proc = self.app.proc_container.new(_("Generating panel ... Please wait."))
  433. def job_thread(app_obj):
  434. try:
  435. panelize_2()
  436. self.app.inform.emit(_("[success]Panel created successfully."))
  437. except Exception as e:
  438. proc.done()
  439. log.debug(str(e))
  440. return
  441. proc.done()
  442. self.app.collection.promise(self.outname)
  443. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  444. def reset_fields(self):
  445. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  446. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))