ToolPaint.py 161 KB

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