ToolIsolation.py 157 KB

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