ToolPaint.py 194 KB

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