ToolPaint.py 141 KB

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