ToolIsolation.py 156 KB

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