ToolIsolation.py 155 KB

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