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