ToolPanelize.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. import builtins
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class Panelize(FlatCAMTool):
  19. toolName = _("Panelize PCB")
  20. def __init__(self, app):
  21. super(Panelize, self).__init__(self)
  22. self.app = app
  23. ## Title
  24. title_label = QtWidgets.QLabel("%s" % self.toolName)
  25. title_label.setStyleSheet("""
  26. QLabel
  27. {
  28. font-size: 16px;
  29. font-weight: bold;
  30. }
  31. """)
  32. self.layout.addWidget(title_label)
  33. ## Form Layout
  34. form_layout = QtWidgets.QFormLayout()
  35. self.layout.addLayout(form_layout)
  36. ## Type of object to be panelized
  37. self.type_obj_combo = QtWidgets.QComboBox()
  38. self.type_obj_combo.addItem("Gerber")
  39. self.type_obj_combo.addItem("Excellon")
  40. self.type_obj_combo.addItem("Geometry")
  41. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  42. self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  43. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  44. self.type_obj_combo_label = QtWidgets.QLabel(_("Object Type:"))
  45. self.type_obj_combo_label.setToolTip(
  46. _("Specify the type of object to be panelized\n"
  47. "It can be of type: Gerber, Excellon or Geometry.\n"
  48. "The selection here decide the type of objects that will be\n"
  49. "in the Object combobox.")
  50. )
  51. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  52. ## Object to be panelized
  53. self.object_combo = QtWidgets.QComboBox()
  54. self.object_combo.setModel(self.app.collection)
  55. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  56. self.object_combo.setCurrentIndex(1)
  57. self.object_label = QtWidgets.QLabel(_("Object:"))
  58. self.object_label.setToolTip(
  59. _("Object to be panelized. This means that it will\n"
  60. "be duplicated in an array of rows and columns.")
  61. )
  62. form_layout.addRow(self.object_label, self.object_combo)
  63. ## Type of Box Object to be used as an envelope for panelization
  64. self.type_box_combo = QtWidgets.QComboBox()
  65. self.type_box_combo.addItem("Gerber")
  66. self.type_box_combo.addItem("Excellon")
  67. self.type_box_combo.addItem("Geometry")
  68. # we get rid of item1 ("Excellon") as it is not suitable for use as a "box" for panelizing
  69. self.type_box_combo.view().setRowHidden(1, True)
  70. self.type_box_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  71. self.type_box_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  72. self.type_box_combo_label = QtWidgets.QLabel(_("Box Type:"))
  73. self.type_box_combo_label.setToolTip(
  74. _("Specify the type of object to be used as an container for\n"
  75. "panelization. It can be: Gerber or Geometry type.\n"
  76. "The selection here decide the type of objects that will be\n"
  77. "in the Box Object combobox.")
  78. )
  79. form_layout.addRow(self.type_box_combo_label, self.type_box_combo)
  80. ## Box
  81. self.box_combo = QtWidgets.QComboBox()
  82. self.box_combo.setModel(self.app.collection)
  83. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  84. self.box_combo.setCurrentIndex(1)
  85. self.box_combo_label = QtWidgets.QLabel(_("Box Object:"))
  86. self.box_combo_label.setToolTip(
  87. _("The actual object that is used a container for the\n "
  88. "selected object that is to be panelized.")
  89. )
  90. form_layout.addRow(self.box_combo_label, self.box_combo)
  91. ## Spacing Columns
  92. self.spacing_columns = FCEntry()
  93. self.spacing_columns_label = QtWidgets.QLabel(_("Spacing cols:"))
  94. self.spacing_columns_label.setToolTip(
  95. _("Spacing between columns of the desired panel.\n"
  96. "In current units.")
  97. )
  98. form_layout.addRow(self.spacing_columns_label, self.spacing_columns)
  99. ## Spacing Rows
  100. self.spacing_rows = FCEntry()
  101. self.spacing_rows_label = QtWidgets.QLabel(_("Spacing rows:"))
  102. self.spacing_rows_label.setToolTip(
  103. _("Spacing between rows of the desired panel.\n"
  104. "In current units.")
  105. )
  106. form_layout.addRow(self.spacing_rows_label, self.spacing_rows)
  107. ## Columns
  108. self.columns = FCEntry()
  109. self.columns_label = QtWidgets.QLabel(_("Columns:"))
  110. self.columns_label.setToolTip(
  111. _("Number of columns of the desired panel")
  112. )
  113. form_layout.addRow(self.columns_label, self.columns)
  114. ## Rows
  115. self.rows = FCEntry()
  116. self.rows_label = QtWidgets.QLabel(_("Rows:"))
  117. self.rows_label.setToolTip(
  118. _("Number of rows of the desired panel")
  119. )
  120. form_layout.addRow(self.rows_label, self.rows)
  121. ## Type of resulting Panel object
  122. self.panel_type_radio = RadioSet([{'label': 'Gerber', 'value': 'gerber'},
  123. {'label': 'Geometry', 'value': 'geometry'}])
  124. self.panel_type_label = QtWidgets.QLabel(_("Panel Type:"))
  125. self.panel_type_label.setToolTip(
  126. _("Choose the type of object for the panel object:\n"
  127. "- Geometry\n"
  128. "- Gerber")
  129. )
  130. form_layout.addRow(self.panel_type_label)
  131. form_layout.addRow(self.panel_type_radio)
  132. ## Constrains
  133. self.constrain_cb = FCCheckBox(_("Constrain panel within:"))
  134. self.constrain_cb.setToolTip(
  135. _("Area define by DX and DY within to constrain the panel.\n"
  136. "DX and DY values are in current units.\n"
  137. "Regardless of how many columns and rows are desired,\n"
  138. "the final panel will have as many columns and rows as\n"
  139. "they fit completely within selected area.")
  140. )
  141. form_layout.addRow(self.constrain_cb)
  142. self.x_width_entry = FCEntry()
  143. self.x_width_lbl = QtWidgets.QLabel(_("Width (DX):"))
  144. self.x_width_lbl.setToolTip(
  145. _("The width (DX) within which the panel must fit.\n"
  146. "In current units.")
  147. )
  148. form_layout.addRow(self.x_width_lbl, self.x_width_entry)
  149. self.y_height_entry = FCEntry()
  150. self.y_height_lbl = QtWidgets.QLabel(_("Height (DY):"))
  151. self.y_height_lbl.setToolTip(
  152. _("The height (DY)within which the panel must fit.\n"
  153. "In current units.")
  154. )
  155. form_layout.addRow(self.y_height_lbl, self.y_height_entry)
  156. self.constrain_sel = OptionalInputSection(
  157. self.constrain_cb, [self.x_width_lbl, self.x_width_entry, self.y_height_lbl, self.y_height_entry])
  158. ## Buttons
  159. hlay_2 = QtWidgets.QHBoxLayout()
  160. self.layout.addLayout(hlay_2)
  161. hlay_2.addStretch()
  162. self.panelize_object_button = QtWidgets.QPushButton(_("Panelize Object"))
  163. self.panelize_object_button.setToolTip(
  164. _("Panelize the specified object around the specified box.\n"
  165. "In other words it creates multiple copies of the source object,\n"
  166. "arranged in a 2D array of rows and columns.")
  167. )
  168. hlay_2.addWidget(self.panelize_object_button)
  169. self.layout.addStretch()
  170. ## Signals
  171. self.panelize_object_button.clicked.connect(self.on_panelize)
  172. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  173. self.type_box_combo.currentIndexChanged.connect(self.on_type_box_index_changed)
  174. # list to hold the temporary objects
  175. self.objs = []
  176. # final name for the panel object
  177. self.outname = ""
  178. # flag to signal the constrain was activated
  179. self.constrain_flag = False
  180. def run(self, toggle=True):
  181. self.app.report_usage("ToolPanelize()")
  182. if toggle:
  183. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  184. if self.app.ui.splitter.sizes()[0] == 0:
  185. self.app.ui.splitter.setSizes([1, 1])
  186. else:
  187. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  188. self.app.ui.splitter.setSizes([0, 1])
  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()))