ToolPaint.py 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from PyQt5.QtCore import Qt
  9. from appTool import AppTool
  10. from copy import deepcopy
  11. from appParsers.ParseGerber import Gerber
  12. from camlib import Geometry, FlatCAMRTreeStorage, grace
  13. from appGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox, \
  14. FCLabel, FCComboBox2
  15. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point
  16. from shapely.ops import unary_union, linemerge
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import numpy as np
  19. from numpy import Inf
  20. import traceback
  21. import sys
  22. import logging
  23. import simplejson as json
  24. import gettext
  25. import appTranslation as fcTranslate
  26. import builtins
  27. fcTranslate.apply_language('strings')
  28. if '_' not in builtins.__dict__:
  29. _ = gettext.gettext
  30. log = logging.getLogger('base')
  31. class ToolPaint(AppTool, Gerber):
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = self.app.decimals
  35. AppTool.__init__(self, app)
  36. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  37. # #############################################################################
  38. # ######################### Tool GUI ##########################################
  39. # #############################################################################
  40. self.ui = PaintUI(layout=self.layout, app=self.app)
  41. self.toolName = self.ui.toolName
  42. # #############################################################################
  43. # ########################## VARIABLES ########################################
  44. # #############################################################################
  45. self.obj_name = ""
  46. self.paint_obj = None
  47. self.bound_obj_name = ""
  48. self.bound_obj = None
  49. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  50. self.tooldia_list = []
  51. self.tooldia = None
  52. self.sel_rect = None
  53. self.o_name = None
  54. self.overlap = None
  55. self.connect = None
  56. self.contour = None
  57. self.select_method = None
  58. self.units = ''
  59. self.paint_tools = {}
  60. self.tooluid = 0
  61. self.first_click = False
  62. self.cursor_pos = None
  63. self.mouse_is_dragging = False
  64. self.mm = None
  65. self.mp = None
  66. self.mr = None
  67. self.kp = None
  68. # disconnect flags
  69. self.area_sel_disconnect_flag = False
  70. self.poly_sel_disconnect_flag = False
  71. self.sel_rect = []
  72. # store here if the grid snapping is active
  73. self.grid_status_memory = False
  74. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  75. self.poly_dict = {}
  76. # store here the default data for Geometry Data
  77. self.default_data = {}
  78. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  79. self.form_fields = {
  80. "tools_paint_overlap": self.ui.paintoverlap_entry,
  81. "tools_paint_offset": self.ui.offset_entry,
  82. "tools_paint_method": self.ui.paintmethod_combo,
  83. "tools_paint_connect": self.ui.pathconnect_cb,
  84. "tools_paint_contour": self.ui.paintcontour_cb,
  85. }
  86. self.name2option = {
  87. 'p_overlap': "tools_paint_overlap",
  88. 'p_offset': "tools_paint_offset",
  89. 'p_method': "tools_paint_method",
  90. 'p_connect': "tools_paint_connect",
  91. 'p_contour': "tools_paint_contour",
  92. }
  93. # store here the points for the "Polygon" area selection shape
  94. self.points = []
  95. # set this as True when in middle of drawing a "Polygon" area selection shape
  96. # it is made False by first click to signify that the shape is complete
  97. self.poly_drawn = False
  98. self.connect_signals_at_init()
  99. # #############################################################################
  100. # ###################### Setup CONTEXT MENU ###################################
  101. # #############################################################################
  102. self.ui.tools_table.setupContextMenu()
  103. self.ui.tools_table.addContextMenu(
  104. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  105. )
  106. self.ui.tools_table.addContextMenu(
  107. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  108. )
  109. self.ui.tools_table.addContextMenu(
  110. _("Delete"), lambda:
  111. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  112. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  113. )
  114. def on_type_obj_changed(self, val):
  115. obj_type = 0 if val == 'gerber' else 2
  116. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  117. self.ui.obj_combo.setCurrentIndex(0)
  118. self.ui.obj_combo.obj_type = {"gerber": "Gerber", "geometry": "Geometry"}[val]
  119. idx = self.ui.paintmethod_combo.findText(_("Laser_lines"))
  120. if self.ui.type_obj_radio.get_value().lower() == 'gerber':
  121. self.ui.paintmethod_combo.model().item(idx).setEnabled(True)
  122. else:
  123. self.ui.paintmethod_combo.model().item(idx).setEnabled(False)
  124. if self.ui.paintmethod_combo.get_value() == idx: # if its Laser Lines
  125. self.ui.paintmethod_combo.set_value(idx+1)
  126. def on_reference_combo_changed(self):
  127. obj_type = self.ui.reference_type_combo.currentIndex()
  128. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  129. self.ui.reference_combo.setCurrentIndex(0)
  130. self.ui.reference_combo.obj_type = {0: "Gerber", 1: "Excellon", 2: "Geometry"}[obj_type]
  131. def connect_signals_at_init(self):
  132. # #############################################################################
  133. # ################################# Signals ###################################
  134. # #############################################################################
  135. self.ui.new_tooldia_entry.returnPressed.connect(self.on_tool_add)
  136. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  137. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  138. self.ui.selectmethod_combo.currentIndexChanged.connect(self.ui.on_selection)
  139. self.ui.reference_type_combo.currentIndexChanged.connect(self.on_reference_combo_changed)
  140. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  141. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  142. # adding tools
  143. self.ui.add_newtool_button.clicked.connect(lambda: self.on_tool_add())
  144. self.ui.addtool_from_db_btn.clicked.connect(self.on_paint_tool_add_from_db_clicked)
  145. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  146. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  147. self.app.cleanup.connect(self.set_tool_ui)
  148. def install(self, icon=None, separator=None, **kwargs):
  149. AppTool.install(self, icon, separator, shortcut='Alt+P', **kwargs)
  150. def run(self, toggle=True):
  151. self.app.defaults.report_usage("ToolPaint()")
  152. log.debug("ToolPaint().run() was launched ...")
  153. if toggle:
  154. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  155. if self.app.ui.splitter.sizes()[0] == 0:
  156. self.app.ui.splitter.setSizes([1, 1])
  157. else:
  158. try:
  159. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  160. # if tab is populated with the tool but it does not have the focus, focus on it
  161. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  162. # focus on Tool Tab
  163. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  164. else:
  165. self.app.ui.splitter.setSizes([0, 1])
  166. except AttributeError:
  167. pass
  168. else:
  169. if self.app.ui.splitter.sizes()[0] == 0:
  170. self.app.ui.splitter.setSizes([1, 1])
  171. AppTool.run(self)
  172. self.set_tool_ui()
  173. self.build_ui()
  174. # all the tools are selected by default
  175. self.ui.tools_table.selectAll()
  176. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  177. def on_toggle_all_rows(self):
  178. """
  179. will toggle the selection of all rows in Tools table
  180. :return:
  181. """
  182. sel_model = self.ui.tools_table.selectionModel()
  183. sel_indexes = sel_model.selectedIndexes()
  184. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  185. sel_rows = set()
  186. for idx in sel_indexes:
  187. sel_rows.add(idx.row())
  188. if len(sel_rows) == self.ui.tools_table.rowCount():
  189. self.ui.tools_table.clearSelection()
  190. self.ui.tool_data_label.setText(
  191. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  192. )
  193. else:
  194. self.ui.tools_table.selectAll()
  195. self.ui.tool_data_label.setText(
  196. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  197. )
  198. def on_row_selection_change(self):
  199. sel_model = self.ui.tools_table.selectionModel()
  200. sel_indexes = sel_model.selectedIndexes()
  201. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  202. sel_rows = set()
  203. for idx in sel_indexes:
  204. sel_rows.add(idx.row())
  205. # update UI only if only one row is selected otherwise having multiple rows selected will deform information
  206. # for the rows other that the current one (first selected)
  207. if len(sel_rows) == 1:
  208. self.update_ui()
  209. def update_ui(self):
  210. self.blockSignals(True)
  211. sel_rows = set()
  212. table_items = self.ui.tools_table.selectedItems()
  213. if table_items:
  214. for it in table_items:
  215. sel_rows.add(it.row())
  216. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  217. if not sel_rows or len(sel_rows) == 0:
  218. self.ui.generate_paint_button.setDisabled(True)
  219. self.ui.tool_data_label.setText(
  220. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  221. )
  222. self.blockSignals(False)
  223. return
  224. else:
  225. self.ui.generate_paint_button.setDisabled(False)
  226. for current_row in sel_rows:
  227. # populate the form with the data from the tool associated with the row parameter
  228. try:
  229. item = self.ui.tools_table.item(current_row, 3)
  230. if item is None:
  231. return 'fail'
  232. tooluid = int(item.text())
  233. except Exception as e:
  234. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  235. return
  236. # update the QLabel that shows for which Tool we have the parameters in the UI form
  237. if len(sel_rows) == 1:
  238. cr = self.ui.tools_table.item(current_row, 0).text()
  239. self.ui.tool_data_label.setText(
  240. "<b>%s: <font color='#0000FF'>%s %s</font></b>" % (_('Parameters for'), _("Tool"), cr)
  241. )
  242. try:
  243. # set the form with data from the newly selected tool
  244. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  245. if int(tooluid_key) == tooluid:
  246. self.storage_to_form(tooluid_value['data'])
  247. except Exception as e:
  248. log.debug("ToolPaint ---> update_ui() " + str(e))
  249. else:
  250. self.ui.tool_data_label.setText(
  251. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  252. )
  253. self.blockSignals(False)
  254. def storage_to_form(self, dict_storage):
  255. for k in self.form_fields:
  256. try:
  257. self.form_fields[k].set_value(dict_storage[k])
  258. except Exception as err:
  259. log.debug("ToolPaint.storage.form() --> %s" % str(err))
  260. def form_to_storage(self):
  261. if self.ui.tools_table.rowCount() == 0:
  262. # there is no tool in tool table so we can't save the GUI elements values to storage
  263. return
  264. self.blockSignals(True)
  265. widget_changed = self.sender()
  266. wdg_objname = widget_changed.objectName()
  267. option_changed = self.name2option[wdg_objname]
  268. # row = self.ui.tools_table.currentRow()
  269. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  270. for row in rows:
  271. if row < 0:
  272. row = 0
  273. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  274. for tooluid_key, tooluid_val in self.paint_tools.items():
  275. if int(tooluid_key) == tooluid_item:
  276. new_option_value = self.form_fields[option_changed].get_value()
  277. if option_changed in tooluid_val:
  278. tooluid_val[option_changed] = new_option_value
  279. if option_changed in tooluid_val['data']:
  280. tooluid_val['data'][option_changed] = new_option_value
  281. self.blockSignals(False)
  282. def on_apply_param_to_all_clicked(self):
  283. if self.ui.tools_table.rowCount() == 0:
  284. # there is no tool in tool table so we can't save the GUI elements values to storage
  285. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  286. return
  287. self.blockSignals(True)
  288. row = self.ui.tools_table.currentRow()
  289. if row < 0:
  290. row = 0
  291. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  292. temp_tool_data = {}
  293. for tooluid_key, tooluid_val in self.paint_tools.items():
  294. if int(tooluid_key) == tooluid_item:
  295. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  296. # the current row in the tool table
  297. temp_tool_data = tooluid_val['data']
  298. break
  299. for tooluid_key, tooluid_val in self.paint_tools.items():
  300. tooluid_val['data'] = deepcopy(temp_tool_data)
  301. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  302. self.blockSignals(False)
  303. def on_add_tool_by_key(self):
  304. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  305. text='%s:' % _('Enter a Tool Diameter'),
  306. min=0.0000, max=99.9999, decimals=4)
  307. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  308. val, ok = tool_add_popup.get_value()
  309. if ok:
  310. if float(val) == 0:
  311. self.app.inform.emit('[WARNING_NOTCL] %s' %
  312. _("Please enter a tool diameter with non-zero value, in Float format."))
  313. return
  314. self.on_tool_add(custom_dia=float(val))
  315. else:
  316. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  317. def on_tooltable_cellwidget_change(self):
  318. cw = self.sender()
  319. assert isinstance(cw, QtWidgets.QComboBox), \
  320. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  321. cw_index = self.ui.tools_table.indexAt(cw.pos())
  322. cw_row = cw_index.row()
  323. cw_col = cw_index.column()
  324. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  325. # if the sender is in the column with index 2 then we update the tool_type key
  326. if cw_col == 2:
  327. tt = cw.currentText()
  328. typ = 'Iso' if tt == 'V' else "Rough"
  329. self.paint_tools[current_uid].update({
  330. 'type': typ,
  331. 'tool_type': tt,
  332. })
  333. def on_order_changed(self, order):
  334. if order != 'no':
  335. self.build_ui()
  336. def set_tool_ui(self):
  337. self.ui.tools_frame.show()
  338. self.reset_fields()
  339. # updated units
  340. self.units = self.app.defaults['units'].upper()
  341. # set the working variables to a known state
  342. self.paint_tools.clear()
  343. self.tooluid = 0
  344. self.default_data.clear()
  345. self.default_data.update({
  346. "name": '_paint',
  347. "plot": self.app.defaults["geometry_plot"],
  348. "cutz": float(self.app.defaults["tools_paint_cutz"]),
  349. "vtipdia": float(self.app.defaults["tools_paint_tipdia"]),
  350. "vtipangle": float(self.app.defaults["tools_paint_tipangle"]),
  351. "travelz": float(self.app.defaults["geometry_travelz"]),
  352. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  353. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  354. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  355. "dwell": self.app.defaults["geometry_dwell"],
  356. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  357. "multidepth": self.app.defaults["geometry_multidepth"],
  358. "ppname_g": self.app.defaults["geometry_ppname_g"],
  359. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  360. "extracut": self.app.defaults["geometry_extracut"],
  361. "extracut_length": self.app.defaults["geometry_extracut_length"],
  362. "toolchange": self.app.defaults["geometry_toolchange"],
  363. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  364. "endz": float(self.app.defaults["geometry_endz"]),
  365. "endxy": self.app.defaults["geometry_endxy"],
  366. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  367. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  368. "startz": self.app.defaults["geometry_startz"],
  369. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  370. "area_shape": self.app.defaults["geometry_area_shape"],
  371. "area_strategy": self.app.defaults["geometry_area_strategy"],
  372. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  373. "optimization_type": self.app.defaults["geometry_optimization_type"],
  374. "tooldia": self.app.defaults["tools_paint_tooldia"],
  375. "tools_paint_offset": self.app.defaults["tools_paint_offset"],
  376. "tools_paint_method": self.app.defaults["tools_paint_method"],
  377. "tools_paint_selectmethod": self.app.defaults["tools_paint_selectmethod"],
  378. "tools_paint_connect": self.app.defaults["tools_paint_connect"],
  379. "tools_paint_contour": self.app.defaults["tools_paint_contour"],
  380. "tools_paint_overlap": self.app.defaults["tools_paint_overlap"],
  381. "tools_paint_rest": self.app.defaults["tools_paint_rest"],
  382. })
  383. # ## Init the GUI interface
  384. self.ui.order_radio.set_value(self.app.defaults["tools_paint_order"])
  385. self.ui.offset_entry.set_value(self.app.defaults["tools_paint_offset"])
  386. self.ui.paintmethod_combo.set_value(self.app.defaults["tools_paint_method"])
  387. self.ui.selectmethod_combo.set_value(self.app.defaults["tools_paint_selectmethod"])
  388. self.ui.area_shape_radio.set_value(self.app.defaults["tools_paint_area_shape"])
  389. self.ui.pathconnect_cb.set_value(self.app.defaults["tools_paint_connect"])
  390. self.ui.paintcontour_cb.set_value(self.app.defaults["tools_paint_contour"])
  391. self.ui.paintoverlap_entry.set_value(self.app.defaults["tools_paint_overlap"])
  392. self.ui.new_tooldia_entry.set_value(self.app.defaults["tools_paint_newdia"])
  393. self.ui.rest_cb.set_value(self.app.defaults["tools_paint_rest"])
  394. # # make the default object type, "Geometry"
  395. # self.type_obj_radio.set_value("geometry")
  396. # use the current selected object and make it visible in the Paint object combobox
  397. sel_list = self.app.collection.get_selected()
  398. if len(sel_list) == 1:
  399. active = self.app.collection.get_active()
  400. kind = active.kind
  401. if kind == 'gerber':
  402. self.ui.type_obj_radio.set_value(kind)
  403. else:
  404. kind = 'geometry'
  405. self.ui.type_obj_radio.set_value(kind)
  406. # run those once so the obj_type attribute is updated in the FCComboBoxes
  407. # to make sure that the last loaded object is displayed in the combobox
  408. self.on_type_obj_changed(val=kind)
  409. self.on_reference_combo_changed()
  410. self.ui.obj_combo.set_value(active.options['name'])
  411. else:
  412. kind = 'geometry'
  413. self.ui.type_obj_radio.set_value('geometry')
  414. # run those once so the obj_type attribute is updated in the FCComboBoxes
  415. # to make sure that the last loaded object is displayed in the combobox
  416. self.on_type_obj_changed(val=kind)
  417. self.on_reference_combo_changed()
  418. try:
  419. diameters = [float(self.app.defaults["tools_paint_tooldia"])]
  420. except (ValueError, TypeError):
  421. if isinstance(self.app.defaults["tools_paint_tooldia"], str):
  422. diameters = [eval(x) for x in self.app.defaults["tools_paint_tooldia"].split(",") if x != '']
  423. else:
  424. diameters = self.app.defaults["tools_paint_tooldia"]
  425. if not diameters:
  426. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  427. self.build_ui()
  428. # if the Paint Method is "Single" disable the tool table context menu
  429. if self.default_data["tools_paint_selectmethod"] == "single":
  430. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  431. return
  432. for dia in diameters:
  433. self.on_tool_add(custom_dia=dia)
  434. self.ui.on_rest_machining_check(state=self.app.defaults["tools_paint_rest"])
  435. # if the Paint Method is "Polygon Selection" disable the tool table context menu
  436. if self.default_data["tools_paint_selectmethod"] == 1:
  437. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  438. # make sure that we can't get selection of Laser Lines for Geometry even if it's set in the Preferences
  439. # because we don't select the default object type in Preferences but here
  440. idx = self.ui.paintmethod_combo.findText(_("Laser_lines"))
  441. if self.ui.type_obj_radio.get_value().lower() == 'gerber':
  442. self.ui.paintmethod_combo.model().item(idx).setEnabled(True)
  443. else:
  444. self.ui.paintmethod_combo.model().item(idx).setEnabled(False)
  445. if self.ui.paintmethod_combo.get_value() == idx: # if its Laser Lines
  446. self.ui.paintmethod_combo.set_value(idx + 1)
  447. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  448. def rebuild_ui(self):
  449. # read the table tools uid
  450. current_uid_list = []
  451. for row in range(self.ui.tools_table.rowCount()):
  452. uid = int(self.ui.tools_table.item(row, 3).text())
  453. current_uid_list.append(uid)
  454. new_tools = {}
  455. new_uid = 1
  456. for current_uid in current_uid_list:
  457. new_tools[new_uid] = deepcopy(self.paint_tools[current_uid])
  458. new_uid += 1
  459. self.paint_tools = new_tools
  460. # the tools table changed therefore we need to rebuild it
  461. QtCore.QTimer.singleShot(20, self.build_ui)
  462. def build_ui(self):
  463. self.ui_disconnect()
  464. # updated units
  465. self.units = self.app.defaults['units'].upper()
  466. sorted_tools = []
  467. for k, v in self.paint_tools.items():
  468. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  469. order = self.ui.order_radio.get_value()
  470. if order == 'fwd':
  471. sorted_tools.sort(reverse=False)
  472. elif order == 'rev':
  473. sorted_tools.sort(reverse=True)
  474. else:
  475. pass
  476. n = len(sorted_tools)
  477. self.ui.tools_table.setRowCount(n)
  478. tool_id = 0
  479. for tool_sorted in sorted_tools:
  480. for tooluid_key, tooluid_value in self.paint_tools.items():
  481. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  482. tool_id += 1
  483. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  484. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  485. row_no = tool_id - 1
  486. self.ui.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  487. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  488. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  489. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  490. tool_type_item = FCComboBox()
  491. for item in self.tool_type_item_options:
  492. tool_type_item.addItem(item)
  493. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  494. idx = tool_type_item.findText(tooluid_value['tool_type'])
  495. tool_type_item.setCurrentIndex(idx)
  496. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  497. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  498. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  499. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  500. # make the diameter column editable
  501. for row in range(tool_id):
  502. self.ui.tools_table.item(row, 1).setFlags(
  503. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  504. # all the tools are selected by default
  505. self.ui.tools_table.selectColumn(0)
  506. #
  507. self.ui.tools_table.resizeColumnsToContents()
  508. self.ui.tools_table.resizeRowsToContents()
  509. vertical_header = self.ui.tools_table.verticalHeader()
  510. vertical_header.hide()
  511. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  512. horizontal_header = self.ui.tools_table.horizontalHeader()
  513. horizontal_header.setMinimumSectionSize(10)
  514. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  515. horizontal_header.resizeSection(0, 20)
  516. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  517. # self.ui.tools_table.setSortingEnabled(True)
  518. # sort by tool diameter
  519. # self.ui.tools_table.sortItems(1)
  520. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  521. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  522. self.ui_connect()
  523. # set the text on tool_data_label after loading the object
  524. sel_rows = set()
  525. sel_items = self.ui.tools_table.selectedItems()
  526. for it in sel_items:
  527. sel_rows.add(it.row())
  528. if len(sel_rows) > 1:
  529. self.ui.tool_data_label.setText(
  530. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  531. )
  532. def on_tool_add(self, custom_dia=None):
  533. self.blockSignals(True)
  534. filename = self.app.data_path + '\\tools_db.FlatDB'
  535. new_tools_dict = deepcopy(self.default_data)
  536. updated_tooldia = None
  537. # construct a list of all 'tooluid' in the self.iso_tools
  538. tool_uid_list = [int(tooluid_key) for tooluid_key in self.paint_tools]
  539. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  540. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  541. tooluid = int(max_uid + 1)
  542. tool_dias = []
  543. for k, v in self.paint_tools.items():
  544. for tool_v in v.keys():
  545. if tool_v == 'tooldia':
  546. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  547. # determine the new tool diameter
  548. if custom_dia is None:
  549. tool_dia = self.ui.new_tooldia_entry.get_value()
  550. else:
  551. tool_dia = custom_dia
  552. if tool_dia is None or tool_dia == 0:
  553. self.build_ui()
  554. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  555. "in Float format."))
  556. self.blockSignals(False)
  557. return
  558. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  559. # if new tool diameter already in the Tool List then abort
  560. if truncated_tooldia in tool_dias:
  561. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  562. self.blockSignals(False)
  563. return
  564. # load the database tools from the file
  565. try:
  566. with open(filename) as f:
  567. tools = f.read()
  568. except IOError:
  569. self.app.log.error("Could not load tools DB file.")
  570. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  571. self.blockSignals(False)
  572. self.on_tool_default_add(dia=tool_dia)
  573. return
  574. try:
  575. # store here the tools from Tools Database when searching in Tools Database
  576. tools_db_dict = json.loads(tools)
  577. except Exception:
  578. e = sys.exc_info()[0]
  579. self.app.log.error(str(e))
  580. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  581. self.blockSignals(False)
  582. self.on_tool_default_add(dia=tool_dia)
  583. return
  584. tool_found = 0
  585. offset = 'Path'
  586. offset_val = 0.0
  587. typ = "Rough"
  588. tool_type = 'V'
  589. # look in database tools
  590. for db_tool, db_tool_val in tools_db_dict.items():
  591. offset = db_tool_val['offset']
  592. offset_val = db_tool_val['offset_value']
  593. typ = db_tool_val['type']
  594. tool_type = db_tool_val['tool_type']
  595. db_tooldia = db_tool_val['tooldia']
  596. low_limit = float(db_tool_val['data']['tol_min'])
  597. high_limit = float(db_tool_val['data']['tol_max'])
  598. # we need only tool marked for Paint Tool
  599. if db_tool_val['data']['tool_target'] != _('Paint'):
  600. continue
  601. # if we find a tool with the same diameter in the Tools DB just update it's data
  602. if truncated_tooldia == db_tooldia:
  603. tool_found += 1
  604. for d in db_tool_val['data']:
  605. if d.find('tools_paint') == 0:
  606. new_tools_dict[d] = db_tool_val['data'][d]
  607. elif d.find('tools_') == 0:
  608. # don't need data for other App Tools; this tests after 'tools_drill_'
  609. continue
  610. else:
  611. new_tools_dict[d] = db_tool_val['data'][d]
  612. # search for a tool that has a tolerance that the tool fits in
  613. elif high_limit >= truncated_tooldia >= low_limit:
  614. tool_found += 1
  615. updated_tooldia = db_tooldia
  616. for d in db_tool_val['data']:
  617. if d.find('tools_paint') == 0:
  618. new_tools_dict[d] = db_tool_val['data'][d]
  619. elif d.find('tools_') == 0:
  620. # don't need data for other App Tools; this tests after 'tools_drill_'
  621. continue
  622. else:
  623. new_tools_dict[d] = db_tool_val['data'][d]
  624. # test we found a suitable tool in Tools Database or if multiple ones
  625. if tool_found == 0:
  626. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Tool not in Tools Database. Adding a default tool."))
  627. self.on_tool_default_add(dia=tool_dia)
  628. self.blockSignals(False)
  629. return
  630. if tool_found > 1:
  631. self.app.inform.emit(
  632. '[WARNING_NOTCL] %s' % _("Cancelled.\n"
  633. "Multiple tools for one tool diameter found in Tools Database."))
  634. self.blockSignals(False)
  635. return
  636. # if new tool diameter found in Tools Database already in the Tool List then abort
  637. if updated_tooldia is not None and updated_tooldia in tool_dias:
  638. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  639. self.blockSignals(False)
  640. return
  641. new_tdia = deepcopy(updated_tooldia) if updated_tooldia is not None else deepcopy(truncated_tooldia)
  642. self.paint_tools.update({
  643. tooluid: {
  644. 'tooldia': new_tdia,
  645. 'offset': deepcopy(offset),
  646. 'offset_value': deepcopy(offset_val),
  647. 'type': deepcopy(typ),
  648. 'tool_type': deepcopy(tool_type),
  649. 'data': deepcopy(new_tools_dict),
  650. 'solid_geometry': []
  651. }
  652. })
  653. self.blockSignals(False)
  654. self.build_ui()
  655. # select the tool just added
  656. for row in range(self.ui.tools_table.rowCount()):
  657. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  658. self.ui.tools_table.selectRow(row)
  659. break
  660. # update the UI form
  661. self.update_ui()
  662. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table from Tools Database."))
  663. def on_tool_default_add(self, dia=None, muted=None):
  664. self.blockSignals(True)
  665. self.units = self.app.defaults['units'].upper()
  666. if dia:
  667. tool_dia = dia
  668. else:
  669. tool_dia = self.ui.new_tooldia_entry.get_value()
  670. if tool_dia is None or tool_dia == 0:
  671. self.build_ui()
  672. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  673. "in Float format."))
  674. self.blockSignals(False)
  675. return
  676. # construct a list of all 'tooluid' in the self.tools
  677. tool_uid_list = [int(tooluid_key) for tooluid_key in self.paint_tools]
  678. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  679. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  680. self.tooluid = int(max_uid + 1)
  681. tool_dias = []
  682. for k, v in self.paint_tools.items():
  683. for tool_v in v.keys():
  684. if tool_v == 'tooldia':
  685. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  686. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  687. if truncated_tooldia in tool_dias:
  688. if muted is None:
  689. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  690. self.blockSignals(False)
  691. return
  692. self.paint_tools.update({
  693. int(self.tooluid): {
  694. 'tooldia': truncated_tooldia,
  695. 'offset': 'Path',
  696. 'offset_value': 0.0,
  697. 'type': 'Iso',
  698. 'tool_type': 'V',
  699. 'data': deepcopy(self.default_data),
  700. 'solid_geometry': []
  701. }
  702. })
  703. self.blockSignals(False)
  704. self.build_ui()
  705. # select the tool just added
  706. for row in range(self.ui.tools_table.rowCount()):
  707. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  708. self.ui.tools_table.selectRow(row)
  709. break
  710. # update the UI form
  711. self.update_ui()
  712. if muted is None:
  713. self.app.inform.emit('[success] %s' % _("Default tool added to Tool Table."))
  714. def on_tool_edit(self, item):
  715. self.blockSignals(True)
  716. edited_row = item.row()
  717. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  718. tool_dias = []
  719. try:
  720. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  721. except ValueError:
  722. # try to convert comma to decimal point. if it's still not working error message and return
  723. try:
  724. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  725. except ValueError:
  726. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  727. return
  728. for k, v in self.paint_tools.items():
  729. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  730. # identify the tool that was edited and get it's tooluid
  731. if new_tool_dia not in tool_dias:
  732. self.paint_tools[editeduid]['tooldia'] = new_tool_dia
  733. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  734. self.blockSignals(False)
  735. self.build_ui()
  736. return
  737. # identify the old tool_dia and restore the text in tool table
  738. for k, v in self.paint_tools.items():
  739. if k == editeduid:
  740. old_tool_dia = v['tooldia']
  741. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  742. restore_dia_item.setText(str(old_tool_dia))
  743. break
  744. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  745. self.blockSignals(False)
  746. self.build_ui()
  747. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  748. """
  749. Will delete a tool in the tool table
  750. :param rows_to_delete: which rows to delete; can be a list
  751. :param all_tools: delete all tools in the tool table
  752. :return:
  753. """
  754. self.blockSignals(True)
  755. deleted_tools_list = []
  756. if all_tools:
  757. self.paint_tools.clear()
  758. self.blockSignals(False)
  759. self.build_ui()
  760. return
  761. if rows_to_delete:
  762. try:
  763. for row in rows_to_delete:
  764. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  765. deleted_tools_list.append(tooluid_del)
  766. except TypeError:
  767. deleted_tools_list.append(rows_to_delete)
  768. for t in deleted_tools_list:
  769. self.paint_tools.pop(t, None)
  770. self.blockSignals(False)
  771. self.build_ui()
  772. return
  773. try:
  774. if self.ui.tools_table.selectedItems():
  775. for row_sel in self.ui.tools_table.selectedItems():
  776. row = row_sel.row()
  777. if row < 0:
  778. continue
  779. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  780. deleted_tools_list.append(tooluid_del)
  781. for t in deleted_tools_list:
  782. self.paint_tools.pop(t, None)
  783. except AttributeError:
  784. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  785. self.blockSignals(False)
  786. return
  787. except Exception as e:
  788. log.debug(str(e))
  789. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  790. self.blockSignals(False)
  791. self.build_ui()
  792. def on_paint_button_click(self):
  793. """
  794. Slot for clicking signal
  795. :return: None
  796. """
  797. self.app.defaults.report_usage("on_paint_button_click")
  798. self.first_click = False
  799. self.cursor_pos = None
  800. self.mouse_is_dragging = False
  801. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  802. if prog_plot:
  803. self.temp_shapes.clear(update=True)
  804. self.sel_rect = []
  805. obj_type = self.ui.type_obj_radio.get_value()
  806. self.circle_steps = int(self.app.defaults["gerber_circle_steps"]) if obj_type == 'gerber' else \
  807. int(self.app.defaults["geometry_circle_steps"])
  808. self.obj_name = self.ui.obj_combo.currentText()
  809. # Get source object.
  810. try:
  811. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  812. except Exception as e:
  813. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  814. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object: %s"), self.obj_name))
  815. return
  816. if self.paint_obj is None:
  817. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), self.paint_obj))
  818. return
  819. # test if the Geometry Object is multigeo with more than one tool and return Fail if True because
  820. # for now Paint don't work on MultiGeo with more than one tools
  821. if self.paint_obj.kind == 'geometry' and self.paint_obj.multigeo is True and len(self.paint_obj.tools) > 1:
  822. self.app.inform.emit('[ERROR_NOTCL] %s...' % _("Can't do Paint on MultiGeo geometries"))
  823. return 'Fail'
  824. self.o_name = '%s_mt_paint' % self.obj_name
  825. # use the selected tools in the tool table; get diameters
  826. self.tooldia_list = []
  827. table_items = self.ui.tools_table.selectedItems()
  828. sel_rows = {t.row() for t in table_items}
  829. if len(sel_rows) > 0:
  830. for row in sel_rows:
  831. try:
  832. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  833. except ValueError:
  834. # try to convert comma to decimal point. if it's still not working error message and return
  835. try:
  836. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  837. except ValueError:
  838. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  839. continue
  840. self.tooldia_list.append(self.tooldia)
  841. else:
  842. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  843. return
  844. self.select_method = self.ui.selectmethod_combo.get_value()
  845. if self.select_method == 0: # _("All")
  846. self.paint_poly_all(self.paint_obj, tooldia=self.tooldia_list, outname=self.o_name)
  847. elif self.select_method == 1: # _("Polygon Selection")
  848. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  849. if self.app.ui.grid_snap_btn.isChecked():
  850. self.grid_status_memory = True
  851. self.app.ui.grid_snap_btn.trigger()
  852. else:
  853. self.grid_status_memory = False
  854. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  855. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  856. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  857. if self.app.is_legacy is False:
  858. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  859. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  860. else:
  861. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  862. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  863. # disconnect flags
  864. self.poly_sel_disconnect_flag = True
  865. elif self.select_method == 2: # _("Area Selection")
  866. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  867. if self.app.is_legacy is False:
  868. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  869. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  870. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  871. else:
  872. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  873. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  874. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  875. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  876. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  877. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  878. # disconnect flags
  879. self.area_sel_disconnect_flag = True
  880. elif self.select_method == 3: # _("Reference Object")
  881. self.bound_obj_name = self.reference_combo.currentText()
  882. # Get source object.
  883. try:
  884. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  885. except Exception:
  886. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  887. return "Could not retrieve object: %s" % self.obj_name
  888. self.paint_poly_ref(obj=self.paint_obj, sel_obj=self.bound_obj, tooldia=self.tooldia_list,
  889. outname=self.o_name)
  890. # To be called after clicking on the plot.
  891. def on_single_poly_mouse_release(self, event):
  892. if self.app.is_legacy is False:
  893. event_pos = event.pos
  894. right_button = 2
  895. event_is_dragging = self.app.event_is_dragging
  896. else:
  897. event_pos = (event.xdata, event.ydata)
  898. right_button = 3
  899. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  900. try:
  901. x = float(event_pos[0])
  902. y = float(event_pos[1])
  903. except TypeError:
  904. return
  905. event_pos = (x, y)
  906. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  907. # do paint single only for left mouse clicks
  908. if event.button == 1:
  909. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  910. if clicked_poly:
  911. if clicked_poly not in self.poly_dict.values():
  912. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  913. layer=0,
  914. shape=clicked_poly,
  915. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  916. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  917. visible=True)
  918. self.poly_dict[shape_id] = clicked_poly
  919. self.app.inform.emit(
  920. '%s: %d. %s' % (_("Added polygon"),
  921. int(len(self.poly_dict)),
  922. _("Click to add next polygon or right click to start painting."))
  923. )
  924. else:
  925. try:
  926. for k, v in list(self.poly_dict.items()):
  927. if v == clicked_poly:
  928. self.app.tool_shapes.remove(k)
  929. self.poly_dict.pop(k)
  930. break
  931. except TypeError:
  932. return
  933. self.app.inform.emit(
  934. '%s. %s' % (_("Removed polygon"),
  935. _("Click to add/remove next polygon or right click to start painting."))
  936. )
  937. self.app.tool_shapes.redraw()
  938. else:
  939. self.app.inform.emit(_("No polygon detected under click position."))
  940. elif event.button == right_button and event_is_dragging is False:
  941. # restore the Grid snapping if it was active before
  942. if self.grid_status_memory is True:
  943. self.app.ui.grid_snap_btn.trigger()
  944. if self.app.is_legacy is False:
  945. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  946. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  947. else:
  948. self.app.plotcanvas.graph_event_disconnect(self.mr)
  949. self.app.plotcanvas.graph_event_disconnect(self.kp)
  950. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  951. self.app.on_mouse_click_over_plot)
  952. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  953. self.app.on_mouse_click_release_over_plot)
  954. # disconnect flags
  955. self.poly_sel_disconnect_flag = False
  956. self.app.tool_shapes.clear(update=True)
  957. if self.poly_dict:
  958. poly_list = deepcopy(list(self.poly_dict.values()))
  959. self.paint_poly(self.paint_obj, inside_pt=(curr_pos[0], curr_pos[1]), poly_list=poly_list,
  960. tooldia=self.tooldia_list)
  961. self.poly_dict.clear()
  962. else:
  963. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  964. # To be called after clicking on the plot.
  965. def on_mouse_release(self, event):
  966. if self.app.is_legacy is False:
  967. event_pos = event.pos
  968. # event_is_dragging = event.is_dragging
  969. right_button = 2
  970. else:
  971. event_pos = (event.xdata, event.ydata)
  972. # event_is_dragging = self.app.plotcanvas.is_dragging
  973. right_button = 3
  974. try:
  975. x = float(event_pos[0])
  976. y = float(event_pos[1])
  977. except TypeError:
  978. return
  979. event_pos = (x, y)
  980. shape_type = self.ui.area_shape_radio.get_value()
  981. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  982. if self.app.grid_status():
  983. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  984. x1, y1 = curr_pos[0], curr_pos[1]
  985. # do paint single only for left mouse clicks
  986. if event.button == 1:
  987. if shape_type == "square":
  988. if not self.first_click:
  989. self.first_click = True
  990. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  991. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  992. if self.app.grid_status():
  993. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  994. else:
  995. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  996. self.app.delete_selection_shape()
  997. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  998. pt1 = (x0, y0)
  999. pt2 = (x1, y0)
  1000. pt3 = (x1, y1)
  1001. pt4 = (x0, y1)
  1002. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1003. self.sel_rect.append(new_rectangle)
  1004. # add a temporary shape on canvas
  1005. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1006. self.first_click = False
  1007. return
  1008. else:
  1009. self.points.append((x1, y1))
  1010. if len(self.points) > 1:
  1011. self.poly_drawn = True
  1012. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1013. return ""
  1014. elif event.button == right_button and self.mouse_is_dragging is False:
  1015. shape_type = self.ui.area_shape_radio.get_value()
  1016. if shape_type == "square":
  1017. self.first_click = False
  1018. else:
  1019. # if we finish to add a polygon
  1020. if self.poly_drawn is True:
  1021. try:
  1022. # try to add the point where we last clicked if it is not already in the self.points
  1023. last_pt = (x1, y1)
  1024. if last_pt != self.points[-1]:
  1025. self.points.append(last_pt)
  1026. except IndexError:
  1027. pass
  1028. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1029. if len(self.points) > 2:
  1030. self.delete_moving_selection_shape()
  1031. pol = Polygon(self.points)
  1032. # do not add invalid polygons even if they are drawn by utility geometry
  1033. if pol.is_valid:
  1034. self.sel_rect.append(pol)
  1035. self.draw_selection_shape_polygon(points=self.points)
  1036. self.app.inform.emit(
  1037. _("Zone added. Click to start adding next zone or right click to finish."))
  1038. self.points = []
  1039. self.poly_drawn = False
  1040. return
  1041. self.delete_tool_selection_shape()
  1042. if self.app.is_legacy is False:
  1043. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1044. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1045. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1046. else:
  1047. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1048. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1049. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1050. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1051. self.app.on_mouse_click_over_plot)
  1052. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1053. self.app.on_mouse_move_over_plot)
  1054. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1055. self.app.on_mouse_click_release_over_plot)
  1056. # disconnect flags
  1057. self.area_sel_disconnect_flag = False
  1058. if len(self.sel_rect) == 0:
  1059. return
  1060. self.sel_rect = unary_union(self.sel_rect)
  1061. self.paint_poly_area(obj=self.paint_obj, tooldia=self.tooldia_list, sel_obj=self.sel_rect,
  1062. outname=self.o_name)
  1063. # called on mouse move
  1064. def on_mouse_move(self, event):
  1065. shape_type = self.ui.area_shape_radio.get_value()
  1066. if self.app.is_legacy is False:
  1067. event_pos = event.pos
  1068. event_is_dragging = event.is_dragging
  1069. # right_button = 2
  1070. else:
  1071. event_pos = (event.xdata, event.ydata)
  1072. event_is_dragging = self.app.plotcanvas.is_dragging
  1073. # right_button = 3
  1074. try:
  1075. x = float(event_pos[0])
  1076. y = float(event_pos[1])
  1077. except TypeError:
  1078. return
  1079. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1080. # detect mouse dragging motion
  1081. if event_is_dragging == 1:
  1082. self.mouse_is_dragging = True
  1083. else:
  1084. self.mouse_is_dragging = False
  1085. # update the cursor position
  1086. if self.app.grid_status():
  1087. # Update cursor
  1088. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1089. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1090. symbol='++', edge_color=self.app.cursor_color_3D,
  1091. edge_width=self.app.defaults["global_cursor_width"],
  1092. size=self.app.defaults["global_cursor_size"])
  1093. if self.cursor_pos is None:
  1094. self.cursor_pos = (0, 0)
  1095. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1096. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1097. # # update the positions on status bar
  1098. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1099. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1100. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1101. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1102. units = self.app.defaults["units"].lower()
  1103. self.app.plotcanvas.text_hud.text = \
  1104. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1105. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1106. # draw the utility geometry
  1107. if shape_type == "square":
  1108. if self.first_click:
  1109. self.app.delete_selection_shape()
  1110. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1111. coords=(curr_pos[0], curr_pos[1]))
  1112. else:
  1113. self.delete_moving_selection_shape()
  1114. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1115. def on_key_press(self, event):
  1116. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1117. # matplotlib_key_flag = False
  1118. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1119. if type(event) is int:
  1120. key = event
  1121. # events from the GUI are of type QKeyEvent
  1122. elif type(event) == QtGui.QKeyEvent:
  1123. key = event.key()
  1124. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1125. # matplotlib_key_flag = True
  1126. key = event.key
  1127. key = QtGui.QKeySequence(key)
  1128. # check for modifiers
  1129. key_string = key.toString().lower()
  1130. if '+' in key_string:
  1131. mod, __, key_text = key_string.rpartition('+')
  1132. if mod.lower() == 'ctrl':
  1133. # modifiers = QtCore.Qt.ControlModifier
  1134. pass
  1135. elif mod.lower() == 'alt':
  1136. # modifiers = QtCore.Qt.AltModifier
  1137. pass
  1138. elif mod.lower() == 'shift':
  1139. # modifiers = QtCore.Qt.ShiftModifier
  1140. pass
  1141. else:
  1142. # modifiers = QtCore.Qt.NoModifier
  1143. pass
  1144. key = QtGui.QKeySequence(key_text)
  1145. # events from Vispy are of type KeyEvent
  1146. else:
  1147. key = event.key
  1148. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1149. if self.area_sel_disconnect_flag is True:
  1150. try:
  1151. if self.app.is_legacy is False:
  1152. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1153. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1154. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1155. else:
  1156. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1157. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1158. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1159. except Exception as e:
  1160. log.debug("ToolPaint.on_key_press() _1 --> %s" % str(e))
  1161. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1162. self.app.on_mouse_click_over_plot)
  1163. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1164. self.app.on_mouse_move_over_plot)
  1165. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1166. self.app.on_mouse_click_release_over_plot)
  1167. if self.poly_sel_disconnect_flag is False:
  1168. try:
  1169. # restore the Grid snapping if it was active before
  1170. if self.grid_status_memory is True:
  1171. self.app.ui.grid_snap_btn.trigger()
  1172. if self.app.is_legacy is False:
  1173. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1174. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1175. else:
  1176. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1177. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1178. self.app.tool_shapes.clear(update=True)
  1179. except Exception as e:
  1180. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1181. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1182. self.app.on_mouse_click_release_over_plot)
  1183. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1184. self.app.on_mouse_click_over_plot)
  1185. self.points = []
  1186. self.poly_drawn = False
  1187. self.poly_dict.clear()
  1188. self.delete_moving_selection_shape()
  1189. self.delete_tool_selection_shape()
  1190. def paint_polygon_worker(self, polyg, tooldiameter, paint_method, over, conn, cont, prog_plot, obj):
  1191. cpoly = None
  1192. if paint_method == 0: # _("Standard")
  1193. try:
  1194. # Type(cp) == FlatCAMRTreeStorage | None
  1195. cpoly = self.clear_polygon(polyg,
  1196. tooldia=tooldiameter,
  1197. steps_per_circle=self.circle_steps,
  1198. overlap=over,
  1199. contour=cont,
  1200. connect=conn,
  1201. prog_plot=prog_plot)
  1202. except grace:
  1203. return "fail"
  1204. except Exception as ee:
  1205. log.debug("ToolPaint.paint_polygon_worker() Standard --> %s" % str(ee))
  1206. elif paint_method == 1: # _("Seed")
  1207. try:
  1208. # Type(cp) == FlatCAMRTreeStorage | None
  1209. cpoly = self.clear_polygon2(polyg,
  1210. tooldia=tooldiameter,
  1211. steps_per_circle=self.circle_steps,
  1212. overlap=over,
  1213. contour=cont,
  1214. connect=conn,
  1215. prog_plot=prog_plot)
  1216. except grace:
  1217. return "fail"
  1218. except Exception as ee:
  1219. log.debug("ToolPaint.paint_polygon_worker() Seed --> %s" % str(ee))
  1220. elif paint_method == 2: # _("Lines")
  1221. try:
  1222. # Type(cp) == FlatCAMRTreeStorage | None
  1223. cpoly = self.clear_polygon3(polyg,
  1224. tooldia=tooldiameter,
  1225. steps_per_circle=self.circle_steps,
  1226. overlap=over,
  1227. contour=cont,
  1228. connect=conn,
  1229. prog_plot=prog_plot)
  1230. except grace:
  1231. return "fail"
  1232. except Exception as ee:
  1233. log.debug("ToolPaint.paint_polygon_worker() Lines --> %s" % str(ee))
  1234. elif paint_method == 3: # _("Laser_lines")
  1235. try:
  1236. # line = None
  1237. # aperture_size = None
  1238. # the key is the aperture type and the val is a list of geo elements
  1239. flash_el_dict = {}
  1240. # the key is the aperture size, the val is a list of geo elements
  1241. traces_el_dict = {}
  1242. # find the flashes and the lines that are in the selected polygon and store them separately
  1243. for apid, apval in obj.apertures.items():
  1244. for geo_el in apval['geometry']:
  1245. if apval["size"] == 0.0:
  1246. if apval["size"] in traces_el_dict:
  1247. traces_el_dict[apval["size"]].append(geo_el)
  1248. else:
  1249. traces_el_dict[apval["size"]] = [geo_el]
  1250. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1251. if isinstance(geo_el['follow'], Point):
  1252. if apval["type"] == 'C':
  1253. if 'C' in flash_el_dict:
  1254. flash_el_dict['C'].append(geo_el)
  1255. else:
  1256. flash_el_dict['C'] = [geo_el]
  1257. elif apval["type"] == 'O':
  1258. if 'O' in flash_el_dict:
  1259. flash_el_dict['O'].append(geo_el)
  1260. else:
  1261. flash_el_dict['O'] = [geo_el]
  1262. elif apval["type"] == 'R':
  1263. if 'R' in flash_el_dict:
  1264. flash_el_dict['R'].append(geo_el)
  1265. else:
  1266. flash_el_dict['R'] = [geo_el]
  1267. else:
  1268. aperture_size = apval['size']
  1269. if aperture_size in traces_el_dict:
  1270. traces_el_dict[aperture_size].append(geo_el)
  1271. else:
  1272. traces_el_dict[aperture_size] = [geo_el]
  1273. cpoly = FlatCAMRTreeStorage()
  1274. pads_lines_list = []
  1275. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1276. # flashes and with _("Seed") for oblong and circular flashes
  1277. # and pads (flashes) need the contour therefore I override the GUI settings with always True
  1278. for ap_type in flash_el_dict:
  1279. for elem in flash_el_dict[ap_type]:
  1280. if 'solid' in elem:
  1281. if ap_type == 'C':
  1282. f_o = self.clear_polygon2(elem['solid'],
  1283. tooldia=tooldiameter,
  1284. steps_per_circle=self.app.defaults[
  1285. "geometry_circle_steps"],
  1286. overlap=over,
  1287. contour=True,
  1288. connect=conn,
  1289. prog_plot=prog_plot)
  1290. pads_lines_list += [p for p in f_o.get_objects() if p]
  1291. # this is the same as above but I keep it in case I will modify something in the future
  1292. elif ap_type == 'O':
  1293. f_o = self.clear_polygon2(elem['solid'],
  1294. tooldia=tooldiameter,
  1295. steps_per_circle=self.app.defaults[
  1296. "geometry_circle_steps"],
  1297. overlap=over,
  1298. contour=True,
  1299. connect=conn,
  1300. prog_plot=prog_plot)
  1301. pads_lines_list += [p for p in f_o.get_objects() if p]
  1302. elif ap_type == 'R':
  1303. f_o = self.clear_polygon3(elem['solid'],
  1304. tooldia=tooldiameter,
  1305. steps_per_circle=self.app.defaults[
  1306. "geometry_circle_steps"],
  1307. overlap=over,
  1308. contour=True,
  1309. connect=conn,
  1310. prog_plot=prog_plot)
  1311. pads_lines_list += [p for p in f_o.get_objects() if p]
  1312. # add the lines from pads to the storage
  1313. try:
  1314. for lin in pads_lines_list:
  1315. if lin:
  1316. cpoly.insert(lin)
  1317. except TypeError:
  1318. cpoly.insert(pads_lines_list)
  1319. copper_lines_list = []
  1320. # process the traces found in the selected polygon using the 'laser_lines' method,
  1321. # method which will follow the 'follow' line therefore use the longer path possible for the
  1322. # laser, therefore the acceleration will play a smaller factor
  1323. for aperture_size in traces_el_dict:
  1324. for elem in traces_el_dict[aperture_size]:
  1325. line = elem['follow']
  1326. if line:
  1327. t_o = self.fill_with_lines(line, aperture_size,
  1328. tooldia=tooldiameter,
  1329. steps_per_circle=self.app.defaults[
  1330. "geometry_circle_steps"],
  1331. overlap=over,
  1332. contour=cont,
  1333. connect=conn,
  1334. prog_plot=prog_plot)
  1335. copper_lines_list += [p for p in t_o.get_objects() if p]
  1336. # add the lines from copper features to storage but first try to make as few lines as possible
  1337. # by trying to fuse them
  1338. lines_union = linemerge(unary_union(copper_lines_list))
  1339. try:
  1340. for lin in lines_union:
  1341. if lin:
  1342. cpoly.insert(lin)
  1343. except TypeError:
  1344. cpoly.insert(lines_union)
  1345. # # determine the Gerber follow line
  1346. # for apid, apval in obj.apertures.items():
  1347. # for geo_el in apval['geometry']:
  1348. # if 'solid' in geo_el:
  1349. # if Point(inside_pt).within(geo_el['solid']):
  1350. # if not isinstance(geo_el['follow'], Point):
  1351. # line = geo_el['follow']
  1352. #
  1353. # if apval['type'] == 'C':
  1354. # aperture_size = apval['size']
  1355. # else:
  1356. # if apval['width'] > apval['height']:
  1357. # aperture_size = apval['height']
  1358. # else:
  1359. # aperture_size = apval['width']
  1360. #
  1361. # if line:
  1362. # cpoly = self.fill_with_lines(line, aperture_size,
  1363. # tooldia=tooldiameter,
  1364. # steps_per_circle=self.circle_steps,
  1365. # overlap=over,
  1366. # contour=cont,
  1367. # connect=conn,
  1368. # prog_plot=prog_plot)
  1369. except grace:
  1370. return "fail"
  1371. except Exception as ee:
  1372. log.debug("ToolPaint.paint_polygon_worker() Laser Lines --> %s" % str(ee))
  1373. elif paint_method == 4: # _("Combo")
  1374. try:
  1375. self.app.inform.emit(_("Painting polygon with method: lines."))
  1376. cpoly = self.clear_polygon3(polyg,
  1377. tooldia=tooldiameter,
  1378. steps_per_circle=self.circle_steps,
  1379. overlap=over,
  1380. contour=cont,
  1381. connect=conn,
  1382. prog_plot=prog_plot)
  1383. if cpoly and cpoly.objects:
  1384. pass
  1385. else:
  1386. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1387. cpoly = self.clear_polygon2(polyg,
  1388. tooldia=tooldiameter,
  1389. steps_per_circle=self.circle_steps,
  1390. overlap=over,
  1391. contour=cont,
  1392. connect=conn,
  1393. prog_plot=prog_plot)
  1394. if cpoly and cpoly.objects:
  1395. pass
  1396. else:
  1397. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1398. cpoly = self.clear_polygon(polyg,
  1399. tooldia=tooldiameter,
  1400. steps_per_circle=self.circle_steps,
  1401. overlap=over,
  1402. contour=cont,
  1403. connect=conn,
  1404. prog_plot=prog_plot)
  1405. except grace:
  1406. return "fail"
  1407. except Exception as ee:
  1408. log.debug("ToolPaint.paint_polygon_worker() Combo --> %s" % str(ee))
  1409. if cpoly and cpoly.objects:
  1410. return cpoly
  1411. else:
  1412. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1413. return None
  1414. def paint_geo(self, obj, geometry, tooldia=None, order=None, method=None, outname=None,
  1415. tools_storage=None, plot=True, run_threaded=True):
  1416. """
  1417. Paints a given geometry.
  1418. :param obj: painted object
  1419. :param geometry: geometry to Paint
  1420. :param tooldia: Diameter of the painting tool
  1421. :param order: if the tools are ordered and how
  1422. :param outname: Name of the resulting Geometry Object.
  1423. :param method: choice out of _("Seed"), 'normal', 'lines'
  1424. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1425. Usage of the different one is related to when this function is called
  1426. from a TcL command.
  1427. :param plot:
  1428. :param run_threaded:
  1429. :return: None
  1430. """
  1431. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1432. # determine if to use the progressive plotting
  1433. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1434. name = outname if outname is not None else self.obj_name + "_paint"
  1435. order = order if order is not None else self.ui.order_radio.get_value()
  1436. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1437. sorted_tools = []
  1438. if tooldia is not None:
  1439. try:
  1440. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1441. except AttributeError:
  1442. if not isinstance(tooldia, list):
  1443. sorted_tools = [float(tooldia)]
  1444. else:
  1445. sorted_tools = tooldia
  1446. else:
  1447. table_items = self.ui.tools_table.selectedItems()
  1448. sel_rows = {t.row() for t in table_items}
  1449. for row in sel_rows:
  1450. try:
  1451. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  1452. except ValueError:
  1453. # try to convert comma to decimal point. if it's still not working error message and return
  1454. try:
  1455. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  1456. except ValueError:
  1457. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1458. continue
  1459. sorted_tools.append(self.tooldia)
  1460. if not sorted_tools:
  1461. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  1462. return 'fail'
  1463. # Initializes the new geometry object
  1464. def job_normal_clear(geo_obj, app_obj):
  1465. tool_dia = None
  1466. current_uid = None
  1467. final_solid_geometry = []
  1468. old_disp_number = 0
  1469. # sort the tools if we have an order selected in the UI
  1470. if order == 'fwd':
  1471. sorted_tools.sort(reverse=False)
  1472. elif order == 'rev':
  1473. sorted_tools.sort(reverse=True)
  1474. else:
  1475. pass
  1476. for tool_dia in sorted_tools:
  1477. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1478. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1479. str(tool_dia),
  1480. self.units.lower(),
  1481. _('started'))
  1482. self.app.inform.emit(msg)
  1483. self.app.proc_container.update_view_text(' %d%%' % 0)
  1484. # find the tooluid associated with the current tool_dia so we know what tool to use
  1485. for k, v in tools_storage.items():
  1486. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1487. current_uid = int(k)
  1488. if not current_uid:
  1489. return "fail"
  1490. # determine the tool parameters to use
  1491. over = float(tools_storage[current_uid]['data']['tools_paint_overlap']) / 100.0
  1492. conn = tools_storage[current_uid]['data']['tools_paint_connect']
  1493. cont = tools_storage[current_uid]['data']['tools_paint_contour']
  1494. paint_offset = float(tools_storage[current_uid]['data']['tools_paint_offset'])
  1495. poly_buf = []
  1496. for pol in geometry:
  1497. buffered_pol = pol.buffer(-paint_offset)
  1498. if buffered_pol and not buffered_pol.is_empty:
  1499. poly_buf.append(buffered_pol)
  1500. if not poly_buf:
  1501. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1502. continue
  1503. # variables to display the percentage of work done
  1504. geo_len = len(poly_buf)
  1505. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1506. pol_nr = 0
  1507. # -----------------------------
  1508. # effective polygon clearing job
  1509. # -----------------------------
  1510. try:
  1511. cp = []
  1512. try:
  1513. for pp in poly_buf:
  1514. # provide the app with a way to process the GUI events when in a blocking loop
  1515. QtWidgets.QApplication.processEvents()
  1516. if self.app.abort_flag:
  1517. # graceful abort requested by the user
  1518. raise grace
  1519. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1520. cont=cont, paint_method=paint_method, obj=obj,
  1521. prog_plot=prog_plot)
  1522. if geo_res:
  1523. cp.append(geo_res)
  1524. pol_nr += 1
  1525. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1526. # log.debug("Polygons cleared: %d" % pol_nr)
  1527. if old_disp_number < disp_number <= 100:
  1528. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1529. old_disp_number = disp_number
  1530. except TypeError:
  1531. # provide the app with a way to process the GUI events when in a blocking loop
  1532. QtWidgets.QApplication.processEvents()
  1533. if self.app.abort_flag:
  1534. # graceful abort requested by the user
  1535. raise grace
  1536. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1537. cont=cont, paint_method=paint_method, obj=obj,
  1538. prog_plot=prog_plot)
  1539. if geo_res:
  1540. cp.append(geo_res)
  1541. total_geometry = []
  1542. if cp:
  1543. for x in cp:
  1544. total_geometry += list(x.get_objects())
  1545. # clean the geometry
  1546. new_geo = [g for g in total_geometry if g and not g.is_empty]
  1547. total_geometry = new_geo
  1548. final_solid_geometry += total_geometry
  1549. except grace:
  1550. return "fail"
  1551. except Exception as e:
  1552. log.debug("Could not Paint the polygons. %s" % str(e))
  1553. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1554. "Or a different strategy of paint"), str(e))
  1555. self.app.inform.emit(mssg)
  1556. continue
  1557. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1558. # dictionary and then reset the temporary list that stored that solid_geometry
  1559. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1560. tools_storage[current_uid]['data']['name'] = name
  1561. # clean the progressive plotted shapes if it was used
  1562. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1563. self.temp_shapes.clear(update=True)
  1564. # delete tools with empty geometry
  1565. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1566. for uid in list(tools_storage.keys()):
  1567. # if the solid_geometry (type=list) is empty
  1568. if not tools_storage[uid]['solid_geometry']:
  1569. tools_storage.pop(uid, None)
  1570. if not tools_storage:
  1571. return 'fail'
  1572. geo_obj.options["cnctooldia"] = str(tool_dia)
  1573. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1574. geo_obj.multigeo = True
  1575. geo_obj.multitool = True
  1576. geo_obj.tools.clear()
  1577. geo_obj.tools = dict(tools_storage)
  1578. geo_obj.solid_geometry = unary_union(final_solid_geometry)
  1579. try:
  1580. if isinstance(geo_obj.solid_geometry, list):
  1581. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1582. else:
  1583. a, b, c, d = geo_obj.solid_geometry.bounds
  1584. geo_obj.options['xmin'] = a
  1585. geo_obj.options['ymin'] = b
  1586. geo_obj.options['xmax'] = c
  1587. geo_obj.options['ymax'] = d
  1588. except Exception as ee:
  1589. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1590. return
  1591. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1592. has_solid_geo = 0
  1593. for tooluid in geo_obj.tools:
  1594. if geo_obj.tools[tooluid]['solid_geometry']:
  1595. has_solid_geo += 1
  1596. if has_solid_geo == 0:
  1597. app_obj.inform.emit('[ERROR] %s' %
  1598. _("There is no Painting Geometry in the file.\n"
  1599. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1600. "Change the painting parameters and try again."))
  1601. return "fail"
  1602. # Experimental...
  1603. # print("Indexing...", end=' ')
  1604. # geo_obj.make_index()
  1605. # Initializes the new geometry object
  1606. def job_rest_clear(geo_obj, app_obj):
  1607. current_uid = None
  1608. final_solid_geometry = []
  1609. old_disp_number = 0
  1610. # sort the tools reversed for the rest machining
  1611. sorted_tools.sort(reverse=True)
  1612. paint_offset = self.ui.rest_offset_entry.get_value()
  1613. poly_buf = []
  1614. for pol in geometry:
  1615. buffered_pol = pol.buffer(-paint_offset)
  1616. if buffered_pol and not buffered_pol.is_empty:
  1617. try:
  1618. for x in buffered_pol:
  1619. poly_buf.append(x)
  1620. except TypeError:
  1621. poly_buf.append(buffered_pol)
  1622. poly_buf = unary_union(poly_buf)
  1623. if not poly_buf:
  1624. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1625. return 'fail'
  1626. # variables to display the percentage of work done
  1627. geo_len = len(poly_buf)
  1628. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1629. for tool_dia in sorted_tools:
  1630. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1631. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1632. str(tool_dia),
  1633. self.units.lower(),
  1634. _('started'))
  1635. self.app.inform.emit(msg)
  1636. self.app.proc_container.update_view_text(' %d%%' % 0)
  1637. # find the tooluid associated with the current tool_dia so we know what tool to use
  1638. for k, v in tools_storage.items():
  1639. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1640. current_uid = int(k)
  1641. if not current_uid:
  1642. return "fail"
  1643. # store here the cleared geometry
  1644. # cleared_geo = []
  1645. # determine the tool parameters to use
  1646. over = float(tools_storage[current_uid]['data']['tools_paint_overlap']) / 100.0
  1647. conn = tools_storage[current_uid]['data']['tools_paint_connect']
  1648. cont = tools_storage[current_uid]['data']['tools_paint_contour']
  1649. pol_nr = 0
  1650. # store here the parts of polygons that could not be cleared; actually those are parts of polygons
  1651. rest_list = []
  1652. # -----------------------------
  1653. # effective polygon clearing job
  1654. # -----------------------------
  1655. try:
  1656. cleared_geo = []
  1657. try:
  1658. for pp in poly_buf:
  1659. # provide the app with a way to process the GUI events when in a blocking loop
  1660. QtWidgets.QApplication.processEvents()
  1661. if self.app.abort_flag:
  1662. # graceful abort requested by the user
  1663. raise grace
  1664. # speedup the clearing by not trying to clear polygons that is clear they can't be
  1665. # cleared with the current tool. this tremendously reduce the clearing time
  1666. check_dist = -tool_dia / 2.0
  1667. check_buff = pp.buffer(check_dist)
  1668. if not check_buff or check_buff.is_empty:
  1669. continue
  1670. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1671. cont=cont, paint_method=paint_method, obj=obj,
  1672. prog_plot=prog_plot)
  1673. geo_elems = list(geo_res.get_objects())
  1674. # See if the polygon was completely cleared
  1675. pp_cleared = unary_union(geo_elems).buffer(tool_dia / 2.0)
  1676. rest = pp.difference(pp_cleared)
  1677. if rest and not rest.is_empty:
  1678. try:
  1679. for r in rest:
  1680. if r.is_valid:
  1681. rest_list.append(r)
  1682. except TypeError:
  1683. if rest.is_valid:
  1684. rest_list.append(rest)
  1685. if geo_res:
  1686. cleared_geo += geo_elems
  1687. pol_nr += 1
  1688. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1689. # log.debug("Polygons cleared: %d" % pol_nr)
  1690. if old_disp_number < disp_number <= 100:
  1691. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1692. old_disp_number = disp_number
  1693. except TypeError:
  1694. # provide the app with a way to process the GUI events when in a blocking loop
  1695. QtWidgets.QApplication.processEvents()
  1696. if self.app.abort_flag:
  1697. # graceful abort requested by the user
  1698. raise grace
  1699. # speedup the clearing by not trying to clear polygons that is clear they can't be
  1700. # cleared with the current tool. this tremendously reduce the clearing time
  1701. check_dist = -tool_dia / 2.0
  1702. check_buff = poly_buf.buffer(check_dist)
  1703. if not check_buff or check_buff.is_empty:
  1704. continue
  1705. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1706. cont=cont, paint_method=paint_method, obj=obj,
  1707. prog_plot=prog_plot)
  1708. geo_elems = list(geo_res.get_objects())
  1709. # See if the polygon was completely cleared
  1710. pp_cleared = unary_union(geo_elems).buffer(tool_dia / 2.0)
  1711. rest = poly_buf.difference(pp_cleared)
  1712. if rest and not rest.is_empty:
  1713. try:
  1714. for r in rest:
  1715. if r.is_valid:
  1716. rest_list.append(r)
  1717. except TypeError:
  1718. if rest.is_valid:
  1719. rest_list.append(rest)
  1720. if geo_res:
  1721. cleared_geo += geo_elems
  1722. except grace:
  1723. return "fail"
  1724. except Exception as e:
  1725. log.debug("Could not Paint the polygons. %s" % str(e))
  1726. msg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1727. "Or a different strategy of paint"), str(e))
  1728. self.app.inform.emit(msg)
  1729. continue
  1730. if cleared_geo:
  1731. final_solid_geometry += cleared_geo
  1732. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1733. # dictionary and then reset the temporary list that stored that solid_geometry
  1734. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1735. tools_storage[current_uid]['data']['name'] = name
  1736. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1737. else:
  1738. log.debug("There are no geometries in the cleared polygon.")
  1739. # Area to clear next
  1740. log.debug("Generating rest geometry for the next tool.")
  1741. buffered_cleared = unary_union(cleared_geo)
  1742. buffered_cleared = buffered_cleared.buffer(tool_dia / 2.0)
  1743. poly_buf = poly_buf.difference(buffered_cleared)
  1744. tmp = []
  1745. try:
  1746. for p in poly_buf:
  1747. if p.is_valid:
  1748. tmp.append(p)
  1749. except TypeError:
  1750. if poly_buf.is_valid:
  1751. tmp.append(poly_buf)
  1752. tmp += rest_list
  1753. poly_buf = MultiPolygon(tmp)
  1754. if not poly_buf.is_valid:
  1755. poly_buf = unary_union(tmp)
  1756. if not poly_buf or poly_buf.is_empty or not poly_buf.is_valid:
  1757. log.debug("Rest geometry empty. Breaking.")
  1758. break
  1759. geo_obj.multigeo = True
  1760. geo_obj.options["cnctooldia"] = '0.0'
  1761. # clean the progressive plotted shapes if it was used
  1762. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1763. self.temp_shapes.clear(update=True)
  1764. # delete tools with empty geometry
  1765. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1766. for uid in list(tools_storage.keys()):
  1767. # if the solid_geometry (type=list) is empty
  1768. if not tools_storage[uid]['solid_geometry']:
  1769. tools_storage.pop(uid, None)
  1770. if not tools_storage:
  1771. return 'fail'
  1772. geo_obj.multitool = True
  1773. if geo_obj.tools:
  1774. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1775. has_solid_geo = 0
  1776. for tooluid in geo_obj.tools:
  1777. if geo_obj.tools[tooluid]['solid_geometry']:
  1778. has_solid_geo += 1
  1779. if has_solid_geo == 0:
  1780. app_obj.inform.emit(
  1781. '[ERROR] %s' %
  1782. _("There is no Painting Geometry in the file.\n"
  1783. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1784. "Change the painting parameters and try again.")
  1785. )
  1786. return "fail"
  1787. geo_obj.solid_geometry = unary_union(final_solid_geometry)
  1788. else:
  1789. return 'fail'
  1790. try:
  1791. if isinstance(geo_obj.solid_geometry, list):
  1792. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1793. else:
  1794. a, b, c, d = geo_obj.solid_geometry.bounds
  1795. geo_obj.options['xmin'] = a
  1796. geo_obj.options['ymin'] = b
  1797. geo_obj.options['xmax'] = c
  1798. geo_obj.options['ymax'] = d
  1799. except Exception as ee:
  1800. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1801. return
  1802. # Experimental...
  1803. # print("Indexing...", end=' ')
  1804. # geo_obj.make_index()
  1805. def job_thread(app_obj):
  1806. try:
  1807. if self.ui.rest_cb.get_value():
  1808. ret = app_obj.app_obj.new_object("geometry", name, job_rest_clear, plot=plot)
  1809. else:
  1810. ret = app_obj.app_obj.new_object("geometry", name, job_normal_clear, plot=plot)
  1811. except grace:
  1812. proc.done()
  1813. return
  1814. except Exception as er:
  1815. proc.done()
  1816. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_geo()', str(er)))
  1817. traceback.print_stack()
  1818. return
  1819. proc.done()
  1820. if ret == 'fail':
  1821. self.app.inform.emit('[ERROR] %s' % _("Paint failed."))
  1822. return
  1823. # focus on Properties Tab
  1824. # self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  1825. self.app.inform.emit('[success] %s' % _("Paint Done."))
  1826. # Promise object with the new name
  1827. self.app.collection.promise(name)
  1828. proc = self.app.proc_container.new(_("Painting..."))
  1829. if run_threaded:
  1830. # Background
  1831. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1832. else:
  1833. job_thread(app_obj=self.app)
  1834. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, order=None, method=None, outname=None,
  1835. tools_storage=None, plot=True, run_threaded=True):
  1836. """
  1837. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1838. Note:
  1839. * The margin is taken directly from the form.
  1840. :param run_threaded:
  1841. :param plot:
  1842. :param poly_list:
  1843. :param obj: painted object
  1844. :param inside_pt: [x, y]
  1845. :param tooldia: Diameter of the painting tool
  1846. :param order: if the tools are ordered and how
  1847. :param outname: Name of the resulting Geometry Object.
  1848. :param method: choice out of _("Seed"), 'normal', 'lines'
  1849. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1850. Usage of the different one is related to when this function is called
  1851. from a TcL command.
  1852. :return: None
  1853. """
  1854. if obj.kind == 'gerber':
  1855. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1856. if self.app.defaults["gerber_buffering"] == 'no':
  1857. msg = '%s %s %s' % (_("Paint Tool."),
  1858. _("Normal painting polygon task started."),
  1859. _("Buffering geometry..."))
  1860. self.app.inform.emit(msg)
  1861. else:
  1862. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1863. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1864. if isinstance(obj.solid_geometry, list):
  1865. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1866. else:
  1867. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1868. else:
  1869. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1870. if inside_pt and poly_list is None:
  1871. polygon_list = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  1872. if polygon_list:
  1873. polygon_list = [polygon_list]
  1874. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1875. polygon_list = poly_list
  1876. else:
  1877. return
  1878. # No polygon?
  1879. if polygon_list is None:
  1880. self.app.log.warning('No polygon found.')
  1881. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1882. return "fail"
  1883. self.paint_geo(obj, polygon_list, tooldia=tooldia, order=order, method=method, outname=outname,
  1884. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  1885. def paint_poly_all(self, obj, tooldia=None, order=None, method=None, outname=None, tools_storage=None, plot=True,
  1886. run_threaded=True):
  1887. """
  1888. Paints all polygons in this object.
  1889. :param obj: painted object
  1890. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1891. :param order: if the tools are ordered and how
  1892. :param outname: name of the resulting object
  1893. :param method: choice out of _("Seed"), 'normal', 'lines'
  1894. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1895. Usage of the different one is related to when this function is called from
  1896. a TcL command.
  1897. :param run_threaded:
  1898. :param plot:
  1899. :return:
  1900. """
  1901. # This is a recursive generator of individual Polygons.
  1902. # Note: Double check correct implementation. Might exit
  1903. # early if it finds something that is not a Polygon?
  1904. # def recurse(geo):
  1905. # try:
  1906. # for subg in geo:
  1907. # for subsubg in recurse(subg):
  1908. # yield subsubg
  1909. # except TypeError:
  1910. # if isinstance(geo, Polygon):
  1911. # yield geo
  1912. #
  1913. # raise StopIteration
  1914. def recurse(geometry, reset=True):
  1915. """
  1916. Creates a list of non-iterable linear geometry objects.
  1917. Results are placed in self.flat_geometry
  1918. :param geometry: Shapely type or list or list of list of such.
  1919. :param reset: Clears the contents of self.flat_geometry.
  1920. """
  1921. if self.app.abort_flag:
  1922. # graceful abort requested by the user
  1923. raise grace
  1924. if geometry is None:
  1925. return
  1926. if reset:
  1927. self.flat_geometry = []
  1928. # ## If iterable, expand recursively.
  1929. try:
  1930. for geo in geometry:
  1931. if geo and not geo.is_empty and geo.is_valid:
  1932. recurse(geometry=geo, reset=False)
  1933. # ## Not iterable, do the actual indexing and add.
  1934. except TypeError:
  1935. if isinstance(geometry, LinearRing):
  1936. g = Polygon(geometry)
  1937. self.flat_geometry.append(g)
  1938. else:
  1939. self.flat_geometry.append(geometry)
  1940. return self.flat_geometry
  1941. if obj.kind == 'gerber':
  1942. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1943. if self.app.defaults["gerber_buffering"] == 'no':
  1944. msg = '%s %s %s' % (_("Paint Tool."), _("Paint all polygons task started."), _("Buffering geometry..."))
  1945. self.app.inform.emit(msg)
  1946. else:
  1947. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1948. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1949. if isinstance(obj.solid_geometry, list):
  1950. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1951. else:
  1952. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1953. else:
  1954. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1955. painted_area = recurse(obj.solid_geometry)
  1956. # No polygon?
  1957. if not painted_area:
  1958. self.app.log.warning('No polygon found.')
  1959. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1960. return
  1961. self.paint_geo(obj, painted_area, tooldia=tooldia, order=order, method=method, outname=outname,
  1962. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  1963. def paint_poly_area(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  1964. tools_storage=None, plot=True, run_threaded=True):
  1965. """
  1966. Paints all polygons in this object that are within the sel_obj object
  1967. :param obj: painted object
  1968. :param sel_obj: paint only what is inside this object bounds
  1969. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1970. :param order: if the tools are ordered and how
  1971. :param outname: name of the resulting object
  1972. :param method: choice out of _("Seed"), 'normal', 'lines'
  1973. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1974. Usage of the different one is related to when this function is called from a TcL command.
  1975. :param run_threaded:
  1976. :param plot:
  1977. :return:
  1978. """
  1979. def recurse(geometry, reset=True):
  1980. """
  1981. Creates a list of non-iterable linear geometry objects.
  1982. Results are placed in self.flat_geometry
  1983. :param geometry: Shapely type or list or list of list of such.
  1984. :param reset: Clears the contents of self.flat_geometry.
  1985. """
  1986. if self.app.abort_flag:
  1987. # graceful abort requested by the user
  1988. raise grace
  1989. if geometry is None:
  1990. return
  1991. if reset:
  1992. self.flat_geometry = []
  1993. # ## If iterable, expand recursively.
  1994. try:
  1995. for geo in geometry:
  1996. if geo is not None:
  1997. recurse(geometry=geo, reset=False)
  1998. # ## Not iterable, do the actual indexing and add.
  1999. except TypeError:
  2000. if isinstance(geometry, LinearRing):
  2001. g = Polygon(geometry)
  2002. self.flat_geometry.append(g)
  2003. else:
  2004. self.flat_geometry.append(geometry)
  2005. return self.flat_geometry
  2006. # this is were heavy lifting is done and creating the geometry to be painted
  2007. target_geo = MultiPolygon(obj.solid_geometry)
  2008. if obj.kind == 'gerber':
  2009. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  2010. if self.app.defaults["gerber_buffering"] == 'no':
  2011. msg = '%s %s %s' % (_("Paint Tool."),
  2012. _("Painting area task started."),
  2013. _("Buffering geometry..."))
  2014. self.app.inform.emit(msg)
  2015. else:
  2016. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2017. if obj.kind == 'gerber':
  2018. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2019. target_geo = target_geo.buffer(0)
  2020. else:
  2021. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2022. geo_to_paint = target_geo.intersection(sel_obj)
  2023. painted_area = recurse(geo_to_paint)
  2024. # No polygon?
  2025. if not painted_area:
  2026. self.app.log.warning('No polygon found.')
  2027. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  2028. return
  2029. self.paint_geo(obj, painted_area, tooldia=tooldia, order=order, method=method, outname=outname,
  2030. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  2031. def paint_poly_ref(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2032. tools_storage=None, plot=True, run_threaded=True):
  2033. """
  2034. Paints all polygons in this object that are within the sel_obj object
  2035. :param obj: painted object
  2036. :param sel_obj: paint only what is inside this object bounds
  2037. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2038. :param order: if the tools are ordered and how
  2039. :param outname: name of the resulting object
  2040. :param method: choice out of _("Seed"), 'normal', 'lines'
  2041. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2042. Usage of the different one is related to when this function is called from a TcL command.
  2043. :param run_threaded:
  2044. :param plot:
  2045. :return:
  2046. """
  2047. geo = sel_obj.solid_geometry
  2048. try:
  2049. if isinstance(geo, MultiPolygon):
  2050. env_obj = geo.convex_hull
  2051. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2052. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2053. env_obj = unary_union(self.bound_obj.solid_geometry)
  2054. else:
  2055. env_obj = unary_union(self.bound_obj.solid_geometry)
  2056. env_obj = env_obj.convex_hull
  2057. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2058. except Exception as e:
  2059. log.debug("ToolPaint.paint_poly_ref() --> %s" % str(e))
  2060. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2061. return
  2062. self.paint_poly_area(obj=obj,
  2063. sel_obj=sel_rect,
  2064. tooldia=tooldia,
  2065. order=order,
  2066. method=method,
  2067. outname=outname,
  2068. tools_storage=tools_storage,
  2069. plot=plot,
  2070. run_threaded=run_threaded)
  2071. def ui_connect(self):
  2072. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  2073. # rows selected
  2074. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2075. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  2076. # Table widgets
  2077. for row in range(self.ui.tools_table.rowCount()):
  2078. try:
  2079. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2080. except AttributeError:
  2081. pass
  2082. try:
  2083. self.ui.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2084. except AttributeError:
  2085. pass
  2086. # Parameters FORM UI
  2087. # first disconnect
  2088. for opt in self.form_fields:
  2089. current_widget = self.form_fields[opt]
  2090. if isinstance(current_widget, FCCheckBox):
  2091. try:
  2092. current_widget.stateChanged.disconnect()
  2093. except (TypeError, ValueError):
  2094. pass
  2095. if isinstance(current_widget, RadioSet):
  2096. try:
  2097. current_widget.activated_custom.disconnect()
  2098. except (TypeError, ValueError):
  2099. pass
  2100. elif isinstance(current_widget, FCDoubleSpinner):
  2101. try:
  2102. current_widget.returnPressed.disconnect()
  2103. except (TypeError, ValueError):
  2104. pass
  2105. # then reconnect
  2106. for opt in self.form_fields:
  2107. current_widget = self.form_fields[opt]
  2108. if isinstance(current_widget, FCCheckBox):
  2109. current_widget.stateChanged.connect(self.form_to_storage)
  2110. if isinstance(current_widget, RadioSet):
  2111. current_widget.activated_custom.connect(self.form_to_storage)
  2112. elif isinstance(current_widget, FCDoubleSpinner):
  2113. current_widget.returnPressed.connect(self.form_to_storage)
  2114. elif isinstance(current_widget, FCComboBox):
  2115. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2116. self.ui.rest_cb.stateChanged.connect(self.ui.on_rest_machining_check)
  2117. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  2118. def ui_disconnect(self):
  2119. try:
  2120. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2121. self.ui.tools_table.itemChanged.disconnect()
  2122. except (TypeError, AttributeError):
  2123. pass
  2124. # rows selected
  2125. try:
  2126. self.ui.tools_table.clicked.disconnect()
  2127. except (TypeError, AttributeError):
  2128. pass
  2129. try:
  2130. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2131. except (TypeError, AttributeError):
  2132. pass
  2133. # Table widgets
  2134. for row in range(self.ui.tools_table.rowCount()):
  2135. for col in [2, 4]:
  2136. try:
  2137. self.ui.tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2138. except (TypeError, AttributeError):
  2139. pass
  2140. # Parameters FORM UI
  2141. for opt in self.form_fields:
  2142. current_widget = self.form_fields[opt]
  2143. if isinstance(current_widget, FCCheckBox):
  2144. try:
  2145. current_widget.stateChanged.disconnect(self.form_to_storage)
  2146. except (TypeError, ValueError):
  2147. pass
  2148. if isinstance(current_widget, RadioSet):
  2149. try:
  2150. current_widget.activated_custom.disconnect(self.form_to_storage)
  2151. except (TypeError, ValueError):
  2152. pass
  2153. elif isinstance(current_widget, FCDoubleSpinner):
  2154. try:
  2155. current_widget.returnPressed.disconnect(self.form_to_storage)
  2156. except (TypeError, ValueError):
  2157. pass
  2158. elif isinstance(current_widget, FCComboBox):
  2159. try:
  2160. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2161. except (TypeError, ValueError):
  2162. pass
  2163. try:
  2164. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2165. self.ui.rest_cb.stateChanged.disconnect()
  2166. except (TypeError, AttributeError):
  2167. pass
  2168. try:
  2169. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2170. self.ui.order_radio.activated_custom[str].disconnect()
  2171. except (TypeError, AttributeError):
  2172. pass
  2173. @staticmethod
  2174. def paint_bounds(geometry):
  2175. def bounds_rec(o):
  2176. if type(o) is list:
  2177. minx = Inf
  2178. miny = Inf
  2179. maxx = -Inf
  2180. maxy = -Inf
  2181. for k in o:
  2182. try:
  2183. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2184. except Exception as e:
  2185. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2186. return
  2187. minx = min(minx, minx_)
  2188. miny = min(miny, miny_)
  2189. maxx = max(maxx, maxx_)
  2190. maxy = max(maxy, maxy_)
  2191. return minx, miny, maxx, maxy
  2192. else:
  2193. # it's a Shapely object, return it's bounds
  2194. return o.bounds
  2195. return bounds_rec(geometry)
  2196. def on_paint_tool_add_from_db_executed(self, tool):
  2197. """
  2198. Here add the tool from DB in the selected geometry object
  2199. :return:
  2200. """
  2201. tool_from_db = deepcopy(tool)
  2202. if tool['data']['tool_target'] != _("Paint"):
  2203. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  2204. return
  2205. res = self.on_paint_tool_from_db_inserted(tool=tool_from_db)
  2206. for idx in range(self.app.ui.plot_tab_area.count()):
  2207. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2208. wdg = self.app.ui.plot_tab_area.widget(idx)
  2209. wdg.deleteLater()
  2210. self.app.ui.plot_tab_area.removeTab(idx)
  2211. if res == 'fail':
  2212. return
  2213. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2214. # select last tool added
  2215. toolid = res
  2216. for row in range(self.ui.tools_table.rowCount()):
  2217. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2218. self.ui.tools_table.selectRow(row)
  2219. self.on_row_selection_change()
  2220. def on_paint_tool_from_db_inserted(self, tool):
  2221. """
  2222. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2223. :param tool: a dict with the tool data
  2224. :return: None
  2225. """
  2226. self.ui_disconnect()
  2227. self.units = self.app.defaults['units'].upper()
  2228. tooldia = float(tool['tooldia'])
  2229. # construct a list of all 'tooluid' in the self.tools
  2230. tool_uid_list = []
  2231. for tooluid_key in self.paint_tools:
  2232. tool_uid_item = int(tooluid_key)
  2233. tool_uid_list.append(tool_uid_item)
  2234. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2235. if not tool_uid_list:
  2236. max_uid = 0
  2237. else:
  2238. max_uid = max(tool_uid_list)
  2239. tooluid = max_uid + 1
  2240. tooldia = self.app.dec_format(tooldia, self.decimals)
  2241. tool_dias = []
  2242. for k, v in self.paint_tools.items():
  2243. for tool_v in v.keys():
  2244. if tool_v == 'tooldia':
  2245. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2246. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2247. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2248. self.ui_connect()
  2249. return 'fail'
  2250. self.paint_tools.update({
  2251. tooluid: {
  2252. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2253. 'offset': tool['offset'],
  2254. 'offset_value': tool['offset_value'],
  2255. 'type': tool['type'],
  2256. 'tool_type': tool['tool_type'],
  2257. 'data': deepcopy(tool['data']),
  2258. 'solid_geometry': []
  2259. }
  2260. })
  2261. self.paint_tools[tooluid]['data']['name'] = '_paint'
  2262. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2263. self.ui_connect()
  2264. self.build_ui()
  2265. # select the tool just added
  2266. for row in range(self.ui.tools_table.rowCount()):
  2267. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  2268. self.ui.tools_table.selectRow(row)
  2269. break
  2270. return tooluid
  2271. def on_paint_tool_add_from_db_clicked(self):
  2272. """
  2273. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2274. and display the Tools Database tab in the form needed for the Tool adding
  2275. :return: None
  2276. """
  2277. # if the Tools Database is already opened focus on it
  2278. for idx in range(self.app.ui.plot_tab_area.count()):
  2279. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2280. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2281. break
  2282. self.app.on_tools_database(source='paint')
  2283. self.app.tools_db_tab.ok_to_add = True
  2284. self.app.tools_db_tab.ui.buttons_frame.hide()
  2285. self.app.tools_db_tab.ui.add_tool_from_db.show()
  2286. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  2287. def reset_fields(self):
  2288. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2289. class PaintUI:
  2290. toolName = _("Paint Tool")
  2291. def __init__(self, layout, app):
  2292. self.app = app
  2293. self.decimals = self.app.decimals
  2294. self.layout = layout
  2295. # ## Title
  2296. title_label = FCLabel("%s" % self.toolName)
  2297. title_label.setStyleSheet("""
  2298. QLabel
  2299. {
  2300. font-size: 16px;
  2301. font-weight: bold;
  2302. }
  2303. """)
  2304. self.layout.addWidget(title_label)
  2305. self.tools_frame = QtWidgets.QFrame()
  2306. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2307. self.layout.addWidget(self.tools_frame)
  2308. self.tools_box = QtWidgets.QVBoxLayout()
  2309. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2310. self.tools_frame.setLayout(self.tools_box)
  2311. # ## Form Layout
  2312. grid0 = QtWidgets.QGridLayout()
  2313. grid0.setColumnStretch(0, 0)
  2314. grid0.setColumnStretch(1, 1)
  2315. self.tools_box.addLayout(grid0)
  2316. # ################################################
  2317. # ##### Type of object to be painted #############
  2318. # ################################################
  2319. self.type_obj_combo_label = FCLabel('%s:' % _("Obj Type"))
  2320. self.type_obj_combo_label.setToolTip(
  2321. _("Specify the type of object to be painted.\n"
  2322. "It can be of type: Gerber or Geometry.\n"
  2323. "What is selected here will dictate the kind\n"
  2324. "of objects that will populate the 'Object' combobox.")
  2325. )
  2326. self.type_obj_combo_label.setMinimumWidth(60)
  2327. self.type_obj_radio = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  2328. {'label': "Gerber", 'value': 'gerber'}])
  2329. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  2330. grid0.addWidget(self.type_obj_radio, 1, 1)
  2331. # ################################################
  2332. # ##### The object to be painted #################
  2333. # ################################################
  2334. self.obj_combo = FCComboBox()
  2335. self.obj_combo.setModel(self.app.collection)
  2336. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2337. self.obj_combo.is_last = True
  2338. self.object_label = FCLabel('%s:' % _("Object"))
  2339. self.object_label.setToolTip(_("Object to be painted."))
  2340. grid0.addWidget(self.object_label, 2, 0)
  2341. grid0.addWidget(self.obj_combo, 2, 1)
  2342. separator_line = QtWidgets.QFrame()
  2343. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2344. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2345. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2346. # ### Tools ## ##
  2347. self.tools_table_label = FCLabel('<b>%s</b>' % _('Tools Table'))
  2348. self.tools_table_label.setToolTip(
  2349. _("Tools pool from which the algorithm\n"
  2350. "will pick the ones used for painting.")
  2351. )
  2352. self.tools_table = FCTable(drag_drop=True)
  2353. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2354. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  2355. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  2356. self.tools_table.setColumnCount(4)
  2357. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2358. self.tools_table.setColumnHidden(3, True)
  2359. # self.tools_table.setSortingEnabled(False)
  2360. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2361. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2362. _("This is the Tool Number.\n"
  2363. "Painting will start with the tool with the biggest diameter,\n"
  2364. "continuing until there are no more tools.\n"
  2365. "Only tools that create painting geometry will still be present\n"
  2366. "in the resulting geometry. This is because with some tools\n"
  2367. "this function will not be able to create painting geometry.")
  2368. )
  2369. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2370. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2371. "is the cut width into the material."))
  2372. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2373. _("The Tool Type (TT) can be:\n"
  2374. "- Circular -> it is informative only. Being circular,\n"
  2375. "the cut width in material is exactly the tool diameter.\n"
  2376. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2377. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2378. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2379. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2380. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2381. "column of this table.\n"
  2382. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2383. "in the resulting geometry as Isolation."))
  2384. self.order_label = FCLabel('<b>%s:</b>' % _('Tool order'))
  2385. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2386. "'No' --> means that the used order is the one in the tool table\n"
  2387. "'Forward' --> means that the tools will be ordered from small to big\n"
  2388. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2389. "WARNING: using rest machining will automatically set the order\n"
  2390. "in reverse and disable this control."))
  2391. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2392. {'label': _('Forward'), 'value': 'fwd'},
  2393. {'label': _('Reverse'), 'value': 'rev'}])
  2394. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2395. "'No' --> means that the used order is the one in the tool table\n"
  2396. "'Forward' --> means that the tools will be ordered from small to big\n"
  2397. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2398. "WARNING: using rest machining will automatically set the order\n"
  2399. "in reverse and disable this control."))
  2400. grid0.addWidget(self.order_label, 9, 0)
  2401. grid0.addWidget(self.order_radio, 9, 1)
  2402. separator_line = QtWidgets.QFrame()
  2403. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2404. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2405. grid0.addWidget(separator_line, 10, 0, 1, 2)
  2406. # ##############################################################################
  2407. # ###################### ADD A NEW TOOL ########################################
  2408. # ##############################################################################
  2409. self.grid3 = QtWidgets.QGridLayout()
  2410. self.grid3.setColumnStretch(0, 0)
  2411. self.grid3.setColumnStretch(1, 1)
  2412. self.tools_box.addLayout(self.grid3)
  2413. self.tool_sel_label = FCLabel('<b>%s</b>' % _('Add from DB'))
  2414. self.grid3.addWidget(self.tool_sel_label, 0, 0, 1, 2)
  2415. # ### Tool Diameter ####
  2416. self.new_tooldia_lbl = FCLabel('%s:' % _('Tool Dia'))
  2417. self.new_tooldia_lbl.setToolTip(
  2418. _("Diameter for the new tool to add in the Tool Table.\n"
  2419. "If the tool is V-shape type then this value is automatically\n"
  2420. "calculated from the other parameters.")
  2421. )
  2422. self.new_tooldia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2423. self.new_tooldia_entry.set_precision(self.decimals)
  2424. self.new_tooldia_entry.set_range(0.000, 9999.9999)
  2425. self.new_tooldia_entry.setObjectName('p_tool_dia')
  2426. self.grid3.addWidget(self.new_tooldia_lbl, 2, 0)
  2427. self.grid3.addWidget(self.new_tooldia_entry, 2, 1)
  2428. hlay = QtWidgets.QHBoxLayout()
  2429. self.add_newtool_button = FCButton(_('Search and Add'))
  2430. self.add_newtool_button.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  2431. self.add_newtool_button.setToolTip(
  2432. _("Add a new tool to the Tool Table\n"
  2433. "with the diameter specified above.\n"
  2434. "This is done by a background search\n"
  2435. "in the Tools Database. If nothing is found\n"
  2436. "in the Tools DB then a default tool is added.")
  2437. )
  2438. hlay.addWidget(self.add_newtool_button)
  2439. self.addtool_from_db_btn = FCButton(_('Pick from DB'))
  2440. self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
  2441. self.addtool_from_db_btn.setToolTip(
  2442. _("Add a new tool to the Tool Table\n"
  2443. "from the Tools Database.\n"
  2444. "Tools database administration in in:\n"
  2445. "Menu: Options -> Tools Database")
  2446. )
  2447. hlay.addWidget(self.addtool_from_db_btn)
  2448. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  2449. separator_line = QtWidgets.QFrame()
  2450. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2451. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2452. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2453. self.deltool_btn = FCButton(_('Delete'))
  2454. self.deltool_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/trash16.png'))
  2455. self.deltool_btn.setToolTip(
  2456. _("Delete a selection of tools in the Tool Table\n"
  2457. "by first selecting a row(s) in the Tool Table.")
  2458. )
  2459. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2460. separator_line = QtWidgets.QFrame()
  2461. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2462. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2463. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2464. self.tool_data_label = FCLabel(
  2465. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2466. self.tool_data_label.setToolTip(
  2467. _(
  2468. "The data used for creating GCode.\n"
  2469. "Each tool store it's own set of such data."
  2470. )
  2471. )
  2472. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2473. grid4 = QtWidgets.QGridLayout()
  2474. grid4.setColumnStretch(0, 0)
  2475. grid4.setColumnStretch(1, 1)
  2476. self.tools_box.addLayout(grid4)
  2477. # Overlap
  2478. ovlabel = FCLabel('%s:' % _('Overlap'))
  2479. ovlabel.setToolTip(
  2480. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  2481. "Adjust the value starting with lower values\n"
  2482. "and increasing it if areas that should be painted are still \n"
  2483. "not painted.\n"
  2484. "Lower values = faster processing, faster execution on CNC.\n"
  2485. "Higher values = slow processing and slow execution on CNC\n"
  2486. "due of too many paths.")
  2487. )
  2488. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  2489. self.paintoverlap_entry.set_precision(3)
  2490. self.paintoverlap_entry.setWrapping(True)
  2491. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  2492. self.paintoverlap_entry.setSingleStep(0.1)
  2493. self.paintoverlap_entry.setObjectName('p_overlap')
  2494. grid4.addWidget(ovlabel, 1, 0)
  2495. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  2496. # Offset
  2497. self.offset_label = FCLabel('%s:' % _('Offset'))
  2498. self.offset_label.setToolTip(
  2499. _("Distance by which to avoid\n"
  2500. "the edges of the polygon to\n"
  2501. "be painted.")
  2502. )
  2503. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2504. self.offset_entry.set_precision(self.decimals)
  2505. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2506. self.offset_entry.setObjectName('p_offset')
  2507. grid4.addWidget(self.offset_label, 2, 0)
  2508. grid4.addWidget(self.offset_entry, 2, 1)
  2509. # Method
  2510. methodlabel = FCLabel('%s:' % _('Method'))
  2511. methodlabel.setToolTip(
  2512. _("Algorithm for painting:\n"
  2513. "- Standard: Fixed step inwards.\n"
  2514. "- Seed-based: Outwards from seed.\n"
  2515. "- Line-based: Parallel lines.\n"
  2516. "- Laser-lines: Active only for Gerber objects.\n"
  2517. "Will create lines that follow the traces.\n"
  2518. "- Combo: In case of failure a new method will be picked from the above\n"
  2519. "in the order specified.")
  2520. )
  2521. self.paintmethod_combo = FCComboBox2()
  2522. self.paintmethod_combo.addItems(
  2523. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  2524. )
  2525. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  2526. self.paintmethod_combo.model().item(idx).setEnabled(False)
  2527. self.paintmethod_combo.setObjectName('p_method')
  2528. grid4.addWidget(methodlabel, 7, 0)
  2529. grid4.addWidget(self.paintmethod_combo, 7, 1)
  2530. # Connect lines
  2531. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  2532. self.pathconnect_cb.setObjectName('p_connect')
  2533. self.pathconnect_cb.setToolTip(
  2534. _("Draw lines between resulting\n"
  2535. "segments to minimize tool lifts.")
  2536. )
  2537. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  2538. self.paintcontour_cb.setObjectName('p_contour')
  2539. self.paintcontour_cb.setToolTip(
  2540. _("Cut around the perimeter of the polygon\n"
  2541. "to trim rough edges.")
  2542. )
  2543. grid4.addWidget(self.pathconnect_cb, 10, 0)
  2544. grid4.addWidget(self.paintcontour_cb, 10, 1)
  2545. separator_line = QtWidgets.QFrame()
  2546. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2547. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2548. grid4.addWidget(separator_line, 11, 0, 1, 2)
  2549. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2550. self.apply_param_to_all.setIcon(QtGui.QIcon(self.app.resource_location + '/param_all32.png'))
  2551. self.apply_param_to_all.setToolTip(
  2552. _("The parameters in the current form will be applied\n"
  2553. "on all the tools from the Tool Table.")
  2554. )
  2555. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  2556. separator_line = QtWidgets.QFrame()
  2557. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2558. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2559. grid4.addWidget(separator_line, 13, 0, 1, 2)
  2560. # General Parameters
  2561. self.gen_param_label = FCLabel('<b>%s</b>' % _("Common Parameters"))
  2562. self.gen_param_label.setToolTip(
  2563. _("Parameters that are common for all tools.")
  2564. )
  2565. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  2566. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  2567. self.rest_cb.setObjectName('p_rest_machining')
  2568. self.rest_cb.setToolTip(
  2569. _("If checked, use 'rest machining'.\n"
  2570. "Basically it will clear copper outside PCB features,\n"
  2571. "using the biggest tool and continue with the next tools,\n"
  2572. "from bigger to smaller, to clear areas of copper that\n"
  2573. "could not be cleared by previous tool, until there is\n"
  2574. "no more copper to clear or there are no more tools.\n\n"
  2575. "If not checked, use the standard algorithm.")
  2576. )
  2577. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  2578. # Rest Offset
  2579. self.rest_offset_label = FCLabel('%s:' % _('Offset'))
  2580. self.rest_offset_label.setToolTip(
  2581. _("Distance by which to avoid\n"
  2582. "the edges of the polygon to\n"
  2583. "be painted.")
  2584. )
  2585. self.rest_offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2586. self.rest_offset_entry.set_precision(self.decimals)
  2587. self.rest_offset_entry.set_range(-9999.9999, 9999.9999)
  2588. grid4.addWidget(self.rest_offset_label, 17, 0)
  2589. grid4.addWidget(self.rest_offset_entry, 17, 1)
  2590. # Polygon selection
  2591. selectlabel = FCLabel('%s:' % _('Selection'))
  2592. selectlabel.setToolTip(
  2593. _("Selection of area to be processed.\n"
  2594. "- 'Polygon Selection' - left mouse click to add/remove polygons to be processed.\n"
  2595. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  2596. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  2597. "- 'All Polygons' - the process will start after click.\n"
  2598. "- 'Reference Object' - will process the area specified by another object.")
  2599. )
  2600. self.selectmethod_combo = FCComboBox2()
  2601. self.selectmethod_combo.addItems(
  2602. [_("All"), _("Polygon Selection"), _("Area Selection"), _("Reference Object")]
  2603. )
  2604. self.selectmethod_combo.setObjectName('p_selection')
  2605. grid4.addWidget(selectlabel, 18, 0)
  2606. grid4.addWidget(self.selectmethod_combo, 18, 1)
  2607. form1 = QtWidgets.QFormLayout()
  2608. grid4.addLayout(form1, 20, 0, 1, 2)
  2609. self.reference_type_label = FCLabel('%s:' % _("Ref. Type"))
  2610. self.reference_type_label.setToolTip(
  2611. _("The type of FlatCAM object to be used as paint reference.\n"
  2612. "It can be Gerber, Excellon or Geometry.")
  2613. )
  2614. self.reference_type_combo = FCComboBox2()
  2615. self.reference_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  2616. form1.addRow(self.reference_type_label, self.reference_type_combo)
  2617. self.reference_combo_label = FCLabel('%s:' % _("Ref. Object"))
  2618. self.reference_combo_label.setToolTip(
  2619. _("The FlatCAM object to be used as non copper clearing reference.")
  2620. )
  2621. self.reference_combo = FCComboBox()
  2622. self.reference_combo.setModel(self.app.collection)
  2623. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2624. self.reference_combo.is_last = True
  2625. form1.addRow(self.reference_combo_label, self.reference_combo)
  2626. self.reference_combo.hide()
  2627. self.reference_combo_label.hide()
  2628. self.reference_type_combo.hide()
  2629. self.reference_type_label.hide()
  2630. # Area Selection shape
  2631. self.area_shape_label = FCLabel('%s:' % _("Shape"))
  2632. self.area_shape_label.setToolTip(
  2633. _("The kind of selection shape used for area selection.")
  2634. )
  2635. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2636. {'label': _("Polygon"), 'value': 'polygon'}])
  2637. grid4.addWidget(self.area_shape_label, 21, 0)
  2638. grid4.addWidget(self.area_shape_radio, 21, 1)
  2639. self.area_shape_label.hide()
  2640. self.area_shape_radio.hide()
  2641. # GO Button
  2642. self.generate_paint_button = FCButton(_('Generate Geometry'))
  2643. self.generate_paint_button.setIcon(QtGui.QIcon(self.app.resource_location + '/geometry32.png'))
  2644. self.generate_paint_button.setToolTip(
  2645. _("Create a Geometry Object which paints the polygons.")
  2646. )
  2647. self.generate_paint_button.setStyleSheet("""
  2648. QPushButton
  2649. {
  2650. font-weight: bold;
  2651. }
  2652. """)
  2653. self.tools_box.addWidget(self.generate_paint_button)
  2654. self.tools_box.addStretch()
  2655. # ## Reset Tool
  2656. self.reset_button = FCButton(_("Reset Tool"))
  2657. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  2658. self.reset_button.setToolTip(
  2659. _("Will reset the tool parameters.")
  2660. )
  2661. self.reset_button.setStyleSheet("""
  2662. QPushButton
  2663. {
  2664. font-weight: bold;
  2665. }
  2666. """)
  2667. self.tools_box.addWidget(self.reset_button)
  2668. # #################################### FINSIHED GUI ###########################
  2669. # #############################################################################
  2670. def on_rest_machining_check(self, state):
  2671. if state:
  2672. self.order_radio.set_value('rev')
  2673. self.order_label.setDisabled(True)
  2674. self.order_radio.setDisabled(True)
  2675. self.offset_label.hide()
  2676. self.offset_entry.hide()
  2677. self.rest_offset_label.show()
  2678. self.rest_offset_entry.show()
  2679. else:
  2680. self.order_label.setDisabled(False)
  2681. self.order_radio.setDisabled(False)
  2682. self.offset_label.show()
  2683. self.offset_entry.show()
  2684. self.rest_offset_label.hide()
  2685. self.rest_offset_entry.hide()
  2686. def on_selection(self):
  2687. sel_combo = self.selectmethod_combo.get_value()
  2688. if sel_combo == 3: # _("Reference Object")
  2689. self.reference_combo.show()
  2690. self.reference_combo_label.show()
  2691. self.reference_type_combo.show()
  2692. self.reference_type_label.show()
  2693. else:
  2694. self.reference_combo.hide()
  2695. self.reference_combo_label.hide()
  2696. self.reference_type_combo.hide()
  2697. self.reference_type_label.hide()
  2698. if sel_combo == 1: # _("Polygon Selection")
  2699. # disable rest-machining for single polygon painting
  2700. # self.ui.rest_cb.set_value(False)
  2701. # self.ui.rest_cb.setDisabled(True)
  2702. pass
  2703. if sel_combo == 2: # _("Area Selection") index 2 in combobox (FCComboBox2() returns index instead of text)
  2704. # disable rest-machining for area painting
  2705. # self.ui.rest_cb.set_value(False)
  2706. # self.ui.rest_cb.setDisabled(True)
  2707. self.area_shape_label.show()
  2708. self.area_shape_radio.show()
  2709. else: # All = index 0 in combobox
  2710. self.new_tooldia_entry.setDisabled(False)
  2711. self.add_newtool_button.setDisabled(False)
  2712. self.deltool_btn.setDisabled(False)
  2713. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  2714. self.area_shape_label.hide()
  2715. self.area_shape_radio.hide()
  2716. def confirmation_message(self, accepted, minval, maxval):
  2717. if accepted is False:
  2718. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2719. self.decimals,
  2720. minval,
  2721. self.decimals,
  2722. maxval), False)
  2723. else:
  2724. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2725. def confirmation_message_int(self, accepted, minval, maxval):
  2726. if accepted is False:
  2727. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2728. (_("Edited value is out of range"), minval, maxval), False)
  2729. else:
  2730. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)