ToolIsolation.py 132 KB

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