ToolIsolation.py 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  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. hlay = 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. hlay.addWidget(self.addtool_btn)
  237. hlay.addWidget(self.addtool_from_db_btn)
  238. self.grid3.addLayout(hlay, 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. self.form_fields = {
  554. "tools_iso_passes": self.passes_entry,
  555. "tools_iso_overlap": self.iso_overlap_entry,
  556. "tools_iso_milling_type": self.milling_type_radio,
  557. "tools_iso_combine": self.combine_passes_cb,
  558. "tools_iso_follow": self.follow_cb,
  559. "tools_iso_isotype": self.iso_type_radio
  560. }
  561. self.name2option = {
  562. "i_passes": "tools_iso_passes",
  563. "i_overlap": "tools_iso_overlap",
  564. "i_milling_type": "tools_iso_milling_type",
  565. "i_combine": "tools_iso_combine",
  566. "i_follow": "tools_iso_follow",
  567. "i_iso_type": "tools_iso_isotype"
  568. }
  569. self.old_tool_dia = None
  570. # #############################################################################
  571. # ############################ SIGNALS ########################################
  572. # #############################################################################
  573. self.addtool_btn.clicked.connect(self.on_tool_add)
  574. self.addtool_entry.returnPressed.connect(self.on_tooldia_updated)
  575. self.deltool_btn.clicked.connect(self.on_tool_delete)
  576. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  577. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  578. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  579. self.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  580. self.select_combo.currentIndexChanged.connect(self.on_toggle_reference)
  581. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  582. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  583. self.type_excobj_radio.activated_custom.connect(self.on_type_excobj_index_changed)
  584. self.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  585. self.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  586. self.generate_iso_button.clicked.connect(self.on_iso_button_click)
  587. self.reset_button.clicked.connect(self.set_tool_ui)
  588. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  589. self.app.cleanup.connect(self.reset_usage)
  590. def on_type_excobj_index_changed(self, val):
  591. obj_type = 0 if val == 'gerber' else 2
  592. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  593. self.exc_obj_combo.setCurrentIndex(0)
  594. self.exc_obj_combo.obj_type = {
  595. "gerber": "Gerber", "geometry": "Geometry"
  596. }[self.type_excobj_radio.get_value()]
  597. def install(self, icon=None, separator=None, **kwargs):
  598. AppTool.install(self, icon, separator, shortcut='Alt+I', **kwargs)
  599. def run(self, toggle=True):
  600. self.app.defaults.report_usage("ToolIsolation()")
  601. log.debug("ToolIsolation().run() was launched ...")
  602. if toggle:
  603. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  604. if self.app.ui.splitter.sizes()[0] == 0:
  605. self.app.ui.splitter.setSizes([1, 1])
  606. else:
  607. try:
  608. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  609. # if tab is populated with the tool but it does not have the focus, focus on it
  610. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  611. # focus on Tool Tab
  612. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  613. else:
  614. self.app.ui.splitter.setSizes([0, 1])
  615. except AttributeError:
  616. pass
  617. else:
  618. if self.app.ui.splitter.sizes()[0] == 0:
  619. self.app.ui.splitter.setSizes([1, 1])
  620. AppTool.run(self)
  621. self.set_tool_ui()
  622. # reset those objects on a new run
  623. self.grb_obj = None
  624. self.obj_name = ''
  625. self.build_ui()
  626. self.app.ui.notebook.setTabText(2, _("Isolation Tool"))
  627. def set_tool_ui(self):
  628. self.units = self.app.defaults['units'].upper()
  629. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  630. # try to select in the Gerber combobox the active object
  631. try:
  632. selected_obj = self.app.collection.get_active()
  633. if selected_obj.kind == 'gerber':
  634. current_name = selected_obj.options['name']
  635. self.object_combo.set_value(current_name)
  636. except Exception:
  637. pass
  638. app_mode = self.app.defaults["global_app_level"]
  639. # Show/Hide Advanced Options
  640. if app_mode == 'b':
  641. self.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  642. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  643. self.tool_type_radio.set_value('C1')
  644. self.tool_type_label.hide()
  645. self.tool_type_radio.hide()
  646. self.milling_type_label.hide()
  647. self.milling_type_radio.hide()
  648. self.iso_type_label.hide()
  649. self.iso_type_radio.set_value('full')
  650. self.iso_type_radio.hide()
  651. self.follow_cb.set_value(False)
  652. self.follow_cb.hide()
  653. self.follow_label.hide()
  654. self.rest_cb.set_value(False)
  655. self.rest_cb.hide()
  656. self.except_cb.set_value(False)
  657. self.except_cb.hide()
  658. self.select_combo.setCurrentIndex(0)
  659. self.select_combo.hide()
  660. self.select_label.hide()
  661. else:
  662. self.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  663. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  664. self.tool_type_label.show()
  665. self.tool_type_radio.show()
  666. self.milling_type_label.show()
  667. self.milling_type_radio.show()
  668. self.iso_type_label.show()
  669. self.iso_type_radio.set_value(self.app.defaults["tools_iso_isotype"])
  670. self.iso_type_radio.show()
  671. self.follow_cb.set_value(self.app.defaults["tools_iso_follow"])
  672. self.follow_cb.show()
  673. self.follow_label.show()
  674. self.rest_cb.set_value(self.app.defaults["tools_iso_rest"])
  675. self.rest_cb.show()
  676. self.except_cb.set_value(self.app.defaults["tools_iso_isoexcept"])
  677. self.except_cb.show()
  678. self.select_combo.set_value(self.app.defaults["tools_iso_selection"])
  679. self.select_combo.show()
  680. self.select_label.show()
  681. if self.app.defaults["gerber_buffering"] == 'no':
  682. self.create_buffer_button.show()
  683. try:
  684. self.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  685. except TypeError:
  686. pass
  687. self.create_buffer_button.clicked.connect(self.on_generate_buffer)
  688. else:
  689. self.create_buffer_button.hide()
  690. self.tools_frame.show()
  691. self.type_excobj_radio.set_value('gerber')
  692. # run those once so the obj_type attribute is updated for the FCComboboxes
  693. # so the last loaded object is displayed
  694. self.on_type_excobj_index_changed(val="gerber")
  695. self.on_reference_combo_changed()
  696. self.order_radio.set_value(self.app.defaults["tools_iso_order"])
  697. self.passes_entry.set_value(self.app.defaults["tools_iso_passes"])
  698. self.iso_overlap_entry.set_value(self.app.defaults["tools_iso_overlap"])
  699. self.milling_type_radio.set_value(self.app.defaults["tools_iso_milling_type"])
  700. self.combine_passes_cb.set_value(self.app.defaults["tools_iso_combine_passes"])
  701. self.area_shape_radio.set_value(self.app.defaults["tools_iso_area_shape"])
  702. self.cutz_entry.set_value(self.app.defaults["tools_iso_tool_cutz"])
  703. self.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  704. self.tipdia_entry.set_value(self.app.defaults["tools_iso_tool_vtipdia"])
  705. self.tipangle_entry.set_value(self.app.defaults["tools_iso_tool_vtipangle"])
  706. self.addtool_entry.set_value(self.app.defaults["tools_iso_newdia"])
  707. self.on_tool_type(val=self.tool_type_radio.get_value())
  708. loaded_obj = self.app.collection.get_by_name(self.object_combo.get_value())
  709. if loaded_obj:
  710. outname = loaded_obj.options['name']
  711. else:
  712. outname = ''
  713. # init the working variables
  714. self.default_data.clear()
  715. self.default_data = {
  716. "name": outname + '_iso',
  717. "plot": self.app.defaults["geometry_plot"],
  718. "cutz": float(self.cutz_entry.get_value()),
  719. "vtipdia": float(self.tipdia_entry.get_value()),
  720. "vtipangle": float(self.tipangle_entry.get_value()),
  721. "travelz": self.app.defaults["geometry_travelz"],
  722. "feedrate": self.app.defaults["geometry_feedrate"],
  723. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  724. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  725. "dwell": self.app.defaults["geometry_dwell"],
  726. "dwelltime": self.app.defaults["geometry_dwelltime"],
  727. "multidepth": self.app.defaults["geometry_multidepth"],
  728. "ppname_g": self.app.defaults["geometry_ppname_g"],
  729. "depthperpass": self.app.defaults["geometry_depthperpass"],
  730. "extracut": self.app.defaults["geometry_extracut"],
  731. "extracut_length": self.app.defaults["geometry_extracut_length"],
  732. "toolchange": self.app.defaults["geometry_toolchange"],
  733. "toolchangez": self.app.defaults["geometry_toolchangez"],
  734. "endz": self.app.defaults["geometry_endz"],
  735. "endxy": self.app.defaults["geometry_endxy"],
  736. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  737. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  738. "startz": self.app.defaults["geometry_startz"],
  739. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  740. "area_shape": self.app.defaults["geometry_area_shape"],
  741. "area_strategy": self.app.defaults["geometry_area_strategy"],
  742. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  743. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  744. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  745. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  746. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  747. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  748. "tools_iso_rest": self.app.defaults["tools_iso_rest"],
  749. "tools_iso_combine_passes": self.app.defaults["tools_iso_combine_passes"],
  750. "tools_iso_isoexcept": self.app.defaults["tools_iso_isoexcept"],
  751. "tools_iso_selection": self.app.defaults["tools_iso_selection"],
  752. "tools_iso_area_shape": self.app.defaults["tools_iso_area_shape"]
  753. }
  754. try:
  755. dias = [float(self.app.defaults["tools_iso_tooldia"])]
  756. except (ValueError, TypeError):
  757. dias = [float(eval(dia)) for dia in self.app.defaults["tools_iso_tooldia"].split(",") if dia != '']
  758. if not dias:
  759. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> Isolation Tools.")
  760. return
  761. self.tooluid = 0
  762. self.iso_tools.clear()
  763. for tool_dia in dias:
  764. self.tooluid += 1
  765. self.iso_tools.update({
  766. int(self.tooluid): {
  767. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  768. 'offset': 'Path',
  769. 'offset_value': 0.0,
  770. 'type': 'Iso',
  771. 'tool_type': self.tool_type_radio.get_value(),
  772. 'data': deepcopy(self.default_data),
  773. 'solid_geometry': []
  774. }
  775. })
  776. self.obj_name = ""
  777. self.grb_obj = None
  778. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  779. self.units = self.app.defaults['units'].upper()
  780. def build_ui(self):
  781. self.ui_disconnect()
  782. # updated units
  783. self.units = self.app.defaults['units'].upper()
  784. sorted_tools = []
  785. for k, v in self.iso_tools.items():
  786. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  787. order = self.order_radio.get_value()
  788. if order == 'fwd':
  789. sorted_tools.sort(reverse=False)
  790. elif order == 'rev':
  791. sorted_tools.sort(reverse=True)
  792. else:
  793. pass
  794. n = len(sorted_tools)
  795. self.tools_table.setRowCount(n)
  796. tool_id = 0
  797. for tool_sorted in sorted_tools:
  798. for tooluid_key, tooluid_value in self.iso_tools.items():
  799. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  800. tool_id += 1
  801. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  802. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  803. row_no = tool_id - 1
  804. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  805. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  806. # There are no drill bits in MM with more than 2 decimals diameter
  807. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  808. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  809. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  810. tool_type_item = FCComboBox()
  811. tool_type_item.addItems(self.tool_type_item_options)
  812. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  813. idx = tool_type_item.findText(tooluid_value['tool_type'])
  814. tool_type_item.setCurrentIndex(idx)
  815. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  816. self.tools_table.setItem(row_no, 1, dia) # Diameter
  817. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  818. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  819. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  820. # make the diameter column editable
  821. for row in range(tool_id):
  822. self.tools_table.item(row, 1).setFlags(
  823. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  824. # all the tools are selected by default
  825. self.tools_table.selectColumn(0)
  826. #
  827. self.tools_table.resizeColumnsToContents()
  828. self.tools_table.resizeRowsToContents()
  829. vertical_header = self.tools_table.verticalHeader()
  830. vertical_header.hide()
  831. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  832. horizontal_header = self.tools_table.horizontalHeader()
  833. horizontal_header.setMinimumSectionSize(10)
  834. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  835. horizontal_header.resizeSection(0, 20)
  836. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  837. # self.tools_table.setSortingEnabled(True)
  838. # sort by tool diameter
  839. # self.tools_table.sortItems(1)
  840. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  841. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  842. self.ui_connect()
  843. # set the text on tool_data_label after loading the object
  844. sel_rows = []
  845. sel_items = self.tools_table.selectedItems()
  846. for it in sel_items:
  847. sel_rows.append(it.row())
  848. if len(sel_rows) > 1:
  849. self.tool_data_label.setText(
  850. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  851. )
  852. def ui_connect(self):
  853. self.tools_table.itemChanged.connect(self.on_tool_edit)
  854. # rows selected
  855. self.tools_table.clicked.connect(self.on_row_selection_change)
  856. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  857. for row in range(self.tools_table.rowCount()):
  858. try:
  859. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  860. except AttributeError:
  861. pass
  862. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  863. for opt in self.form_fields:
  864. current_widget = self.form_fields[opt]
  865. if isinstance(current_widget, FCCheckBox):
  866. current_widget.stateChanged.connect(self.form_to_storage)
  867. if isinstance(current_widget, RadioSet):
  868. current_widget.activated_custom.connect(self.form_to_storage)
  869. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  870. current_widget.returnPressed.connect(self.form_to_storage)
  871. elif isinstance(current_widget, FCComboBox):
  872. current_widget.currentIndexChanged.connect(self.form_to_storage)
  873. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  874. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  875. def ui_disconnect(self):
  876. try:
  877. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  878. self.tools_table.itemChanged.disconnect()
  879. except (TypeError, AttributeError):
  880. pass
  881. try:
  882. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  883. self.tool_type_radio.activated_custom.disconnect()
  884. except (TypeError, AttributeError):
  885. pass
  886. for row in range(self.tools_table.rowCount()):
  887. try:
  888. self.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  889. except (TypeError, AttributeError):
  890. pass
  891. for opt in self.form_fields:
  892. current_widget = self.form_fields[opt]
  893. if isinstance(current_widget, FCCheckBox):
  894. try:
  895. current_widget.stateChanged.disconnect(self.form_to_storage)
  896. except (TypeError, ValueError):
  897. pass
  898. if isinstance(current_widget, RadioSet):
  899. try:
  900. current_widget.activated_custom.disconnect(self.form_to_storage)
  901. except (TypeError, ValueError):
  902. pass
  903. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  904. try:
  905. current_widget.returnPressed.disconnect(self.form_to_storage)
  906. except (TypeError, ValueError):
  907. pass
  908. elif isinstance(current_widget, FCComboBox):
  909. try:
  910. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  911. except (TypeError, ValueError):
  912. pass
  913. try:
  914. self.rest_cb.stateChanged.disconnect()
  915. except (TypeError, ValueError):
  916. pass
  917. try:
  918. self.order_radio.activated_custom[str].disconnect()
  919. except (TypeError, ValueError):
  920. pass
  921. # rows selected
  922. try:
  923. self.tools_table.clicked.disconnect()
  924. except (TypeError, AttributeError):
  925. pass
  926. try:
  927. self.tools_table.horizontalHeader().sectionClicked.disconnect()
  928. except (TypeError, AttributeError):
  929. pass
  930. def on_row_selection_change(self):
  931. self.blockSignals(True)
  932. sel_rows = [it.row() for it in self.tools_table.selectedItems()]
  933. # sel_rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  934. if not sel_rows:
  935. sel_rows = [0]
  936. for current_row in sel_rows:
  937. # populate the form with the data from the tool associated with the row parameter
  938. try:
  939. item = self.tools_table.item(current_row, 3)
  940. if item is not None:
  941. tooluid = int(item.text())
  942. else:
  943. return
  944. except Exception as e:
  945. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  946. return
  947. # update the QLabel that shows for which Tool we have the parameters in the UI form
  948. if len(sel_rows) == 1:
  949. cr = current_row + 1
  950. self.tool_data_label.setText(
  951. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  952. )
  953. try:
  954. # set the form with data from the newly selected tool
  955. for tooluid_key, tooluid_value in list(self.iso_tools.items()):
  956. if int(tooluid_key) == tooluid:
  957. for key, value in tooluid_value.items():
  958. if key == 'data':
  959. form_value_storage = tooluid_value[key]
  960. self.storage_to_form(form_value_storage)
  961. except Exception as e:
  962. log.debug("ToolIsolation ---> update_ui() " + str(e))
  963. else:
  964. self.tool_data_label.setText(
  965. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  966. )
  967. self.blockSignals(False)
  968. def storage_to_form(self, dict_storage):
  969. for form_key in self.form_fields:
  970. for storage_key in dict_storage:
  971. if form_key == storage_key:
  972. try:
  973. self.form_fields[form_key].set_value(dict_storage[form_key])
  974. except Exception as e:
  975. log.debug("ToolIsolation.storage_to_form() --> %s" % str(e))
  976. pass
  977. def form_to_storage(self):
  978. if self.tools_table.rowCount() == 0:
  979. # there is no tool in tool table so we can't save the GUI elements values to storage
  980. return
  981. self.blockSignals(True)
  982. widget_changed = self.sender()
  983. wdg_objname = widget_changed.objectName()
  984. option_changed = self.name2option[wdg_objname]
  985. # row = self.tools_table.currentRow()
  986. rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  987. for row in rows:
  988. if row < 0:
  989. row = 0
  990. tooluid_item = int(self.tools_table.item(row, 3).text())
  991. for tooluid_key, tooluid_val in self.iso_tools.items():
  992. if int(tooluid_key) == tooluid_item:
  993. new_option_value = self.form_fields[option_changed].get_value()
  994. if option_changed in tooluid_val:
  995. tooluid_val[option_changed] = new_option_value
  996. if option_changed in tooluid_val['data']:
  997. tooluid_val['data'][option_changed] = new_option_value
  998. self.blockSignals(False)
  999. def on_apply_param_to_all_clicked(self):
  1000. if self.tools_table.rowCount() == 0:
  1001. # there is no tool in tool table so we can't save the GUI elements values to storage
  1002. log.debug("ToolIsolation.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  1003. return
  1004. self.blockSignals(True)
  1005. row = self.tools_table.currentRow()
  1006. if row < 0:
  1007. row = 0
  1008. tooluid_item = int(self.tools_table.item(row, 3).text())
  1009. temp_tool_data = {}
  1010. for tooluid_key, tooluid_val in self.iso_tools.items():
  1011. if int(tooluid_key) == tooluid_item:
  1012. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  1013. # the current row in the tool table
  1014. temp_tool_data = tooluid_val['data']
  1015. break
  1016. for tooluid_key, tooluid_val in self.iso_tools.items():
  1017. tooluid_val['data'] = deepcopy(temp_tool_data)
  1018. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  1019. self.blockSignals(False)
  1020. def on_add_tool_by_key(self):
  1021. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  1022. text='%s:' % _('Enter a Tool Diameter'),
  1023. min=0.0001, max=9999.9999, decimals=self.decimals)
  1024. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  1025. val, ok = tool_add_popup.get_value()
  1026. if ok:
  1027. if float(val) == 0:
  1028. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1029. _("Please enter a tool diameter with non-zero value, in Float format."))
  1030. return
  1031. self.on_tool_add(dia=float(val))
  1032. else:
  1033. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  1034. def on_tooldia_updated(self):
  1035. if self.tool_type_radio.get_value() == 'C1':
  1036. self.old_tool_dia = self.addtool_entry.get_value()
  1037. def on_reference_combo_changed(self):
  1038. obj_type = self.reference_combo_type.currentIndex()
  1039. self.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  1040. self.reference_combo.setCurrentIndex(0)
  1041. self.reference_combo.obj_type = {
  1042. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  1043. }[self.reference_combo_type.get_value()]
  1044. def on_toggle_reference(self):
  1045. val = self.select_combo.get_value()
  1046. if val == _("All"):
  1047. self.reference_combo.hide()
  1048. self.reference_combo_label.hide()
  1049. self.reference_combo_type.hide()
  1050. self.reference_combo_type_label.hide()
  1051. self.area_shape_label.hide()
  1052. self.area_shape_radio.hide()
  1053. # disable rest-machining for area painting
  1054. self.rest_cb.setDisabled(False)
  1055. elif val == _("Area Selection"):
  1056. self.reference_combo.hide()
  1057. self.reference_combo_label.hide()
  1058. self.reference_combo_type.hide()
  1059. self.reference_combo_type_label.hide()
  1060. self.area_shape_label.show()
  1061. self.area_shape_radio.show()
  1062. # disable rest-machining for area isolation
  1063. self.rest_cb.set_value(False)
  1064. self.rest_cb.setDisabled(True)
  1065. elif val == _("Polygon Selection"):
  1066. self.reference_combo.hide()
  1067. self.reference_combo_label.hide()
  1068. self.reference_combo_type.hide()
  1069. self.reference_combo_type_label.hide()
  1070. self.area_shape_label.hide()
  1071. self.area_shape_radio.hide()
  1072. else:
  1073. self.reference_combo.show()
  1074. self.reference_combo_label.show()
  1075. self.reference_combo_type.show()
  1076. self.reference_combo_type_label.show()
  1077. self.area_shape_label.hide()
  1078. self.area_shape_radio.hide()
  1079. # disable rest-machining for area painting
  1080. self.rest_cb.setDisabled(False)
  1081. def on_order_changed(self, order):
  1082. if order != 'no':
  1083. self.build_ui()
  1084. def on_rest_machining_check(self, state):
  1085. if state:
  1086. self.order_radio.set_value('rev')
  1087. self.order_label.setDisabled(True)
  1088. self.order_radio.setDisabled(True)
  1089. self.old_combine_state = self.combine_passes_cb.get_value()
  1090. self.combine_passes_cb.set_value(True)
  1091. self.combine_passes_cb.setDisabled(True)
  1092. else:
  1093. self.order_label.setDisabled(False)
  1094. self.order_radio.setDisabled(False)
  1095. self.combine_passes_cb.set_value(self.old_combine_state)
  1096. self.combine_passes_cb.setDisabled(False)
  1097. def on_tooltable_cellwidget_change(self):
  1098. cw = self.sender()
  1099. assert isinstance(cw, QtWidgets.QComboBox), \
  1100. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  1101. cw_index = self.tools_table.indexAt(cw.pos())
  1102. cw_row = cw_index.row()
  1103. cw_col = cw_index.column()
  1104. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1105. # if the sender is in the column with index 2 then we update the tool_type key
  1106. if cw_col == 2:
  1107. tt = cw.currentText()
  1108. typ = 'Iso' if tt == 'V' else "Rough"
  1109. self.iso_tools[current_uid].update({
  1110. 'type': typ,
  1111. 'tool_type': tt,
  1112. })
  1113. def on_tool_type(self, val):
  1114. if val == 'V':
  1115. self.addtool_entry_lbl.setDisabled(True)
  1116. self.addtool_entry.setDisabled(True)
  1117. self.tipdialabel.show()
  1118. self.tipdia_entry.show()
  1119. self.tipanglelabel.show()
  1120. self.tipangle_entry.show()
  1121. self.on_calculate_tooldia()
  1122. else:
  1123. self.addtool_entry_lbl.setDisabled(False)
  1124. self.addtool_entry.setDisabled(False)
  1125. self.tipdialabel.hide()
  1126. self.tipdia_entry.hide()
  1127. self.tipanglelabel.hide()
  1128. self.tipangle_entry.hide()
  1129. self.addtool_entry.set_value(self.old_tool_dia)
  1130. def on_calculate_tooldia(self):
  1131. if self.tool_type_radio.get_value() == 'V':
  1132. tip_dia = float(self.tipdia_entry.get_value())
  1133. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1134. cut_z = float(self.cutz_entry.get_value())
  1135. cut_z = -cut_z if cut_z < 0 else cut_z
  1136. # calculated tool diameter so the cut_z parameter is obeyed
  1137. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1138. # update the default_data so it is used in the iso_tools dict
  1139. self.default_data.update({
  1140. "vtipdia": tip_dia,
  1141. "vtipangle": (tip_angle * 2),
  1142. })
  1143. self.addtool_entry.set_value(tool_dia)
  1144. return tool_dia
  1145. else:
  1146. return float(self.addtool_entry.get_value())
  1147. def on_tool_add(self, dia=None, muted=None):
  1148. self.blockSignals(True)
  1149. self.units = self.app.defaults['units'].upper()
  1150. if dia:
  1151. tool_dia = dia
  1152. else:
  1153. tool_dia = self.on_calculate_tooldia()
  1154. if tool_dia is None:
  1155. self.build_ui()
  1156. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1157. return
  1158. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1159. if tool_dia == 0:
  1160. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1161. "in Float format."))
  1162. return
  1163. # construct a list of all 'tooluid' in the self.tools
  1164. tool_uid_list = []
  1165. for tooluid_key in self.iso_tools:
  1166. tool_uid_item = int(tooluid_key)
  1167. tool_uid_list.append(tool_uid_item)
  1168. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1169. if not tool_uid_list:
  1170. max_uid = 0
  1171. else:
  1172. max_uid = max(tool_uid_list)
  1173. self.tooluid = int(max_uid + 1)
  1174. tool_dias = []
  1175. for k, v in self.iso_tools.items():
  1176. for tool_v in v.keys():
  1177. if tool_v == 'tooldia':
  1178. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1179. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1180. if muted is None:
  1181. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1182. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1183. self.blockSignals(False)
  1184. return
  1185. else:
  1186. if muted is None:
  1187. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1188. self.iso_tools.update({
  1189. int(self.tooluid): {
  1190. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1191. 'offset': 'Path',
  1192. 'offset_value': 0.0,
  1193. 'type': 'Iso',
  1194. 'tool_type': self.tool_type_radio.get_value(),
  1195. 'data': deepcopy(self.default_data),
  1196. 'solid_geometry': []
  1197. }
  1198. })
  1199. self.blockSignals(False)
  1200. self.build_ui()
  1201. def on_tool_edit(self):
  1202. self.blockSignals(True)
  1203. old_tool_dia = ''
  1204. tool_dias = []
  1205. for k, v in self.iso_tools.items():
  1206. for tool_v in v.keys():
  1207. if tool_v == 'tooldia':
  1208. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1209. for row in range(self.tools_table.rowCount()):
  1210. try:
  1211. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1212. except ValueError:
  1213. # try to convert comma to decimal point. if it's still not working error message and return
  1214. try:
  1215. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1216. except ValueError:
  1217. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1218. self.blockSignals(False)
  1219. return
  1220. tooluid = int(self.tools_table.item(row, 3).text())
  1221. # identify the tool that was edited and get it's tooluid
  1222. if new_tool_dia not in tool_dias:
  1223. self.iso_tools[tooluid]['tooldia'] = new_tool_dia
  1224. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1225. self.blockSignals(False)
  1226. self.build_ui()
  1227. return
  1228. else:
  1229. # identify the old tool_dia and restore the text in tool table
  1230. for k, v in self.iso_tools.items():
  1231. if k == tooluid:
  1232. old_tool_dia = v['tooldia']
  1233. break
  1234. restore_dia_item = self.tools_table.item(row, 1)
  1235. restore_dia_item.setText(str(old_tool_dia))
  1236. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. "
  1237. "New diameter value is already in the Tool Table."))
  1238. self.blockSignals(False)
  1239. self.build_ui()
  1240. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1241. """
  1242. Will delete a tool in the tool table
  1243. :param rows_to_delete: which rows to delete; can be a list
  1244. :param all_tools: delete all tools in the tool table
  1245. :return:
  1246. """
  1247. self.blockSignals(True)
  1248. deleted_tools_list = []
  1249. if all_tools:
  1250. self.iso_tools.clear()
  1251. self.blockSignals(False)
  1252. self.build_ui()
  1253. return
  1254. if rows_to_delete:
  1255. try:
  1256. for row in rows_to_delete:
  1257. tooluid_del = int(self.tools_table.item(row, 3).text())
  1258. deleted_tools_list.append(tooluid_del)
  1259. except TypeError:
  1260. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1261. deleted_tools_list.append(tooluid_del)
  1262. for t in deleted_tools_list:
  1263. self.iso_tools.pop(t, None)
  1264. self.blockSignals(False)
  1265. self.build_ui()
  1266. return
  1267. try:
  1268. if self.tools_table.selectedItems():
  1269. for row_sel in self.tools_table.selectedItems():
  1270. row = row_sel.row()
  1271. if row < 0:
  1272. continue
  1273. tooluid_del = int(self.tools_table.item(row, 3).text())
  1274. deleted_tools_list.append(tooluid_del)
  1275. for t in deleted_tools_list:
  1276. self.iso_tools.pop(t, None)
  1277. except AttributeError:
  1278. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1279. self.blockSignals(False)
  1280. return
  1281. except Exception as e:
  1282. log.debug(str(e))
  1283. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1284. self.blockSignals(False)
  1285. self.build_ui()
  1286. def on_generate_buffer(self):
  1287. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  1288. self.obj_name = self.object_combo.currentText()
  1289. # Get source object.
  1290. try:
  1291. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1292. except Exception as e:
  1293. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1294. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1295. if self.grb_obj is None:
  1296. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1297. return
  1298. def buffer_task():
  1299. with self.app.proc_container.new('%s...' % _("Buffering")):
  1300. if isinstance(self.grb_obj.solid_geometry, list):
  1301. self.grb_obj.solid_geometry = MultiPolygon(self.grb_obj.solid_geometry)
  1302. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(0.0000001)
  1303. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(-0.0000001)
  1304. self.app.inform.emit('[success] %s.' % _("Done"))
  1305. self.grb_obj.plot_single_object.emit()
  1306. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  1307. def on_iso_button_click(self):
  1308. self.obj_name = self.object_combo.currentText()
  1309. # Get source object.
  1310. try:
  1311. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  1312. except Exception as e:
  1313. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1314. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1315. if self.grb_obj is None:
  1316. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1317. return
  1318. def worker_task(iso_obj):
  1319. with self.app.proc_container.new(_("Isolating...")):
  1320. self.isolate_handler(iso_obj)
  1321. self.app.worker_task.emit({'fcn': worker_task, 'params': [self.grb_obj]})
  1322. def follow_geo(self, followed_obj, outname):
  1323. """
  1324. Creates a geometry object "following" the gerber paths.
  1325. :param followed_obj: Gerber object for which to generate the follow geometry
  1326. :type followed_obj: AppObjects.FlatCAMGerber.GerberObject
  1327. :param outname: Nme of the resulting Geometry object
  1328. :type outname: str
  1329. :return: None
  1330. """
  1331. def follow_init(follow_obj, app_obj):
  1332. # Propagate options
  1333. follow_obj.options["cnctooldia"] = str(tooldia)
  1334. follow_obj.solid_geometry = self.grb_obj.follow_geometry
  1335. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  1336. followed_obj.ui.plot_cb.set_value(False)
  1337. follow_name = outname
  1338. for tool in self.iso_tools:
  1339. tooldia = self.iso_tools[tool]['tooldia']
  1340. new_name = "%s_%.*f" % (follow_name, self.decimals, tooldia)
  1341. follow_state = self.iso_tools[tool]['data']['tools_iso_follow']
  1342. if follow_state:
  1343. ret = self.app.app_obj.new_object("geometry", new_name, follow_init)
  1344. if ret == 'fail':
  1345. self.app.inform.emit("[ERROR_NOTCL] %s: %.*f" % (
  1346. _("Failed to create Follow Geometry with tool diameter"), self.decimals, tooldia))
  1347. else:
  1348. self.app.inform.emit("[success] %s: %.*f" % (
  1349. _("Follow Geometry was created with tool diameter"), self.decimals, tooldia))
  1350. def isolate_handler(self, isolated_obj):
  1351. """
  1352. Creates a geometry object with paths around the gerber features.
  1353. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1354. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1355. :return: None
  1356. """
  1357. selection = self.select_combo.get_value()
  1358. if selection == _("All"):
  1359. self.isolate(isolated_obj=isolated_obj)
  1360. elif selection == _("Area Selection"):
  1361. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1362. if self.app.is_legacy is False:
  1363. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1364. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1365. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1366. else:
  1367. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1368. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1369. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1370. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1371. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1372. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1373. elif selection == _("Polygon Selection"):
  1374. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1375. if self.app.ui.grid_snap_btn.isChecked():
  1376. self.grid_status_memory = True
  1377. self.app.ui.grid_snap_btn.trigger()
  1378. else:
  1379. self.grid_status_memory = False
  1380. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_poly_mouse_click_release)
  1381. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1382. if self.app.is_legacy is False:
  1383. self.app.plotcanvas.graph_event_disconnect('mouse_release',
  1384. self.app.on_mouse_click_release_over_plot)
  1385. else:
  1386. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1387. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  1388. elif selection == _("Reference Object"):
  1389. ref_obj = self.app.collection.get_by_name(self.reference_combo.get_value())
  1390. ref_geo = cascaded_union(ref_obj.solid_geometry)
  1391. use_geo = cascaded_union(isolated_obj.solid_geometry).difference(ref_geo)
  1392. self.isolate(isolated_obj=isolated_obj, geometry=use_geo)
  1393. def isolate(self, isolated_obj, geometry=None, limited_area=None, plot=True):
  1394. """
  1395. Creates an isolation routing geometry object in the project.
  1396. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1397. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1398. :param geometry: specific geometry to isolate
  1399. :type geometry: List of Shapely polygon
  1400. :param limited_area: if not None isolate only this area
  1401. :type limited_area: Shapely Polygon or a list of them
  1402. :param plot: if to plot the resulting geometry object
  1403. :type plot: bool
  1404. :return: None
  1405. """
  1406. combine = self.combine_passes_cb.get_value()
  1407. tools_storage = self.iso_tools
  1408. if combine:
  1409. if self.rest_cb.get_value():
  1410. self.combined_rest(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1411. lim_area=limited_area, plot=plot)
  1412. else:
  1413. self.combined_normal(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1414. lim_area=limited_area, plot=plot)
  1415. else:
  1416. for tool in tools_storage:
  1417. tool_data = tools_storage[tool]['data']
  1418. to_follow = tool_data['tools_iso_follow']
  1419. work_geo = geometry
  1420. if work_geo is None:
  1421. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1422. iso_t = {
  1423. 'ext': 0,
  1424. 'int': 1,
  1425. 'full': 2
  1426. }[tool_data['tools_iso_isotype']]
  1427. passes = tool_data['tools_iso_passes']
  1428. overlap = tool_data['tools_iso_overlap']
  1429. overlap /= 100.0
  1430. milling_type = tool_data['tools_iso_milling_type']
  1431. iso_except = tool_data['tools_iso_isoexcept']
  1432. for i in range(passes):
  1433. tool_dia = tools_storage[tool]['tooldia']
  1434. tool_type = tools_storage[tool]['tool_type']
  1435. iso_offset = tool_dia * ((2 * i + 1) / 2.0000001) - (i * overlap * tool_dia)
  1436. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1437. if passes > 1:
  1438. iso_name = outname + "_iso" + str(i + 1)
  1439. if iso_t == 0:
  1440. iso_name = outname + "_ext_iso" + str(i + 1)
  1441. elif iso_t == 1:
  1442. iso_name = outname + "_int_iso" + str(i + 1)
  1443. else:
  1444. iso_name = outname + "_iso"
  1445. if iso_t == 0:
  1446. iso_name = outname + "_ext_iso"
  1447. elif iso_t == 1:
  1448. iso_name = outname + "_int_iso"
  1449. # if milling type is climb then the move is counter-clockwise around features
  1450. mill_dir = 1 if milling_type == 'cl' else 0
  1451. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1452. follow=to_follow, nr_passes=i)
  1453. if iso_geo == 'fail':
  1454. self.app.inform.emit(
  1455. '[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1456. continue
  1457. # ############################################################
  1458. # ########## AREA SUBTRACTION ################################
  1459. # ############################################################
  1460. if iso_except:
  1461. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1462. iso_geo = self.area_subtraction(iso_geo)
  1463. if limited_area:
  1464. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1465. iso_geo = self.area_intersection(iso_geo, intersection_geo=limited_area)
  1466. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in
  1467. # Gerber UI
  1468. if tool_type.lower() == 'v':
  1469. new_cutz = self.cutz_entry.get_value()
  1470. new_vtipdia = self.tipdia_entry.get_value()
  1471. new_vtipangle = self.tipangle_entry.get_value()
  1472. tool_type = 'V'
  1473. tool_data.update({
  1474. "name": iso_name,
  1475. "cutz": new_cutz,
  1476. "vtipdia": new_vtipdia,
  1477. "vtipangle": new_vtipangle,
  1478. })
  1479. else:
  1480. tool_data.update({
  1481. "name": iso_name,
  1482. })
  1483. tool_type = 'C1'
  1484. def iso_init(geo_obj, fc_obj):
  1485. # Propagate options
  1486. geo_obj.options["cnctooldia"] = str(tool_dia)
  1487. geo_obj.solid_geometry = deepcopy(iso_geo)
  1488. # ############################################################
  1489. # ########## AREA SUBTRACTION ################################
  1490. # ############################################################
  1491. if self.except_cb.get_value():
  1492. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1493. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1494. geo_obj.tools = {}
  1495. geo_obj.tools['1'] = {}
  1496. geo_obj.tools.update({
  1497. '1': {
  1498. 'tooldia': float(tool_dia),
  1499. 'offset': 'Path',
  1500. 'offset_value': 0.0,
  1501. 'type': _('Rough'),
  1502. 'tool_type': tool_type,
  1503. 'data': tool_data,
  1504. 'solid_geometry': geo_obj.solid_geometry
  1505. }
  1506. })
  1507. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1508. # or just looking in the lists (they are one level depth) and if any is not empty
  1509. # proceed with object creation, if there are empty and the number of them is the length
  1510. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1511. empty_cnt = 0
  1512. if not isinstance(geo_obj.solid_geometry, list):
  1513. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1514. for g in geo_obj.solid_geometry:
  1515. if g:
  1516. break
  1517. else:
  1518. empty_cnt += 1
  1519. if empty_cnt == len(geo_obj.solid_geometry):
  1520. fc_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1521. _("Empty Geometry in"), geo_obj.options["name"]))
  1522. return 'fail'
  1523. else:
  1524. fc_obj.inform.emit('[success] %s: %s' %
  1525. (_("Isolation geometry created"), geo_obj.options["name"]))
  1526. geo_obj.multigeo = False
  1527. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1528. def combined_rest(self, iso_obj, iso2geo, tools_storage, lim_area, plot=True):
  1529. """
  1530. :param iso_obj: the isolated Gerber object
  1531. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1532. :param iso2geo: specific geometry to isolate
  1533. :type iso2geo: list of Shapely Polygon
  1534. :param tools_storage: a dictionary that holds the tools and geometry
  1535. :type tools_storage: dict
  1536. :param lim_area: if not None restrict isolation to this area
  1537. :type lim_area: Shapely Polygon or a list of them
  1538. :param plot: if to plot the resulting geometry object
  1539. :type plot: bool
  1540. :return: Isolated solid geometry
  1541. :rtype:
  1542. """
  1543. log.debug("ToolIsolation.combine_rest()")
  1544. total_solid_geometry = []
  1545. iso_name = iso_obj.options["name"] + '_iso_rest'
  1546. work_geo = iso_obj.solid_geometry if iso2geo is None else iso2geo
  1547. sorted_tools = []
  1548. for k, v in self.iso_tools.items():
  1549. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  1550. order = self.order_radio.get_value()
  1551. if order == 'fwd':
  1552. sorted_tools.sort(reverse=False)
  1553. elif order == 'rev':
  1554. sorted_tools.sort(reverse=True)
  1555. else:
  1556. pass
  1557. for sorted_tool in sorted_tools:
  1558. for tool in tools_storage:
  1559. if float('%.*f' % (self.decimals, tools_storage[tool]['tooldia'])) == sorted_tool:
  1560. tool_dia = tools_storage[tool]['tooldia']
  1561. tool_type = tools_storage[tool]['tool_type']
  1562. tool_data = tools_storage[tool]['data']
  1563. iso_t = {
  1564. 'ext': 0,
  1565. 'int': 1,
  1566. 'full': 2
  1567. }[tool_data['tools_iso_isotype']]
  1568. passes = tool_data['tools_iso_passes']
  1569. overlap = tool_data['tools_iso_overlap']
  1570. overlap /= 100.0
  1571. milling_type = tool_data['tools_iso_milling_type']
  1572. # if milling type is climb then the move is counter-clockwise around features
  1573. mill_dir = True if milling_type == 'cl' else False
  1574. iso_except = tool_data['tools_iso_isoexcept']
  1575. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1576. internal_name = outname + "_iso"
  1577. if iso_t == 0:
  1578. internal_name = outname + "_ext_iso"
  1579. elif iso_t == 1:
  1580. internal_name = outname + "_int_iso"
  1581. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1582. if tool_type.lower() == 'v':
  1583. new_cutz = self.ui.cutz_spinner.get_value()
  1584. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1585. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1586. tool_type = 'V'
  1587. tool_data.update({
  1588. "name": internal_name,
  1589. "cutz": new_cutz,
  1590. "vtipdia": new_vtipdia,
  1591. "vtipangle": new_vtipangle,
  1592. })
  1593. else:
  1594. tool_data.update({
  1595. "name": internal_name,
  1596. })
  1597. tool_type = 'C1'
  1598. solid_geo, work_geo = self.generate_rest_geometry(geometry=work_geo, tooldia=tool_dia,
  1599. passes=passes, overlap=overlap, invert=mill_dir,
  1600. env_iso_type=iso_t)
  1601. # ############################################################
  1602. # ########## AREA SUBTRACTION ################################
  1603. # ############################################################
  1604. if iso_except:
  1605. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1606. solid_geo = self.area_subtraction(solid_geo)
  1607. if lim_area:
  1608. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1609. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1610. tools_storage.update({
  1611. tool: {
  1612. 'tooldia': float(tool_dia),
  1613. 'offset': 'Path',
  1614. 'offset_value': 0.0,
  1615. 'type': _('Rough'),
  1616. 'tool_type': tool_type,
  1617. 'data': tool_data,
  1618. 'solid_geometry': deepcopy(solid_geo)
  1619. }
  1620. })
  1621. total_solid_geometry += solid_geo
  1622. # if the geometry is all isolated
  1623. if not work_geo:
  1624. break
  1625. def iso_init(geo_obj, app_obj):
  1626. geo_obj.options["cnctooldia"] = str(tool_dia)
  1627. geo_obj.tools = dict(tools_storage)
  1628. geo_obj.solid_geometry = total_solid_geometry
  1629. # even if combine is checked, one pass is still single-geo
  1630. # remove the tools that have no geometry
  1631. for geo_tool in list(geo_obj.tools.keys()):
  1632. if not geo_obj.tools[geo_tool]['solid_geometry']:
  1633. geo_obj.tools.pop(geo_tool, None)
  1634. if len(tools_storage) > 1:
  1635. geo_obj.multigeo = True
  1636. else:
  1637. for ky in tools_storage.keys():
  1638. passes_no = float(tools_storage[ky]['data']['tools_iso_passes'])
  1639. geo_obj.multigeo = True if passes_no > 1 else False
  1640. break
  1641. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1642. # or just looking in the lists (they are one level depth) and if any is not empty
  1643. # proceed with object creation, if there are empty and the number of them is the length
  1644. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1645. empty_cnt = 0
  1646. if not isinstance(geo_obj.solid_geometry, list) and \
  1647. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1648. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1649. for g in geo_obj.solid_geometry:
  1650. if g:
  1651. break
  1652. else:
  1653. empty_cnt += 1
  1654. if empty_cnt == len(geo_obj.solid_geometry):
  1655. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1656. return 'fail'
  1657. else:
  1658. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1659. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1660. # the tools are finished but the isolation is not finished therefore it failed
  1661. if work_geo:
  1662. self.app.inform.emit("[WARNING] %s" % _("Partial failure. The geometry was processed with all tools.\n"
  1663. "But there are still un-isolated geometry elements. "
  1664. "Try to include a tool with smaller diameter."))
  1665. self.app.shell_message(msg=_("The following are coordinates for the copper features "
  1666. "that could not be isolated:"))
  1667. msg = ''
  1668. for geo in work_geo:
  1669. pt = geo.representative_point()
  1670. coords = '(%s, %s), ' % (str(pt.x), str(pt.y))
  1671. msg += coords
  1672. self.app.shell_message(msg=msg)
  1673. def combined_normal(self, iso_obj, iso2geo, tools_storage, lim_area, plot=True):
  1674. """
  1675. :param iso_obj: the isolated Gerber object
  1676. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1677. :param iso2geo: specific geometry to isolate
  1678. :type iso2geo: list of Shapely Polygon
  1679. :param tools_storage: a dictionary that holds the tools and geometry
  1680. :type tools_storage: dict
  1681. :param lim_area: if not None restrict isolation to this area
  1682. :type lim_area: Shapely Polygon or a list of them
  1683. :param plot: if to plot the resulting geometry object
  1684. :type plot: bool
  1685. :return: Isolated solid geometry
  1686. :rtype:
  1687. """
  1688. log.debug("ToolIsolation.combined_normal()")
  1689. total_solid_geometry = []
  1690. iso_name = iso_obj.options["name"] + '_iso_combined'
  1691. geometry = iso2geo
  1692. for tool in tools_storage:
  1693. tool_dia = tools_storage[tool]['tooldia']
  1694. tool_type = tools_storage[tool]['tool_type']
  1695. tool_data = tools_storage[tool]['data']
  1696. to_follow = tool_data['tools_iso_follow']
  1697. # TODO what to do when the iso2geo param is not None but the Follow cb is checked
  1698. # for the case when limited area is used .... the follow geo should be clipped too
  1699. work_geo = geometry
  1700. if work_geo is None:
  1701. work_geo = iso_obj.follow_geometry if to_follow else iso_obj.solid_geometry
  1702. iso_t = {
  1703. 'ext': 0,
  1704. 'int': 1,
  1705. 'full': 2
  1706. }[tool_data['tools_iso_isotype']]
  1707. passes = tool_data['tools_iso_passes']
  1708. overlap = tool_data['tools_iso_overlap']
  1709. overlap /= 100.0
  1710. milling_type = tool_data['tools_iso_milling_type']
  1711. iso_except = tool_data['tools_iso_isoexcept']
  1712. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1713. internal_name = outname + "_iso"
  1714. if iso_t == 0:
  1715. internal_name = outname + "_ext_iso"
  1716. elif iso_t == 1:
  1717. internal_name = outname + "_int_iso"
  1718. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1719. if tool_type.lower() == 'v':
  1720. new_cutz = self.ui.cutz_spinner.get_value()
  1721. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1722. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1723. tool_type = 'V'
  1724. tool_data.update({
  1725. "name": internal_name,
  1726. "cutz": new_cutz,
  1727. "vtipdia": new_vtipdia,
  1728. "vtipangle": new_vtipangle,
  1729. })
  1730. else:
  1731. tool_data.update({
  1732. "name": internal_name,
  1733. })
  1734. tool_type = 'C1'
  1735. solid_geo = []
  1736. for nr_pass in range(passes):
  1737. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1738. # if milling type is climb then the move is counter-clockwise around features
  1739. mill_dir = 1 if milling_type == 'cl' else 0
  1740. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1741. follow=to_follow, nr_passes=nr_pass)
  1742. if iso_geo == 'fail':
  1743. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1744. continue
  1745. try:
  1746. for geo in iso_geo:
  1747. solid_geo.append(geo)
  1748. except TypeError:
  1749. solid_geo.append(iso_geo)
  1750. # ############################################################
  1751. # ########## AREA SUBTRACTION ################################
  1752. # ############################################################
  1753. if iso_except:
  1754. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1755. solid_geo = self.area_subtraction(solid_geo)
  1756. if lim_area:
  1757. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1758. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1759. tools_storage.update({
  1760. tool: {
  1761. 'tooldia': float(tool_dia),
  1762. 'offset': 'Path',
  1763. 'offset_value': 0.0,
  1764. 'type': _('Rough'),
  1765. 'tool_type': tool_type,
  1766. 'data': tool_data,
  1767. 'solid_geometry': deepcopy(solid_geo)
  1768. }
  1769. })
  1770. total_solid_geometry += solid_geo
  1771. def iso_init(geo_obj, app_obj):
  1772. geo_obj.options["cnctooldia"] = str(tool_dia)
  1773. geo_obj.tools = dict(tools_storage)
  1774. geo_obj.solid_geometry = total_solid_geometry
  1775. # even if combine is checked, one pass is still single-geo
  1776. if len(tools_storage) > 1:
  1777. geo_obj.multigeo = True
  1778. else:
  1779. if to_follow:
  1780. passes_no = 1
  1781. else:
  1782. passes_no = float(tools_storage[0]['data']['tools_iso_passes'])
  1783. geo_obj.multigeo = True if passes_no > 1 else False
  1784. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1785. # or just looking in the lists (they are one level depth) and if any is not empty
  1786. # proceed with object creation, if there are empty and the number of them is the length
  1787. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1788. empty_cnt = 0
  1789. if not isinstance(geo_obj.solid_geometry, list) and \
  1790. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1791. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1792. for g in geo_obj.solid_geometry:
  1793. if g:
  1794. break
  1795. else:
  1796. empty_cnt += 1
  1797. if empty_cnt == len(geo_obj.solid_geometry):
  1798. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1799. return 'fail'
  1800. else:
  1801. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1802. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1803. def area_subtraction(self, geo, subtraction_geo):
  1804. """
  1805. Subtracts the subtraction_geo (if present else self.solid_geometry) from the geo
  1806. :param geo: target geometry from which to subtract
  1807. :param subtraction_geo: geometry that acts as subtraction geo
  1808. :return:
  1809. """
  1810. new_geometry = []
  1811. target_geo = geo
  1812. if subtraction_geo:
  1813. sub_union = cascaded_union(subtraction_geo)
  1814. else:
  1815. name = self.exc_obj_combo.currentText()
  1816. subtractor_obj = self.app.collection.get_by_name(name)
  1817. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1818. try:
  1819. for geo_elem in target_geo:
  1820. if isinstance(geo_elem, Polygon):
  1821. for ring in self.poly2rings(geo_elem):
  1822. new_geo = ring.difference(sub_union)
  1823. if new_geo and not new_geo.is_empty:
  1824. new_geometry.append(new_geo)
  1825. elif isinstance(geo_elem, MultiPolygon):
  1826. for poly in geo_elem:
  1827. for ring in self.poly2rings(poly):
  1828. new_geo = ring.difference(sub_union)
  1829. if new_geo and not new_geo.is_empty:
  1830. new_geometry.append(new_geo)
  1831. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1832. new_geo = geo_elem.difference(sub_union)
  1833. if new_geo:
  1834. if not new_geo.is_empty:
  1835. new_geometry.append(new_geo)
  1836. elif isinstance(geo_elem, MultiLineString):
  1837. for line_elem in geo_elem:
  1838. new_geo = line_elem.difference(sub_union)
  1839. if new_geo and not new_geo.is_empty:
  1840. new_geometry.append(new_geo)
  1841. except TypeError:
  1842. if isinstance(target_geo, Polygon):
  1843. for ring in self.poly2rings(target_geo):
  1844. new_geo = ring.difference(sub_union)
  1845. if new_geo:
  1846. if not new_geo.is_empty:
  1847. new_geometry.append(new_geo)
  1848. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1849. new_geo = target_geo.difference(sub_union)
  1850. if new_geo and not new_geo.is_empty:
  1851. new_geometry.append(new_geo)
  1852. elif isinstance(target_geo, MultiLineString):
  1853. for line_elem in target_geo:
  1854. new_geo = line_elem.difference(sub_union)
  1855. if new_geo and not new_geo.is_empty:
  1856. new_geometry.append(new_geo)
  1857. return new_geometry
  1858. def area_intersection(self, geo, intersection_geo=None):
  1859. """
  1860. Return the intersection geometry between geo and intersection_geo
  1861. :param geo: target geometry
  1862. :param intersection_geo: second geometry
  1863. :return:
  1864. """
  1865. new_geometry = []
  1866. target_geo = geo
  1867. intersect_union = cascaded_union(intersection_geo)
  1868. try:
  1869. for geo_elem in target_geo:
  1870. if isinstance(geo_elem, Polygon):
  1871. for ring in self.poly2rings(geo_elem):
  1872. new_geo = ring.intersection(intersect_union)
  1873. if new_geo and not new_geo.is_empty:
  1874. new_geometry.append(new_geo)
  1875. elif isinstance(geo_elem, MultiPolygon):
  1876. for poly in geo_elem:
  1877. for ring in self.poly2rings(poly):
  1878. new_geo = ring.intersection(intersect_union)
  1879. if new_geo and not new_geo.is_empty:
  1880. new_geometry.append(new_geo)
  1881. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1882. new_geo = geo_elem.intersection(intersect_union)
  1883. if new_geo:
  1884. if not new_geo.is_empty:
  1885. new_geometry.append(new_geo)
  1886. elif isinstance(geo_elem, MultiLineString):
  1887. for line_elem in geo_elem:
  1888. new_geo = line_elem.intersection(intersect_union)
  1889. if new_geo and not new_geo.is_empty:
  1890. new_geometry.append(new_geo)
  1891. except TypeError:
  1892. if isinstance(target_geo, Polygon):
  1893. for ring in self.poly2rings(target_geo):
  1894. new_geo = ring.intersection(intersect_union)
  1895. if new_geo:
  1896. if not new_geo.is_empty:
  1897. new_geometry.append(new_geo)
  1898. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1899. new_geo = target_geo.intersection(intersect_union)
  1900. if new_geo and not new_geo.is_empty:
  1901. new_geometry.append(new_geo)
  1902. elif isinstance(target_geo, MultiLineString):
  1903. for line_elem in target_geo:
  1904. new_geo = line_elem.intersection(intersect_union)
  1905. if new_geo and not new_geo.is_empty:
  1906. new_geometry.append(new_geo)
  1907. return new_geometry
  1908. def on_poly_mouse_click_release(self, event):
  1909. if self.app.is_legacy is False:
  1910. event_pos = event.pos
  1911. right_button = 2
  1912. self.app.event_is_dragging = self.app.event_is_dragging
  1913. else:
  1914. event_pos = (event.xdata, event.ydata)
  1915. right_button = 3
  1916. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1917. try:
  1918. x = float(event_pos[0])
  1919. y = float(event_pos[1])
  1920. except TypeError:
  1921. return
  1922. event_pos = (x, y)
  1923. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1924. if self.app.grid_status():
  1925. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1926. else:
  1927. curr_pos = (curr_pos[0], curr_pos[1])
  1928. if event.button == 1:
  1929. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.grb_obj.solid_geometry)
  1930. if self.app.selection_type is not None:
  1931. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  1932. self.app.selection_type = None
  1933. elif clicked_poly:
  1934. if clicked_poly not in self.poly_dict.values():
  1935. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  1936. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1937. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1938. visible=True)
  1939. self.poly_dict[shape_id] = clicked_poly
  1940. self.app.inform.emit(
  1941. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  1942. _("Click to add next polygon or right click to start isolation."))
  1943. )
  1944. else:
  1945. try:
  1946. for k, v in list(self.poly_dict.items()):
  1947. if v == clicked_poly:
  1948. self.app.tool_shapes.remove(k)
  1949. self.poly_dict.pop(k)
  1950. break
  1951. except TypeError:
  1952. return
  1953. self.app.inform.emit(
  1954. '%s. %s' % (_("Removed polygon"),
  1955. _("Click to add/remove next polygon or right click to start isolation."))
  1956. )
  1957. self.app.tool_shapes.redraw()
  1958. else:
  1959. self.app.inform.emit(_("No polygon detected under click position."))
  1960. elif event.button == right_button and self.app.event_is_dragging is False:
  1961. # restore the Grid snapping if it was active before
  1962. if self.grid_status_memory is True:
  1963. self.app.ui.grid_snap_btn.trigger()
  1964. if self.app.is_legacy is False:
  1965. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1966. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_pres)
  1967. else:
  1968. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1969. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1970. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1971. self.app.on_mouse_click_release_over_plot)
  1972. self.app.tool_shapes.clear(update=True)
  1973. if self.poly_dict:
  1974. poly_list = deepcopy(list(self.poly_dict.values()))
  1975. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list)
  1976. self.poly_dict.clear()
  1977. else:
  1978. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1979. def selection_area_handler(self, start_pos, end_pos, sel_type):
  1980. """
  1981. :param start_pos: mouse position when the selection LMB click was done
  1982. :param end_pos: mouse position when the left mouse button is released
  1983. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1984. :return:
  1985. """
  1986. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1987. # delete previous selection shape
  1988. self.app.delete_selection_shape()
  1989. added_poly_count = 0
  1990. try:
  1991. for geo in self.solid_geometry:
  1992. if geo not in self.poly_dict.values():
  1993. if sel_type is True:
  1994. if geo.within(poly_selection):
  1995. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1996. shape=geo,
  1997. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1998. face_color=self.app.defaults[
  1999. 'global_sel_draw_color'] + 'AF',
  2000. visible=True)
  2001. self.poly_dict[shape_id] = geo
  2002. added_poly_count += 1
  2003. else:
  2004. if poly_selection.intersects(geo):
  2005. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  2006. shape=geo,
  2007. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  2008. face_color=self.app.defaults[
  2009. 'global_sel_draw_color'] + 'AF',
  2010. visible=True)
  2011. self.poly_dict[shape_id] = geo
  2012. added_poly_count += 1
  2013. except TypeError:
  2014. if self.solid_geometry not in self.poly_dict.values():
  2015. if sel_type is True:
  2016. if self.solid_geometry.within(poly_selection):
  2017. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  2018. shape=self.solid_geometry,
  2019. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  2020. face_color=self.app.defaults[
  2021. 'global_sel_draw_color'] + 'AF',
  2022. visible=True)
  2023. self.poly_dict[shape_id] = self.solid_geometry
  2024. added_poly_count += 1
  2025. else:
  2026. if poly_selection.intersects(self.solid_geometry):
  2027. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  2028. shape=self.solid_geometry,
  2029. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  2030. face_color=self.app.defaults[
  2031. 'global_sel_draw_color'] + 'AF',
  2032. visible=True)
  2033. self.poly_dict[shape_id] = self.solid_geometry
  2034. added_poly_count += 1
  2035. if added_poly_count > 0:
  2036. self.app.tool_shapes.redraw()
  2037. self.app.inform.emit(
  2038. '%s: %d. %s' % (_("Added polygon"),
  2039. int(added_poly_count),
  2040. _("Click to add next polygon or right click to start isolation."))
  2041. )
  2042. else:
  2043. self.app.inform.emit(_("No polygon in selection."))
  2044. # To be called after clicking on the plot.
  2045. def on_mouse_release(self, event):
  2046. if self.app.is_legacy is False:
  2047. event_pos = event.pos
  2048. # event_is_dragging = event.is_dragging
  2049. right_button = 2
  2050. else:
  2051. event_pos = (event.xdata, event.ydata)
  2052. # event_is_dragging = self.app.plotcanvas.is_dragging
  2053. right_button = 3
  2054. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  2055. if self.app.grid_status():
  2056. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  2057. else:
  2058. curr_pos = (event_pos[0], event_pos[1])
  2059. x1, y1 = curr_pos[0], curr_pos[1]
  2060. shape_type = self.area_shape_radio.get_value()
  2061. # do clear area only for left mouse clicks
  2062. if event.button == 1:
  2063. if shape_type == "square":
  2064. if self.first_click is False:
  2065. self.first_click = True
  2066. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  2067. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  2068. if self.app.grid_status():
  2069. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  2070. else:
  2071. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  2072. self.app.delete_selection_shape()
  2073. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  2074. pt1 = (x0, y0)
  2075. pt2 = (x1, y0)
  2076. pt3 = (x1, y1)
  2077. pt4 = (x0, y1)
  2078. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  2079. self.sel_rect.append(new_rectangle)
  2080. # add a temporary shape on canvas
  2081. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  2082. self.first_click = False
  2083. return
  2084. else:
  2085. self.points.append((x1, y1))
  2086. if len(self.points) > 1:
  2087. self.poly_drawn = True
  2088. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  2089. return ""
  2090. elif event.button == right_button and self.mouse_is_dragging is False:
  2091. shape_type = self.area_shape_radio.get_value()
  2092. if shape_type == "square":
  2093. self.first_click = False
  2094. else:
  2095. # if we finish to add a polygon
  2096. if self.poly_drawn is True:
  2097. try:
  2098. # try to add the point where we last clicked if it is not already in the self.points
  2099. last_pt = (x1, y1)
  2100. if last_pt != self.points[-1]:
  2101. self.points.append(last_pt)
  2102. except IndexError:
  2103. pass
  2104. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  2105. if len(self.points) > 2:
  2106. self.delete_moving_selection_shape()
  2107. pol = Polygon(self.points)
  2108. # do not add invalid polygons even if they are drawn by utility geometry
  2109. if pol.is_valid:
  2110. self.sel_rect.append(pol)
  2111. self.draw_selection_shape_polygon(points=self.points)
  2112. self.app.inform.emit(
  2113. _("Zone added. Click to start adding next zone or right click to finish."))
  2114. self.points = []
  2115. self.poly_drawn = False
  2116. return
  2117. self.delete_tool_selection_shape()
  2118. if self.app.is_legacy is False:
  2119. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2120. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2121. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2122. else:
  2123. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2124. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2125. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2126. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2127. self.app.on_mouse_click_over_plot)
  2128. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2129. self.app.on_mouse_move_over_plot)
  2130. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2131. self.app.on_mouse_click_release_over_plot)
  2132. if len(self.sel_rect) == 0:
  2133. return
  2134. self.sel_rect = cascaded_union(self.sel_rect)
  2135. self.isolate(isolated_obj=self.grb_obj, limited_area=self.sel_rect, plot=True)
  2136. self.sel_rect = []
  2137. # called on mouse move
  2138. def on_mouse_move(self, event):
  2139. shape_type = self.area_shape_radio.get_value()
  2140. if self.app.is_legacy is False:
  2141. event_pos = event.pos
  2142. event_is_dragging = event.is_dragging
  2143. # right_button = 2
  2144. else:
  2145. event_pos = (event.xdata, event.ydata)
  2146. event_is_dragging = self.app.plotcanvas.is_dragging
  2147. # right_button = 3
  2148. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  2149. # detect mouse dragging motion
  2150. if event_is_dragging is True:
  2151. self.mouse_is_dragging = True
  2152. else:
  2153. self.mouse_is_dragging = False
  2154. # update the cursor position
  2155. if self.app.grid_status():
  2156. # Update cursor
  2157. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  2158. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  2159. symbol='++', edge_color=self.app.cursor_color_3D,
  2160. edge_width=self.app.defaults["global_cursor_width"],
  2161. size=self.app.defaults["global_cursor_size"])
  2162. if self.cursor_pos is None:
  2163. self.cursor_pos = (0, 0)
  2164. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  2165. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  2166. # # update the positions on status bar
  2167. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2168. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  2169. # self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2170. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  2171. units = self.app.defaults["units"].lower()
  2172. self.app.plotcanvas.text_hud.text = \
  2173. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  2174. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  2175. # draw the utility geometry
  2176. if shape_type == "square":
  2177. if self.first_click:
  2178. self.app.delete_selection_shape()
  2179. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  2180. coords=(curr_pos[0], curr_pos[1]))
  2181. else:
  2182. self.delete_moving_selection_shape()
  2183. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  2184. def on_key_press(self, event):
  2185. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  2186. # matplotlib_key_flag = False
  2187. # events out of the self.app.collection view (it's about Project Tab) are of type int
  2188. if type(event) is int:
  2189. key = event
  2190. # events from the GUI are of type QKeyEvent
  2191. elif type(event) == QtGui.QKeyEvent:
  2192. key = event.key()
  2193. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  2194. # matplotlib_key_flag = True
  2195. key = event.key
  2196. key = QtGui.QKeySequence(key)
  2197. # check for modifiers
  2198. key_string = key.toString().lower()
  2199. if '+' in key_string:
  2200. mod, __, key_text = key_string.rpartition('+')
  2201. if mod.lower() == 'ctrl':
  2202. # modifiers = QtCore.Qt.ControlModifier
  2203. pass
  2204. elif mod.lower() == 'alt':
  2205. # modifiers = QtCore.Qt.AltModifier
  2206. pass
  2207. elif mod.lower() == 'shift':
  2208. # modifiers = QtCore.Qt.ShiftModifier
  2209. pass
  2210. else:
  2211. # modifiers = QtCore.Qt.NoModifier
  2212. pass
  2213. key = QtGui.QKeySequence(key_text)
  2214. # events from Vispy are of type KeyEvent
  2215. else:
  2216. key = event.key
  2217. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  2218. if self.app.is_legacy is False:
  2219. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  2220. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  2221. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  2222. else:
  2223. self.app.plotcanvas.graph_event_disconnect(self.mr)
  2224. self.app.plotcanvas.graph_event_disconnect(self.mm)
  2225. self.app.plotcanvas.graph_event_disconnect(self.kp)
  2226. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  2227. self.app.on_mouse_click_over_plot)
  2228. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  2229. self.app.on_mouse_move_over_plot)
  2230. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  2231. self.app.on_mouse_click_release_over_plot)
  2232. self.points = []
  2233. self.poly_drawn = False
  2234. self.delete_moving_selection_shape()
  2235. self.delete_tool_selection_shape()
  2236. @staticmethod
  2237. def poly2rings(poly):
  2238. return [poly.exterior] + [interior for interior in poly.interiors]
  2239. @staticmethod
  2240. def poly2ext(poly):
  2241. return [poly.exterior]
  2242. @staticmethod
  2243. def poly2ints(poly):
  2244. return [interior for interior in poly.interiors]
  2245. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  2246. """
  2247. Isolation_geometry produces an envelope that is going on the left of the geometry
  2248. (the copper features). To leave the least amount of burrs on the features
  2249. the tool needs to travel on the right side of the features (this is called conventional milling)
  2250. the first pass is the one cutting all of the features, so it needs to be reversed
  2251. the other passes overlap preceding ones and cut the left over copper. It is better for them
  2252. to cut on the right side of the left over copper i.e on the left side of the features.
  2253. :param offset: Offset distance to be passed to the obj.isolation_geometry() method
  2254. :type offset: float
  2255. :param invert: If to invert the direction of geometry (CW to CCW or reverse)
  2256. :type invert: int
  2257. :param geometry: Shapely Geometry for which t ogenerate envelope
  2258. :type geometry:
  2259. :param env_iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  2260. :type env_iso_type: int
  2261. :param follow: If the kind of isolation is a "follow" one
  2262. :type follow: bool
  2263. :param nr_passes: Number of passes
  2264. :type nr_passes: int
  2265. :return: The buffered geometry
  2266. :rtype: MultiPolygon or Polygon
  2267. """
  2268. if follow:
  2269. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, follow=follow)
  2270. return geom
  2271. else:
  2272. try:
  2273. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type,
  2274. passes=nr_passes)
  2275. except Exception as e:
  2276. log.debug('ToolIsolation.generate_envelope() --> %s' % str(e))
  2277. return 'fail'
  2278. if invert:
  2279. try:
  2280. pl = []
  2281. for p in geom:
  2282. if p is not None:
  2283. if isinstance(p, Polygon):
  2284. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2285. elif isinstance(p, LinearRing):
  2286. pl.append(Polygon(p.coords[::-1]))
  2287. geom = MultiPolygon(pl)
  2288. except TypeError:
  2289. if isinstance(geom, Polygon) and geom is not None:
  2290. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2291. elif isinstance(geom, LinearRing) and geom is not None:
  2292. geom = Polygon(geom.coords[::-1])
  2293. else:
  2294. log.debug("ToolIsolation.generate_envelope() Error --> Unexpected Geometry %s" %
  2295. type(geom))
  2296. except Exception as e:
  2297. log.debug("ToolIsolation.generate_envelope() Error --> %s" % str(e))
  2298. return 'fail'
  2299. return geom
  2300. @staticmethod
  2301. def generate_rest_geometry(geometry, tooldia, passes, overlap, invert, env_iso_type=2):
  2302. """
  2303. Will try to isolate the geometry and return a tuple made of list of paths made through isolation
  2304. and a list of Shapely Polygons that could not be isolated
  2305. :param geometry: A list of Shapely Polygons to be isolated
  2306. :type geometry: list
  2307. :param tooldia: The tool diameter used to do the isolation
  2308. :type tooldia: float
  2309. :param passes: Number of passes that will made the isolation
  2310. :type passes: int
  2311. :param overlap: How much to overlap the previous pass; in percentage [0.00, 99.99]%
  2312. :type overlap: float
  2313. :param invert: If to invert the direction of the resulting isolated geometries
  2314. :type invert: bool
  2315. :param env_iso_type: can be either 0 = keep exteriors or 1 = keep interiors or 2 = keep all paths
  2316. :type env_iso_type: int
  2317. :return: Tuple made from list of isolating paths and list of not isolated Polygons
  2318. :rtype: tuple
  2319. """
  2320. isolated_geo = []
  2321. not_isolated_geo = []
  2322. work_geo = []
  2323. for idx, geo in enumerate(geometry):
  2324. good_pass_iso = []
  2325. start_idx = idx + 1
  2326. for nr_pass in range(passes):
  2327. iso_offset = tooldia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * tooldia)
  2328. buf_chek = iso_offset * 2
  2329. check_geo = geo.buffer(buf_chek)
  2330. intersect_flag = False
  2331. # find if current pass for current geo is valid (no intersection with other geos))
  2332. for geo_search_idx in range(idx):
  2333. if check_geo.intersects(geometry[geo_search_idx]):
  2334. intersect_flag = True
  2335. break
  2336. if intersect_flag is False:
  2337. for geo_search_idx in range(start_idx, len(geometry)):
  2338. if check_geo.intersects(geometry[geo_search_idx]):
  2339. intersect_flag = True
  2340. break
  2341. # if we had an intersection do nothing, else add the geo to the good pass isolations
  2342. if intersect_flag is False:
  2343. good_pass_iso.append(geo.buffer(iso_offset))
  2344. if good_pass_iso:
  2345. work_geo += good_pass_iso
  2346. else:
  2347. not_isolated_geo.append(geo)
  2348. if invert:
  2349. try:
  2350. pl = []
  2351. for p in work_geo:
  2352. if p is not None:
  2353. if isinstance(p, Polygon):
  2354. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2355. elif isinstance(p, LinearRing):
  2356. pl.append(Polygon(p.coords[::-1]))
  2357. work_geo = MultiPolygon(pl)
  2358. except TypeError:
  2359. if isinstance(work_geo, Polygon) and work_geo is not None:
  2360. work_geo = [Polygon(work_geo.exterior.coords[::-1], work_geo.interiors)]
  2361. elif isinstance(work_geo, LinearRing) and work_geo is not None:
  2362. work_geo = [Polygon(work_geo.coords[::-1])]
  2363. else:
  2364. log.debug("ToolIsolation.generate_rest_geometry() Error --> Unexpected Geometry %s" %
  2365. type(work_geo))
  2366. except Exception as e:
  2367. log.debug("ToolIsolation.generate_rest_geometry() Error --> %s" % str(e))
  2368. return 'fail', 'fail'
  2369. if env_iso_type == 0: # exterior
  2370. for geo in work_geo:
  2371. isolated_geo.append(geo.exterior)
  2372. elif env_iso_type == 1: # interiors
  2373. for geo in work_geo:
  2374. isolated_geo += [interior for interior in geo.interiors]
  2375. else: # exterior + interiors
  2376. for geo in work_geo:
  2377. isolated_geo += [geo.exterior] + [interior for interior in geo.interiors]
  2378. return isolated_geo, not_isolated_geo
  2379. def on_iso_tool_add_from_db_executed(self, tool):
  2380. """
  2381. Here add the tool from DB in the selected geometry object
  2382. :return:
  2383. """
  2384. tool_from_db = deepcopy(tool)
  2385. res = self.on_tool_from_db_inserted(tool=tool_from_db)
  2386. for idx in range(self.app.ui.plot_tab_area.count()):
  2387. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2388. wdg = self.app.ui.plot_tab_area.widget(idx)
  2389. wdg.deleteLater()
  2390. self.app.ui.plot_tab_area.removeTab(idx)
  2391. if res == 'fail':
  2392. return
  2393. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2394. # select last tool added
  2395. toolid = res
  2396. for row in range(self.tools_table.rowCount()):
  2397. if int(self.tools_table.item(row, 3).text()) == toolid:
  2398. self.tools_table.selectRow(row)
  2399. self.on_row_selection_change()
  2400. def on_tool_from_db_inserted(self, tool):
  2401. """
  2402. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2403. :param tool: a dict with the tool data
  2404. :return: None
  2405. """
  2406. self.ui_disconnect()
  2407. self.units = self.app.defaults['units'].upper()
  2408. tooldia = float(tool['tooldia'])
  2409. # construct a list of all 'tooluid' in the self.tools
  2410. tool_uid_list = []
  2411. for tooluid_key in self.iso_tools:
  2412. tool_uid_item = int(tooluid_key)
  2413. tool_uid_list.append(tool_uid_item)
  2414. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2415. if not tool_uid_list:
  2416. max_uid = 0
  2417. else:
  2418. max_uid = max(tool_uid_list)
  2419. tooluid = max_uid + 1
  2420. tooldia = float('%.*f' % (self.decimals, tooldia))
  2421. tool_dias = []
  2422. for k, v in self.iso_tools.items():
  2423. for tool_v in v.keys():
  2424. if tool_v == 'tooldia':
  2425. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2426. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2427. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2428. self.ui_connect()
  2429. return 'fail'
  2430. self.iso_tools.update({
  2431. tooluid: {
  2432. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2433. 'offset': tool['offset'],
  2434. 'offset_value': tool['offset_value'],
  2435. 'type': tool['type'],
  2436. 'tool_type': tool['tool_type'],
  2437. 'data': deepcopy(tool['data']),
  2438. 'solid_geometry': []
  2439. }
  2440. })
  2441. self.iso_tools[tooluid]['data']['name'] = '_iso'
  2442. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2443. self.ui_connect()
  2444. self.build_ui()
  2445. # if self.tools_table.rowCount() != 0:
  2446. # self.param_frame.setDisabled(False)
  2447. def on_tool_add_from_db_clicked(self):
  2448. """
  2449. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2450. and display the Tools Database tab in the form needed for the Tool adding
  2451. :return: None
  2452. """
  2453. # if the Tools Database is already opened focus on it
  2454. for idx in range(self.app.ui.plot_tab_area.count()):
  2455. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2456. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2457. break
  2458. self.app.on_tools_database(source='iso')
  2459. self.app.tools_db_tab.ok_to_add = True
  2460. self.app.tools_db_tab.buttons_frame.hide()
  2461. self.app.tools_db_tab.add_tool_from_db.show()
  2462. self.app.tools_db_tab.cancel_tool_from_db.show()
  2463. def reset_fields(self):
  2464. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2465. def reset_usage(self):
  2466. self.obj_name = ""
  2467. self.grb_obj = None
  2468. self.first_click = False
  2469. self.cursor_pos = None
  2470. self.mouse_is_dragging = False
  2471. prog_plot = True if self.app.defaults["tools_iso_plotting"] == 'progressive' else False
  2472. if prog_plot:
  2473. self.temp_shapes.clear(update=True)
  2474. self.sel_rect = []