ToolPaint.py 162 KB

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