ToolPaint.py 160 KB

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