ToolIsolation.py 163 KB

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