ToolPaint.py 162 KB

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