ToolIsolation.py 146 KB

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