ToolPanelize.py 24 KB

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