ToolIsolation.py 130 KB

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