ToolIsolation.py 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  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, FCButton, \
  10. FCComboBox, OptionalInputSection, FCSpinner, FCLabel, FCInputDialogSpinnerButton, FCComboBox2
  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.search_and_add_btn.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=10000.0000, 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=10000.0000, decimals=self.decimals,
  632. button_icon=btn_icon,
  633. callback=self.on_find_optimal_tooldia,
  634. parent=self.app.ui)
  635. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  636. def find_optimal(valor):
  637. tool_add_popup.set_value(float(valor))
  638. self.optimal_found_sig.connect(find_optimal)
  639. val, ok = tool_add_popup.get_results()
  640. if ok:
  641. if float(val) == 0:
  642. self.app.inform.emit('[WARNING_NOTCL] %s' %
  643. _("Please enter a tool diameter with non-zero value, in Float format."))
  644. self.optimal_found_sig.disconnect(find_optimal)
  645. return
  646. self.on_tool_add(custom_dia=float(val))
  647. else:
  648. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  649. self.optimal_found_sig.disconnect(find_optimal)
  650. def on_reference_combo_changed(self):
  651. obj_type = self.ui.reference_combo_type.currentIndex()
  652. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  653. self.ui.reference_combo.setCurrentIndex(0)
  654. self.ui.reference_combo.obj_type = {0: "Gerber", 1: "Excellon", 2: "Geometry"}[obj_type]
  655. def on_toggle_reference(self):
  656. val = self.ui.select_combo.get_value()
  657. if val == 0: # ALl
  658. self.ui.reference_combo.hide()
  659. self.ui.reference_combo_label.hide()
  660. self.ui.reference_combo_type.hide()
  661. self.ui.reference_combo_type_label.hide()
  662. self.ui.area_shape_label.hide()
  663. self.ui.area_shape_radio.hide()
  664. self.ui.poly_int_cb.hide()
  665. # disable rest-machining for area painting
  666. self.ui.rest_cb.setDisabled(False)
  667. elif val == 1: # Area Selection
  668. self.ui.reference_combo.hide()
  669. self.ui.reference_combo_label.hide()
  670. self.ui.reference_combo_type.hide()
  671. self.ui.reference_combo_type_label.hide()
  672. self.ui.area_shape_label.show()
  673. self.ui.area_shape_radio.show()
  674. self.ui.poly_int_cb.hide()
  675. # disable rest-machining for area isolation
  676. self.ui.rest_cb.set_value(False)
  677. self.ui.rest_cb.setDisabled(True)
  678. elif val == 2: # Polygon Selection
  679. self.ui.reference_combo.hide()
  680. self.ui.reference_combo_label.hide()
  681. self.ui.reference_combo_type.hide()
  682. self.ui.reference_combo_type_label.hide()
  683. self.ui.area_shape_label.hide()
  684. self.ui.area_shape_radio.hide()
  685. self.ui.poly_int_cb.show()
  686. else: # Reference Object
  687. self.ui.reference_combo.show()
  688. self.ui.reference_combo_label.show()
  689. self.ui.reference_combo_type.show()
  690. self.ui.reference_combo_type_label.show()
  691. self.ui.area_shape_label.hide()
  692. self.ui.area_shape_radio.hide()
  693. self.ui.poly_int_cb.hide()
  694. # disable rest-machining for area painting
  695. self.ui.rest_cb.setDisabled(False)
  696. def on_order_changed(self, order):
  697. if order != 'no':
  698. self.build_ui()
  699. def on_rest_machining_check(self, state):
  700. if state:
  701. self.ui.order_radio.set_value('rev')
  702. self.ui.order_label.setDisabled(True)
  703. self.ui.order_radio.setDisabled(True)
  704. self.old_combine_state = self.ui.combine_passes_cb.get_value()
  705. self.ui.combine_passes_cb.set_value(True)
  706. self.ui.combine_passes_cb.setDisabled(True)
  707. self.ui.forced_rest_iso_cb.setDisabled(False)
  708. else:
  709. self.ui.order_label.setDisabled(False)
  710. self.ui.order_radio.setDisabled(False)
  711. self.ui.combine_passes_cb.set_value(self.old_combine_state)
  712. self.ui.combine_passes_cb.setDisabled(False)
  713. self.ui.forced_rest_iso_cb.setDisabled(True)
  714. def on_tooltable_cellwidget_change(self):
  715. cw = self.sender()
  716. assert isinstance(cw, QtWidgets.QComboBox), \
  717. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  718. cw_index = self.ui.tools_table.indexAt(cw.pos())
  719. cw_row = cw_index.row()
  720. cw_col = cw_index.column()
  721. currenuid = int(self.ui.tools_table.item(cw_row, 3).text())
  722. # if the sender is in the column with index 2 then we update the tool_type key
  723. if cw_col == 2:
  724. tt = cw.currentText()
  725. typ = 'Iso' if tt == 'V' else 'Rough'
  726. self.iso_tools[currenuid].update({
  727. 'type': typ,
  728. 'tool_type': tt,
  729. })
  730. def on_find_optimal_tooldia(self):
  731. self.find_safe_tooldia_worker()
  732. @staticmethod
  733. def find_optim_mp(aperture_storage, decimals):
  734. msg = 'ok'
  735. total_geo = []
  736. for ap in list(aperture_storage.keys()):
  737. if 'geometry' in aperture_storage[ap]:
  738. for geo_el in aperture_storage[ap]['geometry']:
  739. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  740. total_geo.append(geo_el['solid'])
  741. total_geo = MultiPolygon(total_geo)
  742. total_geo = total_geo.buffer(0)
  743. try:
  744. __ = iter(total_geo)
  745. geo_len = len(total_geo)
  746. except TypeError:
  747. msg = ('[ERROR_NOTCL] %s' % _("The Gerber object has one Polygon as geometry.\n"
  748. "There are no distances between geometry elements to be found."))
  749. min_dict = {}
  750. idx = 1
  751. for geo in total_geo:
  752. for s_geo in total_geo[idx:]:
  753. # minimize the number of distances by not taking into considerations
  754. # those that are too small
  755. dist = geo.distance(s_geo)
  756. dist = float('%.*f' % (decimals, dist))
  757. loc_1, loc_2 = nearest_points(geo, s_geo)
  758. proc_loc = (
  759. (float('%.*f' % (decimals, loc_1.x)), float('%.*f' % (decimals, loc_1.y))),
  760. (float('%.*f' % (decimals, loc_2.x)), float('%.*f' % (decimals, loc_2.y)))
  761. )
  762. if dist in min_dict:
  763. min_dict[dist].append(proc_loc)
  764. else:
  765. min_dict[dist] = [proc_loc]
  766. idx += 1
  767. min_list = list(min_dict.keys())
  768. min_dist = min(min_list)
  769. return msg, min_dist
  770. # multiprocessing variant
  771. def find_safe_tooldia_multiprocessing(self):
  772. self.app.inform.emit(_("Checking tools for validity."))
  773. self.units = self.app.defaults['units'].upper()
  774. obj_name = self.ui.object_combo.currentText()
  775. # Get source object.
  776. try:
  777. fcobj = self.app.collection.get_by_name(obj_name)
  778. except Exception:
  779. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  780. return
  781. if fcobj is None:
  782. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  783. return
  784. def job_thread(app_obj):
  785. with self.app.proc_container.new(_("Checking ...")):
  786. ap_storage = fcobj.apertures
  787. p = app_obj.pool.apply_async(self.find_optim_mp, args=(ap_storage, self.decimals))
  788. res = p.get()
  789. if res[0] != 'ok':
  790. app_obj.inform.emit(res[0])
  791. return 'fail'
  792. else:
  793. min_dist = res[1]
  794. try:
  795. min_dist_truncated = self.app.dec_format(float(min_dist), self.decimals)
  796. self.safe_tooldia = min_dist_truncated
  797. if self.safe_tooldia:
  798. # find the selected tool ID's
  799. sorted_tools = []
  800. table_items = self.ui.tools_table.selectedItems()
  801. sel_rows = {t.row() for t in table_items}
  802. for row in sel_rows:
  803. tid = int(self.ui.tools_table.item(row, 3).text())
  804. sorted_tools.append(tid)
  805. if not sorted_tools:
  806. msg = _("There are no tools selected in the Tool Table.")
  807. self.app.inform.emit('[ERROR_NOTCL] %s' % msg)
  808. return 'fail'
  809. # check if the tools diameters are less then the safe tool diameter
  810. for tool in sorted_tools:
  811. tool_dia = float(self.iso_tools[tool]['tooldia'])
  812. if tool_dia > self.safe_tooldia:
  813. msg = _("Incomplete isolation. "
  814. "At least one tool could not do a complete isolation.")
  815. self.app.inform.emit('[WARNING] %s' % msg)
  816. break
  817. # reset the value to prepare for another isolation
  818. self.safe_tooldia = None
  819. except Exception as ee:
  820. log.debug(str(ee))
  821. return
  822. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  823. def find_safe_tooldia_worker(self):
  824. self.app.inform.emit(_("Checking tools for validity."))
  825. self.units = self.app.defaults['units'].upper()
  826. obj_name = self.ui.object_combo.currentText()
  827. # Get source object.
  828. try:
  829. fcobj = self.app.collection.get_by_name(obj_name)
  830. except Exception:
  831. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  832. return
  833. if fcobj is None:
  834. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  835. return
  836. def job_thread(app_obj):
  837. with self.app.proc_container.new(_("Checking ...")):
  838. try:
  839. old_disp_number = 0
  840. pol_nr = 0
  841. app_obj.proc_container.update_view_text(' %d%%' % 0)
  842. total_geo = []
  843. for ap in list(fcobj.apertures.keys()):
  844. if 'geometry' in fcobj.apertures[ap]:
  845. for geo_el in fcobj.apertures[ap]['geometry']:
  846. if self.app.abort_flag:
  847. # graceful abort requested by the user
  848. raise grace
  849. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  850. total_geo.append(geo_el['solid'])
  851. total_geo = MultiPolygon(total_geo)
  852. total_geo = total_geo.buffer(0)
  853. try:
  854. __ = iter(total_geo)
  855. geo_len = len(total_geo)
  856. geo_len = (geo_len * (geo_len - 1)) / 2
  857. except TypeError:
  858. msg = _("The Gerber object has one Polygon as geometry.\n"
  859. "There are no distances between geometry elements to be found.")
  860. app_obj.inform.emit('[ERROR_NOTCL] %s' % msg)
  861. return 'fail'
  862. min_dict = {}
  863. idx = 1
  864. for geo in total_geo:
  865. for s_geo in total_geo[idx:]:
  866. if self.app.abort_flag:
  867. # graceful abort requested by the user
  868. raise grace
  869. # minimize the number of distances by not taking into considerations those
  870. # that are too small
  871. dist = geo.distance(s_geo)
  872. dist = float('%.*f' % (self.decimals, dist))
  873. loc_1, loc_2 = nearest_points(geo, s_geo)
  874. proc_loc = (
  875. (float('%.*f' % (self.decimals, loc_1.x)), float('%.*f' % (self.decimals, loc_1.y))),
  876. (float('%.*f' % (self.decimals, loc_2.x)), float('%.*f' % (self.decimals, loc_2.y)))
  877. )
  878. if dist in min_dict:
  879. min_dict[dist].append(proc_loc)
  880. else:
  881. min_dict[dist] = [proc_loc]
  882. pol_nr += 1
  883. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  884. if old_disp_number < disp_number <= 100:
  885. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  886. old_disp_number = disp_number
  887. idx += 1
  888. min_list = list(min_dict.keys())
  889. min_dist = min(min_list)
  890. min_dist_truncated = self.app.dec_format(float(min_dist), self.decimals)
  891. self.safe_tooldia = min_dist_truncated
  892. self.optimal_found_sig.emit(min_dist_truncated)
  893. app_obj.inform.emit('[success] %s: %s %s' %
  894. (_("Optimal tool diameter found"), str(min_dist_truncated),
  895. self.units.lower()))
  896. except Exception as ee:
  897. log.debug(str(ee))
  898. return
  899. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  900. def on_tool_add(self, custom_dia=None):
  901. self.blockSignals(True)
  902. filename = self.app.tools_database_path()
  903. tool_dia = custom_dia if custom_dia is not None else self.ui.new_tooldia_entry.get_value()
  904. # construct a list of all 'tooluid' in the self.iso_tools
  905. tool_uid_list = [int(tooluid_key) for tooluid_key in self.iso_tools]
  906. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  907. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  908. tooluid = int(max_uid) + 1
  909. new_tools_dict = deepcopy(self.default_data)
  910. updated_tooldia = None
  911. tool_dias = []
  912. for k, v in self.iso_tools.items():
  913. for tool_v in v.keys():
  914. if tool_v == 'tooldia':
  915. tool_dias.append(self.app.dec_format(v['tooldia'], self.decimals))
  916. # determine the new tool diameter
  917. if tool_dia is None or tool_dia == 0:
  918. self.build_ui()
  919. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  920. "in Float format."))
  921. self.blockSignals(False)
  922. return
  923. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  924. # if new tool diameter already in the Tool List then abort
  925. if truncated_tooldia in tool_dias:
  926. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  927. self.blockSignals(False)
  928. return
  929. # load the database tools from the file
  930. try:
  931. with open(filename) as f:
  932. tools = f.read()
  933. except IOError:
  934. self.app.log.error("Could not load tools DB file.")
  935. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  936. self.blockSignals(False)
  937. self.on_tool_default_add(dia=tool_dia)
  938. return
  939. try:
  940. # store here the tools from Tools Database when searching in Tools Database
  941. tools_db_dict = json.loads(tools)
  942. except Exception:
  943. e = sys.exc_info()[0]
  944. self.app.log.error(str(e))
  945. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  946. self.blockSignals(False)
  947. self.on_tool_default_add(dia=tool_dia)
  948. return
  949. tool_found = 0
  950. offset = 'Path'
  951. offset_val = 0.0
  952. typ = 'Rough'
  953. tool_type = 'V'
  954. # look in database tools
  955. for db_tool, db_tool_val in tools_db_dict.items():
  956. offset = db_tool_val['offset']
  957. offset_val = db_tool_val['offset_value']
  958. typ = db_tool_val['type']
  959. tool_type = db_tool_val['tool_type']
  960. db_tooldia = db_tool_val['tooldia']
  961. low_limit = float(db_tool_val['data']['tol_min'])
  962. high_limit = float(db_tool_val['data']['tol_max'])
  963. # we need only tool marked for Isolation Tool
  964. if db_tool_val['data']['tool_target'] != 3: # _('Isolation')
  965. continue
  966. # if we find a tool with the same diameter in the Tools DB just update it's data
  967. if truncated_tooldia == db_tooldia:
  968. tool_found += 1
  969. for d in db_tool_val['data']:
  970. if d.find('tools_iso') == 0:
  971. new_tools_dict[d] = db_tool_val['data'][d]
  972. elif d.find('tools_') == 0:
  973. # don't need data for other App Tools; this tests after 'tools_drill_'
  974. continue
  975. else:
  976. new_tools_dict[d] = db_tool_val['data'][d]
  977. # search for a tool that has a tolerance that the tool fits in
  978. elif high_limit >= truncated_tooldia >= low_limit:
  979. tool_found += 1
  980. updated_tooldia = db_tooldia
  981. for d in db_tool_val['data']:
  982. if d.find('tools_iso') == 0:
  983. new_tools_dict[d] = db_tool_val['data'][d]
  984. elif d.find('tools_') == 0:
  985. # don't need data for other App Tools; this tests after 'tools_drill_'
  986. continue
  987. else:
  988. new_tools_dict[d] = db_tool_val['data'][d]
  989. # test we found a suitable tool in Tools Database or if multiple ones
  990. if tool_found == 0:
  991. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Tool not in Tools Database. Adding a default tool."))
  992. self.on_tool_default_add(dia=tool_dia)
  993. self.blockSignals(False)
  994. return
  995. if tool_found > 1:
  996. self.app.inform.emit(
  997. '[WARNING_NOTCL] %s' % _("Cancelled.\n"
  998. "Multiple tools for one tool diameter found in Tools Database."))
  999. self.blockSignals(False)
  1000. return
  1001. # if new tool diameter found in Tools Database already in the Tool List then abort
  1002. if updated_tooldia is not None and updated_tooldia in tool_dias:
  1003. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1004. self.blockSignals(False)
  1005. return
  1006. new_tdia = deepcopy(updated_tooldia) if updated_tooldia is not None else deepcopy(truncated_tooldia)
  1007. self.iso_tools.update({
  1008. tooluid: {
  1009. 'tooldia': new_tdia,
  1010. 'offset': deepcopy(offset),
  1011. 'offset_value': deepcopy(offset_val),
  1012. 'type': deepcopy(typ),
  1013. 'tool_type': deepcopy(tool_type),
  1014. 'data': deepcopy(new_tools_dict),
  1015. 'solid_geometry': []
  1016. }
  1017. })
  1018. self.blockSignals(False)
  1019. self.build_ui()
  1020. # select the tool just added
  1021. for row in range(self.ui.tools_table.rowCount()):
  1022. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  1023. self.ui.tools_table.selectRow(row)
  1024. break
  1025. # update the UI form
  1026. self.update_ui()
  1027. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table from Tools Database."))
  1028. def on_tool_default_add(self, dia=None, muted=None):
  1029. self.blockSignals(True)
  1030. tool_dia = dia if dia is not None else self.ui.new_tooldia_entry.get_value()
  1031. if tool_dia is None or tool_dia == 0:
  1032. self.build_ui()
  1033. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1034. "in Float format."))
  1035. self.blockSignals(False)
  1036. return
  1037. # construct a list of all 'tooluid' in the self.iso_tools
  1038. tool_uid_list = [int(tooluid_key) for tooluid_key in self.iso_tools]
  1039. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1040. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  1041. self.tooluid = int(max_uid + 1)
  1042. tool_dias = []
  1043. for k, v in self.iso_tools.items():
  1044. for tool_v in v.keys():
  1045. if tool_v == 'tooldia':
  1046. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  1047. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  1048. if truncated_tooldia in tool_dias:
  1049. if muted is None:
  1050. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1051. # self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  1052. self.blockSignals(False)
  1053. return
  1054. self.iso_tools.update({
  1055. int(self.tooluid): {
  1056. 'tooldia': truncated_tooldia,
  1057. 'offset': 'Path',
  1058. 'offset_value': 0.0,
  1059. 'type': ' Iso',
  1060. 'tool_type': 'V',
  1061. 'data': deepcopy(self.default_data),
  1062. 'solid_geometry': []
  1063. }
  1064. })
  1065. self.blockSignals(False)
  1066. self.build_ui()
  1067. # select the tool just added
  1068. for row in range(self.ui.tools_table.rowCount()):
  1069. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  1070. self.ui.tools_table.selectRow(row)
  1071. break
  1072. # update the UI form
  1073. self.update_ui()
  1074. if muted is None:
  1075. self.app.inform.emit('[success] %s' % _("Default tool added to Tool Table."))
  1076. def on_tool_edit(self, item):
  1077. self.blockSignals(True)
  1078. edited_row = item.row()
  1079. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  1080. tool_dias = []
  1081. try:
  1082. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  1083. except ValueError:
  1084. # try to convert comma to decimal point. if it's still not working error message and return
  1085. try:
  1086. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  1087. except ValueError:
  1088. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1089. self.blockSignals(False)
  1090. return
  1091. for v in self.iso_tools.values():
  1092. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  1093. # identify the tool that was edited and get it's tooluid
  1094. if new_tool_dia not in tool_dias:
  1095. self.iso_tools[editeduid]['tooldia'] = deepcopy(float('%.*f' % (self.decimals, new_tool_dia)))
  1096. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1097. self.blockSignals(False)
  1098. self.build_ui()
  1099. return
  1100. # identify the old tool_dia and restore the text in tool table
  1101. for k, v in self.iso_tools.items():
  1102. if k == editeduid:
  1103. old_tool_dia = v['tooldia']
  1104. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  1105. restore_dia_item.setText(str(old_tool_dia))
  1106. break
  1107. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  1108. self.blockSignals(False)
  1109. self.build_ui()
  1110. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1111. """
  1112. Will delete a tool in the tool table
  1113. :param rows_to_delete: which rows to delete; can be a list
  1114. :param all_tools: delete all tools in the tool table
  1115. :return:
  1116. """
  1117. self.blockSignals(True)
  1118. deleted_tools_list = []
  1119. if all_tools:
  1120. self.iso_tools.clear()
  1121. self.blockSignals(False)
  1122. self.build_ui()
  1123. return
  1124. if rows_to_delete:
  1125. try:
  1126. for row in rows_to_delete:
  1127. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  1128. deleted_tools_list.append(tooluid_del)
  1129. except TypeError:
  1130. tooluid_del = int(self.ui.tools_table.item(rows_to_delete, 3).text())
  1131. deleted_tools_list.append(tooluid_del)
  1132. for t in deleted_tools_list:
  1133. self.iso_tools.pop(t, None)
  1134. self.blockSignals(False)
  1135. self.build_ui()
  1136. return
  1137. try:
  1138. if self.ui.tools_table.selectedItems():
  1139. for row_sel in self.ui.tools_table.selectedItems():
  1140. row = row_sel.row()
  1141. if row < 0:
  1142. continue
  1143. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  1144. deleted_tools_list.append(tooluid_del)
  1145. for t in deleted_tools_list:
  1146. self.iso_tools.pop(t, None)
  1147. except AttributeError:
  1148. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1149. self.blockSignals(False)
  1150. return
  1151. except Exception as e:
  1152. log.debug(str(e))
  1153. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1154. self.blockSignals(False)
  1155. self.build_ui()
  1156. def on_generate_buffer(self):
  1157. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  1158. self.obj_name = self.ui.object_combo.currentText()
  1159. # Get source object.
  1160. try:
  1161. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1162. except Exception as e:
  1163. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1164. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1165. if self.grb_obj is None:
  1166. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1167. return
  1168. def buffer_task(app_obj):
  1169. with app_obj.proc_container.new('%s...' % _("Buffering")):
  1170. if isinstance(self.grb_obj.solid_geometry, list):
  1171. self.grb_obj.solid_geometry = MultiPolygon(self.grb_obj.solid_geometry)
  1172. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(0.0000001)
  1173. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(-0.0000001)
  1174. app_obj.inform.emit('[success] %s.' % _("Done"))
  1175. self.grb_obj.plot_single_object.emit()
  1176. self.app.worker_task.emit({'fcn': buffer_task, 'params': [self.app]})
  1177. def on_iso_button_click(self):
  1178. self.obj_name = self.ui.object_combo.currentText()
  1179. # Get source object.
  1180. try:
  1181. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1182. except Exception:
  1183. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1184. return
  1185. if self.grb_obj is None:
  1186. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1187. return
  1188. if self.ui.valid_cb.get_value() is True:
  1189. self.find_safe_tooldia_multiprocessing()
  1190. def worker_task(iso_obj):
  1191. with self.app.proc_container.new(_("Isolating ...")):
  1192. self.isolate_handler(iso_obj)
  1193. self.app.worker_task.emit({'fcn': worker_task, 'params': [self.grb_obj]})
  1194. def follow_geo(self, followed_obj, outname):
  1195. """
  1196. Creates a geometry object "following" the gerber paths.
  1197. :param followed_obj: Gerber object for which to generate the follow geometry
  1198. :type followed_obj: AppObjects.FlatCAMGerber.GerberObject
  1199. :param outname: Nme of the resulting Geometry object
  1200. :type outname: str
  1201. :return: None
  1202. """
  1203. def follow_init(follow_obj, app_obj):
  1204. # Propagate options
  1205. follow_obj.options["cnctooldia"] = str(tooldia)
  1206. follow_obj.solid_geometry = self.grb_obj.follow_geometry
  1207. app_obj.inform.emit('[success] %s.' % _("Following geometry was generated"))
  1208. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  1209. followed_obj.ui.plot_cb.set_value(False)
  1210. follow_name = outname
  1211. for tool in self.iso_tools:
  1212. tooldia = self.iso_tools[tool]['tooldia']
  1213. new_name = "%s_%.*f" % (follow_name, self.decimals, tooldia)
  1214. follow_state = self.iso_tools[tool]['data']['tools_iso_follow']
  1215. if follow_state:
  1216. ret = self.app.app_obj.new_object("geometry", new_name, follow_init)
  1217. if ret == 'fail':
  1218. self.app.inform.emit("[ERROR_NOTCL] %s: %.*f" % (
  1219. _("Failed to create Follow Geometry with tool diameter"), self.decimals, tooldia))
  1220. else:
  1221. self.app.inform.emit("[success] %s: %.*f" % (
  1222. _("Follow Geometry was created with tool diameter"), self.decimals, tooldia))
  1223. def isolate_handler(self, isolated_obj):
  1224. """
  1225. Creates a geometry object with paths around the gerber features.
  1226. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1227. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1228. :return: None
  1229. """
  1230. selection = self.ui.select_combo.get_value()
  1231. if selection == 0: # ALL
  1232. self.isolate(isolated_obj=isolated_obj)
  1233. elif selection == 1: # Area Selection
  1234. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1235. if self.app.is_legacy is False:
  1236. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1237. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1238. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1239. else:
  1240. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1241. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1242. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1243. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1244. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1245. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1246. # disconnect flags
  1247. self.area_sel_disconnect_flag = True
  1248. elif selection == 2: # Polygon Selection
  1249. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1250. if self.app.ui.grid_snap_btn.isChecked():
  1251. self.grid_status_memory = True
  1252. self.app.ui.grid_snap_btn.trigger()
  1253. else:
  1254. self.grid_status_memory = False
  1255. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  1256. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_poly_mouse_click_release)
  1257. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1258. if self.app.is_legacy is False:
  1259. self.app.plotcanvas.graph_event_disconnect('mouse_release',
  1260. self.app.on_mouse_click_release_over_plot)
  1261. else:
  1262. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1263. # disconnect flags
  1264. self.poly_sel_disconnect_flag = True
  1265. elif selection == 3: # Reference Object
  1266. ref_obj = self.app.collection.get_by_name(self.ui.reference_combo.get_value())
  1267. ref_geo = unary_union(ref_obj.solid_geometry)
  1268. use_geo = unary_union(isolated_obj.solid_geometry).difference(ref_geo)
  1269. self.isolate(isolated_obj=isolated_obj, geometry=use_geo)
  1270. def isolate(self, isolated_obj, geometry=None, limited_area=None, negative_dia=None, plot=True):
  1271. """
  1272. Creates an isolation routing geometry object in the project.
  1273. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1274. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1275. :param geometry: specific geometry to isolate
  1276. :type geometry: List of Shapely polygon
  1277. :param limited_area: if not None isolate only this area
  1278. :type limited_area: Shapely Polygon or a list of them
  1279. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1280. :type negative_dia: bool
  1281. :param plot: if to plot the resulting geometry object
  1282. :type plot: bool
  1283. :return: None
  1284. """
  1285. combine = self.ui.combine_passes_cb.get_value()
  1286. tools_storage = self.iso_tools
  1287. sorted_tools = []
  1288. table_items = self.ui.tools_table.selectedItems()
  1289. sel_rows = {t.row() for t in table_items}
  1290. for row in sel_rows:
  1291. tid = int(self.ui.tools_table.item(row, 3).text())
  1292. sorted_tools.append(tid)
  1293. if not sorted_tools:
  1294. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  1295. return 'fail'
  1296. # update the Common Parameters values in the self.iso_tools
  1297. for tool_iso in self.iso_tools:
  1298. for key in self.iso_tools[tool_iso]:
  1299. if key == 'data':
  1300. self.iso_tools[tool_iso][key]["tools_iso_rest"] = self.ui.rest_cb.get_value()
  1301. self.iso_tools[tool_iso][key]["tools_iso_combine_passes"] = combine
  1302. self.iso_tools[tool_iso][key]["tools_iso_isoexcept"] = self.ui.except_cb.get_value()
  1303. self.iso_tools[tool_iso][key]["tools_iso_selection"] = self.ui.select_combo.get_value()
  1304. self.iso_tools[tool_iso][key]["tools_iso_area_shape"] = self.ui.area_shape_radio.get_value()
  1305. if combine:
  1306. if self.ui.rest_cb.get_value():
  1307. self.combined_rest(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1308. lim_area=limited_area, negative_dia=negative_dia, plot=plot)
  1309. else:
  1310. self.combined_normal(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1311. lim_area=limited_area, negative_dia=negative_dia, plot=plot)
  1312. else:
  1313. prog_plot = self.app.defaults["tools_iso_plotting"]
  1314. for tool in sorted_tools:
  1315. tool_data = tools_storage[tool]['data']
  1316. to_follow = tool_data['tools_iso_follow']
  1317. work_geo = geometry
  1318. if work_geo is None:
  1319. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1320. iso_t = {
  1321. 'ext': 0,
  1322. 'int': 1,
  1323. 'full': 2
  1324. }[tool_data['tools_iso_isotype']]
  1325. passes = tool_data['tools_iso_passes']
  1326. overlap = tool_data['tools_iso_overlap']
  1327. overlap /= 100.0
  1328. milling_type = tool_data['tools_iso_milling_type']
  1329. iso_except = self.ui.except_cb.get_value()
  1330. for i in range(passes):
  1331. tool_dia = tools_storage[tool]['tooldia']
  1332. tool_type = tools_storage[tool]['tool_type']
  1333. iso_offset = tool_dia * ((2 * i + 1) / 2.0000001) - (i * overlap * tool_dia)
  1334. if negative_dia:
  1335. iso_offset = -iso_offset
  1336. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1337. if passes > 1:
  1338. iso_name = outname + "_iso" + str(i + 1)
  1339. if iso_t == 0:
  1340. iso_name = outname + "_ext_iso" + str(i + 1)
  1341. elif iso_t == 1:
  1342. iso_name = outname + "_int_iso" + str(i + 1)
  1343. else:
  1344. iso_name = outname + "_iso"
  1345. if iso_t == 0:
  1346. iso_name = outname + "_ext_iso"
  1347. elif iso_t == 1:
  1348. iso_name = outname + "_int_iso"
  1349. # if milling type is climb then the move is counter-clockwise around features
  1350. mill_dir = 1 if milling_type == 'cl' else 0
  1351. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1352. follow=to_follow, nr_passes=i, prog_plot=prog_plot)
  1353. if iso_geo == 'fail':
  1354. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1355. continue
  1356. # ############################################################
  1357. # ########## AREA SUBTRACTION ################################
  1358. # ############################################################
  1359. if iso_except:
  1360. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1361. iso_geo = self.area_subtraction(iso_geo)
  1362. if limited_area:
  1363. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1364. iso_geo = self.area_intersection(iso_geo, intersection_geo=limited_area)
  1365. # make sure that no empty geometry element is in the solid_geometry
  1366. new_solid_geo = [geo for geo in iso_geo if not geo.is_empty]
  1367. tool_data.update({
  1368. "name": iso_name,
  1369. })
  1370. def iso_init(geo_obj, fc_obj):
  1371. # Propagate options
  1372. geo_obj.options["cnctooldia"] = str(tool_dia)
  1373. geo_obj.solid_geometry = deepcopy(new_solid_geo)
  1374. # ############################################################
  1375. # ########## AREA SUBTRACTION ################################
  1376. # ############################################################
  1377. if self.ui.except_cb.get_value():
  1378. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1379. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1380. geo_obj.tools = {'1': {}}
  1381. geo_obj.tools.update({
  1382. '1': {
  1383. 'tooldia': float(tool_dia),
  1384. 'offset': 'Path',
  1385. 'offset_value': 0.0,
  1386. 'type': 'Rough',
  1387. 'tool_type': tool_type,
  1388. 'data': tool_data,
  1389. 'solid_geometry': geo_obj.solid_geometry
  1390. }
  1391. })
  1392. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1393. # or just looking in the lists (they are one level depth) and if any is not empty
  1394. # proceed with object creation, if there are empty and the number of them is the length
  1395. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1396. empty_cnt = 0
  1397. if not isinstance(geo_obj.solid_geometry, list):
  1398. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1399. for g in geo_obj.solid_geometry:
  1400. if g:
  1401. break
  1402. else:
  1403. empty_cnt += 1
  1404. if empty_cnt == len(geo_obj.solid_geometry):
  1405. fc_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1406. _("Empty Geometry in"), geo_obj.options["name"]))
  1407. return 'fail'
  1408. else:
  1409. fc_obj.inform.emit('[success] %s: %s' %
  1410. (_("Isolation geometry created"), geo_obj.options["name"]))
  1411. geo_obj.multigeo = True
  1412. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1413. # clean the progressive plotted shapes if it was used
  1414. if prog_plot == 'progressive':
  1415. self.temp_shapes.clear(update=True)
  1416. # Switch notebook to Properties page
  1417. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  1418. def combined_rest(self, iso_obj, iso2geo, tools_storage, lim_area, negative_dia=None, plot=True):
  1419. """
  1420. Isolate the provided Gerber object using "rest machining" strategy
  1421. :param iso_obj: the isolated Gerber object
  1422. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1423. :param iso2geo: specific geometry to isolate
  1424. :type iso2geo: list of Shapely Polygon
  1425. :param tools_storage: a dictionary that holds the tools and geometry
  1426. :type tools_storage: dict
  1427. :param lim_area: if not None restrict isolation to this area
  1428. :type lim_area: Shapely Polygon or a list of them
  1429. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1430. :type negative_dia: bool
  1431. :param plot: if to plot the resulting geometry object
  1432. :type plot: bool
  1433. :return: Isolated solid geometry
  1434. :rtype:
  1435. """
  1436. log.debug("ToolIsolation.combine_rest()")
  1437. total_solid_geometry = []
  1438. iso_name = iso_obj.options["name"] + '_iso_rest'
  1439. work_geo = iso_obj.solid_geometry if iso2geo is None else iso2geo
  1440. # sorted_tools = []
  1441. # for k, v in self.iso_tools.items():
  1442. # sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  1443. sorted_tools = []
  1444. table_items = self.ui.tools_table.selectedItems()
  1445. sel_rows = {t.row() for t in table_items}
  1446. for row in sel_rows:
  1447. try:
  1448. tdia = float(self.ui.tools_table.item(row, 1).text())
  1449. except ValueError:
  1450. # try to convert comma to decimal point. if it's still not working error message and return
  1451. try:
  1452. tdia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  1453. except ValueError:
  1454. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1455. continue
  1456. sorted_tools.append(float('%.*f' % (self.decimals, tdia)))
  1457. if not sorted_tools:
  1458. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  1459. return 'fail'
  1460. order = self.ui.order_radio.get_value()
  1461. if order == 'fwd':
  1462. sorted_tools.sort(reverse=False)
  1463. elif order == 'rev':
  1464. sorted_tools.sort(reverse=True)
  1465. else:
  1466. pass
  1467. # decide to use "progressive" or "normal" plotting
  1468. prog_plot = self.app.defaults["tools_iso_plotting"]
  1469. for sorted_tool in sorted_tools:
  1470. for tool in tools_storage:
  1471. if float('%.*f' % (self.decimals, tools_storage[tool]['tooldia'])) == sorted_tool:
  1472. tool_dia = tools_storage[tool]['tooldia']
  1473. tool_type = tools_storage[tool]['tool_type']
  1474. tool_data = tools_storage[tool]['data']
  1475. passes = tool_data['tools_iso_passes']
  1476. overlap = tool_data['tools_iso_overlap']
  1477. overlap /= 100.0
  1478. milling_type = tool_data['tools_iso_milling_type']
  1479. # if milling type is climb then the move is counter-clockwise around features
  1480. mill_dir = True if milling_type == 'cl' else False
  1481. iso_t = {
  1482. 'ext': 0,
  1483. 'int': 1,
  1484. 'full': 2
  1485. }[tool_data['tools_iso_isotype']]
  1486. forced_rest = self.ui.forced_rest_iso_cb.get_value()
  1487. iso_except = self.ui.except_cb.get_value()
  1488. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1489. internal_name = outname + "_iso"
  1490. if iso_t == 0:
  1491. internal_name = outname + "_ext_iso"
  1492. elif iso_t == 1:
  1493. internal_name = outname + "_int_iso"
  1494. tool_data.update({
  1495. "name": internal_name,
  1496. })
  1497. solid_geo, work_geo = self.generate_rest_geometry(geometry=work_geo, tooldia=tool_dia,
  1498. passes=passes, overlap=overlap, invert=mill_dir,
  1499. env_iso_type=iso_t, negative_dia=negative_dia,
  1500. forced_rest=forced_rest,
  1501. prog_plot=prog_plot,
  1502. prog_plot_handler=self.plot_temp_shapes)
  1503. # ############################################################
  1504. # ########## AREA SUBTRACTION ################################
  1505. # ############################################################
  1506. if iso_except:
  1507. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1508. solid_geo = self.area_subtraction(solid_geo)
  1509. if lim_area:
  1510. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1511. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1512. # make sure that no empty geometry element is in the solid_geometry
  1513. new_solid_geo = [geo for geo in solid_geo if not geo.is_empty]
  1514. tools_storage.update({
  1515. tool: {
  1516. 'tooldia': float(tool_dia),
  1517. 'offset': 'Path',
  1518. 'offset_value': 0.0,
  1519. 'type': 'Rough',
  1520. 'tool_type': tool_type,
  1521. 'data': tool_data,
  1522. 'solid_geometry': deepcopy(new_solid_geo)
  1523. }
  1524. })
  1525. total_solid_geometry += new_solid_geo
  1526. # if the geometry is all isolated
  1527. if not work_geo:
  1528. break
  1529. # clean the progressive plotted shapes if it was used
  1530. if self.app.defaults["tools_iso_plotting"] == 'progressive':
  1531. self.temp_shapes.clear(update=True)
  1532. # remove tools without geometry
  1533. for tool, tool_dict in list(tools_storage.items()):
  1534. if not tool_dict['solid_geometry']:
  1535. tools_storage.pop(tool, None)
  1536. def iso_init(geo_obj, app_obj):
  1537. geo_obj.options["cnctooldia"] = str(tool_dia)
  1538. geo_obj.tools = dict(tools_storage)
  1539. geo_obj.solid_geometry = total_solid_geometry
  1540. # even if combine is checked, one pass is still single-geo
  1541. # remove the tools that have no geometry
  1542. for geo_tool in list(geo_obj.tools.keys()):
  1543. if not geo_obj.tools[geo_tool]['solid_geometry']:
  1544. geo_obj.tools.pop(geo_tool, None)
  1545. if len(tools_storage) > 1:
  1546. geo_obj.multigeo = True
  1547. else:
  1548. for ky in tools_storage.keys():
  1549. passes_no = float(tools_storage[ky]['data']['tools_iso_passes'])
  1550. geo_obj.multigeo = True
  1551. break
  1552. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1553. # or just looking in the lists (they are one level depth) and if any is not empty
  1554. # proceed with object creation, if there are empty and the number of them is the length
  1555. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1556. empty_cnt = 0
  1557. if not isinstance(geo_obj.solid_geometry, list) and \
  1558. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1559. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1560. for g in geo_obj.solid_geometry:
  1561. if g:
  1562. break
  1563. else:
  1564. empty_cnt += 1
  1565. if empty_cnt == len(geo_obj.solid_geometry):
  1566. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1567. return 'fail'
  1568. else:
  1569. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1570. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1571. # the tools are finished but the isolation is not finished therefore it failed
  1572. if work_geo:
  1573. self.app.inform.emit("[WARNING] %s" % _("Partial failure. The geometry was processed with all tools.\n"
  1574. "But there are still not-isolated geometry elements. "
  1575. "Try to include a tool with smaller diameter."))
  1576. msg = _("The following are coordinates for the copper features that could not be isolated:")
  1577. self.app.inform_shell.emit(msg)
  1578. msg = ''
  1579. for geo in work_geo:
  1580. pt = geo.representative_point()
  1581. coords = '(%s, %s), ' % (str(pt.x), str(pt.y))
  1582. msg += coords
  1583. self.app.inform_shell.emit(msg=msg)
  1584. def combined_normal(self, iso_obj, iso2geo, tools_storage, lim_area, negative_dia=None, plot=True):
  1585. """
  1586. :param iso_obj: the isolated Gerber object
  1587. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1588. :param iso2geo: specific geometry to isolate
  1589. :type iso2geo: list of Shapely Polygon
  1590. :param tools_storage: a dictionary that holds the tools and geometry
  1591. :type tools_storage: dict
  1592. :param lim_area: if not None restrict isolation to this area
  1593. :type lim_area: Shapely Polygon or a list of them
  1594. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1595. :type negative_dia: bool
  1596. :param plot: if to plot the resulting geometry object
  1597. :type plot: bool
  1598. :return: Isolated solid geometry
  1599. :rtype:
  1600. """
  1601. log.debug("ToolIsolation.combined_normal()")
  1602. total_solid_geometry = []
  1603. iso_name = iso_obj.options["name"] + '_iso_combined'
  1604. geometry = iso2geo
  1605. prog_plot = self.app.defaults["tools_iso_plotting"]
  1606. sorted_tools = []
  1607. table_items = self.ui.tools_table.selectedItems()
  1608. sel_rows = {t.row() for t in table_items}
  1609. for row in sel_rows:
  1610. tid = int(self.ui.tools_table.item(row, 3).text())
  1611. sorted_tools.append(tid)
  1612. if not sorted_tools:
  1613. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  1614. return 'fail'
  1615. for tool in sorted_tools:
  1616. tool_dia = tools_storage[tool]['tooldia']
  1617. tool_has_offset = tools_storage[tool]['offset']
  1618. tool_offset_value = tools_storage[tool]['offset_value']
  1619. tool_type = tools_storage[tool]['tool_type']
  1620. tool_cut_type = tools_storage[tool]['type']
  1621. tool_data = tools_storage[tool]['data']
  1622. to_follow = tool_data['tools_iso_follow']
  1623. # TODO what to do when the iso2geo param is not None but the Follow cb is checked
  1624. # for the case when limited area is used .... the follow geo should be clipped too
  1625. work_geo = geometry
  1626. if work_geo is None:
  1627. work_geo = iso_obj.follow_geometry if to_follow else iso_obj.solid_geometry
  1628. iso_t = {
  1629. 'ext': 0,
  1630. 'int': 1,
  1631. 'full': 2
  1632. }[tool_data['tools_iso_isotype']]
  1633. passes = tool_data['tools_iso_passes']
  1634. overlap = tool_data['tools_iso_overlap']
  1635. overlap /= 100.0
  1636. milling_type = tool_data['tools_iso_milling_type']
  1637. iso_except = self.ui.except_cb.get_value()
  1638. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1639. internal_name = outname + "_iso"
  1640. if iso_t == 0:
  1641. internal_name = outname + "_ext_iso"
  1642. elif iso_t == 1:
  1643. internal_name = outname + "_int_iso"
  1644. tool_data.update({
  1645. "name": internal_name,
  1646. })
  1647. solid_geo = []
  1648. for nr_pass in range(passes):
  1649. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1650. if negative_dia:
  1651. iso_offset = -iso_offset
  1652. # if milling type is climb then the move is counter-clockwise around features
  1653. mill_dir = 1 if milling_type == 'cl' else 0
  1654. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1655. follow=to_follow, nr_passes=nr_pass, prog_plot=prog_plot)
  1656. if iso_geo == 'fail':
  1657. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1658. continue
  1659. try:
  1660. for geo in iso_geo:
  1661. solid_geo.append(geo)
  1662. except TypeError:
  1663. solid_geo.append(iso_geo)
  1664. # ############################################################
  1665. # ########## AREA SUBTRACTION ################################
  1666. # ############################################################
  1667. if iso_except:
  1668. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1669. solid_geo = self.area_subtraction(solid_geo)
  1670. if lim_area:
  1671. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1672. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1673. # make sure that no empty geometry element is in the solid_geometry
  1674. new_solid_geo = [geo for geo in solid_geo if not geo.is_empty]
  1675. tools_storage.update({
  1676. tool: {
  1677. 'tooldia': float(tool_dia),
  1678. 'offset': tool_has_offset,
  1679. 'offset_value': tool_offset_value,
  1680. 'type': tool_cut_type,
  1681. 'tool_type': tool_type,
  1682. 'data': tool_data,
  1683. 'solid_geometry': deepcopy(new_solid_geo)
  1684. }
  1685. })
  1686. total_solid_geometry += new_solid_geo
  1687. # clean the progressive plotted shapes if it was used
  1688. if prog_plot == 'progressive':
  1689. self.temp_shapes.clear(update=True)
  1690. # remove tools without geometry
  1691. for tool, tool_dict in list(tools_storage.items()):
  1692. if not tool_dict['solid_geometry']:
  1693. tools_storage.pop(tool, None)
  1694. def iso_init(geo_obj, app_obj):
  1695. geo_obj.options["cnctooldia"] = str(tool_dia)
  1696. geo_obj.tools = dict(tools_storage)
  1697. geo_obj.solid_geometry = total_solid_geometry
  1698. # even if combine is checked, one pass is still single-geo
  1699. if len(tools_storage) > 1:
  1700. geo_obj.multigeo = True
  1701. else:
  1702. if to_follow:
  1703. geo_obj.multigeo = False
  1704. else:
  1705. passes_no = 1
  1706. for ky in tools_storage.keys():
  1707. passes_no = float(tools_storage[ky]['data']['tools_iso_passes'])
  1708. geo_obj.multigeo = True
  1709. break
  1710. geo_obj.multigeo = True
  1711. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1712. # or just looking in the lists (they are one level depth) and if any is not empty
  1713. # proceed with object creation, if there are empty and the number of them is the length
  1714. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1715. empty_cnt = 0
  1716. if not isinstance(geo_obj.solid_geometry, list) and \
  1717. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1718. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1719. for g in geo_obj.solid_geometry:
  1720. if g:
  1721. break
  1722. else:
  1723. empty_cnt += 1
  1724. if empty_cnt == len(geo_obj.solid_geometry):
  1725. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1726. return 'fail'
  1727. else:
  1728. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1729. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1730. def area_subtraction(self, geo, subtraction_geo=None):
  1731. """
  1732. Subtracts the subtraction_geo (if present else self.solid_geometry) from the geo
  1733. :param geo: target geometry from which to subtract
  1734. :param subtraction_geo: geometry that acts as subtraction geo
  1735. :return:
  1736. """
  1737. new_geometry = []
  1738. target_geo = geo
  1739. if subtraction_geo:
  1740. sub_union = unary_union(subtraction_geo)
  1741. else:
  1742. name = self.ui.exc_obj_combo.currentText()
  1743. subtractor_obj = self.app.collection.get_by_name(name)
  1744. sub_union = unary_union(subtractor_obj.solid_geometry)
  1745. try:
  1746. for geo_elem in target_geo:
  1747. if isinstance(geo_elem, Polygon):
  1748. for ring in self.poly2rings(geo_elem):
  1749. new_geo = ring.difference(sub_union)
  1750. if new_geo and not new_geo.is_empty:
  1751. new_geometry.append(new_geo)
  1752. elif isinstance(geo_elem, MultiPolygon):
  1753. for poly in geo_elem:
  1754. for ring in self.poly2rings(poly):
  1755. new_geo = ring.difference(sub_union)
  1756. if new_geo and not new_geo.is_empty:
  1757. new_geometry.append(new_geo)
  1758. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1759. new_geo = geo_elem.difference(sub_union)
  1760. if new_geo:
  1761. if not new_geo.is_empty:
  1762. new_geometry.append(new_geo)
  1763. elif isinstance(geo_elem, MultiLineString):
  1764. for line_elem in geo_elem:
  1765. new_geo = line_elem.difference(sub_union)
  1766. if new_geo and not new_geo.is_empty:
  1767. new_geometry.append(new_geo)
  1768. except TypeError:
  1769. if isinstance(target_geo, Polygon):
  1770. for ring in self.poly2rings(target_geo):
  1771. new_geo = ring.difference(sub_union)
  1772. if new_geo:
  1773. if not new_geo.is_empty:
  1774. new_geometry.append(new_geo)
  1775. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1776. new_geo = target_geo.difference(sub_union)
  1777. if new_geo and not new_geo.is_empty:
  1778. new_geometry.append(new_geo)
  1779. elif isinstance(target_geo, MultiLineString):
  1780. for line_elem in target_geo:
  1781. new_geo = line_elem.difference(sub_union)
  1782. if new_geo and not new_geo.is_empty:
  1783. new_geometry.append(new_geo)
  1784. return new_geometry
  1785. def area_intersection(self, geo, intersection_geo=None):
  1786. """
  1787. Return the intersection geometry between geo and intersection_geo
  1788. :param geo: target geometry
  1789. :param intersection_geo: second geometry
  1790. :return:
  1791. """
  1792. new_geometry = []
  1793. target_geo = geo
  1794. intersect_union = unary_union(intersection_geo)
  1795. try:
  1796. for geo_elem in target_geo:
  1797. if isinstance(geo_elem, Polygon):
  1798. for ring in self.poly2rings(geo_elem):
  1799. new_geo = ring.intersection(intersect_union)
  1800. if new_geo and not new_geo.is_empty:
  1801. new_geometry.append(new_geo)
  1802. elif isinstance(geo_elem, MultiPolygon):
  1803. for poly in geo_elem:
  1804. for ring in self.poly2rings(poly):
  1805. new_geo = ring.intersection(intersect_union)
  1806. if new_geo and not new_geo.is_empty:
  1807. new_geometry.append(new_geo)
  1808. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1809. new_geo = geo_elem.intersection(intersect_union)
  1810. if new_geo:
  1811. if not new_geo.is_empty:
  1812. new_geometry.append(new_geo)
  1813. elif isinstance(geo_elem, MultiLineString):
  1814. for line_elem in geo_elem:
  1815. new_geo = line_elem.intersection(intersect_union)
  1816. if new_geo and not new_geo.is_empty:
  1817. new_geometry.append(new_geo)
  1818. except TypeError:
  1819. if isinstance(target_geo, Polygon):
  1820. for ring in self.poly2rings(target_geo):
  1821. new_geo = ring.intersection(intersect_union)
  1822. if new_geo:
  1823. if not new_geo.is_empty:
  1824. new_geometry.append(new_geo)
  1825. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1826. new_geo = target_geo.intersection(intersect_union)
  1827. if new_geo and not new_geo.is_empty:
  1828. new_geometry.append(new_geo)
  1829. elif isinstance(target_geo, MultiLineString):
  1830. for line_elem in target_geo:
  1831. new_geo = line_elem.intersection(intersect_union)
  1832. if new_geo and not new_geo.is_empty:
  1833. new_geometry.append(new_geo)
  1834. return new_geometry
  1835. def on_poly_mouse_click_release(self, event):
  1836. if self.app.is_legacy is False:
  1837. event_pos = event.pos
  1838. right_button = 2
  1839. self.app.event_is_dragging = self.app.event_is_dragging
  1840. else:
  1841. event_pos = (event.xdata, event.ydata)
  1842. right_button = 3
  1843. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1844. try:
  1845. x = float(event_pos[0])
  1846. y = float(event_pos[1])
  1847. except TypeError:
  1848. return
  1849. event_pos = (x, y)
  1850. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1851. if self.app.grid_status():
  1852. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1853. else:
  1854. curr_pos = (curr_pos[0], curr_pos[1])
  1855. if event.button == 1:
  1856. if self.ui.poly_int_cb.get_value() is True:
  1857. clicked_poly = self.find_polygon_ignore_interiors(point=(curr_pos[0], curr_pos[1]),
  1858. geoset=self.grb_obj.solid_geometry)
  1859. clicked_poly = self.get_selected_interior(clicked_poly, point=(curr_pos[0], curr_pos[1]))
  1860. else:
  1861. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.grb_obj.solid_geometry)
  1862. if self.app.selection_type is not None:
  1863. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  1864. self.app.selection_type = None
  1865. elif clicked_poly:
  1866. if clicked_poly not in self.poly_dict.values():
  1867. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  1868. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1869. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1870. visible=True)
  1871. self.poly_dict[shape_id] = clicked_poly
  1872. self.app.inform.emit(
  1873. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  1874. _("Click to add next polygon or right click to start isolation."))
  1875. )
  1876. else:
  1877. try:
  1878. for k, v in list(self.poly_dict.items()):
  1879. if v == clicked_poly:
  1880. self.app.tool_shapes.remove(k)
  1881. self.poly_dict.pop(k)
  1882. break
  1883. except TypeError:
  1884. return
  1885. self.app.inform.emit(
  1886. '%s. %s' % (_("Removed polygon"),
  1887. _("Click to add/remove next polygon or right click to start isolation."))
  1888. )
  1889. self.app.tool_shapes.redraw()
  1890. else:
  1891. self.app.inform.emit(_("No polygon detected under click position."))
  1892. elif event.button == right_button and self.app.event_is_dragging is False:
  1893. # restore the Grid snapping if it was active before
  1894. if self.grid_status_memory is True:
  1895. self.app.ui.grid_snap_btn.trigger()
  1896. if self.app.is_legacy is False:
  1897. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1898. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1899. else:
  1900. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1901. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1902. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1903. self.app.on_mouse_click_release_over_plot)
  1904. # disconnect flags
  1905. self.poly_sel_disconnect_flag = False
  1906. self.app.tool_shapes.clear(update=True)
  1907. if self.poly_dict:
  1908. poly_list = deepcopy(list(self.poly_dict.values()))
  1909. if self.ui.poly_int_cb.get_value() is True:
  1910. # isolate the interior polygons with a negative tool
  1911. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list, negative_dia=True)
  1912. else:
  1913. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list)
  1914. self.poly_dict.clear()
  1915. else:
  1916. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1917. def selection_area_handler(self, start_pos, end_pos, sel_type):
  1918. """
  1919. :param start_pos: mouse position when the selection LMB click was done
  1920. :param end_pos: mouse position when the left mouse button is released
  1921. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1922. :return:
  1923. """
  1924. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1925. # delete previous selection shape
  1926. self.app.delete_selection_shape()
  1927. added_poly_count = 0
  1928. try:
  1929. for geo in self.solid_geometry:
  1930. if geo not in self.poly_dict.values():
  1931. if sel_type is True:
  1932. if geo.within(poly_selection):
  1933. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1934. shape=geo,
  1935. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1936. face_color=self.app.defaults[
  1937. 'global_sel_draw_color'] + 'AF',
  1938. visible=True)
  1939. self.poly_dict[shape_id] = geo
  1940. added_poly_count += 1
  1941. else:
  1942. if poly_selection.intersects(geo):
  1943. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1944. shape=geo,
  1945. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1946. face_color=self.app.defaults[
  1947. 'global_sel_draw_color'] + 'AF',
  1948. visible=True)
  1949. self.poly_dict[shape_id] = geo
  1950. added_poly_count += 1
  1951. except TypeError:
  1952. if self.solid_geometry not in self.poly_dict.values():
  1953. if sel_type is True:
  1954. if poly_selection.contains(self.solid_geometry):
  1955. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1956. shape=self.solid_geometry,
  1957. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1958. face_color=self.app.defaults[
  1959. 'global_sel_draw_color'] + 'AF',
  1960. visible=True)
  1961. self.poly_dict[shape_id] = self.solid_geometry
  1962. added_poly_count += 1
  1963. else:
  1964. if poly_selection.intersects(self.solid_geometry):
  1965. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1966. shape=self.solid_geometry,
  1967. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1968. face_color=self.app.defaults[
  1969. 'global_sel_draw_color'] + 'AF',
  1970. visible=True)
  1971. self.poly_dict[shape_id] = self.solid_geometry
  1972. added_poly_count += 1
  1973. if added_poly_count > 0:
  1974. self.app.tool_shapes.redraw()
  1975. self.app.inform.emit(
  1976. '%s: %d. %s' % (_("Added polygon"),
  1977. int(added_poly_count),
  1978. _("Click to add next polygon or right click to start isolation."))
  1979. )
  1980. else:
  1981. self.app.inform.emit(_("No polygon in selection."))
  1982. # To be called after clicking on the plot.
  1983. def on_mouse_release(self, event):
  1984. shape_type = self.ui.area_shape_radio.get_value()
  1985. if self.app.is_legacy is False:
  1986. event_pos = event.pos
  1987. # event_is_dragging = event.is_dragging
  1988. right_button = 2
  1989. else:
  1990. event_pos = (event.xdata, event.ydata)
  1991. # event_is_dragging = self.app.plotcanvas.is_dragging
  1992. right_button = 3
  1993. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1994. if self.app.grid_status():
  1995. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1996. else:
  1997. curr_pos = (event_pos[0], event_pos[1])
  1998. x1, y1 = curr_pos[0], curr_pos[1]
  1999. # do clear area only for left mouse clicks
  2000. if event.button == 1:
  2001. if shape_type == "square":
  2002. if self.first_click is False:
  2003. self.first_click = True
  2004. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  2005. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  2006. if self.app.grid_status():
  2007. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  2008. else:
  2009. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  2010. self.app.delete_selection_shape()
  2011. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  2012. pt1 = (x0, y0)
  2013. pt2 = (x1, y0)
  2014. pt3 = (x1, y1)
  2015. pt4 = (x0, y1)
  2016. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  2017. self.sel_rect.append(new_rectangle)
  2018. # add a temporary shape on canvas
  2019. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  2020. self.first_click = False
  2021. return
  2022. else:
  2023. self.points.append((x1, y1))
  2024. if len(self.points) > 1:
  2025. self.poly_drawn = True
  2026. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  2027. return ""
  2028. elif event.button == right_button and self.mouse_is_dragging is False:
  2029. shape_type = self.ui.area_shape_radio.get_value()
  2030. if shape_type == "square":
  2031. self.first_click = False
  2032. else:
  2033. # if we finish to add a polygon
  2034. if self.poly_drawn is True:
  2035. try:
  2036. # try to add the point where we last clicked if it is not already in the self.points
  2037. last_pt = (x1, y1)
  2038. if last_pt != self.points[-1]:
  2039. self.points.append(last_pt)
  2040. except IndexError:
  2041. pass
  2042. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  2043. if len(self.points) > 2:
  2044. self.delete_moving_selection_shape()
  2045. pol = Polygon(self.points)
  2046. # do not add invalid polygons even if they are drawn by utility geometry
  2047. if pol.is_valid:
  2048. self.sel_rect.append(pol)
  2049. self.draw_selection_shape_polygon(points=self.points)
  2050. self.app.inform.emit(
  2051. _("Zone added. Click to start adding next zone or right click to finish."))
  2052. self.points = []
  2053. self.poly_drawn = False
  2054. return
  2055. self.delete_tool_selection_shape()
  2056. if self.app.is_legacy is False:
  2057. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2058. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2059. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2060. else:
  2061. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2062. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2063. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2064. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2065. self.app.on_mouse_click_over_plot)
  2066. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2067. self.app.on_mouse_move_over_plot)
  2068. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2069. self.app.on_mouse_click_release_over_plot)
  2070. # disconnect flags
  2071. self.area_sel_disconnect_flag = False
  2072. if len(self.sel_rect) == 0:
  2073. return
  2074. self.sel_rect = unary_union(self.sel_rect)
  2075. self.isolate(isolated_obj=self.grb_obj, limited_area=self.sel_rect, plot=True)
  2076. self.sel_rect = []
  2077. # called on mouse move
  2078. def on_mouse_move(self, event):
  2079. shape_type = self.ui.area_shape_radio.get_value()
  2080. if self.app.is_legacy is False:
  2081. event_pos = event.pos
  2082. event_is_dragging = event.is_dragging
  2083. # right_button = 2
  2084. else:
  2085. event_pos = (event.xdata, event.ydata)
  2086. event_is_dragging = self.app.plotcanvas.is_dragging
  2087. # right_button = 3
  2088. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  2089. # detect mouse dragging motion
  2090. if event_is_dragging is True:
  2091. self.mouse_is_dragging = True
  2092. else:
  2093. self.mouse_is_dragging = False
  2094. # update the cursor position
  2095. if self.app.grid_status():
  2096. # Update cursor
  2097. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  2098. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  2099. symbol='++', edge_color=self.app.cursor_color_3D,
  2100. edge_width=self.app.defaults["global_cursor_width"],
  2101. size=self.app.defaults["global_cursor_size"])
  2102. if self.cursor_pos is None:
  2103. self.cursor_pos = (0, 0)
  2104. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  2105. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  2106. # # update the positions on status bar
  2107. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2108. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  2109. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2110. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  2111. units = self.app.defaults["units"].lower()
  2112. self.app.plotcanvas.text_hud.text = \
  2113. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  2114. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  2115. # draw the utility geometry
  2116. if shape_type == "square":
  2117. if self.first_click:
  2118. self.app.delete_selection_shape()
  2119. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  2120. coords=(curr_pos[0], curr_pos[1]))
  2121. else:
  2122. self.delete_moving_selection_shape()
  2123. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  2124. def on_key_press(self, event):
  2125. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  2126. # matplotlib_key_flag = False
  2127. # events out of the self.app.collection view (it's about Project Tab) are of type int
  2128. if type(event) is int:
  2129. key = event
  2130. # events from the GUI are of type QKeyEvent
  2131. elif type(event) == QtGui.QKeyEvent:
  2132. key = event.key()
  2133. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  2134. # matplotlib_key_flag = True
  2135. key = event.key
  2136. key = QtGui.QKeySequence(key)
  2137. # check for modifiers
  2138. key_string = key.toString().lower()
  2139. if '+' in key_string:
  2140. mod, __, key_text = key_string.rpartition('+')
  2141. if mod.lower() == 'ctrl':
  2142. # modifiers = QtCore.Qt.ControlModifier
  2143. pass
  2144. elif mod.lower() == 'alt':
  2145. # modifiers = QtCore.Qt.AltModifier
  2146. pass
  2147. elif mod.lower() == 'shift':
  2148. # modifiers = QtCore.Qt.ShiftModifier
  2149. pass
  2150. else:
  2151. # modifiers = QtCore.Qt.NoModifier
  2152. pass
  2153. key = QtGui.QKeySequence(key_text)
  2154. # events from Vispy are of type KeyEvent
  2155. else:
  2156. key = event.key
  2157. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  2158. if self.area_sel_disconnect_flag is True:
  2159. if self.app.is_legacy is False:
  2160. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2161. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2162. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2163. else:
  2164. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2165. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2166. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2167. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2168. self.app.on_mouse_click_over_plot)
  2169. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2170. self.app.on_mouse_move_over_plot)
  2171. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2172. self.app.on_mouse_click_release_over_plot)
  2173. if self.poly_sel_disconnect_flag is False:
  2174. # restore the Grid snapping if it was active before
  2175. if self.grid_status_memory is True:
  2176. self.app.ui.grid_snap_btn.trigger()
  2177. if self.app.is_legacy is False:
  2178. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  2179. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2180. else:
  2181. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2182. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2183. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2184. self.app.on_mouse_click_release_over_plot)
  2185. self.points = []
  2186. self.poly_drawn = False
  2187. self.delete_moving_selection_shape()
  2188. self.delete_tool_selection_shape()
  2189. def on_iso_tool_add_from_db_executed(self, tool):
  2190. """
  2191. Here add the tool from DB in the selected geometry object
  2192. :return:
  2193. """
  2194. tool_from_db = deepcopy(tool)
  2195. if tool['data']['tool_target'] not in [0, 3]: # [General, Isolation]
  2196. for idx in range(self.app.ui.plot_tab_area.count()):
  2197. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2198. wdg = self.app.ui.plot_tab_area.widget(idx)
  2199. wdg.deleteLater()
  2200. self.app.ui.plot_tab_area.removeTab(idx)
  2201. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  2202. return
  2203. res = self.on_tool_from_db_inserted(tool=tool_from_db)
  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. wdg = self.app.ui.plot_tab_area.widget(idx)
  2207. wdg.deleteLater()
  2208. self.app.ui.plot_tab_area.removeTab(idx)
  2209. if res == 'fail':
  2210. return
  2211. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2212. # select last tool added
  2213. toolid = res
  2214. for row in range(self.ui.tools_table.rowCount()):
  2215. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2216. self.ui.tools_table.selectRow(row)
  2217. self.on_row_selection_change()
  2218. def on_tool_from_db_inserted(self, tool):
  2219. """
  2220. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2221. :param tool: a dict with the tool data
  2222. :return: None
  2223. """
  2224. self.ui_disconnect()
  2225. self.units = self.app.defaults['units'].upper()
  2226. tooldia = float(tool['tooldia'])
  2227. # construct a list of all 'tooluid' in the self.tools
  2228. tool_uid_list = [int(tooluid_key) for tooluid_key in self.iso_tools]
  2229. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2230. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  2231. tooluid = max_uid + 1
  2232. tool_dias = []
  2233. for k, v in self.iso_tools.items():
  2234. for tool_v in v.keys():
  2235. if tool_v == 'tooldia':
  2236. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  2237. truncated_tooldia = self.app.dec_format(tooldia, self.decimals)
  2238. if truncated_tooldia in tool_dias:
  2239. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2240. self.ui_connect()
  2241. return 'fail'
  2242. self.iso_tools.update({
  2243. tooluid: {
  2244. 'tooldia': truncated_tooldia,
  2245. 'offset': deepcopy(tool['offset']),
  2246. 'offset_value': deepcopy(tool['offset_value']),
  2247. 'type': deepcopy(tool['type']),
  2248. 'tool_type': deepcopy(tool['tool_type']),
  2249. 'data': deepcopy(tool['data']),
  2250. 'solid_geometry': []
  2251. }
  2252. })
  2253. self.iso_tools[tooluid]['data']['name'] = '_iso'
  2254. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2255. self.ui_connect()
  2256. self.build_ui()
  2257. # select the tool just added
  2258. for row in range(self.ui.tools_table.rowCount()):
  2259. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  2260. self.ui.tools_table.selectRow(row)
  2261. break
  2262. # if self.ui.tools_table.rowCount() != 0:
  2263. # self.param_frame.setDisabled(False)
  2264. def on_tool_add_from_db_clicked(self):
  2265. """
  2266. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2267. and display the Tools Database tab in the form needed for the Tool adding
  2268. :return: None
  2269. """
  2270. # if the Tools Database is already opened focus on it
  2271. for idx in range(self.app.ui.plot_tab_area.count()):
  2272. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2273. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2274. break
  2275. ret_val = self.app.on_tools_database(source='iso')
  2276. if ret_val == 'fail':
  2277. return
  2278. self.app.tools_db_tab.ok_to_add = True
  2279. self.app.tools_db_tab.ui.buttons_frame.hide()
  2280. self.app.tools_db_tab.ui.add_tool_from_db.show()
  2281. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  2282. def reset_fields(self):
  2283. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2284. @staticmethod
  2285. def poly2rings(poly):
  2286. return [poly.exterior] + [interior for interior in poly.interiors]
  2287. @staticmethod
  2288. def poly2ext(poly):
  2289. return [poly.exterior]
  2290. @staticmethod
  2291. def poly2ints(poly):
  2292. return [interior for interior in poly.interiors]
  2293. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0,
  2294. prog_plot=False):
  2295. """
  2296. Isolation_geometry produces an envelope that is going on the left of the geometry
  2297. (the copper features). To leave the least amount of burrs on the features
  2298. the tool needs to travel on the right side of the features (this is called conventional milling)
  2299. the first pass is the one cutting all of the features, so it needs to be reversed
  2300. the other passes overlap preceding ones and cut the left over copper. It is better for them
  2301. to cut on the right side of the left over copper i.e on the left side of the features.
  2302. :param offset: Offset distance to be passed to the obj.isolation_geometry() method
  2303. :type offset: float
  2304. :param invert: If to invert the direction of geometry (CW to CCW or reverse)
  2305. :type invert: int
  2306. :param geometry: Shapely Geometry for which t ogenerate envelope
  2307. :type geometry:
  2308. :param env_iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  2309. :type env_iso_type: int
  2310. :param follow: If the kind of isolation is a "follow" one
  2311. :type follow: bool
  2312. :param nr_passes: Number of passes
  2313. :type nr_passes: int
  2314. :param prog_plot: Type of plotting: "normal" or "progressive"
  2315. :type prog_plot: str
  2316. :return: The buffered geometry
  2317. :rtype: MultiPolygon or Polygon
  2318. """
  2319. if follow:
  2320. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, follow=follow, prog_plot=prog_plot)
  2321. return geom
  2322. else:
  2323. try:
  2324. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type,
  2325. passes=nr_passes, prog_plot=prog_plot)
  2326. except Exception as e:
  2327. log.debug('ToolIsolation.generate_envelope() --> %s' % str(e))
  2328. return 'fail'
  2329. if invert:
  2330. try:
  2331. pl = []
  2332. for p in geom:
  2333. if p is not None:
  2334. if isinstance(p, Polygon):
  2335. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2336. elif isinstance(p, LinearRing):
  2337. pl.append(Polygon(p.coords[::-1]))
  2338. geom = MultiPolygon(pl)
  2339. except TypeError:
  2340. if isinstance(geom, Polygon) and geom is not None:
  2341. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2342. elif isinstance(geom, LinearRing) and geom is not None:
  2343. geom = Polygon(geom.coords[::-1])
  2344. else:
  2345. log.debug("ToolIsolation.generate_envelope() Error --> Unexpected Geometry %s" %
  2346. type(geom))
  2347. except Exception as e:
  2348. log.debug("ToolIsolation.generate_envelope() Error --> %s" % str(e))
  2349. return 'fail'
  2350. return geom
  2351. @staticmethod
  2352. def generate_rest_geometry(geometry, tooldia, passes, overlap, invert, env_iso_type=2, negative_dia=None,
  2353. forced_rest=False,
  2354. prog_plot="normal", prog_plot_handler=None):
  2355. """
  2356. Will try to isolate the geometry and return a tuple made of list of paths made through isolation
  2357. and a list of Shapely Polygons that could not be isolated
  2358. :param geometry: A list of Shapely Polygons to be isolated
  2359. :type geometry: list
  2360. :param tooldia: The tool diameter used to do the isolation
  2361. :type tooldia: float
  2362. :param passes: Number of passes that will made the isolation
  2363. :type passes: int
  2364. :param overlap: How much to overlap the previous pass; in percentage [0.00, 99.99]%
  2365. :type overlap: float
  2366. :param invert: If to invert the direction of the resulting isolated geometries
  2367. :type invert: bool
  2368. :param env_iso_type: can be either 0 = keep exteriors or 1 = keep interiors or 2 = keep all paths
  2369. :type env_iso_type: int
  2370. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  2371. :type negative_dia: bool
  2372. :param forced_rest: isolate the polygon even if the interiors can not be isolated
  2373. :type forced_rest: bool
  2374. :param prog_plot: kind of plotting: "progressive" or "normal"
  2375. :type prog_plot: str
  2376. :param prog_plot_handler: method used to plot shapes if plot_prog is "proggressive"
  2377. :type prog_plot_handler:
  2378. :return: Tuple made from list of isolating paths and list of not isolated Polygons
  2379. :rtype: tuple
  2380. """
  2381. isolated_geo = []
  2382. not_isolated_geo = []
  2383. work_geo = []
  2384. for idx, geo in enumerate(geometry):
  2385. good_pass_iso = []
  2386. start_idx = idx + 1
  2387. for nr_pass in range(passes):
  2388. iso_offset = tooldia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * tooldia)
  2389. if negative_dia:
  2390. iso_offset = -iso_offset
  2391. buf_chek = iso_offset * 2
  2392. check_geo = geo.buffer(buf_chek)
  2393. intersect_flag = False
  2394. # find if current pass for current geo is valid (no intersection with other geos))
  2395. for geo_search_idx in range(idx):
  2396. if check_geo.intersects(geometry[geo_search_idx]):
  2397. intersect_flag = True
  2398. break
  2399. if intersect_flag is False:
  2400. for geo_search_idx in range(start_idx, len(geometry)):
  2401. if check_geo.intersects(geometry[geo_search_idx]):
  2402. intersect_flag = True
  2403. break
  2404. # if we had an intersection do nothing, else add the geo to the good pass isolation's
  2405. if intersect_flag is False:
  2406. temp_geo = geo.buffer(iso_offset)
  2407. # this test is done only for the first pass because this is where is relevant
  2408. # test if in the first pass, the geo that is isolated has interiors and if it has then test if the
  2409. # resulting isolated geometry (buffered) number of subgeo is the same as the exterior + interiors
  2410. # if not it means that the geo interiors most likely could not be isolated with this tool so we
  2411. # abandon the whole isolation for this geo and add this geo to the not_isolated_geo
  2412. if nr_pass == 0 and forced_rest is True:
  2413. if geo.interiors:
  2414. len_interiors = len(geo.interiors)
  2415. if len_interiors > 1:
  2416. total_poly_len = 1 + len_interiors # one exterior + len_interiors of interiors
  2417. if isinstance(temp_geo, Polygon):
  2418. # calculate the number of subgeos in the buffered geo
  2419. temp_geo_len = len([1] + list(temp_geo.interiors)) # one exterior + interiors
  2420. if total_poly_len != temp_geo_len:
  2421. # some interiors could not be isolated
  2422. break
  2423. else:
  2424. try:
  2425. temp_geo_len = len(temp_geo)
  2426. if total_poly_len != temp_geo_len:
  2427. # some interiors could not be isolated
  2428. break
  2429. except TypeError:
  2430. # this means that the buffered geo (temp_geo) is not iterable
  2431. # (one geo element only) therefore failure:
  2432. # we have more interiors but the resulting geo is only one
  2433. break
  2434. good_pass_iso.append(temp_geo)
  2435. if prog_plot == 'progressive':
  2436. prog_plot_handler(temp_geo)
  2437. if good_pass_iso:
  2438. work_geo += good_pass_iso
  2439. else:
  2440. not_isolated_geo.append(geo)
  2441. if invert:
  2442. try:
  2443. pl = []
  2444. for p in work_geo:
  2445. if p is not None:
  2446. if isinstance(p, Polygon):
  2447. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2448. elif isinstance(p, LinearRing):
  2449. pl.append(Polygon(p.coords[::-1]))
  2450. work_geo = MultiPolygon(pl)
  2451. except TypeError:
  2452. if isinstance(work_geo, Polygon) and work_geo is not None:
  2453. work_geo = [Polygon(work_geo.exterior.coords[::-1], work_geo.interiors)]
  2454. elif isinstance(work_geo, LinearRing) and work_geo is not None:
  2455. work_geo = [Polygon(work_geo.coords[::-1])]
  2456. else:
  2457. log.debug("ToolIsolation.generate_rest_geometry() Error --> Unexpected Geometry %s" %
  2458. type(work_geo))
  2459. except Exception as e:
  2460. log.debug("ToolIsolation.generate_rest_geometry() Error --> %s" % str(e))
  2461. return 'fail', 'fail'
  2462. if env_iso_type == 0: # exterior
  2463. for geo in work_geo:
  2464. isolated_geo.append(geo.exterior)
  2465. elif env_iso_type == 1: # interiors
  2466. for geo in work_geo:
  2467. isolated_geo += [interior for interior in geo.interiors]
  2468. else: # exterior + interiors
  2469. for geo in work_geo:
  2470. isolated_geo += [geo.exterior] + [interior for interior in geo.interiors]
  2471. return isolated_geo, not_isolated_geo
  2472. @staticmethod
  2473. def get_selected_interior(poly: Polygon, point: tuple) -> [Polygon, None]:
  2474. try:
  2475. ints = [Polygon(x) for x in poly.interiors]
  2476. except AttributeError:
  2477. return None
  2478. for poly in ints:
  2479. if poly.contains(Point(point)):
  2480. return poly
  2481. return None
  2482. def find_polygon_ignore_interiors(self, point, geoset=None):
  2483. """
  2484. Find an object that object.contains(Point(point)) in
  2485. poly, which can can be iterable, contain iterable of, or
  2486. be itself an implementer of .contains(). Will test the Polygon as it is full with no interiors.
  2487. :param point: See description
  2488. :param geoset: a polygon or list of polygons where to find if the param point is contained
  2489. :return: Polygon containing point or None.
  2490. """
  2491. if geoset is None:
  2492. geoset = self.solid_geometry
  2493. try: # Iterable
  2494. for sub_geo in geoset:
  2495. p = self.find_polygon_ignore_interiors(point, geoset=sub_geo)
  2496. if p is not None:
  2497. return p
  2498. except TypeError: # Non-iterable
  2499. try: # Implements .contains()
  2500. if isinstance(geoset, LinearRing):
  2501. geoset = Polygon(geoset)
  2502. poly_ext = Polygon(geoset.exterior)
  2503. if poly_ext.contains(Point(point)):
  2504. return geoset
  2505. except AttributeError: # Does not implement .contains()
  2506. return None
  2507. return None
  2508. class IsoUI:
  2509. toolName = _("Isolation Tool")
  2510. def __init__(self, layout, app):
  2511. self.app = app
  2512. self.decimals = self.app.decimals
  2513. self.layout = layout
  2514. self.tools_frame = QtWidgets.QFrame()
  2515. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2516. self.layout.addWidget(self.tools_frame)
  2517. self.tools_box = QtWidgets.QVBoxLayout()
  2518. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2519. self.tools_frame.setLayout(self.tools_box)
  2520. self.title_box = QtWidgets.QHBoxLayout()
  2521. self.tools_box.addLayout(self.title_box)
  2522. # ## Title
  2523. title_label = FCLabel("%s" % self.toolName)
  2524. title_label.setStyleSheet("""
  2525. QLabel
  2526. {
  2527. font-size: 16px;
  2528. font-weight: bold;
  2529. }
  2530. """)
  2531. title_label.setToolTip(
  2532. _("Create a Geometry object with\n"
  2533. "toolpaths to cut around polygons.")
  2534. )
  2535. self.title_box.addWidget(title_label)
  2536. # App Level label
  2537. self.level = FCLabel("")
  2538. self.level.setToolTip(
  2539. _(
  2540. "BASIC is suitable for a beginner. Many parameters\n"
  2541. "are hidden from the user in this mode.\n"
  2542. "ADVANCED mode will make available all parameters.\n\n"
  2543. "To change the application LEVEL, go to:\n"
  2544. "Edit -> Preferences -> General and check:\n"
  2545. "'APP. LEVEL' radio button."
  2546. )
  2547. )
  2548. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2549. self.title_box.addWidget(self.level)
  2550. self.obj_combo_label = FCLabel('<b>%s</b>:' % _("GERBER"))
  2551. self.obj_combo_label.setToolTip(
  2552. _("Gerber object for isolation routing.")
  2553. )
  2554. self.tools_box.addWidget(self.obj_combo_label)
  2555. # ################################################
  2556. # ##### The object to be copper cleaned ##########
  2557. # ################################################
  2558. self.object_combo = FCComboBox()
  2559. self.object_combo.setModel(self.app.collection)
  2560. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2561. # self.object_combo.setCurrentIndex(1)
  2562. self.object_combo.is_last = True
  2563. self.tools_box.addWidget(self.object_combo)
  2564. separator_line = QtWidgets.QFrame()
  2565. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2566. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2567. self.tools_box.addWidget(separator_line)
  2568. # ### Tools ## ##
  2569. self.tools_table_label = FCLabel('<b>%s</b>' % _('Tools Table'))
  2570. self.tools_table_label.setToolTip(
  2571. _("Tools pool from which the algorithm\n"
  2572. "will pick the ones used for copper clearing.")
  2573. )
  2574. self.tools_box.addWidget(self.tools_table_label)
  2575. self.tools_table = FCTable(drag_drop=True)
  2576. self.tools_box.addWidget(self.tools_table)
  2577. self.tools_table.setColumnCount(4)
  2578. # 3rd column is reserved (and hidden) for the tool ID
  2579. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2580. self.tools_table.setColumnHidden(3, True)
  2581. self.tools_table.setSortingEnabled(False)
  2582. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2583. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2584. _("This is the Tool Number.\n"
  2585. "Isolation routing will start with the tool with the biggest \n"
  2586. "diameter, continuing until there are no more tools.\n"
  2587. "Only tools that create Isolation geometry will still be present\n"
  2588. "in the resulting geometry. This is because with some tools\n"
  2589. "this function will not be able to create routing geometry.")
  2590. )
  2591. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2592. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  2593. "is the cut width into the material."))
  2594. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2595. _("The Tool Type (TT) can be:\n"
  2596. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  2597. "the cut width in material is exactly the tool diameter.\n"
  2598. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2599. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2600. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2601. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2602. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2603. "column of this table.\n"
  2604. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2605. "in the resulting geometry as Isolation."))
  2606. grid1 = QtWidgets.QGridLayout()
  2607. grid1.setColumnStretch(0, 0)
  2608. grid1.setColumnStretch(1, 1)
  2609. self.tools_box.addLayout(grid1)
  2610. # Tool order
  2611. self.order_label = FCLabel('%s:' % _('Tool order'))
  2612. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2613. "'No' --> means that the used order is the one in the tool table\n"
  2614. "'Forward' --> means that the tools will be ordered from small to big\n"
  2615. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2616. "WARNING: using rest machining will automatically set the order\n"
  2617. "in reverse and disable this control."))
  2618. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2619. {'label': _('Forward'), 'value': 'fwd'},
  2620. {'label': _('Reverse'), 'value': 'rev'}])
  2621. grid1.addWidget(self.order_label, 1, 0)
  2622. grid1.addWidget(self.order_radio, 1, 1)
  2623. separator_line = QtWidgets.QFrame()
  2624. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2625. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2626. grid1.addWidget(separator_line, 2, 0, 1, 2)
  2627. # #############################################################
  2628. # ############### Tool selection ##############################
  2629. # #############################################################
  2630. self.grid3 = QtWidgets.QGridLayout()
  2631. self.grid3.setColumnStretch(0, 0)
  2632. self.grid3.setColumnStretch(1, 1)
  2633. self.tools_box.addLayout(self.grid3)
  2634. self.tool_sel_label = FCLabel('<b>%s</b>' % _('Add from DB'))
  2635. self.grid3.addWidget(self.tool_sel_label, 0, 0, 1, 2)
  2636. # ### Tool Diameter ####
  2637. self.new_tooldia_lbl = FCLabel('%s:' % _('Tool Dia'))
  2638. self.new_tooldia_lbl.setToolTip(
  2639. _("Diameter for the new tool")
  2640. )
  2641. self.grid3.addWidget(self.new_tooldia_lbl, 2, 0)
  2642. new_tool_lay = QtWidgets.QHBoxLayout()
  2643. self.new_tooldia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2644. self.new_tooldia_entry.set_precision(self.decimals)
  2645. self.new_tooldia_entry.set_range(0.000, 10000.0000)
  2646. self.new_tooldia_entry.setObjectName("i_new_tooldia")
  2647. new_tool_lay.addWidget(self.new_tooldia_entry)
  2648. # Find Optimal Tooldia
  2649. self.find_optimal_button = QtWidgets.QToolButton()
  2650. self.find_optimal_button.setText(_('Optimal'))
  2651. self.find_optimal_button.setIcon(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'))
  2652. self.find_optimal_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  2653. self.find_optimal_button.setToolTip(
  2654. _("Find a tool diameter that is guaranteed\n"
  2655. "to do a complete isolation.")
  2656. )
  2657. new_tool_lay.addWidget(self.find_optimal_button)
  2658. self.grid3.addLayout(new_tool_lay, 2, 1)
  2659. bhlay = QtWidgets.QHBoxLayout()
  2660. self.search_and_add_btn = FCButton(_('Search and Add'))
  2661. self.search_and_add_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  2662. self.search_and_add_btn.setToolTip(
  2663. _("Add a new tool to the Tool Table\n"
  2664. "with the diameter specified above.\n"
  2665. "This is done by a background search\n"
  2666. "in the Tools Database. If nothing is found\n"
  2667. "in the Tools DB then a default tool is added.")
  2668. )
  2669. bhlay.addWidget(self.search_and_add_btn)
  2670. self.addtool_from_db_btn = FCButton(_('Pick from DB'))
  2671. self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
  2672. self.addtool_from_db_btn.setToolTip(
  2673. _("Add a new tool to the Tool Table\n"
  2674. "from the Tools Database.\n"
  2675. "Tools database administration in in:\n"
  2676. "Menu: Options -> Tools Database")
  2677. )
  2678. bhlay.addWidget(self.addtool_from_db_btn)
  2679. self.grid3.addLayout(bhlay, 7, 0, 1, 2)
  2680. separator_line = QtWidgets.QFrame()
  2681. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2682. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2683. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2684. self.deltool_btn = FCButton(_('Delete'))
  2685. self.deltool_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/trash16.png'))
  2686. self.deltool_btn.setToolTip(
  2687. _("Delete a selection of tools in the Tool Table\n"
  2688. "by first selecting a row(s) in the Tool Table.")
  2689. )
  2690. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2691. # self.grid3.addWidget(FCLabel(''), 10, 0, 1, 2)
  2692. separator_line = QtWidgets.QFrame()
  2693. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2694. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2695. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2696. self.tool_data_label = FCLabel(
  2697. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2698. self.tool_data_label.setToolTip(
  2699. _(
  2700. "The data used for creating GCode.\n"
  2701. "Each tool store it's own set of such data."
  2702. )
  2703. )
  2704. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2705. # Passes
  2706. passlabel = FCLabel('%s:' % _('Passes'))
  2707. passlabel.setToolTip(
  2708. _("Width of the isolation gap in\n"
  2709. "number (integer) of tool widths.")
  2710. )
  2711. self.passes_entry = FCSpinner(callback=self.confirmation_message_int)
  2712. self.passes_entry.set_range(1, 999)
  2713. self.passes_entry.setObjectName("i_passes")
  2714. self.grid3.addWidget(passlabel, 13, 0)
  2715. self.grid3.addWidget(self.passes_entry, 13, 1)
  2716. # Overlap Entry
  2717. overlabel = FCLabel('%s:' % _('Overlap'))
  2718. overlabel.setToolTip(
  2719. _("How much (percentage) of the tool width to overlap each tool pass.")
  2720. )
  2721. self.iso_overlap_entry = FCDoubleSpinner(suffix='%', callback=self.confirmation_message)
  2722. self.iso_overlap_entry.set_precision(self.decimals)
  2723. self.iso_overlap_entry.setWrapping(True)
  2724. self.iso_overlap_entry.set_range(0.0000, 99.9999)
  2725. self.iso_overlap_entry.setSingleStep(0.1)
  2726. self.iso_overlap_entry.setObjectName("i_overlap")
  2727. self.grid3.addWidget(overlabel, 14, 0)
  2728. self.grid3.addWidget(self.iso_overlap_entry, 14, 1)
  2729. # Milling Type Radio Button
  2730. self.milling_type_label = FCLabel('%s:' % _('Milling Type'))
  2731. self.milling_type_label.setToolTip(
  2732. _("Milling type when the selected tool is of type: 'iso_op':\n"
  2733. "- climb / best for precision milling and to reduce tool usage\n"
  2734. "- conventional / useful when there is no backlash compensation")
  2735. )
  2736. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  2737. {'label': _('Conventional'), 'value': 'cv'}])
  2738. self.milling_type_radio.setToolTip(
  2739. _("Milling type when the selected tool is of type: 'iso_op':\n"
  2740. "- climb / best for precision milling and to reduce tool usage\n"
  2741. "- conventional / useful when there is no backlash compensation")
  2742. )
  2743. self.milling_type_radio.setObjectName("i_milling_type")
  2744. self.grid3.addWidget(self.milling_type_label, 15, 0)
  2745. self.grid3.addWidget(self.milling_type_radio, 15, 1)
  2746. # Follow
  2747. self.follow_label = FCLabel('%s:' % _('Follow'))
  2748. self.follow_label.setToolTip(
  2749. _("Generate a 'Follow' geometry.\n"
  2750. "This means that it will cut through\n"
  2751. "the middle of the trace.")
  2752. )
  2753. self.follow_cb = FCCheckBox()
  2754. self.follow_cb.setToolTip(_("Generate a 'Follow' geometry.\n"
  2755. "This means that it will cut through\n"
  2756. "the middle of the trace."))
  2757. self.follow_cb.setObjectName("i_follow")
  2758. self.grid3.addWidget(self.follow_label, 16, 0)
  2759. self.grid3.addWidget(self.follow_cb, 16, 1)
  2760. # Isolation Type
  2761. self.iso_type_label = FCLabel('%s:' % _('Isolation Type'))
  2762. self.iso_type_label.setToolTip(
  2763. _("Choose how the isolation will be executed:\n"
  2764. "- 'Full' -> complete isolation of polygons\n"
  2765. "- 'Ext' -> will isolate only on the outside\n"
  2766. "- 'Int' -> will isolate only on the inside\n"
  2767. "'Exterior' isolation is almost always possible\n"
  2768. "(with the right tool) but 'Interior'\n"
  2769. "isolation can be done only when there is an opening\n"
  2770. "inside of the polygon (e.g polygon is a 'doughnut' shape).")
  2771. )
  2772. self.iso_type_radio = RadioSet([{'label': _('Full'), 'value': 'full'},
  2773. {'label': _('Ext'), 'value': 'ext'},
  2774. {'label': _('Int'), 'value': 'int'}])
  2775. self.iso_type_radio.setObjectName("i_iso_type")
  2776. self.grid3.addWidget(self.iso_type_label, 17, 0)
  2777. self.grid3.addWidget(self.iso_type_radio, 17, 1)
  2778. separator_line = QtWidgets.QFrame()
  2779. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2780. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2781. self.grid3.addWidget(separator_line, 18, 0, 1, 2)
  2782. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2783. self.apply_param_to_all.setIcon(QtGui.QIcon(self.app.resource_location + '/param_all32.png'))
  2784. self.apply_param_to_all.setToolTip(
  2785. _("The parameters in the current form will be applied\n"
  2786. "on all the tools from the Tool Table.")
  2787. )
  2788. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  2789. separator_line = QtWidgets.QFrame()
  2790. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2791. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2792. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  2793. # General Parameters
  2794. self.gen_param_label = FCLabel('<b>%s</b>' % _("Common Parameters"))
  2795. self.gen_param_label.setToolTip(
  2796. _("Parameters that are common for all tools.")
  2797. )
  2798. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  2799. # Rest Machining
  2800. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  2801. self.rest_cb.setObjectName("i_rest")
  2802. self.rest_cb.setToolTip(
  2803. _("If checked, use 'rest machining'.\n"
  2804. "Basically it will isolate outside PCB features,\n"
  2805. "using the biggest tool and continue with the next tools,\n"
  2806. "from bigger to smaller, to isolate the copper features that\n"
  2807. "could not be cleared by previous tool, until there is\n"
  2808. "no more copper features to isolate or there are no more tools.\n"
  2809. "If not checked, use the standard algorithm.")
  2810. )
  2811. self.grid3.addWidget(self.rest_cb, 25, 0)
  2812. # Force isolation even if the interiors are not isolated
  2813. self.forced_rest_iso_cb = FCCheckBox(_("Forced Rest"))
  2814. self.forced_rest_iso_cb.setToolTip(
  2815. _("When checked the isolation will be done with the current tool even if\n"
  2816. "interiors of a polygon (holes in the polygon) could not be isolated.\n"
  2817. "Works when 'rest machining' is used.")
  2818. )
  2819. self.grid3.addWidget(self.forced_rest_iso_cb, 25, 1)
  2820. # Combine All Passes
  2821. self.combine_passes_cb = FCCheckBox(label=_('Combine'))
  2822. self.combine_passes_cb.setToolTip(
  2823. _("Combine all passes into one object")
  2824. )
  2825. self.combine_passes_cb.setObjectName("i_combine")
  2826. self.grid3.addWidget(self.combine_passes_cb, 26, 0, 1, 2)
  2827. # Check Tool validity
  2828. self.valid_cb = FCCheckBox(label=_('Check validity'))
  2829. self.valid_cb.setToolTip(
  2830. _("If checked then the tools diameters are verified\n"
  2831. "if they will provide a complete isolation.")
  2832. )
  2833. self.valid_cb.setObjectName("i_check")
  2834. self.grid3.addWidget(self.valid_cb, 28, 0, 1, 2)
  2835. # Exception Areas
  2836. self.except_cb = FCCheckBox(label=_('Except'))
  2837. self.except_cb.setToolTip(_("When the isolation geometry is generated,\n"
  2838. "by checking this, the area of the object below\n"
  2839. "will be subtracted from the isolation geometry."))
  2840. self.except_cb.setObjectName("i_except")
  2841. self.grid3.addWidget(self.except_cb, 30, 0)
  2842. # Type of object to be excepted
  2843. self.type_excobj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  2844. {'label': _("Gerber"), 'value': 'gerber'}])
  2845. self.type_excobj_radio.setToolTip(
  2846. _("Specify the type of object to be excepted from isolation.\n"
  2847. "It can be of type: Gerber or Geometry.\n"
  2848. "What is selected here will dictate the kind\n"
  2849. "of objects that will populate the 'Object' combobox.")
  2850. )
  2851. self.grid3.addWidget(self.type_excobj_radio, 30, 1)
  2852. # The object to be excepted
  2853. self.exc_obj_combo = FCComboBox()
  2854. self.exc_obj_combo.setToolTip(_("Object whose area will be removed from isolation geometry."))
  2855. # set the model for the Area Exception comboboxes
  2856. self.exc_obj_combo.setModel(self.app.collection)
  2857. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2858. self.exc_obj_combo.is_last = True
  2859. self.exc_obj_combo.obj_type = "gerber"
  2860. self.grid3.addWidget(self.exc_obj_combo, 32, 0, 1, 2)
  2861. self.e_ois = OptionalInputSection(self.except_cb,
  2862. [
  2863. self.type_excobj_radio,
  2864. self.exc_obj_combo
  2865. ])
  2866. # Isolation Scope
  2867. self.select_label = FCLabel('%s:' % _("Selection"))
  2868. self.select_label.setToolTip(
  2869. _("Isolation scope. Choose what to isolate:\n"
  2870. "- 'All' -> Isolate all the polygons in the object\n"
  2871. "- 'Area Selection' -> Isolate polygons within a selection area.\n"
  2872. "- 'Polygon Selection' -> Isolate a selection of polygons.\n"
  2873. "- 'Reference Object' - will process the area specified by another object.")
  2874. )
  2875. self.select_combo = FCComboBox2()
  2876. self.select_combo.addItems(
  2877. [_("All"), _("Area Selection"), _("Polygon Selection"), _("Reference Object")]
  2878. )
  2879. self.select_combo.setObjectName("i_selection")
  2880. self.grid3.addWidget(self.select_label, 34, 0)
  2881. self.grid3.addWidget(self.select_combo, 34, 1)
  2882. self.reference_combo_type_label = FCLabel('%s:' % _("Ref. Type"))
  2883. self.reference_combo_type_label.setToolTip(
  2884. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  2885. "It can be Gerber, Excellon or Geometry.")
  2886. )
  2887. self.reference_combo_type = FCComboBox2()
  2888. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  2889. self.grid3.addWidget(self.reference_combo_type_label, 36, 0)
  2890. self.grid3.addWidget(self.reference_combo_type, 36, 1)
  2891. self.reference_combo_label = FCLabel('%s:' % _("Ref. Object"))
  2892. self.reference_combo_label.setToolTip(
  2893. _("The FlatCAM object to be used as non copper clearing reference.")
  2894. )
  2895. self.reference_combo = FCComboBox()
  2896. self.reference_combo.setModel(self.app.collection)
  2897. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2898. self.reference_combo.is_last = True
  2899. self.grid3.addWidget(self.reference_combo_label, 38, 0)
  2900. self.grid3.addWidget(self.reference_combo, 38, 1)
  2901. self.reference_combo.hide()
  2902. self.reference_combo_label.hide()
  2903. self.reference_combo_type.hide()
  2904. self.reference_combo_type_label.hide()
  2905. # Polygon interiors selection
  2906. self.poly_int_cb = FCCheckBox(_("Interiors"))
  2907. self.poly_int_cb.setToolTip(
  2908. _("When checked the user can select interiors of a polygon.\n"
  2909. "(holes in the polygon).")
  2910. )
  2911. self.grid3.addWidget(self.poly_int_cb, 40, 0)
  2912. self.poly_int_cb.hide()
  2913. # Area Selection shape
  2914. self.area_shape_label = FCLabel('%s:' % _("Shape"))
  2915. self.area_shape_label.setToolTip(
  2916. _("The kind of selection shape used for area selection.")
  2917. )
  2918. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2919. {'label': _("Polygon"), 'value': 'polygon'}])
  2920. self.grid3.addWidget(self.area_shape_label, 42, 0)
  2921. self.grid3.addWidget(self.area_shape_radio, 42, 1)
  2922. self.area_shape_label.hide()
  2923. self.area_shape_radio.hide()
  2924. separator_line = QtWidgets.QFrame()
  2925. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2926. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2927. self.grid3.addWidget(separator_line, 44, 0, 1, 2)
  2928. self.generate_iso_button = FCButton("%s" % _("Generate Geometry"))
  2929. self.generate_iso_button.setIcon(QtGui.QIcon(self.app.resource_location + '/geometry32.png'))
  2930. self.generate_iso_button.setStyleSheet("""
  2931. QPushButton
  2932. {
  2933. font-weight: bold;
  2934. }
  2935. """)
  2936. self.generate_iso_button.setToolTip(
  2937. _("Create a Geometry object with toolpaths to cut \n"
  2938. "isolation outside, inside or on both sides of the\n"
  2939. "object. For a Gerber object outside means outside\n"
  2940. "of the Gerber feature and inside means inside of\n"
  2941. "the Gerber feature, if possible at all. This means\n"
  2942. "that only if the Gerber feature has openings inside, they\n"
  2943. "will be isolated. If what is wanted is to cut isolation\n"
  2944. "inside the actual Gerber feature, use a negative tool\n"
  2945. "diameter above.")
  2946. )
  2947. self.tools_box.addWidget(self.generate_iso_button)
  2948. self.create_buffer_button = FCButton(_('Buffer Solid Geometry'))
  2949. self.create_buffer_button.setToolTip(
  2950. _("This button is shown only when the Gerber file\n"
  2951. "is loaded without buffering.\n"
  2952. "Clicking this will create the buffered geometry\n"
  2953. "required for isolation.")
  2954. )
  2955. self.tools_box.addWidget(self.create_buffer_button)
  2956. self.tools_box.addStretch()
  2957. # ## Reset Tool
  2958. self.reset_button = FCButton(_("Reset Tool"))
  2959. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  2960. self.reset_button.setToolTip(
  2961. _("Will reset the tool parameters.")
  2962. )
  2963. self.reset_button.setStyleSheet("""
  2964. QPushButton
  2965. {
  2966. font-weight: bold;
  2967. }
  2968. """)
  2969. self.tools_box.addWidget(self.reset_button)
  2970. # ############################ FINSIHED GUI ###################################
  2971. # #############################################################################
  2972. def confirmation_message(self, accepted, minval, maxval):
  2973. if accepted is False:
  2974. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2975. self.decimals,
  2976. minval,
  2977. self.decimals,
  2978. maxval), False)
  2979. else:
  2980. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2981. def confirmation_message_int(self, accepted, minval, maxval):
  2982. if accepted is False:
  2983. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2984. (_("Edited value is out of range"), minval, maxval), False)
  2985. else:
  2986. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)