ToolIsolation.py 155 KB

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