ToolIsolation.py 129 KB

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