ToolPaint.py 160 KB

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