ToolIsolation.py 147 KB

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