ToolIsolation.py 158 KB

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