ToolPaint.py 159 KB

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