ToolIsolation.py 153 KB

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