ToolIsolation.py 139 KB

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