ToolIsolation.py 138 KB

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