ToolIsolation.py 130 KB

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