ToolIsolation.py 132 KB

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