ToolIsolation.py 145 KB

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