ToolPaint.py 161 KB

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