ToolPaint.py 144 KB

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