ToolIsolation.py 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  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.first_click = False
  532. self.cursor_pos = None
  533. self.mouse_is_dragging = False
  534. # store here the points for the "Polygon" area selection shape
  535. self.points = []
  536. # set this as True when in middle of drawing a "Polygon" area selection shape
  537. # it is made False by first click to signify that the shape is complete
  538. self.poly_drawn = False
  539. self.mm = None
  540. self.mr = None
  541. self.kp = None
  542. # store geometry from Polygon selection
  543. self.poly_dict = {}
  544. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  545. # store here the state of the combine_cb GUI element
  546. # used when the rest machining is toggled
  547. self.old_combine_state = None
  548. # store here solid_geometry when there are tool with isolation job
  549. self.solid_geometry = []
  550. self.tool_type_item_options = []
  551. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  552. self.tooldia = None
  553. # multiprocessing
  554. self.pool = self.app.pool
  555. self.results = []
  556. self.form_fields = {
  557. "tools_iso_passes": self.passes_entry,
  558. "tools_iso_overlap": self.iso_overlap_entry,
  559. "tools_iso_milling_type": self.milling_type_radio,
  560. "tools_iso_combine": self.combine_passes_cb,
  561. "tools_iso_follow": self.follow_cb,
  562. "tools_iso_isotype": self.iso_type_radio
  563. }
  564. self.name2option = {
  565. "i_passes": "tools_iso_passes",
  566. "i_overlap": "tools_iso_overlap",
  567. "i_milling_type": "tools_iso_milling_type",
  568. "i_combine": "tools_iso_combine",
  569. "i_follow": "tools_iso_follow",
  570. "i_iso_type": "tools_iso_isotype"
  571. }
  572. self.old_tool_dia = None
  573. # #############################################################################
  574. # ############################ SIGNALS ########################################
  575. # #############################################################################
  576. self.addtool_btn.clicked.connect(self.on_tool_add)
  577. self.addtool_entry.returnPressed.connect(self.on_tooldia_updated)
  578. self.deltool_btn.clicked.connect(self.on_tool_delete)
  579. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  580. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  581. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  582. self.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  583. self.select_combo.currentIndexChanged.connect(self.on_toggle_reference)
  584. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  585. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  586. self.type_excobj_radio.activated_custom.connect(self.on_type_excobj_index_changed)
  587. self.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  588. self.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  589. self.generate_iso_button.clicked.connect(self.on_iso_button_click)
  590. self.reset_button.clicked.connect(self.set_tool_ui)
  591. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  592. self.app.cleanup.connect(self.reset_usage)
  593. def on_type_excobj_index_changed(self, val):
  594. obj_type = 0 if val == 'gerber' else 2
  595. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  596. self.exc_obj_combo.setCurrentIndex(0)
  597. self.exc_obj_combo.obj_type = {
  598. "gerber": "Gerber", "geometry": "Geometry"
  599. }[self.type_excobj_radio.get_value()]
  600. def on_row_selection_change(self):
  601. self.blockSignals(True)
  602. sel_rows = [it.row() for it in self.tools_table.selectedItems()]
  603. # sel_rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  604. if not sel_rows:
  605. sel_rows = [0]
  606. for current_row in sel_rows:
  607. # populate the form with the data from the tool associated with the row parameter
  608. try:
  609. item = self.tools_table.item(current_row, 3)
  610. if item is not None:
  611. tooluid = int(item.text())
  612. else:
  613. return
  614. except Exception as e:
  615. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  616. return
  617. # update the QLabel that shows for which Tool we have the parameters in the UI form
  618. if len(sel_rows) == 1:
  619. cr = current_row + 1
  620. self.tool_data_label.setText(
  621. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  622. )
  623. try:
  624. # set the form with data from the newly selected tool
  625. for tooluid_key, tooluid_value in list(self.iso_tools.items()):
  626. if int(tooluid_key) == tooluid:
  627. for key, value in tooluid_value.items():
  628. if key == 'data':
  629. form_value_storage = tooluid_value[key]
  630. self.storage_to_form(form_value_storage)
  631. except Exception as e:
  632. log.debug("ToolIsolation ---> update_ui() " + str(e))
  633. else:
  634. self.tool_data_label.setText(
  635. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  636. )
  637. self.blockSignals(False)
  638. def storage_to_form(self, dict_storage):
  639. for form_key in self.form_fields:
  640. for storage_key in dict_storage:
  641. if form_key == storage_key:
  642. try:
  643. self.form_fields[form_key].set_value(dict_storage[form_key])
  644. except Exception as e:
  645. log.debug("ToolIsolation.storage_to_form() --> %s" % str(e))
  646. pass
  647. def form_to_storage(self):
  648. if self.tools_table.rowCount() == 0:
  649. # there is no tool in tool table so we can't save the GUI elements values to storage
  650. return
  651. self.blockSignals(True)
  652. widget_changed = self.sender()
  653. wdg_objname = widget_changed.objectName()
  654. option_changed = self.name2option[wdg_objname]
  655. # row = self.tools_table.currentRow()
  656. rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  657. for row in rows:
  658. if row < 0:
  659. row = 0
  660. tooluid_item = int(self.tools_table.item(row, 3).text())
  661. for tooluid_key, tooluid_val in self.iso_tools.items():
  662. if int(tooluid_key) == tooluid_item:
  663. new_option_value = self.form_fields[option_changed].get_value()
  664. if option_changed in tooluid_val:
  665. tooluid_val[option_changed] = new_option_value
  666. if option_changed in tooluid_val['data']:
  667. tooluid_val['data'][option_changed] = new_option_value
  668. self.blockSignals(False)
  669. def on_apply_param_to_all_clicked(self):
  670. if self.tools_table.rowCount() == 0:
  671. # there is no tool in tool table so we can't save the GUI elements values to storage
  672. log.debug("ToolIsolation.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  673. return
  674. self.blockSignals(True)
  675. row = self.tools_table.currentRow()
  676. if row < 0:
  677. row = 0
  678. tooluid_item = int(self.tools_table.item(row, 3).text())
  679. temp_tool_data = {}
  680. for tooluid_key, tooluid_val in self.iso_tools.items():
  681. if int(tooluid_key) == tooluid_item:
  682. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  683. # the current row in the tool table
  684. temp_tool_data = tooluid_val['data']
  685. break
  686. for tooluid_key, tooluid_val in self.iso_tools.items():
  687. tooluid_val['data'] = deepcopy(temp_tool_data)
  688. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  689. self.blockSignals(False)
  690. def on_add_tool_by_key(self):
  691. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  692. text='%s:' % _('Enter a Tool Diameter'),
  693. min=0.0001, max=9999.9999, decimals=self.decimals)
  694. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  695. val, ok = tool_add_popup.get_value()
  696. if ok:
  697. if float(val) == 0:
  698. self.app.inform.emit('[WARNING_NOTCL] %s' %
  699. _("Please enter a tool diameter with non-zero value, in Float format."))
  700. return
  701. self.on_tool_add(dia=float(val))
  702. else:
  703. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  704. def install(self, icon=None, separator=None, **kwargs):
  705. AppTool.install(self, icon, separator, shortcut='Alt+I', **kwargs)
  706. def run(self, toggle=True):
  707. self.app.defaults.report_usage("ToolIsolation()")
  708. log.debug("ToolIsolation().run() was launched ...")
  709. if toggle:
  710. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  711. if self.app.ui.splitter.sizes()[0] == 0:
  712. self.app.ui.splitter.setSizes([1, 1])
  713. else:
  714. try:
  715. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  716. # if tab is populated with the tool but it does not have the focus, focus on it
  717. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  718. # focus on Tool Tab
  719. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  720. else:
  721. self.app.ui.splitter.setSizes([0, 1])
  722. except AttributeError:
  723. pass
  724. else:
  725. if self.app.ui.splitter.sizes()[0] == 0:
  726. self.app.ui.splitter.setSizes([1, 1])
  727. AppTool.run(self)
  728. self.set_tool_ui()
  729. # reset those objects on a new run
  730. self.grb_obj = None
  731. self.obj_name = ''
  732. self.build_ui()
  733. self.app.ui.notebook.setTabText(2, _("Isolation Tool"))
  734. def set_tool_ui(self):
  735. self.units = self.app.defaults['units'].upper()
  736. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  737. # try to select in the Gerber combobox the active object
  738. try:
  739. current_name = self.app.collection.get_active().options['name']
  740. self.object_combo.set_value(current_name)
  741. except Exception:
  742. pass
  743. app_mode = self.app.defaults["global_app_level"]
  744. # Show/Hide Advanced Options
  745. if app_mode == 'b':
  746. self.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  747. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  748. self.tool_type_radio.set_value('C1')
  749. self.tool_type_label.hide()
  750. self.tool_type_radio.hide()
  751. self.milling_type_label.hide()
  752. self.milling_type_radio.hide()
  753. self.iso_type_label.hide()
  754. self.iso_type_radio.set_value('full')
  755. self.iso_type_radio.hide()
  756. self.follow_cb.set_value(False)
  757. self.follow_cb.hide()
  758. self.follow_label.hide()
  759. self.rest_cb.set_value(False)
  760. self.rest_cb.hide()
  761. self.except_cb.set_value(False)
  762. self.except_cb.hide()
  763. self.select_combo.setCurrentIndex(0)
  764. self.select_combo.hide()
  765. self.select_label.hide()
  766. else:
  767. self.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  768. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  769. self.tool_type_label.show()
  770. self.tool_type_radio.show()
  771. self.milling_type_label.show()
  772. self.milling_type_radio.show()
  773. self.iso_type_label.show()
  774. self.iso_type_radio.set_value(self.app.defaults["tools_iso_isotype"])
  775. self.iso_type_radio.show()
  776. self.follow_cb.set_value(self.app.defaults["tools_iso_follow"])
  777. self.follow_cb.show()
  778. self.follow_label.show()
  779. self.rest_cb.set_value(self.app.defaults["tools_iso_rest"])
  780. self.rest_cb.show()
  781. self.except_cb.set_value(self.app.defaults["tools_iso_isoexcept"])
  782. self.except_cb.show()
  783. self.select_combo.set_value(self.app.defaults["tools_iso_selection"])
  784. self.select_combo.show()
  785. self.select_label.show()
  786. if self.app.defaults["gerber_buffering"] == 'no':
  787. self.create_buffer_button.show()
  788. try:
  789. self.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  790. except TypeError:
  791. pass
  792. self.create_buffer_button.clicked.connect(self.on_generate_buffer)
  793. else:
  794. self.create_buffer_button.hide()
  795. self.tools_frame.show()
  796. self.type_excobj_radio.set_value('gerber')
  797. # run those once so the obj_type attribute is updated for the FCComboboxes
  798. # so the last loaded object is displayed
  799. self.on_type_excobj_index_changed(val="gerber")
  800. self.on_reference_combo_changed()
  801. self.order_radio.set_value(self.app.defaults["tools_iso_order"])
  802. self.passes_entry.set_value(self.app.defaults["tools_iso_passes"])
  803. self.iso_overlap_entry.set_value(self.app.defaults["tools_iso_overlap"])
  804. self.milling_type_radio.set_value(self.app.defaults["tools_iso_milling_type"])
  805. self.combine_passes_cb.set_value(self.app.defaults["tools_iso_combine_passes"])
  806. self.area_shape_radio.set_value(self.app.defaults["tools_iso_area_shape"])
  807. self.cutz_entry.set_value(self.app.defaults["tools_iso_tool_cutz"])
  808. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  809. self.tipdia_entry.set_value(self.app.defaults["tools_iso_tool_vtipdia"])
  810. self.tipangle_entry.set_value(self.app.defaults["tools_iso_tool_vtipangle"])
  811. self.addtool_entry.set_value(self.app.defaults["tools_iso_newdia"])
  812. self.on_tool_type(val=self.tool_type_radio.get_value())
  813. loaded_obj = self.app.collection.get_by_name(self.object_combo.get_value())
  814. if loaded_obj:
  815. outname = loaded_obj.options['name']
  816. else:
  817. outname = ''
  818. # init the working variables
  819. self.default_data.clear()
  820. self.default_data = {
  821. "name": outname + '_iso',
  822. "plot": self.app.defaults["geometry_plot"],
  823. "cutz": float(self.cutz_entry.get_value()),
  824. "vtipdia": float(self.tipdia_entry.get_value()),
  825. "vtipangle": float(self.tipangle_entry.get_value()),
  826. "travelz": self.app.defaults["geometry_travelz"],
  827. "feedrate": self.app.defaults["geometry_feedrate"],
  828. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  829. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  830. "dwell": self.app.defaults["geometry_dwell"],
  831. "dwelltime": self.app.defaults["geometry_dwelltime"],
  832. "multidepth": self.app.defaults["geometry_multidepth"],
  833. "ppname_g": self.app.defaults["geometry_ppname_g"],
  834. "depthperpass": self.app.defaults["geometry_depthperpass"],
  835. "extracut": self.app.defaults["geometry_extracut"],
  836. "extracut_length": self.app.defaults["geometry_extracut_length"],
  837. "toolchange": self.app.defaults["geometry_toolchange"],
  838. "toolchangez": self.app.defaults["geometry_toolchangez"],
  839. "endz": self.app.defaults["geometry_endz"],
  840. "endxy": self.app.defaults["geometry_endxy"],
  841. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  842. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  843. "startz": self.app.defaults["geometry_startz"],
  844. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  845. "area_shape": self.app.defaults["geometry_area_shape"],
  846. "area_strategy": self.app.defaults["geometry_area_strategy"],
  847. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  848. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  849. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  850. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  851. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  852. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  853. "tools_iso_rest": self.app.defaults["tools_iso_rest"],
  854. "tools_iso_combine_passes": self.app.defaults["tools_iso_combine_passes"],
  855. "tools_iso_isoexcept": self.app.defaults["tools_iso_isoexcept"],
  856. "tools_iso_selection": self.app.defaults["tools_iso_selection"],
  857. "tools_iso_area_shape": self.app.defaults["tools_iso_area_shape"]
  858. }
  859. try:
  860. dias = [float(self.app.defaults["tools_iso_tooldia"])]
  861. except (ValueError, TypeError):
  862. dias = [float(eval(dia)) for dia in self.app.defaults["tools_iso_tooldia"].split(",") if dia != '']
  863. if not dias:
  864. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> Isolation Tools.")
  865. return
  866. self.tooluid = 0
  867. self.iso_tools.clear()
  868. for tool_dia in dias:
  869. self.tooluid += 1
  870. self.iso_tools.update({
  871. int(self.tooluid): {
  872. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  873. 'offset': 'Path',
  874. 'offset_value': 0.0,
  875. 'type': 'Iso',
  876. 'tool_type': self.tool_type_radio.get_value(),
  877. 'data': deepcopy(self.default_data),
  878. 'solid_geometry': []
  879. }
  880. })
  881. self.obj_name = ""
  882. self.grb_obj = None
  883. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  884. self.units = self.app.defaults['units'].upper()
  885. def build_ui(self):
  886. self.ui_disconnect()
  887. # updated units
  888. self.units = self.app.defaults['units'].upper()
  889. sorted_tools = []
  890. for k, v in self.iso_tools.items():
  891. if self.units == "IN":
  892. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  893. else:
  894. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  895. order = self.order_radio.get_value()
  896. if order == 'fwd':
  897. sorted_tools.sort(reverse=False)
  898. elif order == 'rev':
  899. sorted_tools.sort(reverse=True)
  900. else:
  901. pass
  902. n = len(sorted_tools)
  903. self.tools_table.setRowCount(n)
  904. tool_id = 0
  905. for tool_sorted in sorted_tools:
  906. for tooluid_key, tooluid_value in self.iso_tools.items():
  907. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  908. tool_id += 1
  909. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  910. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  911. row_no = tool_id - 1
  912. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  913. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  914. # There are no drill bits in MM with more than 2 decimals diameter
  915. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  916. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  917. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  918. tool_type_item = FCComboBox()
  919. tool_type_item.addItems(self.tool_type_item_options)
  920. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  921. idx = tool_type_item.findText(tooluid_value['tool_type'])
  922. tool_type_item.setCurrentIndex(idx)
  923. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  924. self.tools_table.setItem(row_no, 1, dia) # Diameter
  925. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  926. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  927. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  928. # make the diameter column editable
  929. for row in range(tool_id):
  930. self.tools_table.item(row, 1).setFlags(
  931. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  932. # all the tools are selected by default
  933. self.tools_table.selectColumn(0)
  934. #
  935. self.tools_table.resizeColumnsToContents()
  936. self.tools_table.resizeRowsToContents()
  937. vertical_header = self.tools_table.verticalHeader()
  938. vertical_header.hide()
  939. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  940. horizontal_header = self.tools_table.horizontalHeader()
  941. horizontal_header.setMinimumSectionSize(10)
  942. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  943. horizontal_header.resizeSection(0, 20)
  944. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  945. # self.tools_table.setSortingEnabled(True)
  946. # sort by tool diameter
  947. # self.tools_table.sortItems(1)
  948. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  949. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  950. self.ui_connect()
  951. # set the text on tool_data_label after loading the object
  952. sel_rows = []
  953. sel_items = self.tools_table.selectedItems()
  954. for it in sel_items:
  955. sel_rows.append(it.row())
  956. if len(sel_rows) > 1:
  957. self.tool_data_label.setText(
  958. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  959. )
  960. def ui_connect(self):
  961. self.tools_table.itemChanged.connect(self.on_tool_edit)
  962. # rows selected
  963. self.tools_table.clicked.connect(self.on_row_selection_change)
  964. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  965. for row in range(self.tools_table.rowCount()):
  966. try:
  967. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  968. except AttributeError:
  969. pass
  970. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  971. for opt in self.form_fields:
  972. current_widget = self.form_fields[opt]
  973. if isinstance(current_widget, FCCheckBox):
  974. current_widget.stateChanged.connect(self.form_to_storage)
  975. if isinstance(current_widget, RadioSet):
  976. current_widget.activated_custom.connect(self.form_to_storage)
  977. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  978. current_widget.returnPressed.connect(self.form_to_storage)
  979. elif isinstance(current_widget, FCComboBox):
  980. current_widget.currentIndexChanged.connect(self.form_to_storage)
  981. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  982. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  983. def ui_disconnect(self):
  984. try:
  985. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  986. self.tools_table.itemChanged.disconnect()
  987. except (TypeError, AttributeError):
  988. pass
  989. try:
  990. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  991. self.tool_type_radio.activated_custom.disconnect()
  992. except (TypeError, AttributeError):
  993. pass
  994. for row in range(self.tools_table.rowCount()):
  995. try:
  996. self.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  997. except (TypeError, AttributeError):
  998. pass
  999. for opt in self.form_fields:
  1000. current_widget = self.form_fields[opt]
  1001. if isinstance(current_widget, FCCheckBox):
  1002. try:
  1003. current_widget.stateChanged.disconnect(self.form_to_storage)
  1004. except (TypeError, ValueError):
  1005. pass
  1006. if isinstance(current_widget, RadioSet):
  1007. try:
  1008. current_widget.activated_custom.disconnect(self.form_to_storage)
  1009. except (TypeError, ValueError):
  1010. pass
  1011. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  1012. try:
  1013. current_widget.returnPressed.disconnect(self.form_to_storage)
  1014. except (TypeError, ValueError):
  1015. pass
  1016. elif isinstance(current_widget, FCComboBox):
  1017. try:
  1018. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  1019. except (TypeError, ValueError):
  1020. pass
  1021. try:
  1022. self.rest_cb.stateChanged.disconnect()
  1023. except (TypeError, ValueError):
  1024. pass
  1025. try:
  1026. self.order_radio.activated_custom[str].disconnect()
  1027. except (TypeError, ValueError):
  1028. pass
  1029. # rows selected
  1030. try:
  1031. self.tools_table.clicked.disconnect()
  1032. except (TypeError, AttributeError):
  1033. pass
  1034. try:
  1035. self.tools_table.horizontalHeader().sectionClicked.disconnect()
  1036. except (TypeError, AttributeError):
  1037. pass
  1038. def on_tooldia_updated(self):
  1039. if self.tool_type_radio.get_value() == 'C1':
  1040. self.old_tool_dia = self.addtool_entry.get_value()
  1041. def on_reference_combo_changed(self):
  1042. obj_type = self.reference_combo_type.currentIndex()
  1043. self.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  1044. self.reference_combo.setCurrentIndex(0)
  1045. self.reference_combo.obj_type = {
  1046. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  1047. }[self.reference_combo_type.get_value()]
  1048. def on_toggle_reference(self):
  1049. val = self.select_combo.get_value()
  1050. if val == _("All"):
  1051. self.reference_combo.hide()
  1052. self.reference_combo_label.hide()
  1053. self.reference_combo_type.hide()
  1054. self.reference_combo_type_label.hide()
  1055. self.area_shape_label.hide()
  1056. self.area_shape_radio.hide()
  1057. # disable rest-machining for area painting
  1058. self.rest_cb.setDisabled(False)
  1059. elif val == _("Area Selection"):
  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.show()
  1065. self.area_shape_radio.show()
  1066. # disable rest-machining for area isolation
  1067. self.rest_cb.set_value(False)
  1068. self.rest_cb.setDisabled(True)
  1069. elif val == _("Polygon Selection"):
  1070. self.reference_combo.hide()
  1071. self.reference_combo_label.hide()
  1072. self.reference_combo_type.hide()
  1073. self.reference_combo_type_label.hide()
  1074. self.area_shape_label.hide()
  1075. self.area_shape_radio.hide()
  1076. else:
  1077. self.reference_combo.show()
  1078. self.reference_combo_label.show()
  1079. self.reference_combo_type.show()
  1080. self.reference_combo_type_label.show()
  1081. self.area_shape_label.hide()
  1082. self.area_shape_radio.hide()
  1083. # disable rest-machining for area painting
  1084. self.rest_cb.setDisabled(False)
  1085. def on_order_changed(self, order):
  1086. if order != 'no':
  1087. self.build_ui()
  1088. def on_rest_machining_check(self, state):
  1089. if state:
  1090. self.order_radio.set_value('rev')
  1091. self.ncc_order_label.setDisabled(True)
  1092. self.order_radio.setDisabled(True)
  1093. self.old_combine_state = self.combine_passes_cb.get_value()
  1094. self.combine_passes_cb.set_value(True)
  1095. self.combine_passes_cb.setDisabled(True)
  1096. else:
  1097. self.ncc_order_label.setDisabled(False)
  1098. self.order_radio.setDisabled(False)
  1099. self.combine_passes_cb.set_value(self.old_combine_state)
  1100. self.combine_passes_cb.setDisabled(False)
  1101. def on_tooltable_cellwidget_change(self):
  1102. cw = self.sender()
  1103. assert isinstance(cw, QtWidgets.QComboBox), \
  1104. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  1105. cw_index = self.tools_table.indexAt(cw.pos())
  1106. cw_row = cw_index.row()
  1107. cw_col = cw_index.column()
  1108. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1109. # if the sender is in the column with index 2 then we update the tool_type key
  1110. if cw_col == 2:
  1111. tt = cw.currentText()
  1112. typ = 'Iso' if tt == 'V' else "Rough"
  1113. self.iso_tools[current_uid].update({
  1114. 'type': typ,
  1115. 'tool_type': tt,
  1116. })
  1117. def on_tool_type(self, val):
  1118. if val == 'V':
  1119. self.addtool_entry_lbl.setDisabled(True)
  1120. self.addtool_entry.setDisabled(True)
  1121. self.tipdialabel.show()
  1122. self.tipdia_entry.show()
  1123. self.tipanglelabel.show()
  1124. self.tipangle_entry.show()
  1125. self.on_calculate_tooldia()
  1126. else:
  1127. self.addtool_entry_lbl.setDisabled(False)
  1128. self.addtool_entry.setDisabled(False)
  1129. self.tipdialabel.hide()
  1130. self.tipdia_entry.hide()
  1131. self.tipanglelabel.hide()
  1132. self.tipangle_entry.hide()
  1133. self.addtool_entry.set_value(self.old_tool_dia)
  1134. def on_calculate_tooldia(self):
  1135. if self.tool_type_radio.get_value() == 'V':
  1136. tip_dia = float(self.tipdia_entry.get_value())
  1137. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1138. cut_z = float(self.cutz_entry.get_value())
  1139. cut_z = -cut_z if cut_z < 0 else cut_z
  1140. # calculated tool diameter so the cut_z parameter is obeyed
  1141. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1142. # update the default_data so it is used in the iso_tools dict
  1143. self.default_data.update({
  1144. "vtipdia": tip_dia,
  1145. "vtipangle": (tip_angle * 2),
  1146. })
  1147. self.addtool_entry.set_value(tool_dia)
  1148. return tool_dia
  1149. else:
  1150. return float(self.addtool_entry.get_value())
  1151. def on_tool_add(self, dia=None, muted=None):
  1152. self.blockSignals(True)
  1153. self.units = self.app.defaults['units'].upper()
  1154. if dia:
  1155. tool_dia = dia
  1156. else:
  1157. tool_dia = self.on_calculate_tooldia()
  1158. if tool_dia is None:
  1159. self.build_ui()
  1160. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1161. return
  1162. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1163. if tool_dia == 0:
  1164. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1165. "in Float format."))
  1166. return
  1167. # construct a list of all 'tooluid' in the self.tools
  1168. tool_uid_list = []
  1169. for tooluid_key in self.iso_tools:
  1170. tool_uid_item = int(tooluid_key)
  1171. tool_uid_list.append(tool_uid_item)
  1172. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1173. if not tool_uid_list:
  1174. max_uid = 0
  1175. else:
  1176. max_uid = max(tool_uid_list)
  1177. self.tooluid = int(max_uid + 1)
  1178. tool_dias = []
  1179. for k, v in self.iso_tools.items():
  1180. for tool_v in v.keys():
  1181. if tool_v == 'tooldia':
  1182. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1183. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1184. if muted is None:
  1185. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1186. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1187. self.blockSignals(False)
  1188. return
  1189. else:
  1190. if muted is None:
  1191. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1192. self.iso_tools.update({
  1193. int(self.tooluid): {
  1194. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1195. 'offset': 'Path',
  1196. 'offset_value': 0.0,
  1197. 'type': 'Iso',
  1198. 'tool_type': self.tool_type_radio.get_value(),
  1199. 'data': deepcopy(self.default_data),
  1200. 'solid_geometry': []
  1201. }
  1202. })
  1203. self.blockSignals(False)
  1204. self.build_ui()
  1205. def on_tool_edit(self):
  1206. self.blockSignals(True)
  1207. old_tool_dia = ''
  1208. tool_dias = []
  1209. for k, v in self.iso_tools.items():
  1210. for tool_v in v.keys():
  1211. if tool_v == 'tooldia':
  1212. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1213. for row in range(self.tools_table.rowCount()):
  1214. try:
  1215. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1216. except ValueError:
  1217. # try to convert comma to decimal point. if it's still not working error message and return
  1218. try:
  1219. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1220. except ValueError:
  1221. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1222. self.blockSignals(False)
  1223. return
  1224. tooluid = int(self.tools_table.item(row, 3).text())
  1225. # identify the tool that was edited and get it's tooluid
  1226. if new_tool_dia not in tool_dias:
  1227. self.iso_tools[tooluid]['tooldia'] = new_tool_dia
  1228. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1229. self.blockSignals(False)
  1230. self.build_ui()
  1231. return
  1232. else:
  1233. # identify the old tool_dia and restore the text in tool table
  1234. for k, v in self.iso_tools.items():
  1235. if k == tooluid:
  1236. old_tool_dia = v['tooldia']
  1237. break
  1238. restore_dia_item = self.tools_table.item(row, 1)
  1239. restore_dia_item.setText(str(old_tool_dia))
  1240. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. "
  1241. "New diameter value is already in the Tool Table."))
  1242. self.blockSignals(False)
  1243. self.build_ui()
  1244. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1245. """
  1246. Will delete a tool in the tool table
  1247. :param rows_to_delete: which rows to delete; can be a list
  1248. :param all_tools: delete all tools in the tool table
  1249. :return:
  1250. """
  1251. self.blockSignals(True)
  1252. deleted_tools_list = []
  1253. if all_tools:
  1254. self.iso_tools.clear()
  1255. self.blockSignals(False)
  1256. self.build_ui()
  1257. return
  1258. if rows_to_delete:
  1259. try:
  1260. for row in rows_to_delete:
  1261. tooluid_del = int(self.tools_table.item(row, 3).text())
  1262. deleted_tools_list.append(tooluid_del)
  1263. except TypeError:
  1264. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1265. deleted_tools_list.append(tooluid_del)
  1266. for t in deleted_tools_list:
  1267. self.iso_tools.pop(t, None)
  1268. self.blockSignals(False)
  1269. self.build_ui()
  1270. return
  1271. try:
  1272. if self.tools_table.selectedItems():
  1273. for row_sel in self.tools_table.selectedItems():
  1274. row = row_sel.row()
  1275. if row < 0:
  1276. continue
  1277. tooluid_del = int(self.tools_table.item(row, 3).text())
  1278. deleted_tools_list.append(tooluid_del)
  1279. for t in deleted_tools_list:
  1280. self.iso_tools.pop(t, None)
  1281. except AttributeError:
  1282. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1283. self.blockSignals(False)
  1284. return
  1285. except Exception as e:
  1286. log.debug(str(e))
  1287. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1288. self.blockSignals(False)
  1289. self.build_ui()
  1290. def on_generate_buffer(self):
  1291. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  1292. self.obj_name = self.object_combo.currentText()
  1293. # Get source object.
  1294. try:
  1295. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1296. except Exception as e:
  1297. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1298. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1299. if self.grb_obj is None:
  1300. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1301. return
  1302. def buffer_task():
  1303. with self.app.proc_container.new('%s...' % _("Buffering")):
  1304. if isinstance(self.grb_obj.solid_geometry, list):
  1305. self.grb_obj.solid_geometry = MultiPolygon(self.grb_obj.solid_geometry)
  1306. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(0.0000001)
  1307. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(-0.0000001)
  1308. self.app.inform.emit('[success] %s.' % _("Done"))
  1309. self.grb_obj.plot_single_object.emit()
  1310. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  1311. def on_iso_button_click(self):
  1312. self.obj_name = self.object_combo.currentText()
  1313. # Get source object.
  1314. try:
  1315. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1316. except Exception as e:
  1317. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1318. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1319. if self.grb_obj is None:
  1320. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1321. return
  1322. def worker_task(iso_obj, app_obj):
  1323. with self.app.proc_container.new(_("Isolating...")):
  1324. self.isolate_handler(iso_obj)
  1325. self.app.worker_task.emit({'fcn': worker_task, 'params': [self.grb_obj, self.app]})
  1326. def follow_geo(self, followed_obj, outname):
  1327. """
  1328. Creates a geometry object "following" the gerber paths.
  1329. :param followed_obj: Gerber object for which to generate the follow geometry
  1330. :type followed_obj: AppObjects.FlatCAMGerber.GerberObject
  1331. :param outname: Nme of the resulting Geometry object
  1332. :type outname: str
  1333. :return: None
  1334. """
  1335. def follow_init(follow_obj, app):
  1336. # Propagate options
  1337. follow_obj.options["cnctooldia"] = str(tooldia)
  1338. follow_obj.solid_geometry = self.grb_obj.follow_geometry
  1339. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  1340. followed_obj.ui.plot_cb.set_value(False)
  1341. follow_name = outname
  1342. for tool in self.iso_tools:
  1343. tooldia = self.iso_tools[tool]['tooldia']
  1344. new_name = "%s_%.*f" % (follow_name, self.decimals, tooldia)
  1345. follow_state = self.iso_tools[tool]['data']['tools_iso_follow']
  1346. if follow_state:
  1347. ret = self.app.app_obj.new_object("geometry", new_name, follow_init)
  1348. if ret == 'fail':
  1349. self.app.inform.emit("[ERROR_NOTCL] %s: %.*f" % (
  1350. _("Failed to create Follow Geometry with tool diameter"), self.decimals, tooldia))
  1351. else:
  1352. self.app.inform.emit("[success] %s: %.*f" % (
  1353. _("Follow Geometry was created with tool diameter"), self.decimals, tooldia))
  1354. def isolate_handler(self, isolated_obj):
  1355. """
  1356. Creates a geometry object with paths around the gerber features.
  1357. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1358. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1359. :return: None
  1360. """
  1361. selection = self.select_combo.get_value()
  1362. if selection == _("All"):
  1363. self.isolate(isolated_obj=isolated_obj)
  1364. elif selection == _("Area Selection"):
  1365. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1366. if self.app.is_legacy is False:
  1367. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1368. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1369. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1370. else:
  1371. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1372. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1373. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1374. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1375. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1376. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1377. elif selection == _("Polygon Selection"):
  1378. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1379. if self.app.ui.grid_snap_btn.isChecked():
  1380. self.grid_status_memory = True
  1381. self.app.ui.grid_snap_btn.trigger()
  1382. else:
  1383. self.grid_status_memory = False
  1384. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_poly_mouse_click_release)
  1385. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1386. if self.app.is_legacy is False:
  1387. self.app.plotcanvas.graph_event_disconnect('mouse_release',
  1388. self.app.on_mouse_click_release_over_plot)
  1389. else:
  1390. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1391. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  1392. elif selection == _("Reference Object"):
  1393. ref_obj = self.app.collection.get_by_name(self.reference_combo.get_value())
  1394. ref_geo = cascaded_union(ref_obj.solid_geometry)
  1395. use_geo = cascaded_union(isolated_obj.solid_geometry).difference(ref_geo)
  1396. self.isolate(isolated_obj=isolated_obj, geometry=use_geo)
  1397. def isolate(self, isolated_obj, geometry=None, limited_area=None, plot=True):
  1398. """
  1399. Creates an isolation routing geometry object in the project.
  1400. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1401. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1402. :param geometry: specific geometry to isolate
  1403. :type geometry: List of Shapely polygon
  1404. :param limited_area: if not None isolate only this area
  1405. :type limited_area: Shapely Polygon or a list of them
  1406. :param plot: if to plot the resulting geometry object
  1407. :type plot: bool
  1408. :return: None
  1409. """
  1410. combine = self.combine_passes_cb.get_value()
  1411. tools_storage = self.iso_tools
  1412. if combine:
  1413. if self.rest_cb.get_value():
  1414. self.combined_rest(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1415. lim_area=limited_area, plot=plot)
  1416. else:
  1417. self.combined_normal(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1418. lim_area=limited_area, plot=plot)
  1419. else:
  1420. for tool in tools_storage:
  1421. tool_data = tools_storage[tool]['data']
  1422. to_follow = tool_data['tools_iso_follow']
  1423. work_geo = geometry
  1424. if work_geo is None:
  1425. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1426. iso_t = {
  1427. 'ext': 0,
  1428. 'int': 1,
  1429. 'full': 2
  1430. }[tool_data['tools_iso_isotype']]
  1431. passes = tool_data['tools_iso_passes']
  1432. overlap = tool_data['tools_iso_overlap']
  1433. overlap /= 100.0
  1434. milling_type = tool_data['tools_iso_milling_type']
  1435. iso_except = tool_data['tools_iso_isoexcept']
  1436. for i in range(passes):
  1437. tool_dia = tools_storage[tool]['tooldia']
  1438. tool_type = tools_storage[tool]['tool_type']
  1439. iso_offset = tool_dia * ((2 * i + 1) / 2.0000001) - (i * overlap * tool_dia)
  1440. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1441. if passes > 1:
  1442. iso_name = outname + "_iso" + str(i + 1)
  1443. if iso_t == 0:
  1444. iso_name = outname + "_ext_iso" + str(i + 1)
  1445. elif iso_t == 1:
  1446. iso_name = outname + "_int_iso" + str(i + 1)
  1447. else:
  1448. iso_name = outname + "_iso"
  1449. if iso_t == 0:
  1450. iso_name = outname + "_ext_iso"
  1451. elif iso_t == 1:
  1452. iso_name = outname + "_int_iso"
  1453. # if milling type is climb then the move is counter-clockwise around features
  1454. mill_dir = 1 if milling_type == 'cl' else 0
  1455. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1456. follow=to_follow, nr_passes=i)
  1457. if iso_geo == 'fail':
  1458. self.app.inform.emit(
  1459. '[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1460. continue
  1461. # ############################################################
  1462. # ########## AREA SUBTRACTION ################################
  1463. # ############################################################
  1464. if iso_except:
  1465. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1466. iso_geo = self.area_subtraction(iso_geo)
  1467. if limited_area:
  1468. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1469. iso_geo = self.area_intersection(iso_geo, intersection_geo=limited_area)
  1470. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in
  1471. # Gerber UI
  1472. if tool_type.lower() == 'v':
  1473. new_cutz = self.cutz_entry.get_value()
  1474. new_vtipdia = self.tipdia_entry.get_value()
  1475. new_vtipangle = self.tipangle_entry.get_value()
  1476. tool_type = 'V'
  1477. tool_data.update({
  1478. "name": iso_name,
  1479. "cutz": new_cutz,
  1480. "vtipdia": new_vtipdia,
  1481. "vtipangle": new_vtipangle,
  1482. })
  1483. else:
  1484. tool_data.update({
  1485. "name": iso_name,
  1486. })
  1487. tool_type = 'C1'
  1488. def iso_init(geo_obj, fc_obj):
  1489. # Propagate options
  1490. geo_obj.options["cnctooldia"] = str(tool_dia)
  1491. geo_obj.solid_geometry = deepcopy(iso_geo)
  1492. # ############################################################
  1493. # ########## AREA SUBTRACTION ################################
  1494. # ############################################################
  1495. if self.except_cb.get_value():
  1496. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1497. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1498. geo_obj.tools = {}
  1499. geo_obj.tools['1'] = {}
  1500. geo_obj.tools.update({
  1501. '1': {
  1502. 'tooldia': float(tool_dia),
  1503. 'offset': 'Path',
  1504. 'offset_value': 0.0,
  1505. 'type': _('Rough'),
  1506. 'tool_type': tool_type,
  1507. 'data': tool_data,
  1508. 'solid_geometry': geo_obj.solid_geometry
  1509. }
  1510. })
  1511. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1512. # or just looking in the lists (they are one level depth) and if any is not empty
  1513. # proceed with object creation, if there are empty and the number of them is the length
  1514. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1515. empty_cnt = 0
  1516. if not isinstance(geo_obj.solid_geometry, list):
  1517. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1518. for g in geo_obj.solid_geometry:
  1519. if g:
  1520. break
  1521. else:
  1522. empty_cnt += 1
  1523. if empty_cnt == len(geo_obj.solid_geometry):
  1524. fc_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1525. _("Empty Geometry in"), geo_obj.options["name"]))
  1526. return 'fail'
  1527. else:
  1528. fc_obj.inform.emit('[success] %s: %s' %
  1529. (_("Isolation geometry created"), geo_obj.options["name"]))
  1530. geo_obj.multigeo = False
  1531. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1532. def combined_rest(self, iso_obj, iso2geo, tools_storage, lim_area, plot=True):
  1533. """
  1534. :param iso_obj: the isolated Gerber object
  1535. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1536. :param iso2geo: specific geometry to isolate
  1537. :type iso2geo: list of Shapely Polygon
  1538. :param tools_storage: a dictionary that holds the tools and geometry
  1539. :type tools_storage: dict
  1540. :param lim_area: if not None restrict isolation to this area
  1541. :type lim_area: Shapely Polygon or a list of them
  1542. :param plot: if to plot the resulting geometry object
  1543. :type plot: bool
  1544. :return: Isolated solid geometry
  1545. :rtype:
  1546. """
  1547. log.debug("ToolIsolation.combine_rest()")
  1548. total_solid_geometry = []
  1549. iso_name = iso_obj.options["name"]
  1550. geometry = iso2geo
  1551. for tool in tools_storage:
  1552. tool_dia = tools_storage[tool]['tooldia']
  1553. tool_type = tools_storage[tool]['tool_type']
  1554. tool_data = tools_storage[tool]['data']
  1555. to_follow = tool_data['tools_iso_follow']
  1556. work_geo = geometry
  1557. if work_geo is None:
  1558. work_geo = iso_obj.follow_geometry if to_follow else iso_obj.solid_geometry
  1559. iso_t = {
  1560. 'ext': 0,
  1561. 'int': 1,
  1562. 'full': 2
  1563. }[tool_data['tools_iso_isotype']]
  1564. passes = tool_data['tools_iso_passes']
  1565. overlap = tool_data['tools_iso_overlap']
  1566. overlap /= 100.0
  1567. milling_type = tool_data['tools_iso_milling_type']
  1568. iso_except = tool_data['tools_iso_isoexcept']
  1569. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1570. iso_name = outname + "_iso"
  1571. if iso_t == 0:
  1572. iso_name = outname + "_ext_iso"
  1573. elif iso_t == 1:
  1574. iso_name = outname + "_int_iso"
  1575. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1576. if tool_type.lower() == 'v':
  1577. new_cutz = self.ui.cutz_spinner.get_value()
  1578. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1579. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1580. tool_type = 'V'
  1581. tool_data.update({
  1582. "name": iso_name,
  1583. "cutz": new_cutz,
  1584. "vtipdia": new_vtipdia,
  1585. "vtipangle": new_vtipangle,
  1586. })
  1587. else:
  1588. tool_data.update({
  1589. "name": iso_name,
  1590. })
  1591. tool_type = 'C1'
  1592. solid_geo = []
  1593. for nr_pass in range(passes):
  1594. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1595. # if milling type is climb then the move is counter-clockwise around features
  1596. mill_dir = 1 if milling_type == 'cl' else 0
  1597. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1598. follow=to_follow, nr_passes=nr_pass)
  1599. if iso_geo == 'fail':
  1600. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1601. continue
  1602. try:
  1603. for geo in iso_geo:
  1604. solid_geo.append(geo)
  1605. except TypeError:
  1606. solid_geo.append(iso_geo)
  1607. # ############################################################
  1608. # ########## AREA SUBTRACTION ################################
  1609. # ############################################################
  1610. if iso_except:
  1611. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1612. solid_geo = self.area_subtraction(solid_geo)
  1613. if lim_area:
  1614. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1615. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1616. tools_storage.update({
  1617. tool: {
  1618. 'tooldia': float(tool_dia),
  1619. 'offset': 'Path',
  1620. 'offset_value': 0.0,
  1621. 'type': _('Rough'),
  1622. 'tool_type': tool_type,
  1623. 'data': tool_data,
  1624. 'solid_geometry': deepcopy(solid_geo)
  1625. }
  1626. })
  1627. total_solid_geometry += solid_geo
  1628. def iso_init(geo_obj, app_obj):
  1629. geo_obj.options["cnctooldia"] = str(tool_dia)
  1630. geo_obj.tools = dict(tools_storage)
  1631. geo_obj.solid_geometry = total_solid_geometry
  1632. # even if combine is checked, one pass is still single-geo
  1633. if len(tools_storage) > 1:
  1634. geo_obj.multigeo = True
  1635. else:
  1636. if to_follow:
  1637. passes_no = 1
  1638. else:
  1639. passes_no = float(tools_storage[0]['data']['tools_iso_passes'])
  1640. geo_obj.multigeo = True if passes_no > 1 else False
  1641. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1642. # or just looking in the lists (they are one level depth) and if any is not empty
  1643. # proceed with object creation, if there are empty and the number of them is the length
  1644. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1645. empty_cnt = 0
  1646. if not isinstance(geo_obj.solid_geometry, list) and \
  1647. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1648. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1649. for g in geo_obj.solid_geometry:
  1650. if g:
  1651. break
  1652. else:
  1653. empty_cnt += 1
  1654. if empty_cnt == len(geo_obj.solid_geometry):
  1655. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1656. return 'fail'
  1657. else:
  1658. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1659. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1660. def combined_normal(self, iso_obj, iso2geo, tools_storage, lim_area, plot=True):
  1661. """
  1662. :param iso_obj: the isolated Gerber object
  1663. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1664. :param iso2geo: specific geometry to isolate
  1665. :type iso2geo: list of Shapely Polygon
  1666. :param tools_storage: a dictionary that holds the tools and geometry
  1667. :type tools_storage: dict
  1668. :param lim_area: if not None restrict isolation to this area
  1669. :type lim_area: Shapely Polygon or a list of them
  1670. :param plot: if to plot the resulting geometry object
  1671. :type plot: bool
  1672. :return: Isolated solid geometry
  1673. :rtype:
  1674. """
  1675. log.debug("ToolIsolation.combined_normal()")
  1676. total_solid_geometry = []
  1677. iso_name = iso_obj.options["name"]
  1678. geometry = iso2geo
  1679. for tool in tools_storage:
  1680. tool_dia = tools_storage[tool]['tooldia']
  1681. tool_type = tools_storage[tool]['tool_type']
  1682. tool_data = tools_storage[tool]['data']
  1683. to_follow = tool_data['tools_iso_follow']
  1684. work_geo = geometry
  1685. if work_geo is None:
  1686. work_geo = iso_obj.follow_geometry if to_follow else iso_obj.solid_geometry
  1687. iso_t = {
  1688. 'ext': 0,
  1689. 'int': 1,
  1690. 'full': 2
  1691. }[tool_data['tools_iso_isotype']]
  1692. passes = tool_data['tools_iso_passes']
  1693. overlap = tool_data['tools_iso_overlap']
  1694. overlap /= 100.0
  1695. milling_type = tool_data['tools_iso_milling_type']
  1696. iso_except = tool_data['tools_iso_isoexcept']
  1697. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1698. iso_name = outname + "_iso"
  1699. if iso_t == 0:
  1700. iso_name = outname + "_ext_iso"
  1701. elif iso_t == 1:
  1702. iso_name = outname + "_int_iso"
  1703. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1704. if tool_type.lower() == 'v':
  1705. new_cutz = self.ui.cutz_spinner.get_value()
  1706. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1707. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1708. tool_type = 'V'
  1709. tool_data.update({
  1710. "name": iso_name,
  1711. "cutz": new_cutz,
  1712. "vtipdia": new_vtipdia,
  1713. "vtipangle": new_vtipangle,
  1714. })
  1715. else:
  1716. tool_data.update({
  1717. "name": iso_name,
  1718. })
  1719. tool_type = 'C1'
  1720. solid_geo = []
  1721. for nr_pass in range(passes):
  1722. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1723. # if milling type is climb then the move is counter-clockwise around features
  1724. mill_dir = 1 if milling_type == 'cl' else 0
  1725. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1726. follow=to_follow, nr_passes=nr_pass)
  1727. if iso_geo == 'fail':
  1728. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1729. continue
  1730. try:
  1731. for geo in iso_geo:
  1732. solid_geo.append(geo)
  1733. except TypeError:
  1734. solid_geo.append(iso_geo)
  1735. # ############################################################
  1736. # ########## AREA SUBTRACTION ################################
  1737. # ############################################################
  1738. if iso_except:
  1739. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1740. solid_geo = self.area_subtraction(solid_geo)
  1741. if lim_area:
  1742. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1743. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1744. tools_storage.update({
  1745. tool: {
  1746. 'tooldia': float(tool_dia),
  1747. 'offset': 'Path',
  1748. 'offset_value': 0.0,
  1749. 'type': _('Rough'),
  1750. 'tool_type': tool_type,
  1751. 'data': tool_data,
  1752. 'solid_geometry': deepcopy(solid_geo)
  1753. }
  1754. })
  1755. total_solid_geometry += solid_geo
  1756. def iso_init(geo_obj, app_obj):
  1757. geo_obj.options["cnctooldia"] = str(tool_dia)
  1758. geo_obj.tools = dict(tools_storage)
  1759. geo_obj.solid_geometry = total_solid_geometry
  1760. # even if combine is checked, one pass is still single-geo
  1761. if len(tools_storage) > 1:
  1762. geo_obj.multigeo = True
  1763. else:
  1764. if to_follow:
  1765. passes_no = 1
  1766. else:
  1767. passes_no = float(tools_storage[0]['data']['tools_iso_passes'])
  1768. geo_obj.multigeo = True if passes_no > 1 else False
  1769. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1770. # or just looking in the lists (they are one level depth) and if any is not empty
  1771. # proceed with object creation, if there are empty and the number of them is the length
  1772. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1773. empty_cnt = 0
  1774. if not isinstance(geo_obj.solid_geometry, list) and \
  1775. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1776. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1777. for g in geo_obj.solid_geometry:
  1778. if g:
  1779. break
  1780. else:
  1781. empty_cnt += 1
  1782. if empty_cnt == len(geo_obj.solid_geometry):
  1783. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1784. return 'fail'
  1785. else:
  1786. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1787. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1788. def area_subtraction(self, geo, subtractor_geo):
  1789. """
  1790. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1791. :param geo: target geometry from which to subtract
  1792. :param subtractor_geo: geometry that acts as subtractor
  1793. :return:
  1794. """
  1795. new_geometry = []
  1796. target_geo = geo
  1797. if subtractor_geo:
  1798. sub_union = cascaded_union(subtractor_geo)
  1799. else:
  1800. name = self.exc_obj_combo.currentText()
  1801. subtractor_obj = self.app.collection.get_by_name(name)
  1802. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1803. try:
  1804. for geo_elem in target_geo:
  1805. if isinstance(geo_elem, Polygon):
  1806. for ring in self.poly2rings(geo_elem):
  1807. new_geo = ring.difference(sub_union)
  1808. if new_geo and not new_geo.is_empty:
  1809. new_geometry.append(new_geo)
  1810. elif isinstance(geo_elem, MultiPolygon):
  1811. for poly in geo_elem:
  1812. for ring in self.poly2rings(poly):
  1813. new_geo = ring.difference(sub_union)
  1814. if new_geo and not new_geo.is_empty:
  1815. new_geometry.append(new_geo)
  1816. elif isinstance(geo_elem, LineString):
  1817. new_geo = geo_elem.difference(sub_union)
  1818. if new_geo:
  1819. if not new_geo.is_empty:
  1820. new_geometry.append(new_geo)
  1821. elif isinstance(geo_elem, MultiLineString):
  1822. for line_elem in geo_elem:
  1823. new_geo = line_elem.difference(sub_union)
  1824. if new_geo and not new_geo.is_empty:
  1825. new_geometry.append(new_geo)
  1826. except TypeError:
  1827. if isinstance(target_geo, Polygon):
  1828. for ring in self.poly2rings(target_geo):
  1829. new_geo = ring.difference(sub_union)
  1830. if new_geo:
  1831. if not new_geo.is_empty:
  1832. new_geometry.append(new_geo)
  1833. elif isinstance(target_geo, LineString):
  1834. new_geo = target_geo.difference(sub_union)
  1835. if new_geo and not new_geo.is_empty:
  1836. new_geometry.append(new_geo)
  1837. elif isinstance(target_geo, MultiLineString):
  1838. for line_elem in target_geo:
  1839. new_geo = line_elem.difference(sub_union)
  1840. if new_geo and not new_geo.is_empty:
  1841. new_geometry.append(new_geo)
  1842. return new_geometry
  1843. def area_intersection(self, geo, intersection_geo=None):
  1844. """
  1845. Return the intersection geometry between geo and intersection_geo
  1846. :param geo: target geometry
  1847. :param intersection_geo: second geometry
  1848. :return:
  1849. """
  1850. new_geometry = []
  1851. target_geo = geo
  1852. intersect_union = cascaded_union(intersection_geo)
  1853. try:
  1854. for geo_elem in target_geo:
  1855. if isinstance(geo_elem, Polygon):
  1856. for ring in self.poly2rings(geo_elem):
  1857. new_geo = ring.intersection(intersect_union)
  1858. if new_geo and not new_geo.is_empty:
  1859. new_geometry.append(new_geo)
  1860. elif isinstance(geo_elem, MultiPolygon):
  1861. for poly in geo_elem:
  1862. for ring in self.poly2rings(poly):
  1863. new_geo = ring.intersection(intersect_union)
  1864. if new_geo and not new_geo.is_empty:
  1865. new_geometry.append(new_geo)
  1866. elif isinstance(geo_elem, LineString):
  1867. new_geo = geo_elem.intersection(intersect_union)
  1868. if new_geo:
  1869. if not new_geo.is_empty:
  1870. new_geometry.append(new_geo)
  1871. elif isinstance(geo_elem, MultiLineString):
  1872. for line_elem in geo_elem:
  1873. new_geo = line_elem.intersection(intersect_union)
  1874. if new_geo and not new_geo.is_empty:
  1875. new_geometry.append(new_geo)
  1876. except TypeError:
  1877. if isinstance(target_geo, Polygon):
  1878. for ring in self.poly2rings(target_geo):
  1879. new_geo = ring.intersection(intersect_union)
  1880. if new_geo:
  1881. if not new_geo.is_empty:
  1882. new_geometry.append(new_geo)
  1883. elif isinstance(target_geo, LineString):
  1884. new_geo = target_geo.intersection(intersect_union)
  1885. if new_geo and not new_geo.is_empty:
  1886. new_geometry.append(new_geo)
  1887. elif isinstance(target_geo, MultiLineString):
  1888. for line_elem in target_geo:
  1889. new_geo = line_elem.intersection(intersect_union)
  1890. if new_geo and not new_geo.is_empty:
  1891. new_geometry.append(new_geo)
  1892. return new_geometry
  1893. def on_poly_mouse_click_release(self, event):
  1894. if self.app.is_legacy is False:
  1895. event_pos = event.pos
  1896. right_button = 2
  1897. self.app.event_is_dragging = self.app.event_is_dragging
  1898. else:
  1899. event_pos = (event.xdata, event.ydata)
  1900. right_button = 3
  1901. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1902. try:
  1903. x = float(event_pos[0])
  1904. y = float(event_pos[1])
  1905. except TypeError:
  1906. return
  1907. event_pos = (x, y)
  1908. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1909. if self.app.grid_status():
  1910. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1911. else:
  1912. curr_pos = (curr_pos[0], curr_pos[1])
  1913. if event.button == 1:
  1914. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.grb_obj.solid_geometry)
  1915. if self.app.selection_type is not None:
  1916. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  1917. self.app.selection_type = None
  1918. elif clicked_poly:
  1919. if clicked_poly not in self.poly_dict.values():
  1920. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  1921. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1922. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1923. visible=True)
  1924. self.poly_dict[shape_id] = clicked_poly
  1925. self.app.inform.emit(
  1926. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  1927. _("Click to add next polygon or right click to start isolation."))
  1928. )
  1929. else:
  1930. try:
  1931. for k, v in list(self.poly_dict.items()):
  1932. if v == clicked_poly:
  1933. self.app.tool_shapes.remove(k)
  1934. self.poly_dict.pop(k)
  1935. break
  1936. except TypeError:
  1937. return
  1938. self.app.inform.emit(
  1939. '%s. %s' % (_("Removed polygon"),
  1940. _("Click to add/remove next polygon or right click to start isolation."))
  1941. )
  1942. self.app.tool_shapes.redraw()
  1943. else:
  1944. self.app.inform.emit(_("No polygon detected under click position."))
  1945. elif event.button == right_button and self.app.event_is_dragging is False:
  1946. # restore the Grid snapping if it was active before
  1947. if self.grid_status_memory is True:
  1948. self.app.ui.grid_snap_btn.trigger()
  1949. if self.app.is_legacy is False:
  1950. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1951. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_pres)
  1952. else:
  1953. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1954. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1955. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1956. self.app.on_mouse_click_release_over_plot)
  1957. self.app.tool_shapes.clear(update=True)
  1958. if self.poly_dict:
  1959. poly_list = deepcopy(list(self.poly_dict.values()))
  1960. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list)
  1961. self.poly_dict.clear()
  1962. else:
  1963. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1964. def selection_area_handler(self, start_pos, end_pos, sel_type):
  1965. """
  1966. :param start_pos: mouse position when the selection LMB click was done
  1967. :param end_pos: mouse position when the left mouse button is released
  1968. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1969. :return:
  1970. """
  1971. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1972. # delete previous selection shape
  1973. self.app.delete_selection_shape()
  1974. added_poly_count = 0
  1975. try:
  1976. for geo in self.solid_geometry:
  1977. if geo not in self.poly_dict.values():
  1978. if sel_type is True:
  1979. if geo.within(poly_selection):
  1980. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1981. shape=geo,
  1982. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1983. face_color=self.app.defaults[
  1984. 'global_sel_draw_color'] + 'AF',
  1985. visible=True)
  1986. self.poly_dict[shape_id] = geo
  1987. added_poly_count += 1
  1988. else:
  1989. if poly_selection.intersects(geo):
  1990. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1991. shape=geo,
  1992. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1993. face_color=self.app.defaults[
  1994. 'global_sel_draw_color'] + 'AF',
  1995. visible=True)
  1996. self.poly_dict[shape_id] = geo
  1997. added_poly_count += 1
  1998. except TypeError:
  1999. if self.solid_geometry not in self.poly_dict.values():
  2000. if sel_type is True:
  2001. if self.solid_geometry.within(poly_selection):
  2002. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  2003. shape=self.solid_geometry,
  2004. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  2005. face_color=self.app.defaults[
  2006. 'global_sel_draw_color'] + 'AF',
  2007. visible=True)
  2008. self.poly_dict[shape_id] = self.solid_geometry
  2009. added_poly_count += 1
  2010. else:
  2011. if poly_selection.intersects(self.solid_geometry):
  2012. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  2013. shape=self.solid_geometry,
  2014. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  2015. face_color=self.app.defaults[
  2016. 'global_sel_draw_color'] + 'AF',
  2017. visible=True)
  2018. self.poly_dict[shape_id] = self.solid_geometry
  2019. added_poly_count += 1
  2020. if added_poly_count > 0:
  2021. self.app.tool_shapes.redraw()
  2022. self.app.inform.emit(
  2023. '%s: %d. %s' % (_("Added polygon"),
  2024. int(added_poly_count),
  2025. _("Click to add next polygon or right click to start isolation."))
  2026. )
  2027. else:
  2028. self.app.inform.emit(_("No polygon in selection."))
  2029. # To be called after clicking on the plot.
  2030. def on_mouse_release(self, event):
  2031. if self.app.is_legacy is False:
  2032. event_pos = event.pos
  2033. # event_is_dragging = event.is_dragging
  2034. right_button = 2
  2035. else:
  2036. event_pos = (event.xdata, event.ydata)
  2037. # event_is_dragging = self.app.plotcanvas.is_dragging
  2038. right_button = 3
  2039. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  2040. if self.app.grid_status():
  2041. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  2042. else:
  2043. curr_pos = (event_pos[0], event_pos[1])
  2044. x1, y1 = curr_pos[0], curr_pos[1]
  2045. shape_type = self.area_shape_radio.get_value()
  2046. # do clear area only for left mouse clicks
  2047. if event.button == 1:
  2048. if shape_type == "square":
  2049. if self.first_click is False:
  2050. self.first_click = True
  2051. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  2052. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  2053. if self.app.grid_status():
  2054. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  2055. else:
  2056. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  2057. self.app.delete_selection_shape()
  2058. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  2059. pt1 = (x0, y0)
  2060. pt2 = (x1, y0)
  2061. pt3 = (x1, y1)
  2062. pt4 = (x0, y1)
  2063. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  2064. self.sel_rect.append(new_rectangle)
  2065. # add a temporary shape on canvas
  2066. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  2067. self.first_click = False
  2068. return
  2069. else:
  2070. self.points.append((x1, y1))
  2071. if len(self.points) > 1:
  2072. self.poly_drawn = True
  2073. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  2074. return ""
  2075. elif event.button == right_button and self.mouse_is_dragging is False:
  2076. shape_type = self.area_shape_radio.get_value()
  2077. if shape_type == "square":
  2078. self.first_click = False
  2079. else:
  2080. # if we finish to add a polygon
  2081. if self.poly_drawn is True:
  2082. try:
  2083. # try to add the point where we last clicked if it is not already in the self.points
  2084. last_pt = (x1, y1)
  2085. if last_pt != self.points[-1]:
  2086. self.points.append(last_pt)
  2087. except IndexError:
  2088. pass
  2089. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  2090. if len(self.points) > 2:
  2091. self.delete_moving_selection_shape()
  2092. pol = Polygon(self.points)
  2093. # do not add invalid polygons even if they are drawn by utility geometry
  2094. if pol.is_valid:
  2095. self.sel_rect.append(pol)
  2096. self.draw_selection_shape_polygon(points=self.points)
  2097. self.app.inform.emit(
  2098. _("Zone added. Click to start adding next zone or right click to finish."))
  2099. self.points = []
  2100. self.poly_drawn = False
  2101. return
  2102. self.delete_tool_selection_shape()
  2103. if self.app.is_legacy is False:
  2104. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2105. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2106. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2107. else:
  2108. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2109. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2110. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2111. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2112. self.app.on_mouse_click_over_plot)
  2113. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2114. self.app.on_mouse_move_over_plot)
  2115. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2116. self.app.on_mouse_click_release_over_plot)
  2117. if len(self.sel_rect) == 0:
  2118. return
  2119. self.sel_rect = cascaded_union(self.sel_rect)
  2120. self.isolate(isolated_obj=self.grb_obj, limited_area=self.sel_rect, plot=True)
  2121. self.sel_rect = []
  2122. # called on mouse move
  2123. def on_mouse_move(self, event):
  2124. shape_type = self.area_shape_radio.get_value()
  2125. if self.app.is_legacy is False:
  2126. event_pos = event.pos
  2127. event_is_dragging = event.is_dragging
  2128. # right_button = 2
  2129. else:
  2130. event_pos = (event.xdata, event.ydata)
  2131. event_is_dragging = self.app.plotcanvas.is_dragging
  2132. # right_button = 3
  2133. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  2134. # detect mouse dragging motion
  2135. if event_is_dragging is True:
  2136. self.mouse_is_dragging = True
  2137. else:
  2138. self.mouse_is_dragging = False
  2139. # update the cursor position
  2140. if self.app.grid_status():
  2141. # Update cursor
  2142. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  2143. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  2144. symbol='++', edge_color=self.app.cursor_color_3D,
  2145. edge_width=self.app.defaults["global_cursor_width"],
  2146. size=self.app.defaults["global_cursor_size"])
  2147. if self.cursor_pos is None:
  2148. self.cursor_pos = (0, 0)
  2149. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  2150. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  2151. # # update the positions on status bar
  2152. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2153. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  2154. # self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2155. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  2156. units = self.app.defaults["units"].lower()
  2157. self.app.plotcanvas.text_hud.text = \
  2158. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  2159. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  2160. # draw the utility geometry
  2161. if shape_type == "square":
  2162. if self.first_click:
  2163. self.app.delete_selection_shape()
  2164. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  2165. coords=(curr_pos[0], curr_pos[1]))
  2166. else:
  2167. self.delete_moving_selection_shape()
  2168. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  2169. def on_key_press(self, event):
  2170. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  2171. # matplotlib_key_flag = False
  2172. # events out of the self.app.collection view (it's about Project Tab) are of type int
  2173. if type(event) is int:
  2174. key = event
  2175. # events from the GUI are of type QKeyEvent
  2176. elif type(event) == QtGui.QKeyEvent:
  2177. key = event.key()
  2178. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  2179. # matplotlib_key_flag = True
  2180. key = event.key
  2181. key = QtGui.QKeySequence(key)
  2182. # check for modifiers
  2183. key_string = key.toString().lower()
  2184. if '+' in key_string:
  2185. mod, __, key_text = key_string.rpartition('+')
  2186. if mod.lower() == 'ctrl':
  2187. # modifiers = QtCore.Qt.ControlModifier
  2188. pass
  2189. elif mod.lower() == 'alt':
  2190. # modifiers = QtCore.Qt.AltModifier
  2191. pass
  2192. elif mod.lower() == 'shift':
  2193. # modifiers = QtCore.Qt.ShiftModifier
  2194. pass
  2195. else:
  2196. # modifiers = QtCore.Qt.NoModifier
  2197. pass
  2198. key = QtGui.QKeySequence(key_text)
  2199. # events from Vispy are of type KeyEvent
  2200. else:
  2201. key = event.key
  2202. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  2203. if self.app.is_legacy is False:
  2204. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2205. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2206. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2207. else:
  2208. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2209. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2210. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2211. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2212. self.app.on_mouse_click_over_plot)
  2213. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2214. self.app.on_mouse_move_over_plot)
  2215. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2216. self.app.on_mouse_click_release_over_plot)
  2217. self.points = []
  2218. self.poly_drawn = False
  2219. self.delete_moving_selection_shape()
  2220. self.delete_tool_selection_shape()
  2221. @staticmethod
  2222. def poly2rings(poly):
  2223. return [poly.exterior] + [interior for interior in poly.interiors]
  2224. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  2225. """
  2226. Isolation_geometry produces an envelope that is going on the left of the geometry
  2227. (the copper features). To leave the least amount of burrs on the features
  2228. the tool needs to travel on the right side of the features (this is called conventional milling)
  2229. the first pass is the one cutting all of the features, so it needs to be reversed
  2230. the other passes overlap preceding ones and cut the left over copper. It is better for them
  2231. to cut on the right side of the left over copper i.e on the left side of the features.
  2232. :param offset: Offset distance to be passed to the obj.isolation_geometry() method
  2233. :type offset: float
  2234. :param invert: If to invert the direction of geometry (CW to CCW or reverse)
  2235. :type invert: int
  2236. :param geometry: Shapely Geometry for which t ogenerate envelope
  2237. :type geometry:
  2238. :param env_iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  2239. :type env_iso_type: int
  2240. :param follow: If the kind of isolation is a "follow" one
  2241. :type follow: bool
  2242. :param nr_passes: Number of passes
  2243. :type nr_passes: int
  2244. :return: The buffered geometry
  2245. :rtype: MultiPolygon or Polygon
  2246. """
  2247. if follow:
  2248. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, follow=follow)
  2249. return geom
  2250. else:
  2251. try:
  2252. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type,
  2253. passes=nr_passes)
  2254. except Exception as e:
  2255. log.debug('ToolIsolation.generate_envelope() --> %s' % str(e))
  2256. return 'fail'
  2257. if invert:
  2258. try:
  2259. pl = []
  2260. for p in geom:
  2261. if p is not None:
  2262. if isinstance(p, Polygon):
  2263. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2264. elif isinstance(p, LinearRing):
  2265. pl.append(Polygon(p.coords[::-1]))
  2266. geom = MultiPolygon(pl)
  2267. except TypeError:
  2268. if isinstance(geom, Polygon) and geom is not None:
  2269. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2270. elif isinstance(geom, LinearRing) and geom is not None:
  2271. geom = Polygon(geom.coords[::-1])
  2272. else:
  2273. log.debug("ToolIsolation.generate_envelope() Error --> Unexpected Geometry %s" %
  2274. type(geom))
  2275. except Exception as e:
  2276. log.debug("ToolIsolation.generate_envelope() Error --> %s" % str(e))
  2277. return 'fail'
  2278. return geom
  2279. def on_iso_tool_add_from_db_executed(self, tool):
  2280. """
  2281. Here add the tool from DB in the selected geometry object
  2282. :return:
  2283. """
  2284. tool_from_db = deepcopy(tool)
  2285. res = self.on_tool_from_db_inserted(tool=tool_from_db)
  2286. for idx in range(self.app.ui.plot_tab_area.count()):
  2287. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2288. wdg = self.app.ui.plot_tab_area.widget(idx)
  2289. wdg.deleteLater()
  2290. self.app.ui.plot_tab_area.removeTab(idx)
  2291. if res == 'fail':
  2292. return
  2293. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2294. # select last tool added
  2295. toolid = res
  2296. for row in range(self.tools_table.rowCount()):
  2297. if int(self.tools_table.item(row, 3).text()) == toolid:
  2298. self.tools_table.selectRow(row)
  2299. self.on_row_selection_change()
  2300. def on_tool_from_db_inserted(self, tool):
  2301. """
  2302. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2303. :param tool: a dict with the tool data
  2304. :return: None
  2305. """
  2306. self.ui_disconnect()
  2307. self.units = self.app.defaults['units'].upper()
  2308. tooldia = float(tool['tooldia'])
  2309. # construct a list of all 'tooluid' in the self.tools
  2310. tool_uid_list = []
  2311. for tooluid_key in self.iso_tools:
  2312. tool_uid_item = int(tooluid_key)
  2313. tool_uid_list.append(tool_uid_item)
  2314. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2315. if not tool_uid_list:
  2316. max_uid = 0
  2317. else:
  2318. max_uid = max(tool_uid_list)
  2319. tooluid = max_uid + 1
  2320. tooldia = float('%.*f' % (self.decimals, tooldia))
  2321. tool_dias = []
  2322. for k, v in self.iso_tools.items():
  2323. for tool_v in v.keys():
  2324. if tool_v == 'tooldia':
  2325. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2326. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2327. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2328. self.ui_connect()
  2329. return 'fail'
  2330. self.iso_tools.update({
  2331. tooluid: {
  2332. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2333. 'offset': tool['offset'],
  2334. 'offset_value': tool['offset_value'],
  2335. 'type': tool['type'],
  2336. 'tool_type': tool['tool_type'],
  2337. 'data': deepcopy(tool['data']),
  2338. 'solid_geometry': []
  2339. }
  2340. })
  2341. self.iso_tools[tooluid]['data']['name'] = '_ncc'
  2342. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2343. self.ui_connect()
  2344. self.build_ui()
  2345. # if self.tools_table.rowCount() != 0:
  2346. # self.param_frame.setDisabled(False)
  2347. def on_tool_add_from_db_clicked(self):
  2348. """
  2349. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2350. and display the Tools Database tab in the form needed for the Tool adding
  2351. :return: None
  2352. """
  2353. # if the Tools Database is already opened focus on it
  2354. for idx in range(self.app.ui.plot_tab_area.count()):
  2355. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2356. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2357. break
  2358. self.app.on_tools_database(source='iso')
  2359. self.app.tools_db_tab.ok_to_add = True
  2360. self.app.tools_db_tab.buttons_frame.hide()
  2361. self.app.tools_db_tab.add_tool_from_db.show()
  2362. self.app.tools_db_tab.cancel_tool_from_db.show()
  2363. def reset_fields(self):
  2364. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2365. def reset_usage(self):
  2366. self.obj_name = ""
  2367. self.grb_obj = None
  2368. self.first_click = False
  2369. self.cursor_pos = None
  2370. self.mouse_is_dragging = False
  2371. prog_plot = True if self.app.defaults["tools_iso_plotting"] == 'progressive' else False
  2372. if prog_plot:
  2373. self.temp_shapes.clear(update=True)
  2374. self.sel_rect = []