ToolIsolation.py 153 KB

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