ToolIsolation.py 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File by: Marius Adrian Stanciu (c) #
  4. # Date: 5/25/2020 #
  5. # License: MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from AppTool import AppTool
  9. from AppGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTable, FCInputDialog, FCButton, \
  10. FCComboBox, OptionalHideInputSection, FCSpinner
  11. from AppParsers.ParseGerber import Gerber
  12. from copy import deepcopy
  13. import numpy as np
  14. import math
  15. from shapely.ops import cascaded_union
  16. from shapely.geometry import MultiPolygon, Polygon, MultiLineString, LineString, LinearRing
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import logging
  19. import gettext
  20. import AppTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. class ToolIsolation(AppTool, Gerber):
  27. toolName = _("Isolation Tool")
  28. def __init__(self, app):
  29. self.app = app
  30. self.decimals = self.app.decimals
  31. AppTool.__init__(self, app)
  32. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  33. self.tools_frame = QtWidgets.QFrame()
  34. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  35. self.layout.addWidget(self.tools_frame)
  36. self.tools_box = QtWidgets.QVBoxLayout()
  37. self.tools_box.setContentsMargins(0, 0, 0, 0)
  38. self.tools_frame.setLayout(self.tools_box)
  39. self.title_box = QtWidgets.QHBoxLayout()
  40. self.tools_box.addLayout(self.title_box)
  41. # ## Title
  42. title_label = QtWidgets.QLabel("%s" % self.toolName)
  43. title_label.setStyleSheet("""
  44. QLabel
  45. {
  46. font-size: 16px;
  47. font-weight: bold;
  48. }
  49. """)
  50. title_label.setToolTip(
  51. _("Create a Geometry object with\n"
  52. "toolpaths to cut around polygons.")
  53. )
  54. self.title_box.addWidget(title_label)
  55. # App Level label
  56. self.level = QtWidgets.QLabel("")
  57. self.level.setToolTip(
  58. _(
  59. "BASIC is suitable for a beginner. Many parameters\n"
  60. "are hidden from the user in this mode.\n"
  61. "ADVANCED mode will make available all parameters.\n\n"
  62. "To change the application LEVEL, go to:\n"
  63. "Edit -> Preferences -> General and check:\n"
  64. "'APP. LEVEL' radio button."
  65. )
  66. )
  67. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  68. self.title_box.addWidget(self.level)
  69. # Grid Layout
  70. grid0 = QtWidgets.QGridLayout()
  71. grid0.setColumnStretch(0, 0)
  72. grid0.setColumnStretch(1, 1)
  73. self.tools_box.addLayout(grid0)
  74. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("GERBER"))
  75. self.obj_combo_label.setToolTip(
  76. _("Gerber object for isolation routing.")
  77. )
  78. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  79. # ################################################
  80. # ##### The object to be copper cleaned ##########
  81. # ################################################
  82. self.object_combo = FCComboBox()
  83. self.object_combo.setModel(self.app.collection)
  84. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  85. # self.object_combo.setCurrentIndex(1)
  86. self.object_combo.is_last = True
  87. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  88. separator_line = QtWidgets.QFrame()
  89. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  90. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  91. grid0.addWidget(separator_line, 2, 0, 1, 2)
  92. # ### Tools ## ##
  93. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  94. self.tools_table_label.setToolTip(
  95. _("Tools pool from which the algorithm\n"
  96. "will pick the ones used for copper clearing.")
  97. )
  98. grid0.addWidget(self.tools_table_label, 3, 0, 1, 2)
  99. self.tools_table = FCTable()
  100. grid0.addWidget(self.tools_table, 4, 0, 1, 2)
  101. self.tools_table.setColumnCount(4)
  102. # 3rd column is reserved (and hidden) for the tool ID
  103. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  104. self.tools_table.setColumnHidden(3, True)
  105. self.tools_table.setSortingEnabled(False)
  106. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  107. self.tools_table.horizontalHeaderItem(0).setToolTip(
  108. _("This is the Tool Number.\n"
  109. "Non copper clearing will start with the tool with the biggest \n"
  110. "diameter, continuing until there are no more tools.\n"
  111. "Only tools that create NCC clearing geometry will still be present\n"
  112. "in the resulting geometry. This is because with some tools\n"
  113. "this function will not be able to create painting geometry.")
  114. )
  115. self.tools_table.horizontalHeaderItem(1).setToolTip(
  116. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  117. "is the cut width into the material."))
  118. self.tools_table.horizontalHeaderItem(2).setToolTip(
  119. _("The Tool Type (TT) can be:\n"
  120. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  121. "the cut width in material is exactly the tool diameter.\n"
  122. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  123. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  124. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  125. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  126. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  127. "column of this table.\n"
  128. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  129. "in the resulting geometry as Isolation."))
  130. grid1 = QtWidgets.QGridLayout()
  131. grid1.setColumnStretch(0, 0)
  132. grid1.setColumnStretch(1, 1)
  133. self.tools_box.addLayout(grid1)
  134. # Tool order
  135. self.ncc_order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  136. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  137. "'No' --> means that the used order is the one in the tool table\n"
  138. "'Forward' --> means that the tools will be ordered from small to big\n"
  139. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  140. "WARNING: using rest machining will automatically set the order\n"
  141. "in reverse and disable this control."))
  142. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  143. {'label': _('Forward'), 'value': 'fwd'},
  144. {'label': _('Reverse'), 'value': 'rev'}])
  145. grid1.addWidget(self.ncc_order_label, 1, 0)
  146. grid1.addWidget(self.order_radio, 1, 1)
  147. separator_line = QtWidgets.QFrame()
  148. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  149. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  150. grid1.addWidget(separator_line, 2, 0, 1, 2)
  151. # #############################################################
  152. # ############### Tool selection ##############################
  153. # #############################################################
  154. self.grid3 = QtWidgets.QGridLayout()
  155. self.grid3.setColumnStretch(0, 0)
  156. self.grid3.setColumnStretch(1, 1)
  157. self.tools_box.addLayout(self.grid3)
  158. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  159. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  160. # Tool Type Radio Button
  161. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  162. self.tool_type_label.setToolTip(
  163. _("Default tool type:\n"
  164. "- 'V-shape'\n"
  165. "- Circular")
  166. )
  167. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  168. {'label': _('Circular'), 'value': 'C1'}])
  169. self.tool_type_radio.setToolTip(
  170. _("Default tool type:\n"
  171. "- 'V-shape'\n"
  172. "- Circular")
  173. )
  174. self.tool_type_radio.setObjectName("i_tool_type")
  175. self.grid3.addWidget(self.tool_type_label, 2, 0)
  176. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  177. # Tip Dia
  178. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  179. self.tipdialabel.setToolTip(
  180. _("The tip diameter for V-Shape Tool"))
  181. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  182. self.tipdia_entry.set_precision(self.decimals)
  183. self.tipdia_entry.set_range(0.0000, 9999.9999)
  184. self.tipdia_entry.setSingleStep(0.1)
  185. self.tipdia_entry.setObjectName("i_vtipdia")
  186. self.grid3.addWidget(self.tipdialabel, 3, 0)
  187. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  188. # Tip Angle
  189. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  190. self.tipanglelabel.setToolTip(
  191. _("The tip angle for V-Shape Tool.\n"
  192. "In degree."))
  193. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  194. self.tipangle_entry.set_precision(self.decimals)
  195. self.tipangle_entry.set_range(0.0000, 180.0000)
  196. self.tipangle_entry.setSingleStep(5)
  197. self.tipangle_entry.setObjectName("i_vtipangle")
  198. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  199. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  200. # Cut Z entry
  201. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  202. cutzlabel.setToolTip(
  203. _("Depth of cut into material. Negative value.\n"
  204. "In FlatCAM units.")
  205. )
  206. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  207. self.cutz_entry.set_precision(self.decimals)
  208. self.cutz_entry.set_range(-99999.9999, 0.0000)
  209. self.cutz_entry.setObjectName("i_vcutz")
  210. self.grid3.addWidget(cutzlabel, 5, 0)
  211. self.grid3.addWidget(self.cutz_entry, 5, 1)
  212. # ### Tool Diameter ####
  213. self.addtool_entry_lbl = QtWidgets.QLabel('%s:' % _('Tool Dia'))
  214. self.addtool_entry_lbl.setToolTip(
  215. _("Diameter for the new tool to add in the Tool Table.\n"
  216. "If the tool is V-shape type then this value is automatically\n"
  217. "calculated from the other parameters.")
  218. )
  219. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  220. self.addtool_entry.set_precision(self.decimals)
  221. self.addtool_entry.set_range(0.000, 9999.9999)
  222. self.addtool_entry.setObjectName("i_new_tooldia")
  223. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  224. self.grid3.addWidget(self.addtool_entry, 6, 1)
  225. hlay = QtWidgets.QHBoxLayout()
  226. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  227. self.addtool_btn.setToolTip(
  228. _("Add a new tool to the Tool Table\n"
  229. "with the diameter specified above.")
  230. )
  231. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  232. self.addtool_from_db_btn.setToolTip(
  233. _("Add a new tool to the Tool Table\n"
  234. "from the Tool DataBase.")
  235. )
  236. hlay.addWidget(self.addtool_btn)
  237. hlay.addWidget(self.addtool_from_db_btn)
  238. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  239. separator_line = QtWidgets.QFrame()
  240. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  241. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  242. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  243. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  244. self.deltool_btn.setToolTip(
  245. _("Delete a selection of tools in the Tool Table\n"
  246. "by first selecting a row(s) in the Tool Table.")
  247. )
  248. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  249. # self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  250. separator_line = QtWidgets.QFrame()
  251. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  252. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  253. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  254. self.tool_data_label = QtWidgets.QLabel(
  255. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  256. self.tool_data_label.setToolTip(
  257. _(
  258. "The data used for creating GCode.\n"
  259. "Each tool store it's own set of such data."
  260. )
  261. )
  262. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  263. # Passes
  264. passlabel = QtWidgets.QLabel('%s:' % _('Passes'))
  265. passlabel.setToolTip(
  266. _("Width of the isolation gap in\n"
  267. "number (integer) of tool widths.")
  268. )
  269. self.passes_entry = FCSpinner(callback=self.confirmation_message_int)
  270. self.passes_entry.set_range(1, 999)
  271. self.passes_entry.setObjectName("i_passes")
  272. self.grid3.addWidget(passlabel, 13, 0)
  273. self.grid3.addWidget(self.passes_entry, 13, 1)
  274. # Overlap Entry
  275. overlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  276. overlabel.setToolTip(
  277. _("How much (percentage) of the tool width to overlap each tool pass.")
  278. )
  279. self.iso_overlap_entry = FCDoubleSpinner(suffix='%', callback=self.confirmation_message)
  280. self.iso_overlap_entry.set_precision(self.decimals)
  281. self.iso_overlap_entry.setWrapping(True)
  282. self.iso_overlap_entry.set_range(0.0000, 99.9999)
  283. self.iso_overlap_entry.setSingleStep(0.1)
  284. self.iso_overlap_entry.setObjectName("i_overlap")
  285. self.grid3.addWidget(overlabel, 14, 0)
  286. self.grid3.addWidget(self.iso_overlap_entry, 14, 1)
  287. # Milling Type Radio Button
  288. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  289. self.milling_type_label.setToolTip(
  290. _("Milling type when the selected tool is of type: 'iso_op':\n"
  291. "- climb / best for precision milling and to reduce tool usage\n"
  292. "- conventional / useful when there is no backlash compensation")
  293. )
  294. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  295. {'label': _('Conventional'), 'value': 'cv'}])
  296. self.milling_type_radio.setToolTip(
  297. _("Milling type when the selected tool is of type: 'iso_op':\n"
  298. "- climb / best for precision milling and to reduce tool usage\n"
  299. "- conventional / useful when there is no backlash compensation")
  300. )
  301. self.milling_type_radio.setObjectName("i_milling_type")
  302. self.grid3.addWidget(self.milling_type_label, 15, 0)
  303. self.grid3.addWidget(self.milling_type_radio, 15, 1)
  304. # Follow
  305. self.follow_label = QtWidgets.QLabel('%s:' % _('Follow'))
  306. self.follow_label.setToolTip(
  307. _("Generate a 'Follow' geometry.\n"
  308. "This means that it will cut through\n"
  309. "the middle of the trace.")
  310. )
  311. self.follow_cb = FCCheckBox()
  312. self.follow_cb.setToolTip(_("Generate a 'Follow' geometry.\n"
  313. "This means that it will cut through\n"
  314. "the middle of the trace."))
  315. self.follow_cb.setObjectName("i_follow")
  316. self.grid3.addWidget(self.follow_label, 16, 0)
  317. self.grid3.addWidget(self.follow_cb, 16, 1)
  318. # Isolation Type
  319. self.iso_type_label = QtWidgets.QLabel('%s:' % _('Isolation Type'))
  320. self.iso_type_label.setToolTip(
  321. _("Choose how the isolation will be executed:\n"
  322. "- 'Full' -> complete isolation of polygons\n"
  323. "- 'Ext' -> will isolate only on the outside\n"
  324. "- 'Int' -> will isolate only on the inside\n"
  325. "'Exterior' isolation is almost always possible\n"
  326. "(with the right tool) but 'Interior'\n"
  327. "isolation can be done only when there is an opening\n"
  328. "inside of the polygon (e.g polygon is a 'doughnut' shape).")
  329. )
  330. self.iso_type_radio = RadioSet([{'label': _('Full'), 'value': 'full'},
  331. {'label': _('Ext'), 'value': 'ext'},
  332. {'label': _('Int'), 'value': 'int'}])
  333. self.iso_type_radio.setObjectName("i_iso_type")
  334. self.grid3.addWidget(self.iso_type_label, 17, 0)
  335. self.grid3.addWidget(self.iso_type_radio, 17, 1)
  336. separator_line = QtWidgets.QFrame()
  337. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  338. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  339. self.grid3.addWidget(separator_line, 18, 0, 1, 2)
  340. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  341. self.apply_param_to_all.setToolTip(
  342. _("The parameters in the current form will be applied\n"
  343. "on all the tools from the Tool Table.")
  344. )
  345. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  346. separator_line = QtWidgets.QFrame()
  347. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  348. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  349. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  350. # General Parameters
  351. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  352. self.gen_param_label.setToolTip(
  353. _("Parameters that are common for all tools.")
  354. )
  355. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  356. # Rest Machining
  357. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  358. self.rest_cb.setObjectName("i_rest")
  359. self.rest_cb.setToolTip(
  360. _("If checked, use 'rest machining'.\n"
  361. "Basically it will isolate outside PCB features,\n"
  362. "using the biggest tool and continue with the next tools,\n"
  363. "from bigger to smaller, to isolate the copper features that\n"
  364. "could not be cleared by previous tool, until there is\n"
  365. "no more copper features to isolate or there are no more tools.\n"
  366. "If not checked, use the standard algorithm.")
  367. )
  368. self.grid3.addWidget(self.rest_cb, 25, 0, 1, 2)
  369. # Combine All Passes
  370. self.combine_passes_cb = FCCheckBox(label=_('Combine'))
  371. self.combine_passes_cb.setToolTip(
  372. _("Combine all passes into one object")
  373. )
  374. self.combine_passes_cb.setObjectName("i_combine")
  375. self.grid3.addWidget(self.combine_passes_cb, 26, 0, 1, 2)
  376. # Exception Areas
  377. self.except_cb = FCCheckBox(label=_('Except'))
  378. self.except_cb.setToolTip(_("When the isolation geometry is generated,\n"
  379. "by checking this, the area of the object below\n"
  380. "will be subtracted from the isolation geometry."))
  381. self.except_cb.setObjectName("i_except")
  382. self.grid3.addWidget(self.except_cb, 27, 0, 1, 2)
  383. # Type of object to be excepted
  384. self.type_excobj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  385. self.type_excobj_combo_label.setToolTip(
  386. _("Specify the type of object to be excepted from isolation.\n"
  387. "It can be of type: Gerber or Geometry.\n"
  388. "What is selected here will dictate the kind\n"
  389. "of objects that will populate the 'Object' combobox.")
  390. )
  391. self.type_excobj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  392. {'label': _("Gerber"), 'value': 'gerber'}])
  393. self.grid3.addWidget(self.type_excobj_combo_label, 28, 0)
  394. self.grid3.addWidget(self.type_excobj_radio, 28, 1)
  395. # The object to be excepted
  396. self.exc_obj_combo = FCComboBox()
  397. self.exc_obj_combo.setToolTip(_("Object whose area will be removed from isolation geometry."))
  398. # set the model for the Area Exception comboboxes
  399. self.exc_obj_combo.setModel(self.app.collection)
  400. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  401. self.exc_obj_combo.is_last = True
  402. self.exc_obj_combo.obj_type = self.type_excobj_radio.get_value()
  403. self.grid3.addWidget(self.exc_obj_combo, 29, 0, 1, 2)
  404. self.e_ois = OptionalHideInputSection(self.except_cb,
  405. [
  406. self.type_excobj_combo_label,
  407. self.type_excobj_radio,
  408. self.exc_obj_combo
  409. ])
  410. # Isolation Scope
  411. self.select_label = QtWidgets.QLabel('%s:' % _("Selection"))
  412. self.select_label.setToolTip(
  413. _("Isolation scope. Choose what to isolate:\n"
  414. "- 'All' -> Isolate all the polygons in the object\n"
  415. "- 'Selection' -> Isolate a selection of polygons.\n"
  416. "- 'Reference Object' - will process the area specified by another object.")
  417. )
  418. self.select_combo = FCComboBox()
  419. self.select_combo.addItems(
  420. [_("All"), _("Area Selection"), _("Polygon Selection"), _("Reference Object")]
  421. )
  422. self.select_combo.setObjectName("i_selection")
  423. self.grid3.addWidget(self.select_label, 30, 0)
  424. self.grid3.addWidget(self.select_combo, 30, 1)
  425. self.reference_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  426. self.reference_combo_type_label.setToolTip(
  427. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  428. "It can be Gerber, Excellon or Geometry.")
  429. )
  430. self.reference_combo_type = FCComboBox()
  431. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  432. self.grid3.addWidget(self.reference_combo_type_label, 31, 0)
  433. self.grid3.addWidget(self.reference_combo_type, 31, 1)
  434. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  435. self.reference_combo_label.setToolTip(
  436. _("The FlatCAM object to be used as non copper clearing reference.")
  437. )
  438. self.reference_combo = FCComboBox()
  439. self.reference_combo.setModel(self.app.collection)
  440. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  441. self.reference_combo.is_last = True
  442. self.grid3.addWidget(self.reference_combo_label, 32, 0)
  443. self.grid3.addWidget(self.reference_combo, 32, 1)
  444. self.reference_combo.hide()
  445. self.reference_combo_label.hide()
  446. self.reference_combo_type.hide()
  447. self.reference_combo_type_label.hide()
  448. # Area Selection shape
  449. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  450. self.area_shape_label.setToolTip(
  451. _("The kind of selection shape used for area selection.")
  452. )
  453. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  454. {'label': _("Polygon"), 'value': 'polygon'}])
  455. self.grid3.addWidget(self.area_shape_label, 33, 0)
  456. self.grid3.addWidget(self.area_shape_radio, 33, 1)
  457. self.area_shape_label.hide()
  458. self.area_shape_radio.hide()
  459. separator_line = QtWidgets.QFrame()
  460. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  461. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  462. self.grid3.addWidget(separator_line, 34, 0, 1, 2)
  463. self.generate_iso_button = QtWidgets.QPushButton("%s" % _("Generate Isolation Geometry"))
  464. self.generate_iso_button.setStyleSheet("""
  465. QPushButton
  466. {
  467. font-weight: bold;
  468. }
  469. """)
  470. self.generate_iso_button.setToolTip(
  471. _("Create a Geometry object with toolpaths to cut \n"
  472. "isolation outside, inside or on both sides of the\n"
  473. "object. For a Gerber object outside means outside\n"
  474. "of the Gerber feature and inside means inside of\n"
  475. "the Gerber feature, if possible at all. This means\n"
  476. "that only if the Gerber feature has openings inside, they\n"
  477. "will be isolated. If what is wanted is to cut isolation\n"
  478. "inside the actual Gerber feature, use a negative tool\n"
  479. "diameter above.")
  480. )
  481. self.tools_box.addWidget(self.generate_iso_button)
  482. self.create_buffer_button = QtWidgets.QPushButton(_('Buffer Solid Geometry'))
  483. self.create_buffer_button.setToolTip(
  484. _("This button is shown only when the Gerber file\n"
  485. "is loaded without buffering.\n"
  486. "Clicking this will create the buffered geometry\n"
  487. "required for isolation.")
  488. )
  489. self.tools_box.addWidget(self.create_buffer_button)
  490. self.tools_box.addStretch()
  491. # ## Reset Tool
  492. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  493. self.reset_button.setToolTip(
  494. _("Will reset the tool parameters.")
  495. )
  496. self.reset_button.setStyleSheet("""
  497. QPushButton
  498. {
  499. font-weight: bold;
  500. }
  501. """)
  502. self.tools_box.addWidget(self.reset_button)
  503. # ############################ FINSIHED GUI ###################################
  504. # #############################################################################
  505. # #############################################################################
  506. # ###################### Setup CONTEXT MENU ###################################
  507. # #############################################################################
  508. self.tools_table.setupContextMenu()
  509. self.tools_table.addContextMenu(
  510. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  511. )
  512. self.tools_table.addContextMenu(
  513. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  514. )
  515. self.tools_table.addContextMenu(
  516. _("Delete"), lambda:
  517. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  518. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  519. )
  520. # #############################################################################
  521. # ########################## VARIABLES ########################################
  522. # #############################################################################
  523. self.units = ''
  524. self.iso_tools = {}
  525. self.tooluid = 0
  526. # store here the default data for Geometry Data
  527. self.default_data = {}
  528. self.obj_name = ""
  529. self.grb_obj = None
  530. self.sel_rect = []
  531. self.bound_obj_name = ""
  532. self.bound_obj = None
  533. self.ncc_dia_list = []
  534. self.iso_dia_list = []
  535. self.has_offset = None
  536. self.o_name = None
  537. self.overlap = None
  538. self.connect = None
  539. self.contour = None
  540. self.rest = None
  541. self.first_click = False
  542. self.cursor_pos = None
  543. self.mouse_is_dragging = False
  544. # store here the points for the "Polygon" area selection shape
  545. self.points = []
  546. # set this as True when in middle of drawing a "Polygon" area selection shape
  547. # it is made False by first click to signify that the shape is complete
  548. self.poly_drawn = False
  549. self.mm = None
  550. self.mr = None
  551. self.kp = None
  552. # store geometry from Polygon selection
  553. self.poly_dict = {}
  554. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  555. # store here solid_geometry when there are tool with isolation job
  556. self.solid_geometry = []
  557. self.select_method = None
  558. self.tool_type_item_options = []
  559. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  560. self.tooldia = None
  561. self.form_fields = {
  562. "tools_iso_passes": self.passes_entry,
  563. "tools_iso_overlap": self.iso_overlap_entry,
  564. "tools_iso_milling_type": self.milling_type_radio,
  565. "tools_iso_combine": self.combine_passes_cb,
  566. "tools_iso_follow": self.follow_cb,
  567. "tools_iso_isotype": self.iso_type_radio
  568. }
  569. self.name2option = {
  570. "i_passes": "tools_iso_passes",
  571. "i_overlap": "tools_iso_overlap",
  572. "i_milling_type": "tools_iso_milling_type",
  573. "i_combine": "tools_iso_combine",
  574. "i_follow": "tools_iso_follow",
  575. "i_iso_type": "tools_iso_isotype"
  576. }
  577. self.old_tool_dia = None
  578. # #############################################################################
  579. # ############################ SIGNALS ########################################
  580. # #############################################################################
  581. self.addtool_btn.clicked.connect(self.on_tool_add)
  582. self.addtool_entry.returnPressed.connect(self.on_tooldia_updated)
  583. self.deltool_btn.clicked.connect(self.on_tool_delete)
  584. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  585. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  586. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  587. self.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  588. self.select_combo.currentIndexChanged.connect(self.on_toggle_reference)
  589. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  590. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  591. self.type_excobj_radio.activated_custom.connect(self.on_type_excobj_index_changed)
  592. self.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  593. self.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  594. self.generate_iso_button.clicked.connect(self.on_iso_button_click)
  595. self.reset_button.clicked.connect(self.set_tool_ui)
  596. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  597. self.app.cleanup.connect(self.reset_usage)
  598. def on_type_excobj_index_changed(self, val):
  599. obj_type = 0 if val == 'gerber' else 2
  600. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  601. self.exc_obj_combo.setCurrentIndex(0)
  602. self.exc_obj_combo.obj_type = {
  603. "gerber": "Gerber", "geometry": "Geometry"
  604. }[self.type_excobj_radio.get_value()]
  605. def on_row_selection_change(self):
  606. self.blockSignals(True)
  607. sel_rows = [it.row() for it in self.tools_table.selectedItems()]
  608. # sel_rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  609. if not sel_rows:
  610. sel_rows = [0]
  611. for current_row in sel_rows:
  612. # populate the form with the data from the tool associated with the row parameter
  613. try:
  614. item = self.tools_table.item(current_row, 3)
  615. if item is not None:
  616. tooluid = int(item.text())
  617. else:
  618. return
  619. except Exception as e:
  620. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  621. return
  622. # update the QLabel that shows for which Tool we have the parameters in the UI form
  623. if len(sel_rows) == 1:
  624. cr = current_row + 1
  625. self.tool_data_label.setText(
  626. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  627. )
  628. try:
  629. # set the form with data from the newly selected tool
  630. for tooluid_key, tooluid_value in list(self.iso_tools.items()):
  631. if int(tooluid_key) == tooluid:
  632. for key, value in tooluid_value.items():
  633. if key == 'data':
  634. form_value_storage = tooluid_value[key]
  635. self.storage_to_form(form_value_storage)
  636. except Exception as e:
  637. log.debug("ToolIsolation ---> update_ui() " + str(e))
  638. else:
  639. self.tool_data_label.setText(
  640. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  641. )
  642. self.blockSignals(False)
  643. def storage_to_form(self, dict_storage):
  644. for form_key in self.form_fields:
  645. for storage_key in dict_storage:
  646. if form_key == storage_key:
  647. try:
  648. self.form_fields[form_key].set_value(dict_storage[form_key])
  649. except Exception as e:
  650. log.debug("ToolIsolation.storage_to_form() --> %s" % str(e))
  651. pass
  652. def form_to_storage(self):
  653. if self.tools_table.rowCount() == 0:
  654. # there is no tool in tool table so we can't save the GUI elements values to storage
  655. return
  656. self.blockSignals(True)
  657. widget_changed = self.sender()
  658. wdg_objname = widget_changed.objectName()
  659. option_changed = self.name2option[wdg_objname]
  660. # row = self.tools_table.currentRow()
  661. rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  662. for row in rows:
  663. if row < 0:
  664. row = 0
  665. tooluid_item = int(self.tools_table.item(row, 3).text())
  666. for tooluid_key, tooluid_val in self.iso_tools.items():
  667. if int(tooluid_key) == tooluid_item:
  668. new_option_value = self.form_fields[option_changed].get_value()
  669. if option_changed in tooluid_val:
  670. tooluid_val[option_changed] = new_option_value
  671. if option_changed in tooluid_val['data']:
  672. tooluid_val['data'][option_changed] = new_option_value
  673. self.blockSignals(False)
  674. def on_apply_param_to_all_clicked(self):
  675. if self.tools_table.rowCount() == 0:
  676. # there is no tool in tool table so we can't save the GUI elements values to storage
  677. log.debug("ToolIsolation.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  678. return
  679. self.blockSignals(True)
  680. row = self.tools_table.currentRow()
  681. if row < 0:
  682. row = 0
  683. tooluid_item = int(self.tools_table.item(row, 3).text())
  684. temp_tool_data = {}
  685. for tooluid_key, tooluid_val in self.iso_tools.items():
  686. if int(tooluid_key) == tooluid_item:
  687. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  688. # the current row in the tool table
  689. temp_tool_data = tooluid_val['data']
  690. break
  691. for tooluid_key, tooluid_val in self.iso_tools.items():
  692. tooluid_val['data'] = deepcopy(temp_tool_data)
  693. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  694. self.blockSignals(False)
  695. def on_add_tool_by_key(self):
  696. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  697. text='%s:' % _('Enter a Tool Diameter'),
  698. min=0.0001, max=9999.9999, decimals=self.decimals)
  699. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  700. val, ok = tool_add_popup.get_value()
  701. if ok:
  702. if float(val) == 0:
  703. self.app.inform.emit('[WARNING_NOTCL] %s' %
  704. _("Please enter a tool diameter with non-zero value, in Float format."))
  705. return
  706. self.on_tool_add(dia=float(val))
  707. else:
  708. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  709. def install(self, icon=None, separator=None, **kwargs):
  710. AppTool.install(self, icon, separator, shortcut='Alt+I', **kwargs)
  711. def run(self, toggle=True):
  712. self.app.defaults.report_usage("ToolIsolation()")
  713. log.debug("ToolIsolation().run() was launched ...")
  714. if toggle:
  715. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  716. if self.app.ui.splitter.sizes()[0] == 0:
  717. self.app.ui.splitter.setSizes([1, 1])
  718. else:
  719. try:
  720. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  721. # if tab is populated with the tool but it does not have the focus, focus on it
  722. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  723. # focus on Tool Tab
  724. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  725. else:
  726. self.app.ui.splitter.setSizes([0, 1])
  727. except AttributeError:
  728. pass
  729. else:
  730. if self.app.ui.splitter.sizes()[0] == 0:
  731. self.app.ui.splitter.setSizes([1, 1])
  732. AppTool.run(self)
  733. self.set_tool_ui()
  734. # reset those objects on a new run
  735. self.grb_obj = None
  736. self.bound_obj = None
  737. self.obj_name = ''
  738. self.bound_obj_name = ''
  739. self.build_ui()
  740. self.app.ui.notebook.setTabText(2, _("Isolation Tool"))
  741. def set_tool_ui(self):
  742. self.units = self.app.defaults['units'].upper()
  743. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  744. # try to select in the Gerber combobox the active object
  745. try:
  746. current_name = self.app.collection.get_active().options['name']
  747. self.object_combo.set_value(current_name)
  748. except Exception:
  749. pass
  750. app_mode = self.app.defaults["global_app_level"]
  751. # Show/Hide Advanced Options
  752. if app_mode == 'b':
  753. self.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  754. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  755. self.tool_type_radio.set_value('C1')
  756. self.tool_type_label.hide()
  757. self.tool_type_radio.hide()
  758. self.milling_type_label.hide()
  759. self.milling_type_radio.hide()
  760. self.iso_type_label.hide()
  761. self.iso_type_radio.set_value('full')
  762. self.iso_type_radio.hide()
  763. self.follow_cb.set_value(False)
  764. self.follow_cb.hide()
  765. self.follow_label.hide()
  766. self.rest_cb.set_value(False)
  767. self.rest_cb.hide()
  768. self.except_cb.set_value(False)
  769. self.except_cb.hide()
  770. self.select_combo.setCurrentIndex(0)
  771. self.select_combo.hide()
  772. self.select_label.hide()
  773. else:
  774. self.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  775. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  776. self.tool_type_label.show()
  777. self.tool_type_radio.show()
  778. self.milling_type_label.show()
  779. self.milling_type_radio.show()
  780. self.iso_type_label.show()
  781. self.iso_type_radio.set_value(self.app.defaults["tools_iso_isotype"])
  782. self.iso_type_radio.show()
  783. self.follow_cb.set_value(self.app.defaults["tools_iso_follow"])
  784. self.follow_cb.show()
  785. self.follow_label.show()
  786. self.rest_cb.set_value(self.app.defaults["tools_iso_rest"])
  787. self.rest_cb.show()
  788. self.except_cb.set_value(self.app.defaults["tools_iso_isoexcept"])
  789. self.except_cb.show()
  790. self.select_combo.set_value(self.app.defaults["tools_iso_selection"])
  791. self.select_combo.show()
  792. self.select_label.show()
  793. if self.app.defaults["gerber_buffering"] == 'no':
  794. self.create_buffer_button.show()
  795. try:
  796. self.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  797. except TypeError:
  798. pass
  799. self.create_buffer_button.clicked.connect(self.on_generate_buffer)
  800. else:
  801. self.create_buffer_button.hide()
  802. self.tools_frame.show()
  803. self.type_excobj_radio.set_value('gerber')
  804. # run those once so the obj_type attribute is updated for the FCComboboxes
  805. # so the last loaded object is displayed
  806. self.on_type_excobj_index_changed(val="gerber")
  807. self.on_reference_combo_changed()
  808. self.order_radio.set_value(self.app.defaults["tools_iso_order"])
  809. self.passes_entry.set_value(self.app.defaults["tools_iso_passes"])
  810. self.iso_overlap_entry.set_value(self.app.defaults["tools_iso_overlap"])
  811. self.milling_type_radio.set_value(self.app.defaults["tools_iso_milling_type"])
  812. self.combine_passes_cb.set_value(self.app.defaults["tools_iso_combine_passes"])
  813. self.area_shape_radio.set_value(self.app.defaults["tools_iso_area_shape"])
  814. self.cutz_entry.set_value(self.app.defaults["tools_iso_tool_cutz"])
  815. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  816. self.tipdia_entry.set_value(self.app.defaults["tools_iso_tool_vtipdia"])
  817. self.tipangle_entry.set_value(self.app.defaults["tools_iso_tool_vtipangle"])
  818. self.addtool_entry.set_value(self.app.defaults["tools_iso_newdia"])
  819. self.on_tool_type(val=self.tool_type_radio.get_value())
  820. loaded_obj = self.app.collection.get_by_name(self.object_combo.get_value())
  821. if loaded_obj:
  822. outname = loaded_obj.options['name']
  823. else:
  824. outname = ''
  825. # init the working variables
  826. self.default_data.clear()
  827. self.default_data = {
  828. "name": outname + '_iso',
  829. "plot": self.app.defaults["geometry_plot"],
  830. "cutz": float(self.cutz_entry.get_value()),
  831. "vtipdia": float(self.tipdia_entry.get_value()),
  832. "vtipangle": float(self.tipangle_entry.get_value()),
  833. "travelz": self.app.defaults["geometry_travelz"],
  834. "feedrate": self.app.defaults["geometry_feedrate"],
  835. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  836. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  837. "dwell": self.app.defaults["geometry_dwell"],
  838. "dwelltime": self.app.defaults["geometry_dwelltime"],
  839. "multidepth": self.app.defaults["geometry_multidepth"],
  840. "ppname_g": self.app.defaults["geometry_ppname_g"],
  841. "depthperpass": self.app.defaults["geometry_depthperpass"],
  842. "extracut": self.app.defaults["geometry_extracut"],
  843. "extracut_length": self.app.defaults["geometry_extracut_length"],
  844. "toolchange": self.app.defaults["geometry_toolchange"],
  845. "toolchangez": self.app.defaults["geometry_toolchangez"],
  846. "endz": self.app.defaults["geometry_endz"],
  847. "endxy": self.app.defaults["geometry_endxy"],
  848. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  849. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  850. "startz": self.app.defaults["geometry_startz"],
  851. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  852. "area_shape": self.app.defaults["geometry_area_shape"],
  853. "area_strategy": self.app.defaults["geometry_area_strategy"],
  854. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  855. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  856. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  857. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  858. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  859. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  860. "tools_iso_rest": self.app.defaults["tools_iso_rest"],
  861. "tools_iso_combine_passes": self.app.defaults["tools_iso_combine_passes"],
  862. "tools_iso_isoexcept": self.app.defaults["tools_iso_isoexcept"],
  863. "tools_iso_selection": self.app.defaults["tools_iso_selection"],
  864. "tools_iso_area_shape": self.app.defaults["tools_iso_area_shape"]
  865. }
  866. try:
  867. dias = [float(self.app.defaults["tools_iso_tooldia"])]
  868. except (ValueError, TypeError):
  869. dias = [float(eval(dia)) for dia in self.app.defaults["tools_iso_tooldia"].split(",") if dia != '']
  870. if not dias:
  871. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> Isolation Tools.")
  872. return
  873. self.tooluid = 0
  874. self.iso_tools.clear()
  875. for tool_dia in dias:
  876. self.tooluid += 1
  877. self.iso_tools.update({
  878. int(self.tooluid): {
  879. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  880. 'offset': 'Path',
  881. 'offset_value': 0.0,
  882. 'type': 'Iso',
  883. 'tool_type': self.tool_type_radio.get_value(),
  884. 'data': deepcopy(self.default_data),
  885. 'solid_geometry': []
  886. }
  887. })
  888. self.obj_name = ""
  889. self.grb_obj = None
  890. self.bound_obj_name = ""
  891. self.bound_obj = None
  892. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  893. self.units = self.app.defaults['units'].upper()
  894. def build_ui(self):
  895. self.ui_disconnect()
  896. # updated units
  897. self.units = self.app.defaults['units'].upper()
  898. sorted_tools = []
  899. for k, v in self.iso_tools.items():
  900. if self.units == "IN":
  901. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  902. else:
  903. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  904. order = self.order_radio.get_value()
  905. if order == 'fwd':
  906. sorted_tools.sort(reverse=False)
  907. elif order == 'rev':
  908. sorted_tools.sort(reverse=True)
  909. else:
  910. pass
  911. n = len(sorted_tools)
  912. self.tools_table.setRowCount(n)
  913. tool_id = 0
  914. for tool_sorted in sorted_tools:
  915. for tooluid_key, tooluid_value in self.iso_tools.items():
  916. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  917. tool_id += 1
  918. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  919. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  920. row_no = tool_id - 1
  921. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  922. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  923. # There are no drill bits in MM with more than 2 decimals diameter
  924. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  925. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  926. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  927. tool_type_item = FCComboBox()
  928. tool_type_item.addItems(self.tool_type_item_options)
  929. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  930. idx = tool_type_item.findText(tooluid_value['tool_type'])
  931. tool_type_item.setCurrentIndex(idx)
  932. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  933. self.tools_table.setItem(row_no, 1, dia) # Diameter
  934. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  935. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  936. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  937. # make the diameter column editable
  938. for row in range(tool_id):
  939. self.tools_table.item(row, 1).setFlags(
  940. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  941. # all the tools are selected by default
  942. self.tools_table.selectColumn(0)
  943. #
  944. self.tools_table.resizeColumnsToContents()
  945. self.tools_table.resizeRowsToContents()
  946. vertical_header = self.tools_table.verticalHeader()
  947. vertical_header.hide()
  948. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  949. horizontal_header = self.tools_table.horizontalHeader()
  950. horizontal_header.setMinimumSectionSize(10)
  951. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  952. horizontal_header.resizeSection(0, 20)
  953. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  954. # self.tools_table.setSortingEnabled(True)
  955. # sort by tool diameter
  956. # self.tools_table.sortItems(1)
  957. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  958. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  959. self.ui_connect()
  960. # set the text on tool_data_label after loading the object
  961. sel_rows = []
  962. sel_items = self.tools_table.selectedItems()
  963. for it in sel_items:
  964. sel_rows.append(it.row())
  965. if len(sel_rows) > 1:
  966. self.tool_data_label.setText(
  967. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  968. )
  969. def ui_connect(self):
  970. self.tools_table.itemChanged.connect(self.on_tool_edit)
  971. # rows selected
  972. self.tools_table.clicked.connect(self.on_row_selection_change)
  973. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  974. for row in range(self.tools_table.rowCount()):
  975. try:
  976. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  977. except AttributeError:
  978. pass
  979. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  980. for opt in self.form_fields:
  981. current_widget = self.form_fields[opt]
  982. if isinstance(current_widget, FCCheckBox):
  983. current_widget.stateChanged.connect(self.form_to_storage)
  984. if isinstance(current_widget, RadioSet):
  985. current_widget.activated_custom.connect(self.form_to_storage)
  986. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  987. current_widget.returnPressed.connect(self.form_to_storage)
  988. elif isinstance(current_widget, FCComboBox):
  989. current_widget.currentIndexChanged.connect(self.form_to_storage)
  990. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  991. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  992. def ui_disconnect(self):
  993. try:
  994. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  995. self.tools_table.itemChanged.disconnect()
  996. except (TypeError, AttributeError):
  997. pass
  998. try:
  999. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1000. self.tool_type_radio.activated_custom.disconnect()
  1001. except (TypeError, AttributeError):
  1002. pass
  1003. for row in range(self.tools_table.rowCount()):
  1004. try:
  1005. self.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  1006. except (TypeError, AttributeError):
  1007. pass
  1008. for opt in self.form_fields:
  1009. current_widget = self.form_fields[opt]
  1010. if isinstance(current_widget, FCCheckBox):
  1011. try:
  1012. current_widget.stateChanged.disconnect(self.form_to_storage)
  1013. except (TypeError, ValueError):
  1014. pass
  1015. if isinstance(current_widget, RadioSet):
  1016. try:
  1017. current_widget.activated_custom.disconnect(self.form_to_storage)
  1018. except (TypeError, ValueError):
  1019. pass
  1020. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  1021. try:
  1022. current_widget.returnPressed.disconnect(self.form_to_storage)
  1023. except (TypeError, ValueError):
  1024. pass
  1025. elif isinstance(current_widget, FCComboBox):
  1026. try:
  1027. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  1028. except (TypeError, ValueError):
  1029. pass
  1030. try:
  1031. self.rest_cb.stateChanged.disconnect()
  1032. except (TypeError, ValueError):
  1033. pass
  1034. try:
  1035. self.order_radio.activated_custom[str].disconnect()
  1036. except (TypeError, ValueError):
  1037. pass
  1038. # rows selected
  1039. try:
  1040. self.tools_table.clicked.disconnect()
  1041. except (TypeError, AttributeError):
  1042. pass
  1043. try:
  1044. self.tools_table.horizontalHeader().sectionClicked.disconnect()
  1045. except (TypeError, AttributeError):
  1046. pass
  1047. def on_tooldia_updated(self):
  1048. if self.tool_type_radio.get_value() == 'C1':
  1049. self.old_tool_dia = self.addtool_entry.get_value()
  1050. def on_reference_combo_changed(self):
  1051. obj_type = self.reference_combo_type.currentIndex()
  1052. self.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  1053. self.reference_combo.setCurrentIndex(0)
  1054. self.reference_combo.obj_type = {
  1055. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  1056. }[self.reference_combo_type.get_value()]
  1057. def on_toggle_reference(self):
  1058. val = self.select_combo.get_value()
  1059. if val == _("All"):
  1060. self.reference_combo.hide()
  1061. self.reference_combo_label.hide()
  1062. self.reference_combo_type.hide()
  1063. self.reference_combo_type_label.hide()
  1064. self.area_shape_label.hide()
  1065. self.area_shape_radio.hide()
  1066. # disable rest-machining for area painting
  1067. self.rest_cb.setDisabled(False)
  1068. elif val == _("Area Selection"):
  1069. self.reference_combo.hide()
  1070. self.reference_combo_label.hide()
  1071. self.reference_combo_type.hide()
  1072. self.reference_combo_type_label.hide()
  1073. self.area_shape_label.show()
  1074. self.area_shape_radio.show()
  1075. # disable rest-machining for area isolation
  1076. self.rest_cb.set_value(False)
  1077. self.rest_cb.setDisabled(True)
  1078. elif val == _("Polygon Selection"):
  1079. self.reference_combo.hide()
  1080. self.reference_combo_label.hide()
  1081. self.reference_combo_type.hide()
  1082. self.reference_combo_type_label.hide()
  1083. self.area_shape_label.hide()
  1084. self.area_shape_radio.hide()
  1085. else:
  1086. self.reference_combo.show()
  1087. self.reference_combo_label.show()
  1088. self.reference_combo_type.show()
  1089. self.reference_combo_type_label.show()
  1090. self.area_shape_label.hide()
  1091. self.area_shape_radio.hide()
  1092. # disable rest-machining for area painting
  1093. self.rest_cb.setDisabled(False)
  1094. def on_order_changed(self, order):
  1095. if order != 'no':
  1096. self.build_ui()
  1097. def on_rest_machining_check(self, state):
  1098. if state:
  1099. self.order_radio.set_value('rev')
  1100. self.ncc_order_label.setDisabled(True)
  1101. self.order_radio.setDisabled(True)
  1102. else:
  1103. self.ncc_order_label.setDisabled(False)
  1104. self.order_radio.setDisabled(False)
  1105. def on_tooltable_cellwidget_change(self):
  1106. cw = self.sender()
  1107. assert isinstance(cw, QtWidgets.QComboBox), \
  1108. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  1109. cw_index = self.tools_table.indexAt(cw.pos())
  1110. cw_row = cw_index.row()
  1111. cw_col = cw_index.column()
  1112. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1113. # if the sender is in the column with index 2 then we update the tool_type key
  1114. if cw_col == 2:
  1115. tt = cw.currentText()
  1116. typ = 'Iso' if tt == 'V' else "Rough"
  1117. self.iso_tools[current_uid].update({
  1118. 'type': typ,
  1119. 'tool_type': tt,
  1120. })
  1121. def on_tool_type(self, val):
  1122. if val == 'V':
  1123. self.addtool_entry_lbl.setDisabled(True)
  1124. self.addtool_entry.setDisabled(True)
  1125. self.tipdialabel.show()
  1126. self.tipdia_entry.show()
  1127. self.tipanglelabel.show()
  1128. self.tipangle_entry.show()
  1129. self.on_calculate_tooldia()
  1130. else:
  1131. self.addtool_entry_lbl.setDisabled(False)
  1132. self.addtool_entry.setDisabled(False)
  1133. self.tipdialabel.hide()
  1134. self.tipdia_entry.hide()
  1135. self.tipanglelabel.hide()
  1136. self.tipangle_entry.hide()
  1137. self.addtool_entry.set_value(self.old_tool_dia)
  1138. def on_calculate_tooldia(self):
  1139. if self.tool_type_radio.get_value() == 'V':
  1140. tip_dia = float(self.tipdia_entry.get_value())
  1141. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1142. cut_z = float(self.cutz_entry.get_value())
  1143. cut_z = -cut_z if cut_z < 0 else cut_z
  1144. # calculated tool diameter so the cut_z parameter is obeyed
  1145. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1146. # update the default_data so it is used in the iso_tools dict
  1147. self.default_data.update({
  1148. "vtipdia": tip_dia,
  1149. "vtipangle": (tip_angle * 2),
  1150. })
  1151. self.addtool_entry.set_value(tool_dia)
  1152. return tool_dia
  1153. else:
  1154. return float(self.addtool_entry.get_value())
  1155. def on_tool_add(self, dia=None, muted=None):
  1156. self.blockSignals(True)
  1157. self.units = self.app.defaults['units'].upper()
  1158. if dia:
  1159. tool_dia = dia
  1160. else:
  1161. tool_dia = self.on_calculate_tooldia()
  1162. if tool_dia is None:
  1163. self.build_ui()
  1164. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1165. return
  1166. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1167. if tool_dia == 0:
  1168. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1169. "in Float format."))
  1170. return
  1171. # construct a list of all 'tooluid' in the self.tools
  1172. tool_uid_list = []
  1173. for tooluid_key in self.iso_tools:
  1174. tool_uid_item = int(tooluid_key)
  1175. tool_uid_list.append(tool_uid_item)
  1176. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1177. if not tool_uid_list:
  1178. max_uid = 0
  1179. else:
  1180. max_uid = max(tool_uid_list)
  1181. self.tooluid = int(max_uid + 1)
  1182. tool_dias = []
  1183. for k, v in self.iso_tools.items():
  1184. for tool_v in v.keys():
  1185. if tool_v == 'tooldia':
  1186. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1187. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1188. if muted is None:
  1189. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1190. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1191. self.blockSignals(False)
  1192. return
  1193. else:
  1194. if muted is None:
  1195. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1196. self.iso_tools.update({
  1197. int(self.tooluid): {
  1198. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1199. 'offset': 'Path',
  1200. 'offset_value': 0.0,
  1201. 'type': 'Iso',
  1202. 'tool_type': self.tool_type_radio.get_value(),
  1203. 'data': deepcopy(self.default_data),
  1204. 'solid_geometry': []
  1205. }
  1206. })
  1207. self.blockSignals(False)
  1208. self.build_ui()
  1209. def on_tool_edit(self):
  1210. self.blockSignals(True)
  1211. old_tool_dia = ''
  1212. tool_dias = []
  1213. for k, v in self.iso_tools.items():
  1214. for tool_v in v.keys():
  1215. if tool_v == 'tooldia':
  1216. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1217. for row in range(self.tools_table.rowCount()):
  1218. try:
  1219. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1220. except ValueError:
  1221. # try to convert comma to decimal point. if it's still not working error message and return
  1222. try:
  1223. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1224. except ValueError:
  1225. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1226. self.blockSignals(False)
  1227. return
  1228. tooluid = int(self.tools_table.item(row, 3).text())
  1229. # identify the tool that was edited and get it's tooluid
  1230. if new_tool_dia not in tool_dias:
  1231. self.iso_tools[tooluid]['tooldia'] = new_tool_dia
  1232. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1233. self.blockSignals(False)
  1234. self.build_ui()
  1235. return
  1236. else:
  1237. # identify the old tool_dia and restore the text in tool table
  1238. for k, v in self.iso_tools.items():
  1239. if k == tooluid:
  1240. old_tool_dia = v['tooldia']
  1241. break
  1242. restore_dia_item = self.tools_table.item(row, 1)
  1243. restore_dia_item.setText(str(old_tool_dia))
  1244. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. "
  1245. "New diameter value is already in the Tool Table."))
  1246. self.blockSignals(False)
  1247. self.build_ui()
  1248. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1249. """
  1250. Will delete a tool in the tool table
  1251. :param rows_to_delete: which rows to delete; can be a list
  1252. :param all_tools: delete all tools in the tool table
  1253. :return:
  1254. """
  1255. self.blockSignals(True)
  1256. deleted_tools_list = []
  1257. if all_tools:
  1258. self.iso_tools.clear()
  1259. self.blockSignals(False)
  1260. self.build_ui()
  1261. return
  1262. if rows_to_delete:
  1263. try:
  1264. for row in rows_to_delete:
  1265. tooluid_del = int(self.tools_table.item(row, 3).text())
  1266. deleted_tools_list.append(tooluid_del)
  1267. except TypeError:
  1268. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1269. deleted_tools_list.append(tooluid_del)
  1270. for t in deleted_tools_list:
  1271. self.iso_tools.pop(t, None)
  1272. self.blockSignals(False)
  1273. self.build_ui()
  1274. return
  1275. try:
  1276. if self.tools_table.selectedItems():
  1277. for row_sel in self.tools_table.selectedItems():
  1278. row = row_sel.row()
  1279. if row < 0:
  1280. continue
  1281. tooluid_del = int(self.tools_table.item(row, 3).text())
  1282. deleted_tools_list.append(tooluid_del)
  1283. for t in deleted_tools_list:
  1284. self.iso_tools.pop(t, None)
  1285. except AttributeError:
  1286. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1287. self.blockSignals(False)
  1288. return
  1289. except Exception as e:
  1290. log.debug(str(e))
  1291. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1292. self.blockSignals(False)
  1293. self.build_ui()
  1294. def on_generate_buffer(self):
  1295. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  1296. self.obj_name = self.object_combo.currentText()
  1297. # Get source object.
  1298. try:
  1299. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1300. except Exception as e:
  1301. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1302. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1303. if self.grb_obj is None:
  1304. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1305. return
  1306. def buffer_task():
  1307. with self.app.proc_container.new('%s...' % _("Buffering")):
  1308. if isinstance(self.grb_obj.solid_geometry, list):
  1309. self.grb_obj.solid_geometry = MultiPolygon(self.grb_obj.solid_geometry)
  1310. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(0.0000001)
  1311. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(-0.0000001)
  1312. self.app.inform.emit('[success] %s.' % _("Done"))
  1313. self.grb_obj.plot_single_object.emit()
  1314. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  1315. def on_iso_button_click(self, *args):
  1316. self.obj_name = self.object_combo.currentText()
  1317. # Get source object.
  1318. try:
  1319. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1320. except Exception as e:
  1321. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1322. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1323. if self.grb_obj is None:
  1324. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1325. return
  1326. def worker_task(iso_obj, app_obj):
  1327. with self.app.proc_container.new(_("Isolating...")):
  1328. self.isolate_handler(iso_obj)
  1329. self.app.worker_task.emit({'fcn': worker_task, 'params': [self.grb_obj, self.app]})
  1330. def follow_geo(self, followed_obj, outname):
  1331. """
  1332. Creates a geometry object "following" the gerber paths.
  1333. :param followed_obj: Gerber object for which to generate the follow geometry
  1334. :type followed_obj: AppObjects.FlatCAMGerber.GerberObject
  1335. :param outname: Nme of the resulting Geometry object
  1336. :type outname: str
  1337. :return: None
  1338. """
  1339. def follow_init(follow_obj, app):
  1340. # Propagate options
  1341. follow_obj.options["cnctooldia"] = str(tooldia)
  1342. follow_obj.solid_geometry = self.grb_obj.follow_geometry
  1343. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  1344. followed_obj.ui.plot_cb.set_value(False)
  1345. follow_name = outname
  1346. for tool in self.iso_tools:
  1347. tooldia = self.iso_tools[tool]['tooldia']
  1348. new_name = "%s_%.*f" % (follow_name, self.decimals, tooldia)
  1349. follow_state = self.iso_tools[tool]['data']['tools_iso_follow']
  1350. if follow_state:
  1351. ret = self.app.app_obj.new_object("geometry", new_name, follow_init)
  1352. if ret == 'fail':
  1353. self.app.inform.emit("[ERROR_NOTCL] %s: %.*f" % (
  1354. _("Failed to create Follow Geometry with tool diameter"), self.decimals, tooldia))
  1355. else:
  1356. self.app.inform.emit("[success] %s: %.*f" % (
  1357. _("Follow Geometry was created with tool diameter"), self.decimals, tooldia))
  1358. def isolate_handler(self, isolated_obj):
  1359. """
  1360. Creates a geometry object with paths around the gerber features.
  1361. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1362. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1363. :return: None
  1364. """
  1365. selection = self.select_combo.get_value()
  1366. if selection == _("All"):
  1367. full_geo = isolated_obj.solid_geometry
  1368. self.isolate(isolated_obj=isolated_obj, geometry=full_geo)
  1369. elif selection == _("Area Selection"):
  1370. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1371. if self.app.is_legacy is False:
  1372. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1373. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1374. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1375. else:
  1376. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1377. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1378. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1379. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1380. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1381. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1382. elif selection == _("Polygon Selection"):
  1383. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1384. if self.app.ui.grid_snap_btn.isChecked():
  1385. self.grid_status_memory = True
  1386. self.app.ui.grid_snap_btn.trigger()
  1387. else:
  1388. self.grid_status_memory = False
  1389. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_poly_mouse_click_release)
  1390. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1391. if self.app.is_legacy is False:
  1392. self.app.plotcanvas.graph_event_disconnect('mouse_release',
  1393. self.app.on_mouse_click_release_over_plot)
  1394. else:
  1395. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1396. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  1397. elif selection == _("Reference Object"):
  1398. ref_obj = self.app.collection.get_by_name(self.reference_combo.get_value())
  1399. ref_geo = cascaded_union(ref_obj.solid_geometry)
  1400. use_geo = cascaded_union(isolated_obj.solid_geometry).difference(ref_geo)
  1401. self.isolate(isolated_obj=isolated_obj, geometry=use_geo)
  1402. def isolate(self, isolated_obj, geometry=None, limited_area=None, plot=True):
  1403. """
  1404. Creates an isolation routing geometry object in the project.
  1405. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1406. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1407. :param geometry: specific geometry to isolate
  1408. :type geometry: List of Shapely polygon
  1409. :param limited_area: if not None clear only this area
  1410. :type limited_area: Shapely Polygon or a list of them
  1411. :param plot: if to plot the resulting geometry object
  1412. :type plot: bool
  1413. :return: None
  1414. """
  1415. iso_name = isolated_obj.options["name"]
  1416. combine = self.combine_passes_cb.get_value()
  1417. tools_storage = self.iso_tools
  1418. if combine:
  1419. total_solid_geometry = []
  1420. for tool in tools_storage:
  1421. tool_dia = tools_storage[tool]['tooldia']
  1422. tool_type = tools_storage[tool]['tool_type']
  1423. tool_data = tools_storage[tool]['data']
  1424. to_follow = tool_data['tools_iso_follow']
  1425. work_geo = geometry
  1426. if work_geo is None:
  1427. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1428. iso_t = {
  1429. 'ext': 0,
  1430. 'int': 1,
  1431. 'full': 2
  1432. }[tool_data['tools_iso_isotype']]
  1433. passes = tool_data['tools_iso_passes']
  1434. overlap = tool_data['tools_iso_overlap']
  1435. overlap /= 100.0
  1436. milling_type = tool_data['tools_iso_milling_type']
  1437. iso_except = tool_data['tools_iso_isoexcept']
  1438. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1439. iso_name = outname + "_iso"
  1440. if iso_t == 0:
  1441. iso_name = outname + "_ext_iso"
  1442. elif iso_t == 1:
  1443. iso_name = outname + "_int_iso"
  1444. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1445. if tool_type.lower() == 'v':
  1446. new_cutz = self.ui.cutz_spinner.get_value()
  1447. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1448. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1449. tool_type = 'V'
  1450. tool_data.update({
  1451. "name": iso_name,
  1452. "cutz": new_cutz,
  1453. "vtipdia": new_vtipdia,
  1454. "vtipangle": new_vtipangle,
  1455. })
  1456. else:
  1457. tool_data.update({
  1458. "name": iso_name,
  1459. })
  1460. tool_type = 'C1'
  1461. solid_geo = []
  1462. for nr_pass in range(passes):
  1463. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1464. # if milling type is climb then the move is counter-clockwise around features
  1465. mill_dir = 1 if milling_type == 'cl' else 0
  1466. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1467. follow=to_follow, nr_passes=nr_pass)
  1468. if iso_geo == 'fail':
  1469. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1470. continue
  1471. try:
  1472. for geo in iso_geo:
  1473. solid_geo.append(geo)
  1474. except TypeError:
  1475. solid_geo.append(iso_geo)
  1476. # ############################################################
  1477. # ########## AREA SUBTRACTION ################################
  1478. # ############################################################
  1479. if iso_except:
  1480. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1481. solid_geo = self.area_subtraction(solid_geo)
  1482. if limited_area:
  1483. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1484. solid_geo = self.area_intersection(solid_geo, intersection_geo=limited_area)
  1485. tools_storage.update({
  1486. tool: {
  1487. 'tooldia': float(tool_dia),
  1488. 'offset': 'Path',
  1489. 'offset_value': 0.0,
  1490. 'type': _('Rough'),
  1491. 'tool_type': tool_type,
  1492. 'data': tool_data,
  1493. 'solid_geometry': deepcopy(solid_geo)
  1494. }
  1495. })
  1496. total_solid_geometry += solid_geo
  1497. def iso_init(geo_obj, app_obj):
  1498. geo_obj.options["cnctooldia"] = str(tool_dia)
  1499. geo_obj.tools = dict(tools_storage)
  1500. geo_obj.solid_geometry = total_solid_geometry
  1501. # even if combine is checked, one pass is still single-geo
  1502. if len(self.iso_tools) > 1:
  1503. geo_obj.multigeo = True
  1504. else:
  1505. passes_no = float(self.iso_tools[0]['data']['tools_iso_passes'])
  1506. geo_obj.multigeo = True if passes_no > 1 else False
  1507. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1508. # or just looking in the lists (they are one level depth) and if any is not empty
  1509. # proceed with object creation, if there are empty and the number of them is the length
  1510. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1511. empty_cnt = 0
  1512. if not isinstance(geo_obj.solid_geometry, list) and \
  1513. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1514. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1515. for g in geo_obj.solid_geometry:
  1516. if g:
  1517. break
  1518. else:
  1519. empty_cnt += 1
  1520. if empty_cnt == len(geo_obj.solid_geometry):
  1521. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1522. return 'fail'
  1523. else:
  1524. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1525. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1526. else:
  1527. for tool in tools_storage:
  1528. tool_data = tools_storage[tool]['data']
  1529. to_follow = tool_data['tools_iso_follow']
  1530. work_geo = geometry
  1531. if work_geo is None:
  1532. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1533. iso_t = {
  1534. 'ext': 0,
  1535. 'int': 1,
  1536. 'full': 2
  1537. }[tool_data['tools_iso_isotype']]
  1538. passes = tool_data['tools_iso_passes']
  1539. overlap = tool_data['tools_iso_overlap']
  1540. overlap /= 100.0
  1541. milling_type = tool_data['tools_iso_milling_type']
  1542. iso_except = tool_data['tools_iso_isoexcept']
  1543. for i in range(passes):
  1544. tool_dia = tools_storage[tool]['tooldia']
  1545. tool_type = tools_storage[tool]['tool_type']
  1546. iso_offset = tool_dia * ((2 * i + 1) / 2.0000001) - (i * overlap * tool_dia)
  1547. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1548. if passes > 1:
  1549. iso_name = outname + "_iso" + str(i + 1)
  1550. if iso_t == 0:
  1551. iso_name = outname + "_ext_iso" + str(i + 1)
  1552. elif iso_t == 1:
  1553. iso_name = outname + "_int_iso" + str(i + 1)
  1554. else:
  1555. iso_name = outname + "_iso"
  1556. if iso_t == 0:
  1557. iso_name = outname + "_ext_iso"
  1558. elif iso_t == 1:
  1559. iso_name = outname + "_int_iso"
  1560. # if milling type is climb then the move is counter-clockwise around features
  1561. mill_dir = 1 if milling_type == 'cl' else 0
  1562. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1563. follow=to_follow, nr_passes=i)
  1564. if iso_geo == 'fail':
  1565. self.app.inform.emit(
  1566. '[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1567. continue
  1568. # ############################################################
  1569. # ########## AREA SUBTRACTION ################################
  1570. # ############################################################
  1571. if iso_except:
  1572. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1573. iso_geo = self.area_subtraction(iso_geo)
  1574. if limited_area:
  1575. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1576. iso_geo = self.area_intersection(iso_geo, intersection_geo=limited_area)
  1577. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in
  1578. # Gerber UI
  1579. if tool_type.lower() == 'v':
  1580. new_cutz = self.cutz_entry.get_value()
  1581. new_vtipdia = self.tipdia_entry.get_value()
  1582. new_vtipangle = self.tipangle_entry.get_value()
  1583. tool_type = 'V'
  1584. tool_data.update({
  1585. "name": iso_name,
  1586. "cutz": new_cutz,
  1587. "vtipdia": new_vtipdia,
  1588. "vtipangle": new_vtipangle,
  1589. })
  1590. else:
  1591. tool_data.update({
  1592. "name": iso_name,
  1593. })
  1594. tool_type = 'C1'
  1595. def iso_init(geo_obj, fc_obj):
  1596. # Propagate options
  1597. geo_obj.options["cnctooldia"] = str(tool_dia)
  1598. geo_obj.solid_geometry = deepcopy(iso_geo)
  1599. # ############################################################
  1600. # ########## AREA SUBTRACTION ################################
  1601. # ############################################################
  1602. if self.except_cb.get_value():
  1603. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1604. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1605. geo_obj.tools = {}
  1606. geo_obj.tools['1'] = {}
  1607. geo_obj.tools.update({
  1608. '1': {
  1609. 'tooldia': float(tool_dia),
  1610. 'offset': 'Path',
  1611. 'offset_value': 0.0,
  1612. 'type': _('Rough'),
  1613. 'tool_type': tool_type,
  1614. 'data': tool_data,
  1615. 'solid_geometry': geo_obj.solid_geometry
  1616. }
  1617. })
  1618. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1619. # or just looking in the lists (they are one level depth) and if any is not empty
  1620. # proceed with object creation, if there are empty and the number of them is the length
  1621. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1622. empty_cnt = 0
  1623. if not isinstance(geo_obj.solid_geometry, list):
  1624. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1625. for g in geo_obj.solid_geometry:
  1626. if g:
  1627. break
  1628. else:
  1629. empty_cnt += 1
  1630. if empty_cnt == len(geo_obj.solid_geometry):
  1631. fc_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1632. _("Empty Geometry in"), geo_obj.options["name"]))
  1633. return 'fail'
  1634. else:
  1635. fc_obj.inform.emit('[success] %s: %s' %
  1636. (_("Isolation geometry created"), geo_obj.options["name"]))
  1637. geo_obj.multigeo = False
  1638. # TODO: Do something if this is None. Offer changing name?
  1639. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1640. def area_subtraction(self, geo, subtractor_geo):
  1641. """
  1642. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1643. :param geo: target geometry from which to subtract
  1644. :param subtractor_geo: geometry that acts as subtractor
  1645. :return:
  1646. """
  1647. new_geometry = []
  1648. target_geo = geo
  1649. if subtractor_geo:
  1650. sub_union = cascaded_union(subtractor_geo)
  1651. else:
  1652. name = self.exc_obj_combo.currentText()
  1653. subtractor_obj = self.app.collection.get_by_name(name)
  1654. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1655. try:
  1656. for geo_elem in target_geo:
  1657. if isinstance(geo_elem, Polygon):
  1658. for ring in self.poly2rings(geo_elem):
  1659. new_geo = ring.difference(sub_union)
  1660. if new_geo and not new_geo.is_empty:
  1661. new_geometry.append(new_geo)
  1662. elif isinstance(geo_elem, MultiPolygon):
  1663. for poly in geo_elem:
  1664. for ring in self.poly2rings(poly):
  1665. new_geo = ring.difference(sub_union)
  1666. if new_geo and not new_geo.is_empty:
  1667. new_geometry.append(new_geo)
  1668. elif isinstance(geo_elem, LineString):
  1669. new_geo = geo_elem.difference(sub_union)
  1670. if new_geo:
  1671. if not new_geo.is_empty:
  1672. new_geometry.append(new_geo)
  1673. elif isinstance(geo_elem, MultiLineString):
  1674. for line_elem in geo_elem:
  1675. new_geo = line_elem.difference(sub_union)
  1676. if new_geo and not new_geo.is_empty:
  1677. new_geometry.append(new_geo)
  1678. except TypeError:
  1679. if isinstance(target_geo, Polygon):
  1680. for ring in self.poly2rings(target_geo):
  1681. new_geo = ring.difference(sub_union)
  1682. if new_geo:
  1683. if not new_geo.is_empty:
  1684. new_geometry.append(new_geo)
  1685. elif isinstance(target_geo, LineString):
  1686. new_geo = target_geo.difference(sub_union)
  1687. if new_geo and not new_geo.is_empty:
  1688. new_geometry.append(new_geo)
  1689. elif isinstance(target_geo, MultiLineString):
  1690. for line_elem in target_geo:
  1691. new_geo = line_elem.difference(sub_union)
  1692. if new_geo and not new_geo.is_empty:
  1693. new_geometry.append(new_geo)
  1694. return new_geometry
  1695. def area_intersection(self, geo, intersection_geo=None):
  1696. """
  1697. Return the intersection geometry between geo and intersection_geo
  1698. :param geo: target geometry
  1699. :param intersection_geo: second geometry
  1700. :return:
  1701. """
  1702. new_geometry = []
  1703. target_geo = geo
  1704. intersect_union = cascaded_union(intersection_geo)
  1705. try:
  1706. for geo_elem in target_geo:
  1707. if isinstance(geo_elem, Polygon):
  1708. for ring in self.poly2rings(geo_elem):
  1709. new_geo = ring.intersection(intersect_union)
  1710. if new_geo and not new_geo.is_empty:
  1711. new_geometry.append(new_geo)
  1712. elif isinstance(geo_elem, MultiPolygon):
  1713. for poly in geo_elem:
  1714. for ring in self.poly2rings(poly):
  1715. new_geo = ring.intersection(intersect_union)
  1716. if new_geo and not new_geo.is_empty:
  1717. new_geometry.append(new_geo)
  1718. elif isinstance(geo_elem, LineString):
  1719. new_geo = geo_elem.intersection(intersect_union)
  1720. if new_geo:
  1721. if not new_geo.is_empty:
  1722. new_geometry.append(new_geo)
  1723. elif isinstance(geo_elem, MultiLineString):
  1724. for line_elem in geo_elem:
  1725. new_geo = line_elem.intersection(intersect_union)
  1726. if new_geo and not new_geo.is_empty:
  1727. new_geometry.append(new_geo)
  1728. except TypeError:
  1729. if isinstance(target_geo, Polygon):
  1730. for ring in self.poly2rings(target_geo):
  1731. new_geo = ring.intersection(intersect_union)
  1732. if new_geo:
  1733. if not new_geo.is_empty:
  1734. new_geometry.append(new_geo)
  1735. elif isinstance(target_geo, LineString):
  1736. new_geo = target_geo.intersection(intersect_union)
  1737. if new_geo and not new_geo.is_empty:
  1738. new_geometry.append(new_geo)
  1739. elif isinstance(target_geo, MultiLineString):
  1740. for line_elem in target_geo:
  1741. new_geo = line_elem.intersection(intersect_union)
  1742. if new_geo and not new_geo.is_empty:
  1743. new_geometry.append(new_geo)
  1744. return new_geometry
  1745. def on_poly_mouse_click_release(self, event):
  1746. if self.app.is_legacy is False:
  1747. event_pos = event.pos
  1748. right_button = 2
  1749. self.app.event_is_dragging = self.app.event_is_dragging
  1750. else:
  1751. event_pos = (event.xdata, event.ydata)
  1752. right_button = 3
  1753. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1754. try:
  1755. x = float(event_pos[0])
  1756. y = float(event_pos[1])
  1757. except TypeError:
  1758. return
  1759. event_pos = (x, y)
  1760. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1761. if self.app.grid_status():
  1762. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1763. else:
  1764. curr_pos = (curr_pos[0], curr_pos[1])
  1765. if event.button == 1:
  1766. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.grb_obj.solid_geometry)
  1767. if self.app.selection_type is not None:
  1768. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  1769. self.app.selection_type = None
  1770. elif clicked_poly:
  1771. if clicked_poly not in self.poly_dict.values():
  1772. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  1773. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1774. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1775. visible=True)
  1776. self.poly_dict[shape_id] = clicked_poly
  1777. self.app.inform.emit(
  1778. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  1779. _("Click to add next polygon or right click to start isolation."))
  1780. )
  1781. else:
  1782. try:
  1783. for k, v in list(self.poly_dict.items()):
  1784. if v == clicked_poly:
  1785. self.app.tool_shapes.remove(k)
  1786. self.poly_dict.pop(k)
  1787. break
  1788. except TypeError:
  1789. return
  1790. self.app.inform.emit(
  1791. '%s. %s' % (_("Removed polygon"),
  1792. _("Click to add/remove next polygon or right click to start isolation."))
  1793. )
  1794. self.app.tool_shapes.redraw()
  1795. else:
  1796. self.app.inform.emit(_("No polygon detected under click position."))
  1797. elif event.button == right_button and self.app.event_is_dragging is False:
  1798. # restore the Grid snapping if it was active before
  1799. if self.grid_status_memory is True:
  1800. self.app.ui.grid_snap_btn.trigger()
  1801. if self.app.is_legacy is False:
  1802. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1803. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_pres)
  1804. else:
  1805. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1806. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1807. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1808. self.app.on_mouse_click_release_over_plot)
  1809. self.app.tool_shapes.clear(update=True)
  1810. if self.poly_dict:
  1811. poly_list = deepcopy(list(self.poly_dict.values()))
  1812. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list)
  1813. self.poly_dict.clear()
  1814. else:
  1815. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1816. def selection_area_handler(self, start_pos, end_pos, sel_type):
  1817. """
  1818. :param start_pos: mouse position when the selection LMB click was done
  1819. :param end_pos: mouse position when the left mouse button is released
  1820. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1821. :return:
  1822. """
  1823. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1824. # delete previous selection shape
  1825. self.app.delete_selection_shape()
  1826. added_poly_count = 0
  1827. try:
  1828. for geo in self.solid_geometry:
  1829. if geo not in self.poly_dict.values():
  1830. if sel_type is True:
  1831. if geo.within(poly_selection):
  1832. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1833. shape=geo,
  1834. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1835. face_color=self.app.defaults[
  1836. 'global_sel_draw_color'] + 'AF',
  1837. visible=True)
  1838. self.poly_dict[shape_id] = geo
  1839. added_poly_count += 1
  1840. else:
  1841. if poly_selection.intersects(geo):
  1842. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1843. shape=geo,
  1844. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1845. face_color=self.app.defaults[
  1846. 'global_sel_draw_color'] + 'AF',
  1847. visible=True)
  1848. self.poly_dict[shape_id] = geo
  1849. added_poly_count += 1
  1850. except TypeError:
  1851. if self.solid_geometry not in self.poly_dict.values():
  1852. if sel_type is True:
  1853. if self.solid_geometry.within(poly_selection):
  1854. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1855. shape=self.solid_geometry,
  1856. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1857. face_color=self.app.defaults[
  1858. 'global_sel_draw_color'] + 'AF',
  1859. visible=True)
  1860. self.poly_dict[shape_id] = self.solid_geometry
  1861. added_poly_count += 1
  1862. else:
  1863. if poly_selection.intersects(self.solid_geometry):
  1864. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1865. shape=self.solid_geometry,
  1866. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1867. face_color=self.app.defaults[
  1868. 'global_sel_draw_color'] + 'AF',
  1869. visible=True)
  1870. self.poly_dict[shape_id] = self.solid_geometry
  1871. added_poly_count += 1
  1872. if added_poly_count > 0:
  1873. self.app.tool_shapes.redraw()
  1874. self.app.inform.emit(
  1875. '%s: %d. %s' % (_("Added polygon"),
  1876. int(added_poly_count),
  1877. _("Click to add next polygon or right click to start isolation."))
  1878. )
  1879. else:
  1880. self.app.inform.emit(_("No polygon in selection."))
  1881. # To be called after clicking on the plot.
  1882. def on_mouse_release(self, event):
  1883. if self.app.is_legacy is False:
  1884. event_pos = event.pos
  1885. # event_is_dragging = event.is_dragging
  1886. right_button = 2
  1887. else:
  1888. event_pos = (event.xdata, event.ydata)
  1889. # event_is_dragging = self.app.plotcanvas.is_dragging
  1890. right_button = 3
  1891. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1892. if self.app.grid_status():
  1893. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1894. else:
  1895. curr_pos = (event_pos[0], event_pos[1])
  1896. x1, y1 = curr_pos[0], curr_pos[1]
  1897. shape_type = self.area_shape_radio.get_value()
  1898. # do clear area only for left mouse clicks
  1899. if event.button == 1:
  1900. if shape_type == "square":
  1901. if self.first_click is False:
  1902. self.first_click = True
  1903. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1904. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1905. if self.app.grid_status():
  1906. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1907. else:
  1908. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1909. self.app.delete_selection_shape()
  1910. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1911. pt1 = (x0, y0)
  1912. pt2 = (x1, y0)
  1913. pt3 = (x1, y1)
  1914. pt4 = (x0, y1)
  1915. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1916. self.sel_rect.append(new_rectangle)
  1917. # add a temporary shape on canvas
  1918. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1919. self.first_click = False
  1920. return
  1921. else:
  1922. self.points.append((x1, y1))
  1923. if len(self.points) > 1:
  1924. self.poly_drawn = True
  1925. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1926. return ""
  1927. elif event.button == right_button and self.mouse_is_dragging is False:
  1928. shape_type = self.area_shape_radio.get_value()
  1929. if shape_type == "square":
  1930. self.first_click = False
  1931. else:
  1932. # if we finish to add a polygon
  1933. if self.poly_drawn is True:
  1934. try:
  1935. # try to add the point where we last clicked if it is not already in the self.points
  1936. last_pt = (x1, y1)
  1937. if last_pt != self.points[-1]:
  1938. self.points.append(last_pt)
  1939. except IndexError:
  1940. pass
  1941. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1942. if len(self.points) > 2:
  1943. self.delete_moving_selection_shape()
  1944. pol = Polygon(self.points)
  1945. # do not add invalid polygons even if they are drawn by utility geometry
  1946. if pol.is_valid:
  1947. self.sel_rect.append(pol)
  1948. self.draw_selection_shape_polygon(points=self.points)
  1949. self.app.inform.emit(
  1950. _("Zone added. Click to start adding next zone or right click to finish."))
  1951. self.points = []
  1952. self.poly_drawn = False
  1953. return
  1954. self.delete_tool_selection_shape()
  1955. if self.app.is_legacy is False:
  1956. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1957. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1958. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1959. else:
  1960. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1961. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1962. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1963. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1964. self.app.on_mouse_click_over_plot)
  1965. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1966. self.app.on_mouse_move_over_plot)
  1967. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1968. self.app.on_mouse_click_release_over_plot)
  1969. if len(self.sel_rect) == 0:
  1970. return
  1971. self.sel_rect = cascaded_union(self.sel_rect)
  1972. self.isolate(isolated_obj=self.grb_obj, limited_area=self.sel_rect, plot=True)
  1973. self.sel_rect = []
  1974. # called on mouse move
  1975. def on_mouse_move(self, event):
  1976. shape_type = self.area_shape_radio.get_value()
  1977. if self.app.is_legacy is False:
  1978. event_pos = event.pos
  1979. event_is_dragging = event.is_dragging
  1980. # right_button = 2
  1981. else:
  1982. event_pos = (event.xdata, event.ydata)
  1983. event_is_dragging = self.app.plotcanvas.is_dragging
  1984. # right_button = 3
  1985. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1986. # detect mouse dragging motion
  1987. if event_is_dragging is True:
  1988. self.mouse_is_dragging = True
  1989. else:
  1990. self.mouse_is_dragging = False
  1991. # update the cursor position
  1992. if self.app.grid_status():
  1993. # Update cursor
  1994. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1995. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1996. symbol='++', edge_color=self.app.cursor_color_3D,
  1997. edge_width=self.app.defaults["global_cursor_width"],
  1998. size=self.app.defaults["global_cursor_size"])
  1999. if self.cursor_pos is None:
  2000. self.cursor_pos = (0, 0)
  2001. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  2002. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  2003. # # update the positions on status bar
  2004. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2005. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  2006. # self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2007. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  2008. units = self.app.defaults["units"].lower()
  2009. self.app.plotcanvas.text_hud.text = \
  2010. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  2011. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  2012. # draw the utility geometry
  2013. if shape_type == "square":
  2014. if self.first_click:
  2015. self.app.delete_selection_shape()
  2016. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  2017. coords=(curr_pos[0], curr_pos[1]))
  2018. else:
  2019. self.delete_moving_selection_shape()
  2020. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  2021. def on_key_press(self, event):
  2022. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  2023. # matplotlib_key_flag = False
  2024. # events out of the self.app.collection view (it's about Project Tab) are of type int
  2025. if type(event) is int:
  2026. key = event
  2027. # events from the GUI are of type QKeyEvent
  2028. elif type(event) == QtGui.QKeyEvent:
  2029. key = event.key()
  2030. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  2031. # matplotlib_key_flag = True
  2032. key = event.key
  2033. key = QtGui.QKeySequence(key)
  2034. # check for modifiers
  2035. key_string = key.toString().lower()
  2036. if '+' in key_string:
  2037. mod, __, key_text = key_string.rpartition('+')
  2038. if mod.lower() == 'ctrl':
  2039. # modifiers = QtCore.Qt.ControlModifier
  2040. pass
  2041. elif mod.lower() == 'alt':
  2042. # modifiers = QtCore.Qt.AltModifier
  2043. pass
  2044. elif mod.lower() == 'shift':
  2045. # modifiers = QtCore.Qt.ShiftModifier
  2046. pass
  2047. else:
  2048. # modifiers = QtCore.Qt.NoModifier
  2049. pass
  2050. key = QtGui.QKeySequence(key_text)
  2051. # events from Vispy are of type KeyEvent
  2052. else:
  2053. key = event.key
  2054. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  2055. if self.app.is_legacy is False:
  2056. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2057. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2058. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2059. else:
  2060. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2061. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2062. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2063. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2064. self.app.on_mouse_click_over_plot)
  2065. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2066. self.app.on_mouse_move_over_plot)
  2067. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2068. self.app.on_mouse_click_release_over_plot)
  2069. self.points = []
  2070. self.poly_drawn = False
  2071. self.delete_moving_selection_shape()
  2072. self.delete_tool_selection_shape()
  2073. @staticmethod
  2074. def poly2rings(poly):
  2075. return [poly.exterior] + [interior for interior in poly.interiors]
  2076. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  2077. """
  2078. Isolation_geometry produces an envelope that is going on the left of the geometry
  2079. (the copper features). To leave the least amount of burrs on the features
  2080. the tool needs to travel on the right side of the features (this is called conventional milling)
  2081. the first pass is the one cutting all of the features, so it needs to be reversed
  2082. the other passes overlap preceding ones and cut the left over copper. It is better for them
  2083. to cut on the right side of the left over copper i.e on the left side of the features.
  2084. :param offset: Offset distance to be passed to the obj.isolation_geometry() method
  2085. :type offset: float
  2086. :param invert: If to invert the direction of geometry (CW to CCW or reverse)
  2087. :type invert: int
  2088. :param geometry: Shapely Geometry for which t ogenerate envelope
  2089. :type geometry:
  2090. :param env_iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  2091. :type env_iso_type: int
  2092. :param follow: If the kind of isolation is a "follow" one
  2093. :type follow: bool
  2094. :param nr_passes: Number of passes
  2095. :type nr_passes: int
  2096. :return: The buffered geometry
  2097. :rtype: MultiPolygon or Polygon
  2098. """
  2099. if follow:
  2100. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, follow=follow)
  2101. else:
  2102. try:
  2103. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type,
  2104. passes=nr_passes)
  2105. except Exception as e:
  2106. log.debug('ToolIsolation.isolate().generate_envelope() --> %s' % str(e))
  2107. return 'fail'
  2108. if invert:
  2109. try:
  2110. pl = []
  2111. for p in geom:
  2112. if p is not None:
  2113. if isinstance(p, Polygon):
  2114. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2115. elif isinstance(p, LinearRing):
  2116. pl.append(Polygon(p.coords[::-1]))
  2117. geom = MultiPolygon(pl)
  2118. except TypeError:
  2119. if isinstance(geom, Polygon) and geom is not None:
  2120. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2121. elif isinstance(geom, LinearRing) and geom is not None:
  2122. geom = Polygon(geom.coords[::-1])
  2123. else:
  2124. log.debug("ToolIsolation.generate_envelope() Error --> Unexpected Geometry %s" %
  2125. type(geom))
  2126. except Exception as e:
  2127. log.debug("ToolIsolation.generate_envelope() Error --> %s" % str(e))
  2128. return 'fail'
  2129. return geom
  2130. def on_iso_tool_add_from_db_executed(self, tool):
  2131. """
  2132. Here add the tool from DB in the selected geometry object
  2133. :return:
  2134. """
  2135. tool_from_db = deepcopy(tool)
  2136. res = self.on_tool_from_db_inserted(tool=tool_from_db)
  2137. for idx in range(self.app.ui.plot_tab_area.count()):
  2138. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2139. wdg = self.app.ui.plot_tab_area.widget(idx)
  2140. wdg.deleteLater()
  2141. self.app.ui.plot_tab_area.removeTab(idx)
  2142. if res == 'fail':
  2143. return
  2144. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2145. # select last tool added
  2146. toolid = res
  2147. for row in range(self.tools_table.rowCount()):
  2148. if int(self.tools_table.item(row, 3).text()) == toolid:
  2149. self.tools_table.selectRow(row)
  2150. self.on_row_selection_change()
  2151. def on_tool_from_db_inserted(self, tool):
  2152. """
  2153. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2154. :param tool: a dict with the tool data
  2155. :return: None
  2156. """
  2157. self.ui_disconnect()
  2158. self.units = self.app.defaults['units'].upper()
  2159. tooldia = float(tool['tooldia'])
  2160. # construct a list of all 'tooluid' in the self.tools
  2161. tool_uid_list = []
  2162. for tooluid_key in self.iso_tools:
  2163. tool_uid_item = int(tooluid_key)
  2164. tool_uid_list.append(tool_uid_item)
  2165. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2166. if not tool_uid_list:
  2167. max_uid = 0
  2168. else:
  2169. max_uid = max(tool_uid_list)
  2170. tooluid = max_uid + 1
  2171. tooldia = float('%.*f' % (self.decimals, tooldia))
  2172. tool_dias = []
  2173. for k, v in self.iso_tools.items():
  2174. for tool_v in v.keys():
  2175. if tool_v == 'tooldia':
  2176. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2177. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2178. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2179. self.ui_connect()
  2180. return 'fail'
  2181. self.iso_tools.update({
  2182. tooluid: {
  2183. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2184. 'offset': tool['offset'],
  2185. 'offset_value': tool['offset_value'],
  2186. 'type': tool['type'],
  2187. 'tool_type': tool['tool_type'],
  2188. 'data': deepcopy(tool['data']),
  2189. 'solid_geometry': []
  2190. }
  2191. })
  2192. self.iso_tools[tooluid]['data']['name'] = '_ncc'
  2193. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2194. self.ui_connect()
  2195. self.build_ui()
  2196. # if self.tools_table.rowCount() != 0:
  2197. # self.param_frame.setDisabled(False)
  2198. def on_tool_add_from_db_clicked(self):
  2199. """
  2200. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2201. and display the Tools Database tab in the form needed for the Tool adding
  2202. :return: None
  2203. """
  2204. # if the Tools Database is already opened focus on it
  2205. for idx in range(self.app.ui.plot_tab_area.count()):
  2206. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2207. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2208. break
  2209. self.app.on_tools_database(source='iso')
  2210. self.app.tools_db_tab.ok_to_add = True
  2211. self.app.tools_db_tab.buttons_frame.hide()
  2212. self.app.tools_db_tab.add_tool_from_db.show()
  2213. self.app.tools_db_tab.cancel_tool_from_db.show()
  2214. def reset_fields(self):
  2215. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2216. def reset_usage(self):
  2217. self.obj_name = ""
  2218. self.grb_obj = None
  2219. self.bound_obj = None
  2220. self.first_click = False
  2221. self.cursor_pos = None
  2222. self.mouse_is_dragging = False
  2223. prog_plot = True if self.app.defaults["tools_iso_plotting"] == 'progressive' else False
  2224. if prog_plot:
  2225. self.temp_shapes.clear(update=True)
  2226. self.sel_rect = []