ToolPaint.py 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from PyQt5.QtCore import Qt
  9. from appTool import AppTool
  10. from copy import deepcopy
  11. # from ObjectCollection import *
  12. from appParsers.ParseGerber import Gerber
  13. from camlib import Geometry, FlatCAMRTreeStorage, grace
  14. from appGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox
  15. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point
  16. from shapely.ops import cascaded_union, unary_union, linemerge
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import numpy as np
  19. import math
  20. from numpy import Inf
  21. import traceback
  22. import logging
  23. import gettext
  24. import appTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. log = logging.getLogger('base')
  30. class ToolPaint(AppTool, Gerber):
  31. def __init__(self, app):
  32. self.app = app
  33. self.decimals = self.app.decimals
  34. AppTool.__init__(self, app)
  35. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  36. # #############################################################################
  37. # ######################### Tool GUI ##########################################
  38. # #############################################################################
  39. self.ui = PaintUI(layout=self.layout, app=self.app)
  40. # #############################################################################
  41. # ########################## VARIABLES ########################################
  42. # #############################################################################
  43. self.obj_name = ""
  44. self.paint_obj = None
  45. self.bound_obj_name = ""
  46. self.bound_obj = None
  47. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  48. self.tooldia_list = []
  49. self.tooldia = None
  50. self.sel_rect = None
  51. self.o_name = None
  52. self.overlap = None
  53. self.connect = None
  54. self.contour = None
  55. self.select_method = None
  56. self.units = ''
  57. self.paint_tools = {}
  58. self.tooluid = 0
  59. self.first_click = False
  60. self.cursor_pos = None
  61. self.mouse_is_dragging = False
  62. self.mm = None
  63. self.mp = None
  64. self.mr = None
  65. self.kp = None
  66. # disconnect flags
  67. self.area_sel_disconnect_flag = False
  68. self.poly_sel_disconnect_flag = False
  69. self.sel_rect = []
  70. # store here if the grid snapping is active
  71. self.grid_status_memory = False
  72. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  73. self.poly_dict = {}
  74. # store here the default data for Geometry Data
  75. self.default_data = {}
  76. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  77. self.form_fields = {
  78. "tools_paintoverlap": self.ui.paintoverlap_entry,
  79. "tools_paintoffset": self.ui.offset_entry,
  80. "tools_paintmethod": self.ui.paintmethod_combo,
  81. "tools_pathconnect": self.ui.pathconnect_cb,
  82. "tools_paintcontour": self.ui.paintcontour_cb,
  83. }
  84. self.name2option = {
  85. 'p_overlap': "tools_paintoverlap",
  86. 'p_offset': "tools_paintoffset",
  87. 'p_method': "tools_paintmethod",
  88. 'p_connect': "tools_pathconnect",
  89. 'p_contour': "tools_paintcontour",
  90. }
  91. self.old_tool_dia = None
  92. # store here the points for the "Polygon" area selection shape
  93. self.points = []
  94. # set this as True when in middle of drawing a "Polygon" area selection shape
  95. # it is made False by first click to signify that the shape is complete
  96. self.poly_drawn = False
  97. self.connect_signals_at_init()
  98. # #############################################################################
  99. # ###################### Setup CONTEXT MENU ###################################
  100. # #############################################################################
  101. self.ui.tools_table.setupContextMenu()
  102. self.ui.tools_table.addContextMenu(
  103. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  104. )
  105. self.ui.tools_table.addContextMenu(
  106. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  107. )
  108. self.ui.tools_table.addContextMenu(
  109. _("Delete"), lambda:
  110. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  111. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  112. )
  113. def on_type_obj_changed(self, val):
  114. obj_type = 0 if val == 'gerber' else 2
  115. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  116. self.ui.obj_combo.setCurrentIndex(0)
  117. self.ui.obj_combo.obj_type = {"gerber": "Gerber", "geometry": "Geometry"}[val]
  118. idx = self.ui.paintmethod_combo.findText(_("Laser_lines"))
  119. if self.ui.type_obj_radio.get_value().lower() == 'gerber':
  120. self.ui.paintmethod_combo.model().item(idx).setEnabled(True)
  121. else:
  122. self.ui.paintmethod_combo.model().item(idx).setEnabled(False)
  123. if self.ui.paintmethod_combo.get_value() == _("Laser_lines"):
  124. self.ui.paintmethod_combo.set_value(_("Lines"))
  125. def on_reference_combo_changed(self):
  126. obj_type = self.ui.reference_type_combo.currentIndex()
  127. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  128. self.ui.reference_combo.setCurrentIndex(0)
  129. self.ui.reference_combo.obj_type = {
  130. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  131. }[self.ui.reference_type_combo.get_value()]
  132. def connect_signals_at_init(self):
  133. # #############################################################################
  134. # ################################# Signals ###################################
  135. # #############################################################################
  136. self.ui.addtool_btn.clicked.connect(self.on_tool_add)
  137. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  138. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  139. self.ui.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  140. self.ui.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  141. self.ui.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  142. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  143. self.ui.selectmethod_combo.currentIndexChanged.connect(self.on_selection)
  144. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  145. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  146. self.ui.reference_type_combo.currentIndexChanged.connect(self.on_reference_combo_changed)
  147. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  148. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  149. self.ui.addtool_from_db_btn.clicked.connect(self.on_paint_tool_add_from_db_clicked)
  150. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  151. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  152. self.app.cleanup.connect(self.set_tool_ui)
  153. def install(self, icon=None, separator=None, **kwargs):
  154. AppTool.install(self, icon, separator, shortcut='Alt+P', **kwargs)
  155. def run(self, toggle=True):
  156. self.app.defaults.report_usage("ToolPaint()")
  157. log.debug("ToolPaint().run() was launched ...")
  158. if toggle:
  159. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  160. if self.app.ui.splitter.sizes()[0] == 0:
  161. self.app.ui.splitter.setSizes([1, 1])
  162. else:
  163. try:
  164. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  165. # if tab is populated with the tool but it does not have the focus, focus on it
  166. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  167. # focus on Tool Tab
  168. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  169. else:
  170. self.app.ui.splitter.setSizes([0, 1])
  171. except AttributeError:
  172. pass
  173. else:
  174. if self.app.ui.splitter.sizes()[0] == 0:
  175. self.app.ui.splitter.setSizes([1, 1])
  176. AppTool.run(self)
  177. self.set_tool_ui()
  178. self.build_ui()
  179. # all the tools are selected by default
  180. self.ui.tools_table.selectAll()
  181. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  182. def on_toggle_all_rows(self):
  183. """
  184. will toggle the selection of all rows in Tools table
  185. :return:
  186. """
  187. sel_model = self.ui.tools_table.selectionModel()
  188. sel_indexes = sel_model.selectedIndexes()
  189. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  190. sel_rows = set()
  191. for idx in sel_indexes:
  192. sel_rows.add(idx.row())
  193. if len(sel_rows) == self.ui.tools_table.rowCount():
  194. self.ui.tools_table.clearSelection()
  195. else:
  196. self.ui.tools_table.selectAll()
  197. self.update_ui()
  198. def on_row_selection_change(self):
  199. self.update_ui()
  200. def update_ui(self):
  201. self.blockSignals(True)
  202. sel_rows = set()
  203. table_items = self.ui.tools_table.selectedItems()
  204. if table_items:
  205. for it in table_items:
  206. sel_rows.add(it.row())
  207. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  208. if not sel_rows or len(sel_rows) == 0:
  209. self.ui.generate_paint_button.setDisabled(True)
  210. self.ui.tool_data_label.setText(
  211. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  212. )
  213. self.blockSignals(False)
  214. return
  215. else:
  216. self.ui.generate_paint_button.setDisabled(False)
  217. for current_row in sel_rows:
  218. # populate the form with the data from the tool associated with the row parameter
  219. try:
  220. item = self.ui.tools_table.item(current_row, 3)
  221. if item is None:
  222. return 'fail'
  223. tooluid = int(item.text())
  224. except Exception as e:
  225. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  226. return
  227. # update the QLabel that shows for which Tool we have the parameters in the UI form
  228. if len(sel_rows) == 1:
  229. cr = self.ui.tools_table.item(current_row, 0).text()
  230. self.ui.tool_data_label.setText(
  231. "<b>%s: <font color='#0000FF'>%s %s</font></b>" % (_('Parameters for'), _("Tool"), cr)
  232. )
  233. try:
  234. # set the form with data from the newly selected tool
  235. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  236. if int(tooluid_key) == tooluid:
  237. self.storage_to_form(tooluid_value['data'])
  238. except Exception as e:
  239. log.debug("ToolPaint ---> update_ui() " + str(e))
  240. else:
  241. self.ui.tool_data_label.setText(
  242. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  243. )
  244. self.blockSignals(False)
  245. def storage_to_form(self, dict_storage):
  246. for k in self.form_fields:
  247. try:
  248. self.form_fields[k].set_value(dict_storage[k])
  249. except Exception as err:
  250. log.debug("ToolPaint.storage.form() --> %s" % str(err))
  251. def form_to_storage(self):
  252. if self.ui.tools_table.rowCount() == 0:
  253. # there is no tool in tool table so we can't save the GUI elements values to storage
  254. return
  255. self.blockSignals(True)
  256. widget_changed = self.sender()
  257. wdg_objname = widget_changed.objectName()
  258. option_changed = self.name2option[wdg_objname]
  259. # row = self.ui.tools_table.currentRow()
  260. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  261. for row in rows:
  262. if row < 0:
  263. row = 0
  264. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  265. for tooluid_key, tooluid_val in self.paint_tools.items():
  266. if int(tooluid_key) == tooluid_item:
  267. new_option_value = self.form_fields[option_changed].get_value()
  268. if option_changed in tooluid_val:
  269. tooluid_val[option_changed] = new_option_value
  270. if option_changed in tooluid_val['data']:
  271. tooluid_val['data'][option_changed] = new_option_value
  272. self.blockSignals(False)
  273. def on_apply_param_to_all_clicked(self):
  274. if self.ui.tools_table.rowCount() == 0:
  275. # there is no tool in tool table so we can't save the GUI elements values to storage
  276. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  277. return
  278. self.blockSignals(True)
  279. row = self.ui.tools_table.currentRow()
  280. if row < 0:
  281. row = 0
  282. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  283. temp_tool_data = {}
  284. for tooluid_key, tooluid_val in self.paint_tools.items():
  285. if int(tooluid_key) == tooluid_item:
  286. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  287. # the current row in the tool table
  288. temp_tool_data = tooluid_val['data']
  289. break
  290. for tooluid_key, tooluid_val in self.paint_tools.items():
  291. tooluid_val['data'] = deepcopy(temp_tool_data)
  292. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  293. self.blockSignals(False)
  294. def on_add_tool_by_key(self):
  295. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  296. text='%s:' % _('Enter a Tool Diameter'),
  297. min=0.0000, max=99.9999, decimals=4)
  298. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  299. val, ok = tool_add_popup.get_value()
  300. if ok:
  301. if float(val) == 0:
  302. self.app.inform.emit('[WARNING_NOTCL] %s' %
  303. _("Please enter a tool diameter with non-zero value, in Float format."))
  304. return
  305. self.on_tool_add(dia=float(val))
  306. else:
  307. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  308. def on_tooltable_cellwidget_change(self):
  309. cw = self.sender()
  310. assert isinstance(cw, QtWidgets.QComboBox), \
  311. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  312. cw_index = self.ui.tools_table.indexAt(cw.pos())
  313. cw_row = cw_index.row()
  314. cw_col = cw_index.column()
  315. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  316. # if the sender is in the column with index 2 then we update the tool_type key
  317. if cw_col == 2:
  318. tt = cw.currentText()
  319. typ = 'Iso' if tt == 'V' else "Rough"
  320. self.paint_tools[current_uid].update({
  321. 'type': typ,
  322. 'tool_type': tt,
  323. })
  324. def on_tool_type(self, val):
  325. if val == 'V':
  326. self.ui.addtool_entry_lbl.setDisabled(True)
  327. self.ui.addtool_entry.setDisabled(True)
  328. self.ui.tipdialabel.show()
  329. self.ui.tipdia_entry.show()
  330. self.ui.tipanglelabel.show()
  331. self.ui.tipangle_entry.show()
  332. self.on_calculate_tooldia()
  333. else:
  334. self.ui.addtool_entry_lbl.setDisabled(False)
  335. self.ui.addtool_entry.setDisabled(False)
  336. self.ui.tipdialabel.hide()
  337. self.ui.tipdia_entry.hide()
  338. self.ui.tipanglelabel.hide()
  339. self.ui.tipangle_entry.hide()
  340. self.ui.addtool_entry.set_value(self.old_tool_dia)
  341. def on_calculate_tooldia(self):
  342. if self.ui.tool_type_radio.get_value() == 'V':
  343. tip_dia = float(self.ui.tipdia_entry.get_value())
  344. tip_angle = float(self.ui.tipangle_entry.get_value()) / 2.0
  345. cut_z = float(self.ui.cutz_entry.get_value())
  346. cut_z = -cut_z if cut_z < 0 else cut_z
  347. # calculated tool diameter so the cut_z parameter is obeyed
  348. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  349. # update the default_data so it is used in the ncc_tools dict
  350. self.default_data.update({
  351. "vtipdia": tip_dia,
  352. "vtipangle": (tip_angle * 2),
  353. })
  354. self.ui.addtool_entry.set_value(tool_dia)
  355. return tool_dia
  356. else:
  357. return float(self.ui.addtool_entry.get_value())
  358. def on_selection(self):
  359. sel_combo = self.ui.selectmethod_combo.get_value()
  360. if sel_combo == _("Reference Object"):
  361. self.ui.reference_combo.show()
  362. self.ui.reference_combo_label.show()
  363. self.ui.reference_type_combo.show()
  364. self.ui.reference_type_label.show()
  365. else:
  366. self.ui.reference_combo.hide()
  367. self.ui.reference_combo_label.hide()
  368. self.ui.reference_type_combo.hide()
  369. self.ui.reference_type_label.hide()
  370. if sel_combo == _("Polygon Selection"):
  371. # disable rest-machining for single polygon painting
  372. # self.ui.rest_cb.set_value(False)
  373. # self.ui.rest_cb.setDisabled(True)
  374. pass
  375. if sel_combo == _("Area Selection"):
  376. # disable rest-machining for area painting
  377. # self.ui.rest_cb.set_value(False)
  378. # self.ui.rest_cb.setDisabled(True)
  379. self.ui.area_shape_label.show()
  380. self.ui.area_shape_radio.show()
  381. else:
  382. self.ui.rest_cb.setDisabled(False)
  383. self.ui.rest_cb.set_value(self.app.defaults["tools_paintrest"])
  384. self.ui.addtool_entry.setDisabled(False)
  385. self.ui.addtool_btn.setDisabled(False)
  386. self.ui.deltool_btn.setDisabled(False)
  387. self.ui.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  388. self.ui.area_shape_label.hide()
  389. self.ui.area_shape_radio.hide()
  390. def on_order_changed(self, order):
  391. if order != 'no':
  392. self.build_ui()
  393. def on_rest_machining_check(self, state):
  394. if state:
  395. self.ui.order_radio.set_value('rev')
  396. self.ui.order_label.setDisabled(True)
  397. self.ui.order_radio.setDisabled(True)
  398. else:
  399. self.ui.order_label.setDisabled(False)
  400. self.ui.order_radio.setDisabled(False)
  401. def set_tool_ui(self):
  402. self.ui.tools_frame.show()
  403. self.reset_fields()
  404. self.old_tool_dia = self.app.defaults["tools_paintnewdia"]
  405. # updated units
  406. self.units = self.app.defaults['units'].upper()
  407. # set the working variables to a known state
  408. self.paint_tools.clear()
  409. self.tooluid = 0
  410. self.default_data.clear()
  411. self.default_data.update({
  412. "name": '_paint',
  413. "plot": self.app.defaults["geometry_plot"],
  414. "cutz": float(self.app.defaults["tools_paintcutz"]),
  415. "vtipdia": float(self.app.defaults["tools_painttipdia"]),
  416. "vtipangle": float(self.app.defaults["tools_painttipangle"]),
  417. "travelz": float(self.app.defaults["geometry_travelz"]),
  418. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  419. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  420. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  421. "dwell": self.app.defaults["geometry_dwell"],
  422. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  423. "multidepth": self.app.defaults["geometry_multidepth"],
  424. "ppname_g": self.app.defaults["geometry_ppname_g"],
  425. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  426. "extracut": self.app.defaults["geometry_extracut"],
  427. "extracut_length": self.app.defaults["geometry_extracut_length"],
  428. "toolchange": self.app.defaults["geometry_toolchange"],
  429. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  430. "endz": float(self.app.defaults["geometry_endz"]),
  431. "endxy": self.app.defaults["geometry_endxy"],
  432. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  433. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  434. "startz": self.app.defaults["geometry_startz"],
  435. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  436. "area_shape": self.app.defaults["geometry_area_shape"],
  437. "area_strategy": self.app.defaults["geometry_area_strategy"],
  438. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  439. "tooldia": self.app.defaults["tools_painttooldia"],
  440. "tools_paintoffset": self.app.defaults["tools_paintoffset"],
  441. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  442. "tools_selectmethod": self.app.defaults["tools_selectmethod"],
  443. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  444. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  445. "tools_paintoverlap": self.app.defaults["tools_paintoverlap"],
  446. "tools_paintrest": self.app.defaults["tools_paintrest"],
  447. })
  448. # ## Init the GUI interface
  449. self.ui.order_radio.set_value(self.app.defaults["tools_paintorder"])
  450. self.ui.offset_entry.set_value(self.app.defaults["tools_paintoffset"])
  451. self.ui.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  452. self.ui.selectmethod_combo.set_value(self.app.defaults["tools_selectmethod"])
  453. self.ui.area_shape_radio.set_value(self.app.defaults["tools_paint_area_shape"])
  454. self.ui.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  455. self.ui.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  456. self.ui.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  457. self.ui.cutz_entry.set_value(self.app.defaults["tools_paintcutz"])
  458. self.ui.tool_type_radio.set_value(self.app.defaults["tools_painttool_type"])
  459. self.ui.tipdia_entry.set_value(self.app.defaults["tools_painttipdia"])
  460. self.ui.tipangle_entry.set_value(self.app.defaults["tools_painttipangle"])
  461. self.ui.addtool_entry.set_value(self.app.defaults["tools_paintnewdia"])
  462. self.ui.rest_cb.set_value(self.app.defaults["tools_paintrest"])
  463. self.on_tool_type(val=self.ui.tool_type_radio.get_value())
  464. # # make the default object type, "Geometry"
  465. # self.type_obj_radio.set_value("geometry")
  466. # use the current selected object and make it visible in the Paint object combobox
  467. sel_list = self.app.collection.get_selected()
  468. if len(sel_list) == 1:
  469. active = self.app.collection.get_active()
  470. kind = active.kind
  471. if kind == 'gerber':
  472. self.ui.type_obj_radio.set_value('gerber')
  473. else:
  474. self.ui.type_obj_radio.set_value('geometry')
  475. # run those once so the obj_type attribute is updated in the FCComboBoxes
  476. # to make sure that the last loaded object is displayed in the combobox
  477. self.on_type_obj_changed(val=kind)
  478. self.on_reference_combo_changed()
  479. self.ui.obj_combo.set_value(active.options['name'])
  480. else:
  481. kind = 'geometry'
  482. self.ui.type_obj_radio.set_value('geometry')
  483. # run those once so the obj_type attribute is updated in the FCComboBoxes
  484. # to make sure that the last loaded object is displayed in the combobox
  485. self.on_type_obj_changed(val=kind)
  486. self.on_reference_combo_changed()
  487. try:
  488. diameters = [float(self.app.defaults["tools_painttooldia"])]
  489. except (ValueError, TypeError):
  490. diameters = [eval(x) for x in self.app.defaults["tools_painttooldia"].split(",") if x != '']
  491. if not diameters:
  492. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  493. self.build_ui()
  494. # if the Paint Method is "Single" disable the tool table context menu
  495. if self.default_data["tools_selectmethod"] == "single":
  496. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  497. return
  498. # call on self.on_tool_add() counts as an call to self.build_ui()
  499. # through this, we add a initial row / tool in the tool_table
  500. for dia in diameters:
  501. self.on_tool_add(dia, muted=True)
  502. # if the Paint Method is "Single" disable the tool table context menu
  503. if self.default_data["tools_selectmethod"] == "single":
  504. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  505. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  506. def rebuild_ui(self):
  507. # read the table tools uid
  508. current_uid_list = []
  509. for row in range(self.ui.tools_table.rowCount()):
  510. uid = int(self.ui.tools_table.item(row, 3).text())
  511. current_uid_list.append(uid)
  512. new_tools = {}
  513. new_uid = 1
  514. for current_uid in current_uid_list:
  515. new_tools[new_uid] = deepcopy(self.paint_tools[current_uid])
  516. new_uid += 1
  517. self.paint_tools = new_tools
  518. # the tools table changed therefore we need to rebuild it
  519. QtCore.QTimer.singleShot(20, self.build_ui)
  520. def build_ui(self):
  521. self.ui_disconnect()
  522. # updated units
  523. self.units = self.app.defaults['units'].upper()
  524. sorted_tools = []
  525. for k, v in self.paint_tools.items():
  526. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  527. order = self.ui.order_radio.get_value()
  528. if order == 'fwd':
  529. sorted_tools.sort(reverse=False)
  530. elif order == 'rev':
  531. sorted_tools.sort(reverse=True)
  532. else:
  533. pass
  534. n = len(sorted_tools)
  535. self.ui.tools_table.setRowCount(n)
  536. tool_id = 0
  537. for tool_sorted in sorted_tools:
  538. for tooluid_key, tooluid_value in self.paint_tools.items():
  539. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  540. tool_id += 1
  541. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  542. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  543. row_no = tool_id - 1
  544. self.ui.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  545. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  546. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  547. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  548. tool_type_item = FCComboBox()
  549. for item in self.tool_type_item_options:
  550. tool_type_item.addItem(item)
  551. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  552. idx = tool_type_item.findText(tooluid_value['tool_type'])
  553. tool_type_item.setCurrentIndex(idx)
  554. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  555. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  556. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  557. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  558. # make the diameter column editable
  559. for row in range(tool_id):
  560. self.ui.tools_table.item(row, 1).setFlags(
  561. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  562. # all the tools are selected by default
  563. self.ui.tools_table.selectColumn(0)
  564. #
  565. self.ui.tools_table.resizeColumnsToContents()
  566. self.ui.tools_table.resizeRowsToContents()
  567. vertical_header = self.ui.tools_table.verticalHeader()
  568. vertical_header.hide()
  569. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  570. horizontal_header = self.ui.tools_table.horizontalHeader()
  571. horizontal_header.setMinimumSectionSize(10)
  572. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  573. horizontal_header.resizeSection(0, 20)
  574. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  575. # self.ui.tools_table.setSortingEnabled(True)
  576. # sort by tool diameter
  577. # self.ui.tools_table.sortItems(1)
  578. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  579. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  580. self.ui_connect()
  581. # set the text on tool_data_label after loading the object
  582. sel_rows = set()
  583. sel_items = self.ui.tools_table.selectedItems()
  584. for it in sel_items:
  585. sel_rows.add(it.row())
  586. if len(sel_rows) > 1:
  587. self.ui.tool_data_label.setText(
  588. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  589. )
  590. def on_tool_add(self, dia=None, muted=None):
  591. self.blockSignals(True)
  592. if dia:
  593. tool_dia = dia
  594. else:
  595. tool_dia = self.on_calculate_tooldia()
  596. if tool_dia is None:
  597. self.build_ui()
  598. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  599. return
  600. # construct a list of all 'tooluid' in the self.tools
  601. tool_uid_list = []
  602. for tooluid_key in self.paint_tools:
  603. tool_uid_item = int(tooluid_key)
  604. tool_uid_list.append(tool_uid_item)
  605. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  606. if not tool_uid_list:
  607. max_uid = 0
  608. else:
  609. max_uid = max(tool_uid_list)
  610. self.tooluid = int(max_uid + 1)
  611. tool_dias = []
  612. for k, v in self.paint_tools.items():
  613. for tool_v in v.keys():
  614. if tool_v == 'tooldia':
  615. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  616. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  617. if muted is None:
  618. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  619. self.blockSignals(False)
  620. return
  621. else:
  622. if muted is None:
  623. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  624. self.paint_tools.update({
  625. int(self.tooluid): {
  626. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  627. 'offset': 'Path',
  628. 'offset_value': 0.0,
  629. 'type': 'Iso',
  630. 'tool_type': self.ui.tool_type_radio.get_value(),
  631. 'data': dict(self.default_data),
  632. 'solid_geometry': []
  633. }
  634. })
  635. self.blockSignals(False)
  636. self.build_ui()
  637. # select the tool just added
  638. for row in range(self.ui.tools_table.rowCount()):
  639. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  640. self.ui.tools_table.selectRow(row)
  641. break
  642. def on_tool_edit(self, item):
  643. self.blockSignals(True)
  644. edited_row = item.row()
  645. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  646. tool_dias = []
  647. try:
  648. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  649. except ValueError:
  650. # try to convert comma to decimal point. if it's still not working error message and return
  651. try:
  652. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  653. except ValueError:
  654. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  655. return
  656. for k, v in self.paint_tools.items():
  657. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  658. # identify the tool that was edited and get it's tooluid
  659. if new_tool_dia not in tool_dias:
  660. self.paint_tools[editeduid]['tooldia'] = new_tool_dia
  661. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  662. self.blockSignals(False)
  663. self.build_ui()
  664. return
  665. # identify the old tool_dia and restore the text in tool table
  666. for k, v in self.paint_tools.items():
  667. if k == editeduid:
  668. old_tool_dia = v['tooldia']
  669. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  670. restore_dia_item.setText(str(old_tool_dia))
  671. break
  672. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  673. self.blockSignals(False)
  674. self.build_ui()
  675. # def on_tool_copy(self, all=None):
  676. # try:
  677. # self.ui.tools_table.itemChanged.disconnect()
  678. # except:
  679. # pass
  680. #
  681. # # find the tool_uid maximum value in the self.tools
  682. # uid_list = []
  683. # for key in self.paint_tools:
  684. # uid_list.append(int(key))
  685. # try:
  686. # max_uid = max(uid_list, key=int)
  687. # except ValueError:
  688. # max_uid = 0
  689. #
  690. # if all is None:
  691. # if self.ui.tools_table.selectedItems():
  692. # for current_row in self.ui.tools_table.selectedItems():
  693. # # sometime the header get selected and it has row number -1
  694. # # we don't want to do anything with the header :)
  695. # if current_row.row() < 0:
  696. # continue
  697. # try:
  698. # tooluid_copy = int(self.ui.tools_table.item(current_row.row(), 3).text())
  699. # max_uid += 1
  700. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  701. # for td in self.paint_tools:
  702. # print("COPIED", self.paint_tools[td])
  703. # self.build_ui()
  704. # except AttributeError:
  705. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  706. # self.build_ui()
  707. # return
  708. # except Exception as e:
  709. # log.debug("on_tool_copy() --> " + str(e))
  710. # # deselect the table
  711. # # self.ui.geo_tools_table.clearSelection()
  712. # else:
  713. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  714. # self.build_ui()
  715. # return
  716. # else:
  717. # # we copy all tools in geo_tools_table
  718. # try:
  719. # temp_tools = dict(self.paint_tools)
  720. # max_uid += 1
  721. # for tooluid in temp_tools:
  722. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  723. # temp_tools.clear()
  724. # self.build_ui()
  725. # except Exception as e:
  726. # log.debug("on_tool_copy() --> " + str(e))
  727. #
  728. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  729. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  730. """
  731. Will delete a tool in the tool table
  732. :param rows_to_delete: which rows to delete; can be a list
  733. :param all_tools: delete all tools in the tool table
  734. :return:
  735. """
  736. self.blockSignals(True)
  737. deleted_tools_list = []
  738. if all_tools:
  739. self.paint_tools.clear()
  740. self.blockSignals(False)
  741. self.build_ui()
  742. return
  743. if rows_to_delete:
  744. try:
  745. for row in rows_to_delete:
  746. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  747. deleted_tools_list.append(tooluid_del)
  748. except TypeError:
  749. deleted_tools_list.append(rows_to_delete)
  750. for t in deleted_tools_list:
  751. self.paint_tools.pop(t, None)
  752. self.blockSignals(False)
  753. self.build_ui()
  754. return
  755. try:
  756. if self.ui.tools_table.selectedItems():
  757. for row_sel in self.ui.tools_table.selectedItems():
  758. row = row_sel.row()
  759. if row < 0:
  760. continue
  761. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  762. deleted_tools_list.append(tooluid_del)
  763. for t in deleted_tools_list:
  764. self.paint_tools.pop(t, None)
  765. except AttributeError:
  766. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  767. self.blockSignals(False)
  768. return
  769. except Exception as e:
  770. log.debug(str(e))
  771. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  772. self.blockSignals(False)
  773. self.build_ui()
  774. def on_paint_button_click(self):
  775. """
  776. Slot for clicking signal
  777. :return: None
  778. """
  779. self.app.defaults.report_usage("on_paint_button_click")
  780. self.first_click = False
  781. self.cursor_pos = None
  782. self.mouse_is_dragging = False
  783. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  784. if prog_plot:
  785. self.temp_shapes.clear(update=True)
  786. self.sel_rect = []
  787. obj_type = self.ui.type_obj_radio.get_value
  788. self.circle_steps = int(self.app.defaults["gerber_circle_steps"]) if obj_type == 'gerber' else \
  789. int(self.app.defaults["geometry_circle_steps"])
  790. self.obj_name = self.ui.obj_combo.currentText()
  791. # Get source object.
  792. try:
  793. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  794. except Exception as e:
  795. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  796. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object: %s"), self.obj_name))
  797. return
  798. if self.paint_obj is None:
  799. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), self.paint_obj))
  800. return
  801. # test if the Geometry Object is multigeo and return Fail if True because
  802. # for now Paint don't work on MultiGeo
  803. if self.paint_obj.kind == 'geometry' and self.paint_obj.multigeo is True:
  804. self.app.inform.emit('[ERROR_NOTCL] %s...' % _("Can't do Paint on MultiGeo geometries"))
  805. return 'Fail'
  806. self.o_name = '%s_mt_paint' % self.obj_name
  807. # use the selected tools in the tool table; get diameters
  808. self.tooldia_list = []
  809. table_items = self.ui.tools_table.selectedItems()
  810. if table_items:
  811. for x in table_items:
  812. try:
  813. self.tooldia = float(self.ui.tools_table.item(x.row(), 1).text())
  814. except ValueError:
  815. # try to convert comma to decimal point. if it's still not working error message and return
  816. try:
  817. self.tooldia = float(self.ui.tools_table.item(x.row(), 1).text().replace(',', '.'))
  818. except ValueError:
  819. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  820. continue
  821. self.tooldia_list.append(self.tooldia)
  822. else:
  823. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  824. return
  825. self.select_method = self.ui.selectmethod_combo.get_value()
  826. if self.select_method == _("All"):
  827. self.paint_poly_all(self.paint_obj, tooldia=self.tooldia_list, outname=self.o_name)
  828. elif self.select_method == _("Polygon Selection"):
  829. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  830. if self.app.ui.grid_snap_btn.isChecked():
  831. self.grid_status_memory = True
  832. self.app.ui.grid_snap_btn.trigger()
  833. else:
  834. self.grid_status_memory = False
  835. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  836. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  837. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  838. if self.app.is_legacy is False:
  839. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  840. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  841. else:
  842. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  843. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  844. # disconnect flags
  845. self.poly_sel_disconnect_flag = True
  846. elif self.select_method == _("Area Selection"):
  847. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  848. if self.app.is_legacy is False:
  849. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  850. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  851. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  852. else:
  853. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  854. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  855. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  856. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  857. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  858. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  859. # disconnect flags
  860. self.area_sel_disconnect_flag = True
  861. elif self.select_method == _("Reference Object"):
  862. self.bound_obj_name = self.reference_combo.currentText()
  863. # Get source object.
  864. try:
  865. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  866. except Exception:
  867. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  868. return "Could not retrieve object: %s" % self.obj_name
  869. self.paint_poly_ref(obj=self.paint_obj, sel_obj=self.bound_obj, tooldia=self.tooldia_list,
  870. outname=self.o_name)
  871. # To be called after clicking on the plot.
  872. def on_single_poly_mouse_release(self, event):
  873. if self.app.is_legacy is False:
  874. event_pos = event.pos
  875. right_button = 2
  876. event_is_dragging = self.app.event_is_dragging
  877. else:
  878. event_pos = (event.xdata, event.ydata)
  879. right_button = 3
  880. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  881. try:
  882. x = float(event_pos[0])
  883. y = float(event_pos[1])
  884. except TypeError:
  885. return
  886. event_pos = (x, y)
  887. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  888. # do paint single only for left mouse clicks
  889. if event.button == 1:
  890. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  891. if clicked_poly:
  892. if clicked_poly not in self.poly_dict.values():
  893. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  894. layer=0,
  895. shape=clicked_poly,
  896. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  897. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  898. visible=True)
  899. self.poly_dict[shape_id] = clicked_poly
  900. self.app.inform.emit(
  901. '%s: %d. %s' % (_("Added polygon"),
  902. int(len(self.poly_dict)),
  903. _("Click to add next polygon or right click to start painting."))
  904. )
  905. else:
  906. try:
  907. for k, v in list(self.poly_dict.items()):
  908. if v == clicked_poly:
  909. self.app.tool_shapes.remove(k)
  910. self.poly_dict.pop(k)
  911. break
  912. except TypeError:
  913. return
  914. self.app.inform.emit(
  915. '%s. %s' % (_("Removed polygon"),
  916. _("Click to add/remove next polygon or right click to start painting."))
  917. )
  918. self.app.tool_shapes.redraw()
  919. else:
  920. self.app.inform.emit(_("No polygon detected under click position."))
  921. elif event.button == right_button and event_is_dragging is False:
  922. # restore the Grid snapping if it was active before
  923. if self.grid_status_memory is True:
  924. self.app.ui.grid_snap_btn.trigger()
  925. if self.app.is_legacy is False:
  926. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  927. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  928. else:
  929. self.app.plotcanvas.graph_event_disconnect(self.mr)
  930. self.app.plotcanvas.graph_event_disconnect(self.kp)
  931. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  932. self.app.on_mouse_click_over_plot)
  933. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  934. self.app.on_mouse_click_release_over_plot)
  935. # disconnect flags
  936. self.poly_sel_disconnect_flag = False
  937. self.app.tool_shapes.clear(update=True)
  938. if self.poly_dict:
  939. poly_list = deepcopy(list(self.poly_dict.values()))
  940. self.paint_poly(self.paint_obj, inside_pt=(curr_pos[0], curr_pos[1]), poly_list=poly_list,
  941. tooldia=self.tooldia_list)
  942. self.poly_dict.clear()
  943. else:
  944. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  945. # To be called after clicking on the plot.
  946. def on_mouse_release(self, event):
  947. if self.app.is_legacy is False:
  948. event_pos = event.pos
  949. # event_is_dragging = event.is_dragging
  950. right_button = 2
  951. else:
  952. event_pos = (event.xdata, event.ydata)
  953. # event_is_dragging = self.app.plotcanvas.is_dragging
  954. right_button = 3
  955. try:
  956. x = float(event_pos[0])
  957. y = float(event_pos[1])
  958. except TypeError:
  959. return
  960. event_pos = (x, y)
  961. shape_type = self.ui.area_shape_radio.get_value()
  962. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  963. if self.app.grid_status():
  964. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  965. x1, y1 = curr_pos[0], curr_pos[1]
  966. # do paint single only for left mouse clicks
  967. if event.button == 1:
  968. if shape_type == "square":
  969. if not self.first_click:
  970. self.first_click = True
  971. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  972. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  973. if self.app.grid_status():
  974. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  975. else:
  976. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  977. self.app.delete_selection_shape()
  978. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  979. pt1 = (x0, y0)
  980. pt2 = (x1, y0)
  981. pt3 = (x1, y1)
  982. pt4 = (x0, y1)
  983. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  984. self.sel_rect.append(new_rectangle)
  985. # add a temporary shape on canvas
  986. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  987. self.first_click = False
  988. return
  989. else:
  990. self.points.append((x1, y1))
  991. if len(self.points) > 1:
  992. self.poly_drawn = True
  993. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  994. return ""
  995. elif event.button == right_button and self.mouse_is_dragging is False:
  996. shape_type = self.area_shape_radio.get_value()
  997. if shape_type == "square":
  998. self.first_click = False
  999. else:
  1000. # if we finish to add a polygon
  1001. if self.poly_drawn is True:
  1002. try:
  1003. # try to add the point where we last clicked if it is not already in the self.points
  1004. last_pt = (x1, y1)
  1005. if last_pt != self.points[-1]:
  1006. self.points.append(last_pt)
  1007. except IndexError:
  1008. pass
  1009. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1010. if len(self.points) > 2:
  1011. self.delete_moving_selection_shape()
  1012. pol = Polygon(self.points)
  1013. # do not add invalid polygons even if they are drawn by utility geometry
  1014. if pol.is_valid:
  1015. self.sel_rect.append(pol)
  1016. self.draw_selection_shape_polygon(points=self.points)
  1017. self.app.inform.emit(
  1018. _("Zone added. Click to start adding next zone or right click to finish."))
  1019. self.points = []
  1020. self.poly_drawn = False
  1021. return
  1022. self.delete_tool_selection_shape()
  1023. if self.app.is_legacy is False:
  1024. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1025. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1026. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1027. else:
  1028. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1029. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1030. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1031. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1032. self.app.on_mouse_click_over_plot)
  1033. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1034. self.app.on_mouse_move_over_plot)
  1035. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1036. self.app.on_mouse_click_release_over_plot)
  1037. # disconnect flags
  1038. self.area_sel_disconnect_flag = False
  1039. if len(self.sel_rect) == 0:
  1040. return
  1041. self.sel_rect = cascaded_union(self.sel_rect)
  1042. self.paint_poly_area(obj=self.paint_obj, tooldia=self.tooldia_list, sel_obj=self.sel_rect,
  1043. outname=self.o_name)
  1044. # called on mouse move
  1045. def on_mouse_move(self, event):
  1046. shape_type = self.ui.area_shape_radio.get_value()
  1047. if self.app.is_legacy is False:
  1048. event_pos = event.pos
  1049. event_is_dragging = event.is_dragging
  1050. # right_button = 2
  1051. else:
  1052. event_pos = (event.xdata, event.ydata)
  1053. event_is_dragging = self.app.plotcanvas.is_dragging
  1054. # right_button = 3
  1055. try:
  1056. x = float(event_pos[0])
  1057. y = float(event_pos[1])
  1058. except TypeError:
  1059. return
  1060. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1061. # detect mouse dragging motion
  1062. if event_is_dragging == 1:
  1063. self.mouse_is_dragging = True
  1064. else:
  1065. self.mouse_is_dragging = False
  1066. # update the cursor position
  1067. if self.app.grid_status():
  1068. # Update cursor
  1069. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1070. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1071. symbol='++', edge_color=self.app.cursor_color_3D,
  1072. edge_width=self.app.defaults["global_cursor_width"],
  1073. size=self.app.defaults["global_cursor_size"])
  1074. if self.cursor_pos is None:
  1075. self.cursor_pos = (0, 0)
  1076. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1077. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1078. # # update the positions on status bar
  1079. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1080. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1081. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1082. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1083. units = self.app.defaults["units"].lower()
  1084. self.app.plotcanvas.text_hud.text = \
  1085. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1086. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1087. # draw the utility geometry
  1088. if shape_type == "square":
  1089. if self.first_click:
  1090. self.app.delete_selection_shape()
  1091. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1092. coords=(curr_pos[0], curr_pos[1]))
  1093. else:
  1094. self.delete_moving_selection_shape()
  1095. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1096. def on_key_press(self, event):
  1097. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1098. # matplotlib_key_flag = False
  1099. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1100. if type(event) is int:
  1101. key = event
  1102. # events from the GUI are of type QKeyEvent
  1103. elif type(event) == QtGui.QKeyEvent:
  1104. key = event.key()
  1105. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1106. # matplotlib_key_flag = True
  1107. key = event.key
  1108. key = QtGui.QKeySequence(key)
  1109. # check for modifiers
  1110. key_string = key.toString().lower()
  1111. if '+' in key_string:
  1112. mod, __, key_text = key_string.rpartition('+')
  1113. if mod.lower() == 'ctrl':
  1114. # modifiers = QtCore.Qt.ControlModifier
  1115. pass
  1116. elif mod.lower() == 'alt':
  1117. # modifiers = QtCore.Qt.AltModifier
  1118. pass
  1119. elif mod.lower() == 'shift':
  1120. # modifiers = QtCore.Qt.ShiftModifier
  1121. pass
  1122. else:
  1123. # modifiers = QtCore.Qt.NoModifier
  1124. pass
  1125. key = QtGui.QKeySequence(key_text)
  1126. # events from Vispy are of type KeyEvent
  1127. else:
  1128. key = event.key
  1129. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1130. if self.area_sel_disconnect_flag is True:
  1131. try:
  1132. if self.app.is_legacy is False:
  1133. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1134. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1135. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1136. else:
  1137. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1138. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1139. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1140. except Exception as e:
  1141. log.debug("ToolPaint.on_key_press() _1 --> %s" % str(e))
  1142. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1143. self.app.on_mouse_click_over_plot)
  1144. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1145. self.app.on_mouse_move_over_plot)
  1146. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1147. self.app.on_mouse_click_release_over_plot)
  1148. if self.poly_sel_disconnect_flag is False:
  1149. try:
  1150. # restore the Grid snapping if it was active before
  1151. if self.grid_status_memory is True:
  1152. self.app.ui.grid_snap_btn.trigger()
  1153. if self.app.is_legacy is False:
  1154. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1155. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1156. else:
  1157. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1158. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1159. self.app.tool_shapes.clear(update=True)
  1160. except Exception as e:
  1161. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1162. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1163. self.app.on_mouse_click_release_over_plot)
  1164. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1165. self.app.on_mouse_click_over_plot)
  1166. self.points = []
  1167. self.poly_drawn = False
  1168. self.poly_dict.clear()
  1169. self.delete_moving_selection_shape()
  1170. self.delete_tool_selection_shape()
  1171. def paint_polygon_worker(self, polyg, tooldiameter, paint_method, over, conn, cont, prog_plot, obj):
  1172. cpoly = None
  1173. if paint_method == _("Standard"):
  1174. try:
  1175. # Type(cp) == FlatCAMRTreeStorage | None
  1176. cpoly = self.clear_polygon(polyg,
  1177. tooldia=tooldiameter,
  1178. steps_per_circle=self.circle_steps,
  1179. overlap=over,
  1180. contour=cont,
  1181. connect=conn,
  1182. prog_plot=prog_plot)
  1183. except grace:
  1184. return "fail"
  1185. except Exception as ee:
  1186. log.debug("ToolPaint.paint_polygon_worker() Standard --> %s" % str(ee))
  1187. elif paint_method == _("Seed"):
  1188. try:
  1189. # Type(cp) == FlatCAMRTreeStorage | None
  1190. cpoly = self.clear_polygon2(polyg,
  1191. tooldia=tooldiameter,
  1192. steps_per_circle=self.circle_steps,
  1193. overlap=over,
  1194. contour=cont,
  1195. connect=conn,
  1196. prog_plot=prog_plot)
  1197. except grace:
  1198. return "fail"
  1199. except Exception as ee:
  1200. log.debug("ToolPaint.paint_polygon_worker() Seed --> %s" % str(ee))
  1201. elif paint_method == _("Lines"):
  1202. try:
  1203. # Type(cp) == FlatCAMRTreeStorage | None
  1204. cpoly = self.clear_polygon3(polyg,
  1205. tooldia=tooldiameter,
  1206. steps_per_circle=self.circle_steps,
  1207. overlap=over,
  1208. contour=cont,
  1209. connect=conn,
  1210. prog_plot=prog_plot)
  1211. except grace:
  1212. return "fail"
  1213. except Exception as ee:
  1214. log.debug("ToolPaint.paint_polygon_worker() Lines --> %s" % str(ee))
  1215. elif paint_method == _("Laser_lines"):
  1216. try:
  1217. # line = None
  1218. # aperture_size = None
  1219. # the key is the aperture type and the val is a list of geo elements
  1220. flash_el_dict = {}
  1221. # the key is the aperture size, the val is a list of geo elements
  1222. traces_el_dict = {}
  1223. # find the flashes and the lines that are in the selected polygon and store them separately
  1224. for apid, apval in obj.apertures.items():
  1225. for geo_el in apval['geometry']:
  1226. if apval["size"] == 0.0:
  1227. if apval["size"] in traces_el_dict:
  1228. traces_el_dict[apval["size"]].append(geo_el)
  1229. else:
  1230. traces_el_dict[apval["size"]] = [geo_el]
  1231. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1232. if isinstance(geo_el['follow'], Point):
  1233. if apval["type"] == 'C':
  1234. if 'C' in flash_el_dict:
  1235. flash_el_dict['C'].append(geo_el)
  1236. else:
  1237. flash_el_dict['C'] = [geo_el]
  1238. elif apval["type"] == 'O':
  1239. if 'O' in flash_el_dict:
  1240. flash_el_dict['O'].append(geo_el)
  1241. else:
  1242. flash_el_dict['O'] = [geo_el]
  1243. elif apval["type"] == 'R':
  1244. if 'R' in flash_el_dict:
  1245. flash_el_dict['R'].append(geo_el)
  1246. else:
  1247. flash_el_dict['R'] = [geo_el]
  1248. else:
  1249. aperture_size = apval['size']
  1250. if aperture_size in traces_el_dict:
  1251. traces_el_dict[aperture_size].append(geo_el)
  1252. else:
  1253. traces_el_dict[aperture_size] = [geo_el]
  1254. cpoly = FlatCAMRTreeStorage()
  1255. pads_lines_list = []
  1256. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1257. # flashes and with _("Seed") for oblong and circular flashes
  1258. # and pads (flahes) need the contour therefore I override the GUI settings with always True
  1259. for ap_type in flash_el_dict:
  1260. for elem in flash_el_dict[ap_type]:
  1261. if 'solid' in elem:
  1262. if ap_type == 'C':
  1263. f_o = self.clear_polygon2(elem['solid'],
  1264. tooldia=tooldiameter,
  1265. steps_per_circle=self.app.defaults[
  1266. "geometry_circle_steps"],
  1267. overlap=over,
  1268. contour=True,
  1269. connect=conn,
  1270. prog_plot=prog_plot)
  1271. pads_lines_list += [p for p in f_o.get_objects() if p]
  1272. elif ap_type == 'O':
  1273. f_o = self.clear_polygon2(elem['solid'],
  1274. tooldia=tooldiameter,
  1275. steps_per_circle=self.app.defaults[
  1276. "geometry_circle_steps"],
  1277. overlap=over,
  1278. contour=True,
  1279. connect=conn,
  1280. prog_plot=prog_plot)
  1281. pads_lines_list += [p for p in f_o.get_objects() if p]
  1282. elif ap_type == 'R':
  1283. f_o = self.clear_polygon3(elem['solid'],
  1284. tooldia=tooldiameter,
  1285. steps_per_circle=self.app.defaults[
  1286. "geometry_circle_steps"],
  1287. overlap=over,
  1288. contour=True,
  1289. connect=conn,
  1290. prog_plot=prog_plot)
  1291. pads_lines_list += [p for p in f_o.get_objects() if p]
  1292. # add the lines from pads to the storage
  1293. try:
  1294. for lin in pads_lines_list:
  1295. if lin:
  1296. cpoly.insert(lin)
  1297. except TypeError:
  1298. cpoly.insert(pads_lines_list)
  1299. copper_lines_list = []
  1300. # process the traces found in the selected polygon using the 'laser_lines' method,
  1301. # method which will follow the 'follow' line therefore use the longer path possible for the
  1302. # laser, therefore the acceleration will play a smaller factor
  1303. for aperture_size in traces_el_dict:
  1304. for elem in traces_el_dict[aperture_size]:
  1305. line = elem['follow']
  1306. if line:
  1307. t_o = self.fill_with_lines(line, aperture_size,
  1308. tooldia=tooldiameter,
  1309. steps_per_circle=self.app.defaults[
  1310. "geometry_circle_steps"],
  1311. overlap=over,
  1312. contour=cont,
  1313. connect=conn,
  1314. prog_plot=prog_plot)
  1315. copper_lines_list += [p for p in t_o.get_objects() if p]
  1316. # add the lines from copper features to storage but first try to make as few lines as possible
  1317. # by trying to fuse them
  1318. lines_union = linemerge(unary_union(copper_lines_list))
  1319. try:
  1320. for lin in lines_union:
  1321. if lin:
  1322. cpoly.insert(lin)
  1323. except TypeError:
  1324. cpoly.insert(lines_union)
  1325. # # determine the Gerber follow line
  1326. # for apid, apval in obj.apertures.items():
  1327. # for geo_el in apval['geometry']:
  1328. # if 'solid' in geo_el:
  1329. # if Point(inside_pt).within(geo_el['solid']):
  1330. # if not isinstance(geo_el['follow'], Point):
  1331. # line = geo_el['follow']
  1332. #
  1333. # if apval['type'] == 'C':
  1334. # aperture_size = apval['size']
  1335. # else:
  1336. # if apval['width'] > apval['height']:
  1337. # aperture_size = apval['height']
  1338. # else:
  1339. # aperture_size = apval['width']
  1340. #
  1341. # if line:
  1342. # cpoly = self.fill_with_lines(line, aperture_size,
  1343. # tooldia=tooldiameter,
  1344. # steps_per_circle=self.circle_steps,
  1345. # overlap=over,
  1346. # contour=cont,
  1347. # connect=conn,
  1348. # prog_plot=prog_plot)
  1349. except grace:
  1350. return "fail"
  1351. except Exception as ee:
  1352. log.debug("ToolPaint.paint_polygon_worker() Laser Lines --> %s" % str(ee))
  1353. elif paint_method == _("Combo"):
  1354. try:
  1355. self.app.inform.emit(_("Painting polygon with method: lines."))
  1356. cpoly = self.clear_polygon3(polyg,
  1357. tooldia=tooldiameter,
  1358. steps_per_circle=self.circle_steps,
  1359. overlap=over,
  1360. contour=cont,
  1361. connect=conn,
  1362. prog_plot=prog_plot)
  1363. if cpoly and cpoly.objects:
  1364. pass
  1365. else:
  1366. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1367. cpoly = self.clear_polygon2(polyg,
  1368. tooldia=tooldiameter,
  1369. steps_per_circle=self.circle_steps,
  1370. overlap=over,
  1371. contour=cont,
  1372. connect=conn,
  1373. prog_plot=prog_plot)
  1374. if cpoly and cpoly.objects:
  1375. pass
  1376. else:
  1377. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1378. cpoly = self.clear_polygon(polyg,
  1379. tooldia=tooldiameter,
  1380. steps_per_circle=self.circle_steps,
  1381. overlap=over,
  1382. contour=cont,
  1383. connect=conn,
  1384. prog_plot=prog_plot)
  1385. except grace:
  1386. return "fail"
  1387. except Exception as ee:
  1388. log.debug("ToolPaint.paint_polygon_worker() Combo --> %s" % str(ee))
  1389. if cpoly and cpoly.objects:
  1390. return cpoly
  1391. else:
  1392. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1393. return None
  1394. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, order=None, method=None, outname=None,
  1395. tools_storage=None, plot=True, run_threaded=True):
  1396. """
  1397. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1398. Note:
  1399. * The margin is taken directly from the form.
  1400. :param run_threaded:
  1401. :param plot:
  1402. :param poly_list:
  1403. :param obj: painted object
  1404. :param inside_pt: [x, y]
  1405. :param tooldia: Diameter of the painting tool
  1406. :param order: if the tools are ordered and how
  1407. :param outname: Name of the resulting Geometry Object.
  1408. :param method: choice out of _("Seed"), 'normal', 'lines'
  1409. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1410. Usage of the different one is related to when this function is called from a TcL command.
  1411. :return: None
  1412. """
  1413. if obj.kind == 'gerber':
  1414. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1415. if self.app.defaults["gerber_buffering"] == 'no':
  1416. msg = '%s %s %s' % (_("Paint Tool."),
  1417. _("Normal painting polygon task started."),
  1418. _("Buffering geometry..."))
  1419. self.app.inform.emit(msg)
  1420. else:
  1421. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1422. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1423. if isinstance(obj.solid_geometry, list):
  1424. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1425. else:
  1426. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1427. else:
  1428. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1429. if inside_pt and poly_list is None:
  1430. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1431. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1432. polygon_list = poly_list
  1433. else:
  1434. return
  1435. # No polygon?
  1436. if polygon_list is None:
  1437. self.app.log.warning('No polygon found.')
  1438. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1439. return
  1440. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1441. # determine if to use the progressive plotting
  1442. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1443. name = outname if outname is not None else self.obj_name + "_paint"
  1444. order = order if order is not None else self.ui.order_radio.get_value()
  1445. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1446. sorted_tools = []
  1447. if tooldia is not None:
  1448. try:
  1449. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1450. except AttributeError:
  1451. if not isinstance(tooldia, list):
  1452. sorted_tools = [float(tooldia)]
  1453. else:
  1454. sorted_tools = tooldia
  1455. else:
  1456. for row in range(self.ui.tools_table.rowCount()):
  1457. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  1458. # sort the tools if we have an order selected in the UI
  1459. if order == 'fwd':
  1460. sorted_tools.sort(reverse=False)
  1461. elif order == 'rev':
  1462. sorted_tools.sort(reverse=True)
  1463. proc = self.app.proc_container.new(_("Painting polygon..."))
  1464. tool_dia = None
  1465. current_uid = None
  1466. final_solid_geometry = []
  1467. old_disp_number = 0
  1468. for tool_dia in sorted_tools:
  1469. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1470. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1471. str(tool_dia),
  1472. self.units.lower(),
  1473. _('started'))
  1474. self.app.inform.emit(msg)
  1475. self.app.proc_container.update_view_text(' %d%%' % 0)
  1476. # find the tooluid associated with the current tool_dia so we know what tool to use
  1477. for k, v in tools_storage.items():
  1478. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1479. current_uid = int(k)
  1480. if not current_uid:
  1481. return "fail"
  1482. # determine the tool parameters to use
  1483. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1484. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1485. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1486. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1487. poly_buf = []
  1488. for pol in polygon_list:
  1489. buffered_pol = pol.buffer(-paint_offset)
  1490. if buffered_pol and not buffered_pol.is_empty:
  1491. poly_buf.append(buffered_pol)
  1492. if not poly_buf:
  1493. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1494. continue
  1495. # variables to display the percentage of work done
  1496. geo_len = len(poly_buf)
  1497. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1498. pol_nr = 0
  1499. # -----------------------------
  1500. # effective polygon clearing job
  1501. # -----------------------------
  1502. try:
  1503. cp = []
  1504. try:
  1505. for pp in poly_buf:
  1506. # provide the app with a way to process the GUI events when in a blocking loop
  1507. QtWidgets.QApplication.processEvents()
  1508. if self.app.abort_flag:
  1509. # graceful abort requested by the user
  1510. raise grace
  1511. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1512. cont=cont, paint_method=paint_method, obj=obj,
  1513. prog_plot=prog_plot)
  1514. if geo_res:
  1515. cp.append(geo_res)
  1516. pol_nr += 1
  1517. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1518. # log.debug("Polygons cleared: %d" % pol_nr)
  1519. if old_disp_number < disp_number <= 100:
  1520. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1521. old_disp_number = disp_number
  1522. except TypeError:
  1523. # provide the app with a way to process the GUI events when in a blocking loop
  1524. QtWidgets.QApplication.processEvents()
  1525. if self.app.abort_flag:
  1526. # graceful abort requested by the user
  1527. raise grace
  1528. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1529. cont=cont, paint_method=paint_method, obj=obj,
  1530. prog_plot=prog_plot)
  1531. if geo_res:
  1532. cp.append(geo_res)
  1533. total_geometry = []
  1534. if cp:
  1535. for x in cp:
  1536. total_geometry += list(x.get_objects())
  1537. final_solid_geometry += total_geometry
  1538. except grace:
  1539. return "fail"
  1540. except Exception as e:
  1541. log.debug("Could not Paint the polygons. %s" % str(e))
  1542. self.app.inform.emit(
  1543. '[ERROR] %s\n%s' %
  1544. (_("Could not do Paint. Try a different combination of parameters. "
  1545. "Or a different strategy of paint"), str(e)
  1546. )
  1547. )
  1548. continue
  1549. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1550. # dictionary and then reset the temporary list that stored that solid_geometry
  1551. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1552. tools_storage[current_uid]['data']['name'] = name
  1553. # clean the progressive plotted shapes if it was used
  1554. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1555. self.temp_shapes.clear(update=True)
  1556. # delete tools with empty geometry
  1557. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1558. for uid in list(tools_storage.keys()):
  1559. # if the solid_geometry (type=list) is empty
  1560. if not tools_storage[uid]['solid_geometry']:
  1561. tools_storage.pop(uid, None)
  1562. if not tools_storage:
  1563. return 'fail'
  1564. def job_init(geo_obj, app_obj):
  1565. geo_obj.options["cnctooldia"] = str(tool_dia)
  1566. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1567. geo_obj.multigeo = True
  1568. geo_obj.multitool = True
  1569. geo_obj.tools.clear()
  1570. geo_obj.tools = dict(tools_storage)
  1571. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1572. try:
  1573. if isinstance(geo_obj.solid_geometry, list):
  1574. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1575. else:
  1576. a, b, c, d = geo_obj.solid_geometry.bounds
  1577. geo_obj.options['xmin'] = a
  1578. geo_obj.options['ymin'] = b
  1579. geo_obj.options['xmax'] = c
  1580. geo_obj.options['ymax'] = d
  1581. except Exception as ee:
  1582. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1583. return
  1584. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1585. has_solid_geo = 0
  1586. for tooluid in geo_obj.tools:
  1587. if geo_obj.tools[tooluid]['solid_geometry']:
  1588. has_solid_geo += 1
  1589. if has_solid_geo == 0:
  1590. app_obj.inform.emit('[ERROR] %s' %
  1591. _("There is no Painting Geometry in the file.\n"
  1592. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1593. "Change the painting parameters and try again."))
  1594. return "fail"
  1595. # Experimental...
  1596. # print("Indexing...", end=' ')
  1597. # geo_obj.make_index()
  1598. def job_thread(app_obj):
  1599. try:
  1600. ret = app_obj.app_obj.new_object("geometry", name, job_init, plot=plot)
  1601. except grace:
  1602. proc.done()
  1603. return
  1604. except Exception as er:
  1605. proc.done()
  1606. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly()', str(er)))
  1607. traceback.print_stack()
  1608. return
  1609. proc.done()
  1610. if ret == 'fail':
  1611. self.app.inform.emit('[ERROR] %s' % _("Paint Single failed."))
  1612. return
  1613. # focus on Selected Tab
  1614. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1615. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1616. self.app.inform.emit(_("Polygon Paint started ..."))
  1617. # Promise object with the new name
  1618. self.app.collection.promise(name)
  1619. if run_threaded:
  1620. # Background
  1621. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1622. else:
  1623. job_thread(app_obj=self.app)
  1624. def paint_poly_all(self, obj, tooldia=None, order=None, method=None, outname=None, tools_storage=None, plot=True,
  1625. run_threaded=True):
  1626. """
  1627. Paints all polygons in this object.
  1628. :param obj: painted object
  1629. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1630. :param order: if the tools are ordered and how
  1631. :param outname: name of the resulting object
  1632. :param method: choice out of _("Seed"), 'normal', 'lines'
  1633. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1634. Usage of the different one is related to when this function is called from
  1635. a TcL command.
  1636. :param run_threaded:
  1637. :param plot:
  1638. :return:
  1639. """
  1640. # This is a recursive generator of individual Polygons.
  1641. # Note: Double check correct implementation. Might exit
  1642. # early if it finds something that is not a Polygon?
  1643. # def recurse(geo):
  1644. # try:
  1645. # for subg in geo:
  1646. # for subsubg in recurse(subg):
  1647. # yield subsubg
  1648. # except TypeError:
  1649. # if isinstance(geo, Polygon):
  1650. # yield geo
  1651. #
  1652. # raise StopIteration
  1653. def recurse(geometry, reset=True):
  1654. """
  1655. Creates a list of non-iterable linear geometry objects.
  1656. Results are placed in self.flat_geometry
  1657. :param geometry: Shapely type or list or list of list of such.
  1658. :param reset: Clears the contents of self.flat_geometry.
  1659. """
  1660. if self.app.abort_flag:
  1661. # graceful abort requested by the user
  1662. raise grace
  1663. if geometry is None:
  1664. return
  1665. if reset:
  1666. self.flat_geometry = []
  1667. # ## If iterable, expand recursively.
  1668. try:
  1669. for geo in geometry:
  1670. if geo is not None:
  1671. recurse(geometry=geo, reset=False)
  1672. # ## Not iterable, do the actual indexing and add.
  1673. except TypeError:
  1674. if isinstance(geometry, LinearRing):
  1675. g = Polygon(geometry)
  1676. self.flat_geometry.append(g)
  1677. else:
  1678. self.flat_geometry.append(geometry)
  1679. return self.flat_geometry
  1680. if obj.kind == 'gerber':
  1681. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1682. if self.app.defaults["gerber_buffering"] == 'no':
  1683. msg = '%s %s %s' % (_("Paint Tool."), _("Paint all polygons task started."), _("Buffering geometry..."))
  1684. self.app.inform.emit(msg)
  1685. else:
  1686. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1687. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1688. if isinstance(obj.solid_geometry, list):
  1689. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1690. else:
  1691. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1692. else:
  1693. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1694. painted_area = recurse(obj.solid_geometry)
  1695. # No polygon?
  1696. if not painted_area:
  1697. self.app.log.warning('No polygon found.')
  1698. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1699. return
  1700. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1701. # determine if to use the progressive plotting
  1702. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1703. name = outname if outname is not None else self.obj_name + "_paint"
  1704. order = order if order is not None else self.ui.order_radio.get_value()
  1705. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1706. sorted_tools = []
  1707. if tooldia is not None:
  1708. try:
  1709. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1710. except AttributeError:
  1711. if not isinstance(tooldia, list):
  1712. sorted_tools = [float(tooldia)]
  1713. else:
  1714. sorted_tools = tooldia
  1715. else:
  1716. for row in range(self.ui.tools_table.rowCount()):
  1717. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  1718. proc = self.app.proc_container.new(_("Painting polygons..."))
  1719. # Initializes the new geometry object
  1720. def gen_paintarea(geo_obj, app_obj):
  1721. log.debug("Paint Tool. Normal painting all task started.")
  1722. if order == 'fwd':
  1723. sorted_tools.sort(reverse=False)
  1724. elif order == 'rev':
  1725. sorted_tools.sort(reverse=True)
  1726. else:
  1727. pass
  1728. tool_dia = None
  1729. current_uid = int(1)
  1730. old_disp_number = 0
  1731. final_solid_geometry = []
  1732. for tool_dia in sorted_tools:
  1733. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1734. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1735. str(tool_dia), self.units.lower(),
  1736. _('started'))
  1737. app_obj.inform.emit(mssg)
  1738. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1739. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1740. for k, v in tools_storage.items():
  1741. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1742. current_uid = int(k)
  1743. break
  1744. if not current_uid:
  1745. return "fail"
  1746. # determine the tool parameters to use
  1747. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1748. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1749. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1750. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1751. poly_buf = []
  1752. for pol in painted_area:
  1753. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  1754. buffered_pol = pol.buffer(-paint_offset)
  1755. if buffered_pol and not buffered_pol.is_empty:
  1756. poly_buf.append(buffered_pol)
  1757. if not poly_buf:
  1758. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1759. continue
  1760. # variables to display the percentage of work done
  1761. geo_len = len(poly_buf)
  1762. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1763. pol_nr = 0
  1764. # -----------------------------
  1765. # effective polygon clearing job
  1766. # -----------------------------
  1767. poly_processed = []
  1768. try:
  1769. cp = []
  1770. try:
  1771. for pp in poly_buf:
  1772. # provide the app with a way to process the GUI events when in a blocking loop
  1773. QtWidgets.QApplication.processEvents()
  1774. if self.app.abort_flag:
  1775. # graceful abort requested by the user
  1776. raise grace
  1777. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1778. cont=cont, paint_method=paint_method, obj=obj,
  1779. prog_plot=prog_plot)
  1780. if geo_res:
  1781. cp.append(geo_res)
  1782. poly_processed.append(True)
  1783. else:
  1784. poly_processed.append(False)
  1785. pol_nr += 1
  1786. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1787. # log.debug("Polygons cleared: %d" % pol_nr)
  1788. if old_disp_number < disp_number <= 100:
  1789. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1790. old_disp_number = disp_number
  1791. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1792. except TypeError:
  1793. # provide the app with a way to process the GUI events when in a blocking loop
  1794. QtWidgets.QApplication.processEvents()
  1795. if self.app.abort_flag:
  1796. # graceful abort requested by the user
  1797. raise grace
  1798. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1799. cont=cont, paint_method=paint_method, obj=obj,
  1800. prog_plot=prog_plot)
  1801. if geo_res:
  1802. cp.append(geo_res)
  1803. poly_processed.append(True)
  1804. else:
  1805. poly_processed.append(False)
  1806. total_geometry = []
  1807. if cp:
  1808. for x in cp:
  1809. total_geometry += list(x.get_objects())
  1810. # clean the geometry
  1811. new_geo = [g for g in total_geometry if g and not g.is_empty]
  1812. total_geometry = new_geo
  1813. final_solid_geometry += total_geometry
  1814. except Exception as err:
  1815. log.debug("Could not Paint the polygons. %s" % str(err))
  1816. self.app.inform.emit(
  1817. '[ERROR] %s\n%s' %
  1818. (_("Could not do Paint. Try a different combination of parameters. "
  1819. "Or a different strategy of paint"), str(err)
  1820. )
  1821. )
  1822. continue
  1823. p_cleared = poly_processed.count(True)
  1824. p_not_cleared = poly_processed.count(False)
  1825. if p_not_cleared:
  1826. app_obj.poly_not_cleared = True
  1827. if p_cleared == 0:
  1828. continue
  1829. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1830. # dictionary and then reset the temporary list that stored that solid_geometry
  1831. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1832. tools_storage[current_uid]['data']['name'] = name
  1833. # clean the progressive plotted shapes if it was used
  1834. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1835. self.temp_shapes.clear(update=True)
  1836. # delete tools with empty geometry
  1837. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1838. for uid in list(tools_storage.keys()):
  1839. # if the solid_geometry (type=list) is empty
  1840. if not tools_storage[uid]['solid_geometry']:
  1841. tools_storage.pop(uid, None)
  1842. if not tools_storage:
  1843. return 'fail'
  1844. geo_obj.options["cnctooldia"] = str(tool_dia)
  1845. # this turn on the FlatCAMCNCJob plot for multiple tools
  1846. geo_obj.multigeo = True
  1847. geo_obj.multitool = True
  1848. geo_obj.tools.clear()
  1849. geo_obj.tools = dict(tools_storage)
  1850. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1851. try:
  1852. # a, b, c, d = obj.bounds()
  1853. if isinstance(geo_obj.solid_geometry, list):
  1854. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1855. else:
  1856. a, b, c, d = geo_obj.solid_geometry.bounds
  1857. geo_obj.options['xmin'] = a
  1858. geo_obj.options['ymin'] = b
  1859. geo_obj.options['xmax'] = c
  1860. geo_obj.options['ymax'] = d
  1861. except Exception as e:
  1862. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1863. return
  1864. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1865. has_solid_geo = 0
  1866. for tooluid in geo_obj.tools:
  1867. if geo_obj.tools[tooluid]['solid_geometry']:
  1868. has_solid_geo += 1
  1869. if has_solid_geo == 0:
  1870. self.app.inform.emit('[ERROR] %s' %
  1871. _("There is no Painting Geometry in the file.\n"
  1872. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1873. "Change the painting parameters and try again."))
  1874. return "fail"
  1875. # Experimental...
  1876. # print("Indexing...", end=' ')
  1877. # geo_obj.make_index()
  1878. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1879. # Initializes the new geometry object
  1880. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1881. log.debug("Paint Tool. Rest machining painting all task started.")
  1882. # when using rest machining use always the reverse order; from bigger tool to smaller one
  1883. sorted_tools.sort(reverse=True)
  1884. tool_dia = None
  1885. cleared_geo = []
  1886. current_uid = int(1)
  1887. old_disp_number = 0
  1888. final_solid_geometry = []
  1889. for tool_dia in sorted_tools:
  1890. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1891. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1892. str(tool_dia),
  1893. self.units.lower(),
  1894. _('started'))
  1895. app_obj.inform.emit(mssg)
  1896. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1897. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1898. for k, v in tools_storage.items():
  1899. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1900. current_uid = int(k)
  1901. break
  1902. if not current_uid:
  1903. return "fail"
  1904. # determine the tool parameters to use
  1905. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1906. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1907. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1908. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1909. poly_buf = []
  1910. for pol in painted_area:
  1911. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  1912. buffered_pol = pol.buffer(-paint_offset)
  1913. if buffered_pol and not buffered_pol.is_empty:
  1914. poly_buf.append(buffered_pol)
  1915. if not poly_buf:
  1916. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1917. continue
  1918. # variables to display the percentage of work done
  1919. geo_len = len(poly_buf)
  1920. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1921. pol_nr = 0
  1922. # -----------------------------
  1923. # effective polygon clearing job
  1924. # -----------------------------
  1925. try:
  1926. cp = []
  1927. try:
  1928. for pp in poly_buf:
  1929. # provide the app with a way to process the GUI events when in a blocking loop
  1930. QtWidgets.QApplication.processEvents()
  1931. if self.app.abort_flag:
  1932. # graceful abort requested by the user
  1933. raise grace
  1934. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1935. cont=cont, paint_method=paint_method, obj=obj,
  1936. prog_plot=prog_plot)
  1937. if geo_res:
  1938. cp.append(geo_res)
  1939. pol_nr += 1
  1940. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1941. # log.debug("Polygons cleared: %d" % pol_nr)
  1942. if old_disp_number < disp_number <= 100:
  1943. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1944. old_disp_number = disp_number
  1945. except TypeError:
  1946. # provide the app with a way to process the GUI events when in a blocking loop
  1947. QtWidgets.QApplication.processEvents()
  1948. if self.app.abort_flag:
  1949. # graceful abort requested by the user
  1950. raise grace
  1951. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1952. cont=cont, paint_method=paint_method, obj=obj,
  1953. prog_plot=prog_plot)
  1954. if geo_res:
  1955. cp.append(geo_res)
  1956. if cp:
  1957. for x in cp:
  1958. cleared_geo += list(x.get_objects())
  1959. final_solid_geometry += cleared_geo
  1960. except grace:
  1961. return "fail"
  1962. except Exception as e:
  1963. log.debug("Could not Paint the polygons. %s" % str(e))
  1964. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1965. "Or a different strategy of paint"),
  1966. str(e))
  1967. self.app.inform.emit(mssg)
  1968. continue
  1969. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1970. # then reset the temporary list that stored that solid_geometry
  1971. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1972. tools_storage[current_uid]['data']['name'] = name
  1973. cleared_geo[:] = []
  1974. # clean the progressive plotted shapes if it was used
  1975. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1976. self.temp_shapes.clear(update=True)
  1977. # delete tools with empty geometry
  1978. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1979. for uid in list(tools_storage.keys()):
  1980. # if the solid_geometry (type=list) is empty
  1981. if not tools_storage[uid]['solid_geometry']:
  1982. tools_storage.pop(uid, None)
  1983. if not tools_storage:
  1984. return 'fail'
  1985. geo_obj.options["cnctooldia"] = str(tool_dia)
  1986. # this turn on the FlatCAMCNCJob plot for multiple tools
  1987. geo_obj.multigeo = True
  1988. geo_obj.multitool = True
  1989. geo_obj.tools.clear()
  1990. geo_obj.tools = dict(tools_storage)
  1991. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1992. try:
  1993. # a, b, c, d = obj.bounds()
  1994. if isinstance(geo_obj.solid_geometry, list):
  1995. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1996. else:
  1997. a, b, c, d = geo_obj.solid_geometry.bounds
  1998. geo_obj.options['xmin'] = a
  1999. geo_obj.options['ymin'] = b
  2000. geo_obj.options['xmax'] = c
  2001. geo_obj.options['ymax'] = d
  2002. except Exception as e:
  2003. log.debug("ToolPaint.paint_poly.gen_paintarea_rest_machining() bounds error --> %s" % str(e))
  2004. return
  2005. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2006. has_solid_geo = 0
  2007. for tooluid in geo_obj.tools:
  2008. if geo_obj.tools[tooluid]['solid_geometry']:
  2009. has_solid_geo += 1
  2010. if has_solid_geo == 0:
  2011. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2012. _("There is no Painting Geometry in the file.\n"
  2013. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2014. "Change the painting parameters and try again."))
  2015. return 'fail'
  2016. # Experimental...
  2017. # print("Indexing...", end=' ')
  2018. # geo_obj.make_index()
  2019. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2020. def job_thread(app_obj):
  2021. try:
  2022. if self.ui.rest_cb.isChecked():
  2023. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2024. else:
  2025. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2026. except grace:
  2027. proc.done()
  2028. return
  2029. except Exception as err:
  2030. proc.done()
  2031. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly_all()', str(err)))
  2032. traceback.print_stack()
  2033. return
  2034. proc.done()
  2035. if ret == 'fail':
  2036. self.app.inform.emit('[ERROR] %s' % _("Paint All failed."))
  2037. return
  2038. # focus on Selected Tab
  2039. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2040. self.app.inform.emit('[success] %s' % _("Paint Poly All Done."))
  2041. self.app.inform.emit(_("Polygon Paint started ..."))
  2042. # Promise object with the new name
  2043. self.app.collection.promise(name)
  2044. if run_threaded:
  2045. # Background
  2046. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2047. else:
  2048. job_thread(app_obj=self.app)
  2049. def paint_poly_area(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2050. tools_storage=None, plot=True, run_threaded=True):
  2051. """
  2052. Paints all polygons in this object that are within the sel_obj object
  2053. :param obj: painted object
  2054. :param sel_obj: paint only what is inside this object bounds
  2055. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2056. :param order: if the tools are ordered and how
  2057. :param outname: name of the resulting object
  2058. :param method: choice out of _("Seed"), 'normal', 'lines'
  2059. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2060. Usage of the different one is related to when this function is called from a TcL command.
  2061. :param run_threaded:
  2062. :param plot:
  2063. :return:
  2064. """
  2065. def recurse(geometry, reset=True):
  2066. """
  2067. Creates a list of non-iterable linear geometry objects.
  2068. Results are placed in self.flat_geometry
  2069. :param geometry: Shapely type or list or list of list of such.
  2070. :param reset: Clears the contents of self.flat_geometry.
  2071. """
  2072. if self.app.abort_flag:
  2073. # graceful abort requested by the user
  2074. raise grace
  2075. if geometry is None:
  2076. return
  2077. if reset:
  2078. self.flat_geometry = []
  2079. # ## If iterable, expand recursively.
  2080. try:
  2081. for geo in geometry:
  2082. if geo is not None:
  2083. recurse(geometry=geo, reset=False)
  2084. # ## Not iterable, do the actual indexing and add.
  2085. except TypeError:
  2086. if isinstance(geometry, LinearRing):
  2087. g = Polygon(geometry)
  2088. self.flat_geometry.append(g)
  2089. else:
  2090. self.flat_geometry.append(geometry)
  2091. return self.flat_geometry
  2092. # this is were heavy lifting is done and creating the geometry to be painted
  2093. target_geo = MultiPolygon(obj.solid_geometry)
  2094. if obj.kind == 'gerber':
  2095. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  2096. if self.app.defaults["gerber_buffering"] == 'no':
  2097. msg = '%s %s %s' % (_("Paint Tool."),
  2098. _("Painting area task started."),
  2099. _("Buffering geometry..."))
  2100. self.app.inform.emit(msg)
  2101. else:
  2102. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2103. if obj.kind == 'gerber':
  2104. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2105. target_geo = target_geo.buffer(0)
  2106. else:
  2107. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2108. geo_to_paint = target_geo.intersection(sel_obj)
  2109. painted_area = recurse(geo_to_paint)
  2110. # No polygon?
  2111. if not painted_area:
  2112. self.app.log.warning('No polygon found.')
  2113. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  2114. return
  2115. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  2116. # determine if to use the progressive plotting
  2117. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  2118. name = outname if outname is not None else self.obj_name + "_paint"
  2119. order = order if order is not None else self.ui.order_radio.get_value()
  2120. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  2121. sorted_tools = []
  2122. if tooldia is not None:
  2123. try:
  2124. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  2125. except AttributeError:
  2126. if not isinstance(tooldia, list):
  2127. sorted_tools = [float(tooldia)]
  2128. else:
  2129. sorted_tools = tooldia
  2130. else:
  2131. for row in range(self.ui.tools_table.rowCount()):
  2132. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  2133. proc = self.app.proc_container.new(_("Painting polygons..."))
  2134. # Initializes the new geometry object
  2135. def gen_paintarea(geo_obj, app_obj):
  2136. log.debug("Paint Tool. Normal painting area task started.")
  2137. if order == 'fwd':
  2138. sorted_tools.sort(reverse=False)
  2139. elif order == 'rev':
  2140. sorted_tools.sort(reverse=True)
  2141. else:
  2142. pass
  2143. tool_dia = None
  2144. current_uid = int(1)
  2145. old_disp_number = 0
  2146. final_solid_geometry = []
  2147. for tool_dia in sorted_tools:
  2148. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2149. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2150. str(tool_dia),
  2151. self.units.lower(),
  2152. _('started'))
  2153. app_obj.inform.emit(mssg)
  2154. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2155. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2156. for k, v in tools_storage.items():
  2157. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2158. current_uid = int(k)
  2159. break
  2160. if not current_uid:
  2161. return "fail"
  2162. # determine the tool parameters to use
  2163. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  2164. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  2165. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  2166. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  2167. poly_buf = []
  2168. for pol in painted_area:
  2169. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  2170. buffered_pol = pol.buffer(-paint_offset)
  2171. if buffered_pol and not buffered_pol.is_empty:
  2172. poly_buf.append(buffered_pol)
  2173. if not poly_buf:
  2174. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  2175. continue
  2176. # variables to display the percentage of work done
  2177. geo_len = len(poly_buf)
  2178. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2179. pol_nr = 0
  2180. # -----------------------------
  2181. # effective polygon clearing job
  2182. # -----------------------------
  2183. poly_processed = []
  2184. total_geometry = []
  2185. try:
  2186. try:
  2187. for pp in poly_buf:
  2188. # provide the app with a way to process the GUI events when in a blocking loop
  2189. QtWidgets.QApplication.processEvents()
  2190. if self.app.abort_flag:
  2191. # graceful abort requested by the user
  2192. raise grace
  2193. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  2194. cont=cont, paint_method=paint_method, obj=obj,
  2195. prog_plot=prog_plot)
  2196. if geo_res and geo_res.objects:
  2197. total_geometry += list(geo_res.get_objects())
  2198. poly_processed.append(True)
  2199. else:
  2200. poly_processed.append(False)
  2201. pol_nr += 1
  2202. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2203. # log.debug("Polygons cleared: %d" % pol_nr)
  2204. if old_disp_number < disp_number <= 100:
  2205. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2206. old_disp_number = disp_number
  2207. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2208. except TypeError:
  2209. # provide the app with a way to process the GUI events when in a blocking loop
  2210. QtWidgets.QApplication.processEvents()
  2211. if self.app.abort_flag:
  2212. # graceful abort requested by the user
  2213. raise grace
  2214. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  2215. cont=cont, paint_method=paint_method, obj=obj,
  2216. prog_plot=prog_plot)
  2217. if geo_res and geo_res.objects:
  2218. total_geometry += list(geo_res.get_objects())
  2219. poly_processed.append(True)
  2220. else:
  2221. poly_processed.append(False)
  2222. except Exception as err:
  2223. log.debug("Could not Paint the polygons. %s" % str(err))
  2224. self.app.inform.emit(
  2225. '[ERROR] %s\n%s' %
  2226. (_("Could not do Paint. Try a different combination of parameters. "
  2227. "Or a different strategy of paint"), str(err)
  2228. )
  2229. )
  2230. continue
  2231. p_cleared = poly_processed.count(True)
  2232. p_not_cleared = poly_processed.count(False)
  2233. if p_not_cleared:
  2234. app_obj.poly_not_cleared = True
  2235. if p_cleared == 0:
  2236. continue
  2237. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  2238. # dictionary and then reset the temporary list that stored that solid_geometry
  2239. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  2240. tools_storage[current_uid]['data']['name'] = name
  2241. total_geometry[:] = []
  2242. # clean the progressive plotted shapes if it was used
  2243. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2244. self.temp_shapes.clear(update=True)
  2245. # delete tools with empty geometry
  2246. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2247. for uid in list(tools_storage.keys()):
  2248. # if the solid_geometry (type=list) is empty
  2249. if not tools_storage[uid]['solid_geometry']:
  2250. tools_storage.pop(uid, None)
  2251. if not tools_storage:
  2252. return 'fail'
  2253. geo_obj.options["cnctooldia"] = str(tool_dia)
  2254. # this turn on the FlatCAMCNCJob plot for multiple tools
  2255. geo_obj.multigeo = True
  2256. geo_obj.multitool = True
  2257. geo_obj.tools.clear()
  2258. geo_obj.tools = dict(tools_storage)
  2259. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  2260. try:
  2261. a, b, c, d = self.paint_bounds(geo_to_paint)
  2262. geo_obj.options['xmin'] = a
  2263. geo_obj.options['ymin'] = b
  2264. geo_obj.options['xmax'] = c
  2265. geo_obj.options['ymax'] = d
  2266. except Exception as e:
  2267. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2268. return
  2269. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2270. has_solid_geo = 0
  2271. for tooluid in geo_obj.tools:
  2272. if geo_obj.tools[tooluid]['solid_geometry']:
  2273. has_solid_geo += 1
  2274. if has_solid_geo == 0:
  2275. self.app.inform.emit('[ERROR] %s' %
  2276. _("There is no Painting Geometry in the file.\n"
  2277. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2278. "Change the painting parameters and try again."))
  2279. return "fail"
  2280. # Experimental...
  2281. # print("Indexing...", end=' ')
  2282. # geo_obj.make_index()
  2283. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  2284. # Initializes the new geometry object
  2285. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2286. log.debug("Paint Tool. Rest machining painting area task started.")
  2287. sorted_tools.sort(reverse=True)
  2288. cleared_geo = []
  2289. tool_dia = None
  2290. current_uid = int(1)
  2291. old_disp_number = 0
  2292. final_solid_geometry = []
  2293. for tool_dia in sorted_tools:
  2294. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2295. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2296. str(tool_dia),
  2297. self.units.lower(),
  2298. _('started'))
  2299. app_obj.inform.emit(mssg)
  2300. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2301. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2302. for k, v in tools_storage.items():
  2303. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2304. current_uid = int(k)
  2305. break
  2306. if not current_uid:
  2307. return "fail"
  2308. # determine the tool parameters to use
  2309. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  2310. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  2311. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  2312. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  2313. poly_buf = []
  2314. for pol in painted_area:
  2315. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  2316. buffered_pol = pol.buffer(-paint_offset)
  2317. if buffered_pol and not buffered_pol.is_empty:
  2318. poly_buf.append(buffered_pol)
  2319. if not poly_buf:
  2320. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  2321. continue
  2322. # variables to display the percentage of work done
  2323. geo_len = len(poly_buf)
  2324. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2325. pol_nr = 0
  2326. # -----------------------------
  2327. # effective polygon clearing job
  2328. # -----------------------------
  2329. poly_processed = []
  2330. try:
  2331. try:
  2332. for pp in poly_buf:
  2333. # provide the app with a way to process the GUI events when in a blocking loop
  2334. QtWidgets.QApplication.processEvents()
  2335. if self.app.abort_flag:
  2336. # graceful abort requested by the user
  2337. raise grace
  2338. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  2339. cont=cont, paint_method=paint_method, obj=obj,
  2340. prog_plot=prog_plot)
  2341. if geo_res and geo_res.objects:
  2342. cleared_geo += list(geo_res.get_objects())
  2343. poly_processed.append(True)
  2344. else:
  2345. poly_processed.append(False)
  2346. pol_nr += 1
  2347. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2348. # log.debug("Polygons cleared: %d" % pol_nr)
  2349. if old_disp_number < disp_number <= 100:
  2350. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2351. old_disp_number = disp_number
  2352. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2353. except TypeError:
  2354. # provide the app with a way to process the GUI events when in a blocking loop
  2355. QtWidgets.QApplication.processEvents()
  2356. if self.app.abort_flag:
  2357. # graceful abort requested by the user
  2358. raise grace
  2359. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  2360. cont=cont, paint_method=paint_method, obj=obj,
  2361. prog_plot=prog_plot)
  2362. if geo_res and geo_res.objects:
  2363. cleared_geo += list(geo_res.get_objects())
  2364. poly_processed.append(True)
  2365. else:
  2366. poly_processed.append(False)
  2367. except Exception as err:
  2368. log.debug("Could not Paint the polygons. %s" % str(err))
  2369. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  2370. "Or a different strategy of paint"),
  2371. str(err))
  2372. self.app.inform.emit(mssg)
  2373. continue
  2374. p_cleared = poly_processed.count(True)
  2375. p_not_cleared = poly_processed.count(False)
  2376. if p_not_cleared:
  2377. app_obj.poly_not_cleared = True
  2378. if p_cleared == 0:
  2379. continue
  2380. final_solid_geometry += cleared_geo
  2381. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2382. # then reset the temporary list that stored that solid_geometry
  2383. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2384. tools_storage[current_uid]['data']['name'] = name
  2385. cleared_geo[:] = []
  2386. # clean the progressive plotted shapes if it was used
  2387. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2388. self.temp_shapes.clear(update=True)
  2389. # delete tools with empty geometry
  2390. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2391. for uid in list(tools_storage.keys()):
  2392. # if the solid_geometry (type=list) is empty
  2393. if not tools_storage[uid]['solid_geometry']:
  2394. tools_storage.pop(uid, None)
  2395. if not tools_storage:
  2396. return 'fail'
  2397. geo_obj.options["cnctooldia"] = str(tool_dia)
  2398. # this turn on the FlatCAMCNCJob plot for multiple tools
  2399. geo_obj.multigeo = True
  2400. geo_obj.multitool = True
  2401. geo_obj.tools.clear()
  2402. geo_obj.tools = dict(tools_storage)
  2403. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  2404. try:
  2405. a, b, c, d = self.paint_bounds(geo_to_paint)
  2406. geo_obj.options['xmin'] = a
  2407. geo_obj.options['ymin'] = b
  2408. geo_obj.options['xmax'] = c
  2409. geo_obj.options['ymax'] = d
  2410. except Exception as e:
  2411. log.debug("ToolPaint.paint_poly.gen_paintarea_rest_machining() bounds error --> %s" % str(e))
  2412. return
  2413. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2414. has_solid_geo = 0
  2415. for tooluid in geo_obj.tools:
  2416. if geo_obj.tools[tooluid]['solid_geometry']:
  2417. has_solid_geo += 1
  2418. if has_solid_geo == 0:
  2419. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2420. _("There is no Painting Geometry in the file.\n"
  2421. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2422. "Change the painting parameters and try again."))
  2423. return 'fail'
  2424. # Experimental...
  2425. # print("Indexing...", end=' ')
  2426. # geo_obj.make_index()
  2427. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2428. def job_thread(app_obj):
  2429. try:
  2430. if self.ui.rest_cb.isChecked():
  2431. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2432. else:
  2433. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2434. except grace:
  2435. proc.done()
  2436. return
  2437. except Exception as err:
  2438. proc.done()
  2439. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly_area()', str(err)))
  2440. traceback.print_stack()
  2441. return
  2442. proc.done()
  2443. if ret == 'fail':
  2444. self.app.inform.emit('[ERROR] %s' % _("Paint Area failed."))
  2445. return
  2446. # focus on Selected Tab
  2447. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2448. self.app.inform.emit('[success] %s' % _("Paint Poly Area Done."))
  2449. self.app.inform.emit(_("Polygon Paint started ..."))
  2450. # Promise object with the new name
  2451. self.app.collection.promise(name)
  2452. if run_threaded:
  2453. # Background
  2454. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2455. else:
  2456. job_thread(app_obj=self.app)
  2457. def paint_poly_ref(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2458. tools_storage=None, plot=True, run_threaded=True):
  2459. """
  2460. Paints all polygons in this object that are within the sel_obj object
  2461. :param obj: painted object
  2462. :param sel_obj: paint only what is inside this object bounds
  2463. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2464. :param order: if the tools are ordered and how
  2465. :param outname: name of the resulting object
  2466. :param method: choice out of _("Seed"), 'normal', 'lines'
  2467. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2468. Usage of the different one is related to when this function is called from a TcL command.
  2469. :param run_threaded:
  2470. :param plot:
  2471. :return:
  2472. """
  2473. geo = sel_obj.solid_geometry
  2474. try:
  2475. if isinstance(geo, MultiPolygon):
  2476. env_obj = geo.convex_hull
  2477. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2478. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2479. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2480. else:
  2481. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2482. env_obj = env_obj.convex_hull
  2483. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2484. except Exception as e:
  2485. log.debug("ToolPaint.paint_poly_ref() --> %s" % str(e))
  2486. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2487. return
  2488. self.paint_poly_area(obj=obj,
  2489. sel_obj=sel_rect,
  2490. tooldia=tooldia,
  2491. order=order,
  2492. method=method,
  2493. outname=outname,
  2494. tools_storage=tools_storage,
  2495. plot=plot,
  2496. run_threaded=run_threaded)
  2497. def ui_connect(self):
  2498. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  2499. # rows selected
  2500. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2501. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  2502. for row in range(self.ui.tools_table.rowCount()):
  2503. try:
  2504. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2505. except AttributeError:
  2506. pass
  2507. try:
  2508. self.ui.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2509. except AttributeError:
  2510. pass
  2511. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  2512. # first disconnect
  2513. for opt in self.form_fields:
  2514. current_widget = self.form_fields[opt]
  2515. if isinstance(current_widget, FCCheckBox):
  2516. try:
  2517. current_widget.stateChanged.disconnect()
  2518. except (TypeError, ValueError):
  2519. pass
  2520. if isinstance(current_widget, RadioSet):
  2521. try:
  2522. current_widget.activated_custom.disconnect()
  2523. except (TypeError, ValueError):
  2524. pass
  2525. elif isinstance(current_widget, FCDoubleSpinner):
  2526. try:
  2527. current_widget.returnPressed.disconnect()
  2528. except (TypeError, ValueError):
  2529. pass
  2530. # then reconnect
  2531. for opt in self.form_fields:
  2532. current_widget = self.form_fields[opt]
  2533. if isinstance(current_widget, FCCheckBox):
  2534. current_widget.stateChanged.connect(self.form_to_storage)
  2535. if isinstance(current_widget, RadioSet):
  2536. current_widget.activated_custom.connect(self.form_to_storage)
  2537. elif isinstance(current_widget, FCDoubleSpinner):
  2538. current_widget.returnPressed.connect(self.form_to_storage)
  2539. elif isinstance(current_widget, FCComboBox):
  2540. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2541. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  2542. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  2543. def ui_disconnect(self):
  2544. try:
  2545. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2546. self.ui.tools_table.itemChanged.disconnect()
  2547. except (TypeError, AttributeError):
  2548. pass
  2549. try:
  2550. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_row_selection_change)
  2551. except (TypeError, AttributeError):
  2552. pass
  2553. try:
  2554. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2555. self.ui.tool_type_radio.activated_custom.disconnect()
  2556. except (TypeError, AttributeError):
  2557. pass
  2558. for row in range(self.ui.tools_table.rowCount()):
  2559. for col in [2, 4]:
  2560. try:
  2561. self.ui.tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2562. except (TypeError, AttributeError):
  2563. pass
  2564. for opt in self.form_fields:
  2565. current_widget = self.form_fields[opt]
  2566. if isinstance(current_widget, FCCheckBox):
  2567. try:
  2568. current_widget.stateChanged.disconnect(self.form_to_storage)
  2569. except (TypeError, ValueError):
  2570. pass
  2571. if isinstance(current_widget, RadioSet):
  2572. try:
  2573. current_widget.activated_custom.disconnect(self.form_to_storage)
  2574. except (TypeError, ValueError):
  2575. pass
  2576. elif isinstance(current_widget, FCDoubleSpinner):
  2577. try:
  2578. current_widget.returnPressed.disconnect(self.form_to_storage)
  2579. except (TypeError, ValueError):
  2580. pass
  2581. elif isinstance(current_widget, FCComboBox):
  2582. try:
  2583. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2584. except (TypeError, ValueError):
  2585. pass
  2586. # rows selected
  2587. try:
  2588. self.ui.tools_table.clicked.disconnect()
  2589. except (TypeError, AttributeError):
  2590. pass
  2591. try:
  2592. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2593. except (TypeError, AttributeError):
  2594. pass
  2595. @staticmethod
  2596. def paint_bounds(geometry):
  2597. def bounds_rec(o):
  2598. if type(o) is list:
  2599. minx = Inf
  2600. miny = Inf
  2601. maxx = -Inf
  2602. maxy = -Inf
  2603. for k in o:
  2604. try:
  2605. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2606. except Exception as e:
  2607. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2608. return
  2609. minx = min(minx, minx_)
  2610. miny = min(miny, miny_)
  2611. maxx = max(maxx, maxx_)
  2612. maxy = max(maxy, maxy_)
  2613. return minx, miny, maxx, maxy
  2614. else:
  2615. # it's a Shapely object, return it's bounds
  2616. return o.bounds
  2617. return bounds_rec(geometry)
  2618. def on_paint_tool_add_from_db_executed(self, tool):
  2619. """
  2620. Here add the tool from DB in the selected geometry object
  2621. :return:
  2622. """
  2623. tool_from_db = deepcopy(tool)
  2624. res = self.on_paint_tool_from_db_inserted(tool=tool_from_db)
  2625. for idx in range(self.app.ui.plot_tab_area.count()):
  2626. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2627. wdg = self.app.ui.plot_tab_area.widget(idx)
  2628. wdg.deleteLater()
  2629. self.app.ui.plot_tab_area.removeTab(idx)
  2630. if res == 'fail':
  2631. return
  2632. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2633. # select last tool added
  2634. toolid = res
  2635. for row in range(self.ui.tools_table.rowCount()):
  2636. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2637. self.ui.tools_table.selectRow(row)
  2638. self.on_row_selection_change()
  2639. def on_paint_tool_from_db_inserted(self, tool):
  2640. """
  2641. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2642. :param tool: a dict with the tool data
  2643. :return: None
  2644. """
  2645. self.ui_disconnect()
  2646. self.units = self.app.defaults['units'].upper()
  2647. tooldia = float(tool['tooldia'])
  2648. # construct a list of all 'tooluid' in the self.tools
  2649. tool_uid_list = []
  2650. for tooluid_key in self.paint_tools:
  2651. tool_uid_item = int(tooluid_key)
  2652. tool_uid_list.append(tool_uid_item)
  2653. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2654. if not tool_uid_list:
  2655. max_uid = 0
  2656. else:
  2657. max_uid = max(tool_uid_list)
  2658. tooluid = max_uid + 1
  2659. tooldia = float('%.*f' % (self.decimals, tooldia))
  2660. tool_dias = []
  2661. for k, v in self.paint_tools.items():
  2662. for tool_v in v.keys():
  2663. if tool_v == 'tooldia':
  2664. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2665. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2666. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2667. self.ui_connect()
  2668. return 'fail'
  2669. self.paint_tools.update({
  2670. tooluid: {
  2671. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2672. 'offset': tool['offset'],
  2673. 'offset_value': tool['offset_value'],
  2674. 'type': tool['type'],
  2675. 'tool_type': tool['tool_type'],
  2676. 'data': deepcopy(tool['data']),
  2677. 'solid_geometry': []
  2678. }
  2679. })
  2680. self.paint_tools[tooluid]['data']['name'] = '_paint'
  2681. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2682. self.ui_connect()
  2683. self.build_ui()
  2684. # select the tool just added
  2685. for row in range(self.ui.tools_table.rowCount()):
  2686. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  2687. self.ui.tools_table.selectRow(row)
  2688. break
  2689. return tooluid
  2690. def on_paint_tool_add_from_db_clicked(self):
  2691. """
  2692. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2693. and display the Tools Database tab in the form needed for the Tool adding
  2694. :return: None
  2695. """
  2696. # if the Tools Database is already opened focus on it
  2697. for idx in range(self.app.ui.plot_tab_area.count()):
  2698. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2699. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2700. break
  2701. self.app.on_tools_database(source='paint')
  2702. self.app.tools_db_tab.ok_to_add = True
  2703. self.app.tools_db_tab.buttons_frame.hide()
  2704. self.app.tools_db_tab.add_tool_from_db.show()
  2705. self.app.tools_db_tab.cancel_tool_from_db.show()
  2706. def reset_fields(self):
  2707. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2708. class PaintUI:
  2709. toolName = _("Paint Tool")
  2710. def __init__(self, layout, app):
  2711. self.app = app
  2712. self.decimals = self.app.decimals
  2713. self.layout = layout
  2714. # ## Title
  2715. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2716. title_label.setStyleSheet("""
  2717. QLabel
  2718. {
  2719. font-size: 16px;
  2720. font-weight: bold;
  2721. }
  2722. """)
  2723. self.layout.addWidget(title_label)
  2724. self.tools_frame = QtWidgets.QFrame()
  2725. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2726. self.layout.addWidget(self.tools_frame)
  2727. self.tools_box = QtWidgets.QVBoxLayout()
  2728. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2729. self.tools_frame.setLayout(self.tools_box)
  2730. # ## Form Layout
  2731. grid0 = QtWidgets.QGridLayout()
  2732. grid0.setColumnStretch(0, 0)
  2733. grid0.setColumnStretch(1, 1)
  2734. self.tools_box.addLayout(grid0)
  2735. # ################################################
  2736. # ##### Type of object to be painted #############
  2737. # ################################################
  2738. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  2739. self.type_obj_combo_label.setToolTip(
  2740. _("Specify the type of object to be painted.\n"
  2741. "It can be of type: Gerber or Geometry.\n"
  2742. "What is selected here will dictate the kind\n"
  2743. "of objects that will populate the 'Object' combobox.")
  2744. )
  2745. self.type_obj_combo_label.setMinimumWidth(60)
  2746. self.type_obj_radio = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  2747. {'label': "Gerber", 'value': 'gerber'}])
  2748. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  2749. grid0.addWidget(self.type_obj_radio, 1, 1)
  2750. # ################################################
  2751. # ##### The object to be painted #################
  2752. # ################################################
  2753. self.obj_combo = FCComboBox()
  2754. self.obj_combo.setModel(self.app.collection)
  2755. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2756. self.obj_combo.is_last = True
  2757. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  2758. self.object_label.setToolTip(_("Object to be painted."))
  2759. grid0.addWidget(self.object_label, 2, 0)
  2760. grid0.addWidget(self.obj_combo, 2, 1)
  2761. separator_line = QtWidgets.QFrame()
  2762. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2763. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2764. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2765. # ### Tools ## ##
  2766. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  2767. self.tools_table_label.setToolTip(
  2768. _("Tools pool from which the algorithm\n"
  2769. "will pick the ones used for painting.")
  2770. )
  2771. self.tools_table = FCTable(drag_drop=True)
  2772. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2773. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  2774. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  2775. self.tools_table.setColumnCount(4)
  2776. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2777. self.tools_table.setColumnHidden(3, True)
  2778. # self.tools_table.setSortingEnabled(False)
  2779. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2780. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2781. _("This is the Tool Number.\n"
  2782. "Painting will start with the tool with the biggest diameter,\n"
  2783. "continuing until there are no more tools.\n"
  2784. "Only tools that create painting geometry will still be present\n"
  2785. "in the resulting geometry. This is because with some tools\n"
  2786. "this function will not be able to create painting geometry.")
  2787. )
  2788. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2789. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2790. "is the cut width into the material."))
  2791. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2792. _("The Tool Type (TT) can be:\n"
  2793. "- Circular -> it is informative only. Being circular,\n"
  2794. "the cut width in material is exactly the tool diameter.\n"
  2795. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2796. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2797. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2798. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2799. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2800. "column of this table.\n"
  2801. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2802. "in the resulting geometry as Isolation."))
  2803. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  2804. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2805. "'No' --> means that the used order is the one in the tool table\n"
  2806. "'Forward' --> means that the tools will be ordered from small to big\n"
  2807. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2808. "WARNING: using rest machining will automatically set the order\n"
  2809. "in reverse and disable this control."))
  2810. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2811. {'label': _('Forward'), 'value': 'fwd'},
  2812. {'label': _('Reverse'), 'value': 'rev'}])
  2813. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2814. "'No' --> means that the used order is the one in the tool table\n"
  2815. "'Forward' --> means that the tools will be ordered from small to big\n"
  2816. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2817. "WARNING: using rest machining will automatically set the order\n"
  2818. "in reverse and disable this control."))
  2819. grid0.addWidget(self.order_label, 9, 0)
  2820. grid0.addWidget(self.order_radio, 9, 1)
  2821. separator_line = QtWidgets.QFrame()
  2822. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2823. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2824. grid0.addWidget(separator_line, 10, 0, 1, 2)
  2825. self.grid3 = QtWidgets.QGridLayout()
  2826. self.tools_box.addLayout(self.grid3)
  2827. self.grid3.setColumnStretch(0, 0)
  2828. self.grid3.setColumnStretch(1, 1)
  2829. # ##############################################################################
  2830. # ###################### ADD A NEW TOOL ########################################
  2831. # ##############################################################################
  2832. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  2833. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  2834. # Tool Type Radio Button
  2835. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  2836. self.tool_type_label.setToolTip(
  2837. _("Default tool type:\n"
  2838. "- 'V-shape'\n"
  2839. "- Circular")
  2840. )
  2841. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  2842. {'label': _('Circular'), 'value': 'C1'}])
  2843. self.tool_type_radio.setToolTip(
  2844. _("Default tool type:\n"
  2845. "- 'V-shape'\n"
  2846. "- Circular")
  2847. )
  2848. self.tool_type_radio.setObjectName('p_tool_type')
  2849. self.grid3.addWidget(self.tool_type_label, 2, 0)
  2850. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  2851. # Tip Dia
  2852. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  2853. self.tipdialabel.setToolTip(
  2854. _("The tip diameter for V-Shape Tool"))
  2855. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2856. self.tipdia_entry.set_precision(self.decimals)
  2857. self.tipdia_entry.set_range(0.0000, 9999.9999)
  2858. self.tipdia_entry.setSingleStep(0.1)
  2859. self.tipdia_entry.setObjectName('p_vtip_dia')
  2860. self.grid3.addWidget(self.tipdialabel, 3, 0)
  2861. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  2862. # Tip Angle
  2863. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  2864. self.tipanglelabel.setToolTip(
  2865. _("The tip angle for V-Shape Tool.\n"
  2866. "In degree."))
  2867. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2868. self.tipangle_entry.set_precision(self.decimals)
  2869. self.tipangle_entry.set_range(0.0000, 180.0000)
  2870. self.tipangle_entry.setSingleStep(5)
  2871. self.tipangle_entry.setObjectName('p_vtip_angle')
  2872. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  2873. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  2874. # Cut Z entry
  2875. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2876. cutzlabel.setToolTip(
  2877. _("Depth of cut into material. Negative value.\n"
  2878. "In FlatCAM units.")
  2879. )
  2880. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2881. self.cutz_entry.set_precision(self.decimals)
  2882. self.cutz_entry.set_range(-99999.9999, 0.0000)
  2883. self.cutz_entry.setObjectName('p_cutz')
  2884. self.cutz_entry.setToolTip(
  2885. _("Depth of cut into material. Negative value.\n"
  2886. "In FlatCAM units.")
  2887. )
  2888. self.grid3.addWidget(cutzlabel, 5, 0)
  2889. self.grid3.addWidget(self.cutz_entry, 5, 1)
  2890. # ### Tool Diameter ####
  2891. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  2892. self.addtool_entry_lbl.setToolTip(
  2893. _("Diameter for the new tool to add in the Tool Table.\n"
  2894. "If the tool is V-shape type then this value is automatically\n"
  2895. "calculated from the other parameters.")
  2896. )
  2897. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2898. self.addtool_entry.set_precision(self.decimals)
  2899. self.addtool_entry.set_range(0.000, 9999.9999)
  2900. self.addtool_entry.setObjectName('p_tool_dia')
  2901. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  2902. self.grid3.addWidget(self.addtool_entry, 6, 1)
  2903. hlay = QtWidgets.QHBoxLayout()
  2904. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  2905. self.addtool_btn.setToolTip(
  2906. _("Add a new tool to the Tool Table\n"
  2907. "with the diameter specified above.")
  2908. )
  2909. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  2910. self.addtool_from_db_btn.setToolTip(
  2911. _("Add a new tool to the Tool Table\n"
  2912. "from the Tool Database.\n"
  2913. "Tool database administration in Menu: Options -> Tools Database")
  2914. )
  2915. hlay.addWidget(self.addtool_btn)
  2916. hlay.addWidget(self.addtool_from_db_btn)
  2917. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  2918. separator_line = QtWidgets.QFrame()
  2919. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2920. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2921. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2922. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  2923. self.deltool_btn.setToolTip(
  2924. _("Delete a selection of tools in the Tool Table\n"
  2925. "by first selecting a row(s) in the Tool Table.")
  2926. )
  2927. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2928. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  2929. separator_line = QtWidgets.QFrame()
  2930. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2931. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2932. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2933. self.tool_data_label = QtWidgets.QLabel(
  2934. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2935. self.tool_data_label.setToolTip(
  2936. _(
  2937. "The data used for creating GCode.\n"
  2938. "Each tool store it's own set of such data."
  2939. )
  2940. )
  2941. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2942. grid4 = QtWidgets.QGridLayout()
  2943. grid4.setColumnStretch(0, 0)
  2944. grid4.setColumnStretch(1, 1)
  2945. self.tools_box.addLayout(grid4)
  2946. # Overlap
  2947. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  2948. ovlabel.setToolTip(
  2949. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  2950. "Adjust the value starting with lower values\n"
  2951. "and increasing it if areas that should be painted are still \n"
  2952. "not painted.\n"
  2953. "Lower values = faster processing, faster execution on CNC.\n"
  2954. "Higher values = slow processing and slow execution on CNC\n"
  2955. "due of too many paths.")
  2956. )
  2957. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  2958. self.paintoverlap_entry.set_precision(3)
  2959. self.paintoverlap_entry.setWrapping(True)
  2960. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  2961. self.paintoverlap_entry.setSingleStep(0.1)
  2962. self.paintoverlap_entry.setObjectName('p_overlap')
  2963. grid4.addWidget(ovlabel, 1, 0)
  2964. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  2965. # Margin
  2966. marginlabel = QtWidgets.QLabel('%s:' % _('Offset'))
  2967. marginlabel.setToolTip(
  2968. _("Distance by which to avoid\n"
  2969. "the edges of the polygon to\n"
  2970. "be painted.")
  2971. )
  2972. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2973. self.offset_entry.set_precision(self.decimals)
  2974. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2975. self.offset_entry.setObjectName('p_offset')
  2976. grid4.addWidget(marginlabel, 2, 0)
  2977. grid4.addWidget(self.offset_entry, 2, 1)
  2978. # Method
  2979. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  2980. methodlabel.setToolTip(
  2981. _("Algorithm for painting:\n"
  2982. "- Standard: Fixed step inwards.\n"
  2983. "- Seed-based: Outwards from seed.\n"
  2984. "- Line-based: Parallel lines.\n"
  2985. "- Laser-lines: Active only for Gerber objects.\n"
  2986. "Will create lines that follow the traces.\n"
  2987. "- Combo: In case of failure a new method will be picked from the above\n"
  2988. "in the order specified.")
  2989. )
  2990. # self.paintmethod_combo = RadioSet([
  2991. # {"label": _("Standard"), "value": "standard"},
  2992. # {"label": _("Seed-based"), "value": _("Seed")},
  2993. # {"label": _("Straight lines"), "value": _("Lines")},
  2994. # {"label": _("Laser lines"), "value": _("Laser_lines")},
  2995. # {"label": _("Combo"), "value": _("Combo")}
  2996. # ], orientation='vertical', stretch=False)
  2997. # for choice in self.paintmethod_combo.choices:
  2998. # if choice['value'] == _("Laser_lines"):
  2999. # choice["radio"].setEnabled(False)
  3000. self.paintmethod_combo = FCComboBox()
  3001. self.paintmethod_combo.addItems(
  3002. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  3003. )
  3004. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  3005. self.paintmethod_combo.model().item(idx).setEnabled(False)
  3006. self.paintmethod_combo.setObjectName('p_method')
  3007. grid4.addWidget(methodlabel, 7, 0)
  3008. grid4.addWidget(self.paintmethod_combo, 7, 1)
  3009. # Connect lines
  3010. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  3011. self.pathconnect_cb.setObjectName('p_connect')
  3012. self.pathconnect_cb.setToolTip(
  3013. _("Draw lines between resulting\n"
  3014. "segments to minimize tool lifts.")
  3015. )
  3016. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  3017. self.paintcontour_cb.setObjectName('p_contour')
  3018. self.paintcontour_cb.setToolTip(
  3019. _("Cut around the perimeter of the polygon\n"
  3020. "to trim rough edges.")
  3021. )
  3022. grid4.addWidget(self.pathconnect_cb, 10, 0)
  3023. grid4.addWidget(self.paintcontour_cb, 10, 1)
  3024. separator_line = QtWidgets.QFrame()
  3025. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3026. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3027. grid4.addWidget(separator_line, 11, 0, 1, 2)
  3028. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  3029. self.apply_param_to_all.setToolTip(
  3030. _("The parameters in the current form will be applied\n"
  3031. "on all the tools from the Tool Table.")
  3032. )
  3033. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  3034. separator_line = QtWidgets.QFrame()
  3035. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3036. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3037. grid4.addWidget(separator_line, 13, 0, 1, 2)
  3038. # General Parameters
  3039. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  3040. self.gen_param_label.setToolTip(
  3041. _("Parameters that are common for all tools.")
  3042. )
  3043. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  3044. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  3045. self.rest_cb.setObjectName('p_rest_machining')
  3046. self.rest_cb.setToolTip(
  3047. _("If checked, use 'rest machining'.\n"
  3048. "Basically it will clear copper outside PCB features,\n"
  3049. "using the biggest tool and continue with the next tools,\n"
  3050. "from bigger to smaller, to clear areas of copper that\n"
  3051. "could not be cleared by previous tool, until there is\n"
  3052. "no more copper to clear or there are no more tools.\n\n"
  3053. "If not checked, use the standard algorithm.")
  3054. )
  3055. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  3056. # Polygon selection
  3057. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  3058. selectlabel.setToolTip(
  3059. _("Selection of area to be processed.\n"
  3060. "- 'Polygon Selection' - left mouse click to add/remove polygons to be processed.\n"
  3061. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  3062. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  3063. "- 'All Polygons' - the process will start after click.\n"
  3064. "- 'Reference Object' - will process the area specified by another object.")
  3065. )
  3066. # grid3 = QtWidgets.QGridLayout()
  3067. # self.selectmethod_combo = RadioSet([
  3068. # {"label": _("Polygon Selection"), "value": "single"},
  3069. # {"label": _("Area Selection"), "value": "area"},
  3070. # {"label": _("All Polygons"), "value": "all"},
  3071. # {"label": _("Reference Object"), "value": "ref"}
  3072. # ], orientation='vertical', stretch=False)
  3073. # self.selectmethod_combo.setObjectName('p_selection')
  3074. # self.selectmethod_combo.setToolTip(
  3075. # _("How to select Polygons to be painted.\n"
  3076. # "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  3077. # "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  3078. # "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  3079. # "- 'All Polygons' - the Paint will start after click.\n"
  3080. # "- 'Reference Object' - will do non copper clearing within the area\n"
  3081. # "specified by another object.")
  3082. # )
  3083. self.selectmethod_combo = FCComboBox()
  3084. self.selectmethod_combo.addItems(
  3085. [_("Polygon Selection"), _("Area Selection"), _("All"), _("Reference Object")]
  3086. )
  3087. self.selectmethod_combo.setObjectName('p_selection')
  3088. grid4.addWidget(selectlabel, 18, 0)
  3089. grid4.addWidget(self.selectmethod_combo, 18, 1)
  3090. form1 = QtWidgets.QFormLayout()
  3091. grid4.addLayout(form1, 20, 0, 1, 2)
  3092. self.reference_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  3093. self.reference_type_label.setToolTip(
  3094. _("The type of FlatCAM object to be used as paint reference.\n"
  3095. "It can be Gerber, Excellon or Geometry.")
  3096. )
  3097. self.reference_type_combo = FCComboBox()
  3098. self.reference_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  3099. form1.addRow(self.reference_type_label, self.reference_type_combo)
  3100. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  3101. self.reference_combo_label.setToolTip(
  3102. _("The FlatCAM object to be used as non copper clearing reference.")
  3103. )
  3104. self.reference_combo = FCComboBox()
  3105. self.reference_combo.setModel(self.app.collection)
  3106. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3107. self.reference_combo.is_last = True
  3108. form1.addRow(self.reference_combo_label, self.reference_combo)
  3109. self.reference_combo.hide()
  3110. self.reference_combo_label.hide()
  3111. self.reference_type_combo.hide()
  3112. self.reference_type_label.hide()
  3113. # Area Selection shape
  3114. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  3115. self.area_shape_label.setToolTip(
  3116. _("The kind of selection shape used for area selection.")
  3117. )
  3118. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  3119. {'label': _("Polygon"), 'value': 'polygon'}])
  3120. grid4.addWidget(self.area_shape_label, 21, 0)
  3121. grid4.addWidget(self.area_shape_radio, 21, 1)
  3122. self.area_shape_label.hide()
  3123. self.area_shape_radio.hide()
  3124. # GO Button
  3125. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  3126. self.generate_paint_button.setToolTip(
  3127. _("Create a Geometry Object which paints the polygons.")
  3128. )
  3129. self.generate_paint_button.setStyleSheet("""
  3130. QPushButton
  3131. {
  3132. font-weight: bold;
  3133. }
  3134. """)
  3135. self.tools_box.addWidget(self.generate_paint_button)
  3136. self.tools_box.addStretch()
  3137. # ## Reset Tool
  3138. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  3139. self.reset_button.setToolTip(
  3140. _("Will reset the tool parameters.")
  3141. )
  3142. self.reset_button.setStyleSheet("""
  3143. QPushButton
  3144. {
  3145. font-weight: bold;
  3146. }
  3147. """)
  3148. self.tools_box.addWidget(self.reset_button)
  3149. # #################################### FINSIHED GUI ###########################
  3150. # #############################################################################
  3151. def confirmation_message(self, accepted, minval, maxval):
  3152. if accepted is False:
  3153. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  3154. self.decimals,
  3155. minval,
  3156. self.decimals,
  3157. maxval), False)
  3158. else:
  3159. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  3160. def confirmation_message_int(self, accepted, minval, maxval):
  3161. if accepted is False:
  3162. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  3163. (_("Edited value is out of range"), minval, maxval), False)
  3164. else:
  3165. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)