ToolPaint.py 194 KB

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