ToolIsolation.py 163 KB

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