ToolPanelize.py 25 KB

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