FlatCAMObj.py 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from io import StringIO
  9. from PyQt5 import QtCore, QtGui
  10. from PyQt5.QtCore import Qt
  11. from copy import copy, deepcopy
  12. import inspect # TODO: For debugging only.
  13. from shapely.geometry.base import JOIN_STYLE
  14. from datetime import datetime
  15. import FlatCAMApp
  16. from ObjectUI import *
  17. from FlatCAMCommon import LoudDict
  18. from FlatCAMEditor import FlatCAMGeoEditor
  19. from camlib import *
  20. from VisPyVisuals import ShapeCollectionVisual
  21. import itertools
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. class ObjectDeleted(Exception):
  24. pass
  25. class ValidationError(Exception):
  26. def __init__(self, message, errors):
  27. super().__init__(message)
  28. self.errors = errors
  29. ########################################
  30. ## FlatCAMObj ##
  31. ########################################
  32. class FlatCAMObj(QtCore.QObject):
  33. """
  34. Base type of objects handled in FlatCAM. These become interactive
  35. in the GUI, can be plotted, and their options can be modified
  36. by the user in their respective forms.
  37. """
  38. # Instance of the application to which these are related.
  39. # The app should set this value.
  40. app = None
  41. def __init__(self, name):
  42. """
  43. Constructor.
  44. :param name: Name of the object given by the user.
  45. :return: FlatCAMObj
  46. """
  47. QtCore.QObject.__init__(self)
  48. # View
  49. self.ui = None
  50. self.options = LoudDict(name=name)
  51. self.options.set_change_callback(self.on_options_change)
  52. self.form_fields = {}
  53. self.kind = None # Override with proper name
  54. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  55. self.shapes = self.app.plotcanvas.new_shape_group()
  56. self.item = None # Link with project view item
  57. self.muted_ui = False
  58. self.deleted = False
  59. self._drawing_tolerance = 0.01
  60. # assert isinstance(self.ui, ObjectUI)
  61. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  62. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  63. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  64. def __del__(self):
  65. pass
  66. def __str__(self):
  67. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  68. def from_dict(self, d):
  69. """
  70. This supersedes ``from_dict`` in derived classes. Derived classes
  71. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  72. ``self.options`` is only updated, not overwritten. This ensures that
  73. options set by the app do not vanish when reading the objects
  74. from a project file.
  75. :param d: Dictionary with attributes to set.
  76. :return: None
  77. """
  78. for attr in self.ser_attrs:
  79. if attr == 'options':
  80. self.options.update(d[attr])
  81. else:
  82. setattr(self, attr, d[attr])
  83. def on_options_change(self, key):
  84. # Update form on programmatically options change
  85. self.set_form_item(key)
  86. # Set object visibility
  87. if key == 'plot':
  88. self.visible = self.options['plot']
  89. # self.emit(QtCore.SIGNAL("optionChanged"), key)
  90. self.optionChanged.emit(key)
  91. def set_ui(self, ui):
  92. self.ui = ui
  93. self.form_fields = {"name": self.ui.name_entry}
  94. assert isinstance(self.ui, ObjectUI)
  95. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  96. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  97. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  98. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  99. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  100. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  101. def build_ui(self):
  102. """
  103. Sets up the UI/form for this object. Show the UI
  104. in the App.
  105. :return: None
  106. :rtype: None
  107. """
  108. self.muted_ui = True
  109. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  110. # Remove anything else in the box
  111. # box_children = self.app.ui.notebook.selected_contents.get_children()
  112. # for child in box_children:
  113. # self.app.ui.notebook.selected_contents.remove(child)
  114. # while self.app.ui.selected_layout.count():
  115. # self.app.ui.selected_layout.takeAt(0)
  116. # Put in the UI
  117. # box_selected.pack_start(sw, True, True, 0)
  118. # self.app.ui.notebook.selected_contents.add(self.ui)
  119. # self.app.ui.selected_layout.addWidget(self.ui)
  120. try:
  121. self.app.ui.selected_scroll_area.takeWidget()
  122. except:
  123. self.app.log.debug("Nothing to remove")
  124. self.app.ui.selected_scroll_area.setWidget(self.ui)
  125. self.muted_ui = False
  126. def on_name_activate(self):
  127. old_name = copy(self.options["name"])
  128. new_name = self.ui.name_entry.get_value()
  129. # update the SHELL auto-completer model data
  130. try:
  131. self.app.myKeywords.remove(old_name)
  132. self.app.myKeywords.append(new_name)
  133. self.app.shell._edit.set_model_data(self.app.myKeywords)
  134. except:
  135. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  136. self.options["name"] = self.ui.name_entry.get_value()
  137. self.app.inform.emit("[success]Name changed from %s to %s" % (old_name, new_name))
  138. def on_offset_button_click(self):
  139. self.app.report_usage("obj_on_offset_button")
  140. self.read_form()
  141. vect = self.ui.offsetvector_entry.get_value()
  142. self.offset(vect)
  143. self.plot()
  144. self.app.object_changed.emit(self)
  145. def on_scale_button_click(self):
  146. self.app.report_usage("obj_on_scale_button")
  147. self.read_form()
  148. factor = self.ui.scale_entry.get_value()
  149. self.scale(factor)
  150. self.plot()
  151. self.app.object_changed.emit(self)
  152. def on_skew_button_click(self):
  153. self.app.report_usage("obj_on_skew_button")
  154. self.read_form()
  155. xangle = self.ui.xangle_entry.get_value()
  156. yangle = self.ui.yangle_entry.get_value()
  157. self.skew(xangle, yangle)
  158. self.plot()
  159. self.app.object_changed.emit(self)
  160. def to_form(self):
  161. """
  162. Copies options to the UI form.
  163. :return: None
  164. """
  165. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  166. for option in self.options:
  167. try:
  168. self.set_form_item(option)
  169. except:
  170. self.app.log.warning("Unexpected error:", sys.exc_info())
  171. def read_form(self):
  172. """
  173. Reads form into ``self.options``.
  174. :return: None
  175. :rtype: None
  176. """
  177. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  178. for option in self.options:
  179. try:
  180. self.read_form_item(option)
  181. except:
  182. self.app.log.warning("Unexpected error:", sys.exc_info())
  183. def set_form_item(self, option):
  184. """
  185. Copies the specified option to the UI form.
  186. :param option: Name of the option (Key in ``self.options``).
  187. :type option: str
  188. :return: None
  189. """
  190. try:
  191. self.form_fields[option].set_value(self.options[option])
  192. except KeyError:
  193. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  194. pass
  195. def read_form_item(self, option):
  196. """
  197. Reads the specified option from the UI form into ``self.options``.
  198. :param option: Name of the option.
  199. :type option: str
  200. :return: None
  201. """
  202. try:
  203. self.options[option] = self.form_fields[option].get_value()
  204. except KeyError:
  205. self.app.log.warning("Failed to read option from field: %s" % option)
  206. def plot(self):
  207. """
  208. Plot this object (Extend this method to implement the actual plotting).
  209. Call this in descendants before doing the plotting.
  210. :return: Whether to continue plotting or not depending on the "plot" option.
  211. :rtype: bool
  212. """
  213. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  214. if self.deleted:
  215. return False
  216. self.clear()
  217. return True
  218. def serialize(self):
  219. """
  220. Returns a representation of the object as a dictionary so
  221. it can be later exported as JSON. Override this method.
  222. :return: Dictionary representing the object
  223. :rtype: dict
  224. """
  225. return
  226. def deserialize(self, obj_dict):
  227. """
  228. Re-builds an object from its serialized version.
  229. :param obj_dict: Dictionary representing a FlatCAMObj
  230. :type obj_dict: dict
  231. :return: None
  232. """
  233. return
  234. def add_shape(self, **kwargs):
  235. if self.deleted:
  236. raise ObjectDeleted()
  237. else:
  238. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  239. return key
  240. @property
  241. def visible(self):
  242. return self.shapes.visible
  243. @visible.setter
  244. def visible(self, value):
  245. self.shapes.visible = value
  246. # Not all object types has annotations
  247. try:
  248. self.annotation.visible = value
  249. except AttributeError:
  250. pass
  251. @property
  252. def drawing_tolerance(self):
  253. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  254. @drawing_tolerance.setter
  255. def drawing_tolerance(self, value):
  256. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  257. def clear(self, update=False):
  258. self.shapes.clear(update)
  259. # Not all object types has annotations
  260. try:
  261. self.annotation.clear(update)
  262. except AttributeError:
  263. pass
  264. def delete(self):
  265. # Free resources
  266. del self.ui
  267. del self.options
  268. # Set flag
  269. self.deleted = True
  270. class FlatCAMGerber(FlatCAMObj, Gerber):
  271. """
  272. Represents Gerber code.
  273. """
  274. optionChanged = QtCore.pyqtSignal(str)
  275. ui_type = GerberObjectUI
  276. @staticmethod
  277. def merge(grb_list, grb_final):
  278. """
  279. Merges the geometry of objects in geo_list into
  280. the geometry of geo_final.
  281. :param grb_list: List of FlatCAMGerber Objects to join.
  282. :param grb_final: Destination FlatCAMGeometry object.
  283. :return: None
  284. """
  285. if grb_final.solid_geometry is None:
  286. grb_final.solid_geometry = []
  287. if type(grb_final.solid_geometry) is not list:
  288. grb_final.solid_geometry = [grb_final.solid_geometry]
  289. for grb in grb_list:
  290. for option in grb.options:
  291. if option is not 'name':
  292. try:
  293. grb_final.options[option] = grb.options[option]
  294. except:
  295. log.warning("Failed to copy option.", option)
  296. # Expand lists
  297. if type(grb) is list:
  298. FlatCAMGerber.merge(grb, grb_final)
  299. # If not list, just append
  300. else:
  301. grb_final.solid_geometry.append(grb.solid_geometry)
  302. def __init__(self, name):
  303. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  304. FlatCAMObj.__init__(self, name)
  305. self.kind = "gerber"
  306. # The 'name' is already in self.options from FlatCAMObj
  307. # Automatically updates the UI
  308. self.options.update({
  309. "plot": True,
  310. "multicolored": False,
  311. "solid": False,
  312. "isotooldia": 0.016,
  313. "isopasses": 1,
  314. "isooverlap": 0.15,
  315. "milling_type": "cl",
  316. "combine_passes": True,
  317. "ncctools": "1.0, 0.5",
  318. "nccoverlap": 0.4,
  319. "nccmargin": 1,
  320. "noncoppermargin": 0.0,
  321. "noncopperrounded": False,
  322. "bboxmargin": 0.0,
  323. "bboxrounded": False
  324. })
  325. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  326. self.iso_type = 2
  327. # Attributes to be included in serialization
  328. # Always append to it because it carries contents
  329. # from predecessors.
  330. self.ser_attrs += ['options', 'kind']
  331. self.multigeo = False
  332. # assert isinstance(self.ui, GerberObjectUI)
  333. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  334. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  335. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  336. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  337. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  338. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  339. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  340. def set_ui(self, ui):
  341. """
  342. Maps options with GUI inputs.
  343. Connects GUI events to methods.
  344. :param ui: GUI object.
  345. :type ui: GerberObjectUI
  346. :return: None
  347. """
  348. FlatCAMObj.set_ui(self, ui)
  349. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  350. self.form_fields.update({
  351. "plot": self.ui.plot_cb,
  352. "multicolored": self.ui.multicolored_cb,
  353. "solid": self.ui.solid_cb,
  354. "isotooldia": self.ui.iso_tool_dia_entry,
  355. "isopasses": self.ui.iso_width_entry,
  356. "isooverlap": self.ui.iso_overlap_entry,
  357. "milling_type": self.ui.milling_type_radio,
  358. "combine_passes": self.ui.combine_passes_cb,
  359. "noncoppermargin": self.ui.noncopper_margin_entry,
  360. "noncopperrounded": self.ui.noncopper_rounded_cb,
  361. "bboxmargin": self.ui.bbmargin_entry,
  362. "bboxrounded": self.ui.bbrounded_cb
  363. })
  364. # Fill form fields only on object create
  365. self.to_form()
  366. assert isinstance(self.ui, GerberObjectUI)
  367. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  368. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  369. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  370. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  371. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  372. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  373. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  374. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  375. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  376. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  377. def on_generatenoncopper_button_click(self, *args):
  378. self.app.report_usage("gerber_on_generatenoncopper_button")
  379. self.read_form()
  380. name = self.options["name"] + "_noncopper"
  381. def geo_init(geo_obj, app_obj):
  382. assert isinstance(geo_obj, FlatCAMGeometry)
  383. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  384. if not self.options["noncopperrounded"]:
  385. bounding_box = bounding_box.envelope
  386. non_copper = bounding_box.difference(self.solid_geometry)
  387. geo_obj.solid_geometry = non_copper
  388. # TODO: Check for None
  389. self.app.new_object("geometry", name, geo_init)
  390. def on_generatebb_button_click(self, *args):
  391. self.app.report_usage("gerber_on_generatebb_button")
  392. self.read_form()
  393. name = self.options["name"] + "_bbox"
  394. def geo_init(geo_obj, app_obj):
  395. assert isinstance(geo_obj, FlatCAMGeometry)
  396. # Bounding box with rounded corners
  397. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  398. if not self.options["bboxrounded"]: # Remove rounded corners
  399. bounding_box = bounding_box.envelope
  400. geo_obj.solid_geometry = bounding_box
  401. self.app.new_object("geometry", name, geo_init)
  402. def on_ext_iso_button_click(self, *args):
  403. if self.ui.follow_cb.get_value() == True:
  404. obj = self.app.collection.get_active()
  405. obj.follow()
  406. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  407. obj.ui.plot_cb.toggle()
  408. else:
  409. self.app.report_usage("gerber_on_iso_button")
  410. self.read_form()
  411. self.isolate(iso_type=0)
  412. def on_int_iso_button_click(self, *args):
  413. if self.ui.follow_cb.get_value() == True:
  414. obj = self.app.collection.get_active()
  415. obj.follow()
  416. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  417. obj.ui.plot_cb.toggle()
  418. else:
  419. self.app.report_usage("gerber_on_iso_button")
  420. self.read_form()
  421. self.isolate(iso_type=1)
  422. def on_iso_button_click(self, *args):
  423. if self.ui.follow_cb.get_value() == True:
  424. obj = self.app.collection.get_active()
  425. obj.follow()
  426. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  427. obj.ui.plot_cb.toggle()
  428. else:
  429. self.app.report_usage("gerber_on_iso_button")
  430. self.read_form()
  431. self.isolate()
  432. def follow(self, outname=None):
  433. """
  434. Creates a geometry object "following" the gerber paths.
  435. :return: None
  436. """
  437. # default_name = self.options["name"] + "_follow"
  438. # follow_name = outname or default_name
  439. if outname is None:
  440. follow_name = self.options["name"] + "_follow"
  441. else:
  442. follow_name = outname
  443. def follow_init(follow_obj, app):
  444. # Propagate options
  445. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  446. follow_obj.solid_geometry = self.solid_geometry
  447. # TODO: Do something if this is None. Offer changing name?
  448. try:
  449. self.app.new_object("geometry", follow_name, follow_init)
  450. except Exception as e:
  451. return "Operation failed: %s" % str(e)
  452. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  453. outname=None, combine=None, milling_type=None):
  454. """
  455. Creates an isolation routing geometry object in the project.
  456. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  457. :param dia: Tool diameter
  458. :param passes: Number of tool widths to cut
  459. :param overlap: Overlap between passes in fraction of tool diameter
  460. :param outname: Base name of the output object
  461. :return: None
  462. """
  463. if dia is None:
  464. dia = self.options["isotooldia"]
  465. if passes is None:
  466. passes = int(self.options["isopasses"])
  467. if overlap is None:
  468. overlap = self.options["isooverlap"]
  469. if combine is None:
  470. combine = self.options["combine_passes"]
  471. else:
  472. combine = bool(combine)
  473. if milling_type is None:
  474. milling_type = self.options["milling_type"]
  475. if iso_type is None:
  476. self.iso_type = 2
  477. else:
  478. self.iso_type = iso_type
  479. base_name = self.options["name"] + "_iso"
  480. base_name = outname or base_name
  481. def generate_envelope(offset, invert, envelope_iso_type=2):
  482. # isolation_geometry produces an envelope that is going on the left of the geometry
  483. # (the copper features). To leave the least amount of burrs on the features
  484. # the tool needs to travel on the right side of the features (this is called conventional milling)
  485. # the first pass is the one cutting all of the features, so it needs to be reversed
  486. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  487. # to cut on the right side of the left over copper i.e on the left side of the features.
  488. try:
  489. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type)
  490. except Exception as e:
  491. log.debug(str(e))
  492. return 'fail'
  493. if invert:
  494. try:
  495. if type(geom) is MultiPolygon:
  496. pl = []
  497. for p in geom:
  498. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  499. geom = MultiPolygon(pl)
  500. elif type(geom) is Polygon:
  501. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  502. else:
  503. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  504. except Exception as e:
  505. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  506. return geom
  507. if combine:
  508. if self.iso_type == 0:
  509. iso_name = self.options["name"] + "_ext_iso"
  510. elif self.iso_type == 1:
  511. iso_name = self.options["name"] + "_int_iso"
  512. else:
  513. iso_name = base_name
  514. # TODO: This is ugly. Create way to pass data into init function.
  515. def iso_init(geo_obj, app_obj):
  516. # Propagate options
  517. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  518. geo_obj.solid_geometry = []
  519. for i in range(passes):
  520. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  521. # if milling type is climb then the move is counter-clockwise around features
  522. if milling_type == 'cl':
  523. # geom = generate_envelope (offset, i == 0)
  524. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type)
  525. else:
  526. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type)
  527. geo_obj.solid_geometry.append(geom)
  528. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  529. # or just looking in the lists (they are one level depth) and if any is not empty
  530. # proceed with object creation, if there are empty and the number of them is the length
  531. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  532. empty_cnt = 0
  533. if not isinstance(geo_obj.solid_geometry, list):
  534. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  535. for g in geo_obj.solid_geometry:
  536. if g:
  537. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  538. break
  539. else:
  540. empty_cnt += 1
  541. if empty_cnt == len(geo_obj.solid_geometry):
  542. raise ValidationError("Empty Geometry", None)
  543. geo_obj.multigeo = False
  544. # TODO: Do something if this is None. Offer changing name?
  545. self.app.new_object("geometry", iso_name, iso_init)
  546. else:
  547. for i in range(passes):
  548. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  549. if passes > 1:
  550. if self.iso_type == 0:
  551. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  552. elif self.iso_type == 1:
  553. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  554. else:
  555. iso_name = base_name + str(i + 1)
  556. else:
  557. if self.iso_type == 0:
  558. iso_name = self.options["name"] + "_ext_iso"
  559. elif self.iso_type == 1:
  560. iso_name = self.options["name"] + "_int_iso"
  561. else:
  562. iso_name = base_name
  563. # TODO: This is ugly. Create way to pass data into init function.
  564. def iso_init(geo_obj, app_obj):
  565. # Propagate options
  566. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  567. # if milling type is climb then the move is counter-clockwise around features
  568. if milling_type == 'cl':
  569. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  570. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type)
  571. else:
  572. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type)
  573. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  574. # or just looking in the lists (they are one level depth) and if any is not empty
  575. # proceed with object creation, if there are empty and the number of them is the length
  576. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  577. empty_cnt = 0
  578. if not isinstance(geo_obj.solid_geometry, list):
  579. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  580. for g in geo_obj.solid_geometry:
  581. if g:
  582. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  583. break
  584. else:
  585. empty_cnt += 1
  586. if empty_cnt == len(geo_obj.solid_geometry):
  587. raise ValidationError("Empty Geometry", None)
  588. geo_obj.multigeo = False
  589. # TODO: Do something if this is None. Offer changing name?
  590. self.app.new_object("geometry", iso_name, iso_init)
  591. def on_plot_cb_click(self, *args):
  592. if self.muted_ui:
  593. return
  594. self.read_form_item('plot')
  595. def on_solid_cb_click(self, *args):
  596. if self.muted_ui:
  597. return
  598. self.read_form_item('solid')
  599. self.plot()
  600. def on_multicolored_cb_click(self, *args):
  601. if self.muted_ui:
  602. return
  603. self.read_form_item('multicolored')
  604. self.plot()
  605. def convert_units(self, units):
  606. """
  607. Converts the units of the object by scaling dimensions in all geometry
  608. and options.
  609. :param units: Units to which to convert the object: "IN" or "MM".
  610. :type units: str
  611. :return: None
  612. :rtype: None
  613. """
  614. factor = Gerber.convert_units(self, units)
  615. self.options['isotooldia'] *= factor
  616. self.options['cutoutmargin'] *= factor
  617. self.options['cutoutgapsize'] *= factor
  618. self.options['noncoppermargin'] *= factor
  619. self.options['bboxmargin'] *= factor
  620. def plot(self, **kwargs):
  621. """
  622. :param kwargs: color and face_color
  623. :return:
  624. """
  625. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  626. # Does all the required setup and returns False
  627. # if the 'ptint' option is set to False.
  628. if not FlatCAMObj.plot(self):
  629. return
  630. if 'color' in kwargs:
  631. color = kwargs['color']
  632. else:
  633. color = self.app.defaults['global_plot_line']
  634. if 'face_color' in kwargs:
  635. face_color = kwargs['face_color']
  636. else:
  637. face_color = self.app.defaults['global_plot_fill']
  638. geometry = self.solid_geometry
  639. # Make sure geometry is iterable.
  640. try:
  641. _ = iter(geometry)
  642. except TypeError:
  643. geometry = [geometry]
  644. def random_color():
  645. color = np.random.rand(4)
  646. color[3] = 1
  647. return color
  648. try:
  649. if self.options["solid"]:
  650. for g in geometry:
  651. if type(g) == Polygon or type(g) == LineString:
  652. self.add_shape(shape=g, color=color,
  653. face_color=random_color() if self.options['multicolored']
  654. else face_color, visible=self.options['plot'])
  655. else:
  656. for el in g:
  657. self.add_shape(shape=el, color=color,
  658. face_color=random_color() if self.options['multicolored']
  659. else face_color, visible=self.options['plot'])
  660. else:
  661. for g in geometry:
  662. if type(g) == Polygon or type(g) == LineString:
  663. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  664. visible=self.options['plot'])
  665. else:
  666. for el in g:
  667. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  668. visible=self.options['plot'])
  669. self.shapes.redraw()
  670. except (ObjectDeleted, AttributeError):
  671. self.shapes.clear(update=True)
  672. def serialize(self):
  673. return {
  674. "options": self.options,
  675. "kind": self.kind
  676. }
  677. class FlatCAMExcellon(FlatCAMObj, Excellon):
  678. """
  679. Represents Excellon/Drill code.
  680. """
  681. ui_type = ExcellonObjectUI
  682. optionChanged = QtCore.pyqtSignal(str)
  683. def __init__(self, name):
  684. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  685. FlatCAMObj.__init__(self, name)
  686. self.kind = "excellon"
  687. self.options.update({
  688. "plot": True,
  689. "solid": False,
  690. "drillz": -0.1,
  691. "travelz": 0.1,
  692. "feedrate": 5.0,
  693. "feedrate_rapid": 5.0,
  694. "tooldia": 0.1,
  695. "slot_tooldia": 0.1,
  696. "toolchange": False,
  697. "toolchangez": 1.0,
  698. "toolchangexy": "0.0, 0.0",
  699. "endz": 2.0,
  700. "startz": None,
  701. "spindlespeed": None,
  702. "dwell": True,
  703. "dwelltime": 1000,
  704. "ppname_e": 'defaults',
  705. "optimization_type": "R",
  706. "gcode_type": "drills"
  707. })
  708. # TODO: Document this.
  709. self.tool_cbs = {}
  710. # Attributes to be included in serialization
  711. # Always append to it because it carries contents
  712. # from predecessors.
  713. self.ser_attrs += ['options', 'kind']
  714. # variable to store the total amount of drills per job
  715. self.tot_drill_cnt = 0
  716. self.tool_row = 0
  717. # variable to store the total amount of slots per job
  718. self.tot_slot_cnt = 0
  719. self.tool_row_slots = 0
  720. self.multigeo = False
  721. @staticmethod
  722. def merge(exc_list, exc_final):
  723. """
  724. Merge Excellon objects found in exc_list parameter into exc_final object.
  725. Options are always copied from source .
  726. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  727. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  728. tool_name to be used in the final Excellon object, exc_final.
  729. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  730. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  731. :param exc_final: Destination FlatCAMExcellon object.
  732. :return: None
  733. """
  734. try:
  735. flattened_list = list(itertools.chain(*exc_list))
  736. except TypeError:
  737. flattened_list = exc_list
  738. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  739. # values will be list of Shapely Points
  740. custom_dict = {}
  741. for exc in flattened_list:
  742. # copy options of the current excellon obj to the final excellon obj
  743. for option in exc.options:
  744. if option is not 'name':
  745. try:
  746. exc_final.options[option] = exc.options[option]
  747. except:
  748. exc.app.log.warning("Failed to copy option.", option)
  749. for drill in exc.drills:
  750. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  751. if exc_tool_dia not in custom_dict:
  752. custom_dict[exc_tool_dia] = [drill['point']]
  753. else:
  754. custom_dict[exc_tool_dia].append(drill['point'])
  755. # add the zeros and units to the exc_final object
  756. exc_final.zeros = exc.zeros
  757. exc_final.units = exc.units
  758. # variable to make tool_name for the tools
  759. current_tool = 0
  760. # Here we add data to the exc_final object
  761. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points
  762. for tool_dia in custom_dict:
  763. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  764. current_tool += 1
  765. tool_name = str(current_tool)
  766. spec = {"C": float(tool_dia)}
  767. exc_final.tools[tool_name] = spec
  768. # rebuild the drills list of dict's that belong to the exc_final object
  769. for point in custom_dict[tool_dia]:
  770. exc_final.drills.append(
  771. {
  772. "point": point,
  773. "tool": str(current_tool)
  774. }
  775. )
  776. # create the geometry for the exc_final object
  777. exc_final.create_geometry()
  778. def build_ui(self):
  779. FlatCAMObj.build_ui(self)
  780. n = len(self.tools)
  781. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  782. self.ui.tools_table.setRowCount(n + 2)
  783. self.tot_drill_cnt = 0
  784. self.tot_slot_cnt = 0
  785. self.tool_row = 0
  786. sort = []
  787. for k, v in list(self.tools.items()):
  788. sort.append((k, v.get('C')))
  789. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  790. tools = [i[0] for i in sorted_tools]
  791. for tool_no in tools:
  792. drill_cnt = 0 # variable to store the nr of drills per tool
  793. slot_cnt = 0 # variable to store the nr of slots per tool
  794. # Find no of drills for the current tool
  795. for drill in self.drills:
  796. if drill['tool'] == tool_no:
  797. drill_cnt += 1
  798. self.tot_drill_cnt += drill_cnt
  799. # Find no of slots for the current tool
  800. for slot in self.slots:
  801. if slot['tool'] == tool_no:
  802. slot_cnt += 1
  803. self.tot_slot_cnt += slot_cnt
  804. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  805. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  806. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  807. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  808. # There are no drill bits in MM with more than 3 decimals diameter
  809. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  810. if self.units == 'MM':
  811. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  812. else:
  813. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  814. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  815. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  816. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  817. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  818. if slot_cnt > 0:
  819. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  820. else:
  821. slot_count = QtWidgets.QTableWidgetItem('')
  822. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  823. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  824. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  825. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  826. self.tool_row += 1
  827. # add a last row with the Total number of drills
  828. empty = QtWidgets.QTableWidgetItem('')
  829. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  830. empty_1 = QtWidgets.QTableWidgetItem('')
  831. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  832. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  833. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  834. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  835. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  836. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  837. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  838. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  839. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  840. font = QtGui.QFont()
  841. font.setBold(True)
  842. font.setWeight(75)
  843. for k in [1, 2]:
  844. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  845. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  846. self.tool_row += 1
  847. # add a last row with the Total number of slots
  848. empty_2 = QtWidgets.QTableWidgetItem('')
  849. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  850. empty_3 = QtWidgets.QTableWidgetItem('')
  851. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  852. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  853. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  854. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  855. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  856. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  857. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  858. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  859. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  860. for kl in [1, 2, 3]:
  861. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  862. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  863. # sort the tool diameter column
  864. # self.ui.tools_table.sortItems(1)
  865. # all the tools are selected by default
  866. self.ui.tools_table.selectColumn(0)
  867. #
  868. self.ui.tools_table.resizeColumnsToContents()
  869. self.ui.tools_table.resizeRowsToContents()
  870. vertical_header = self.ui.tools_table.verticalHeader()
  871. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  872. vertical_header.hide()
  873. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  874. horizontal_header = self.ui.tools_table.horizontalHeader()
  875. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  876. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  877. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  878. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  879. # horizontal_header.setStretchLastSection(True)
  880. self.ui.tools_table.setSortingEnabled(False)
  881. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  882. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  883. if not self.drills:
  884. self.ui.tdlabel.hide()
  885. self.ui.tooldia_entry.hide()
  886. self.ui.generate_milling_button.hide()
  887. else:
  888. self.ui.tdlabel.show()
  889. self.ui.tooldia_entry.show()
  890. self.ui.generate_milling_button.show()
  891. if not self.slots:
  892. self.ui.stdlabel.hide()
  893. self.ui.slot_tooldia_entry.hide()
  894. self.ui.generate_milling_slots_button.hide()
  895. else:
  896. self.ui.stdlabel.show()
  897. self.ui.slot_tooldia_entry.show()
  898. self.ui.generate_milling_slots_button.show()
  899. def set_ui(self, ui):
  900. """
  901. Configures the user interface for this object.
  902. Connects options to form fields.
  903. :param ui: User interface object.
  904. :type ui: ExcellonObjectUI
  905. :return: None
  906. """
  907. FlatCAMObj.set_ui(self, ui)
  908. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  909. self.form_fields.update({
  910. "plot": self.ui.plot_cb,
  911. "solid": self.ui.solid_cb,
  912. "drillz": self.ui.cutz_entry,
  913. "travelz": self.ui.travelz_entry,
  914. "feedrate": self.ui.feedrate_entry,
  915. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  916. "tooldia": self.ui.tooldia_entry,
  917. "slot_tooldia": self.ui.slot_tooldia_entry,
  918. "toolchange": self.ui.toolchange_cb,
  919. "toolchangez": self.ui.toolchangez_entry,
  920. "spindlespeed": self.ui.spindlespeed_entry,
  921. "dwell": self.ui.dwell_cb,
  922. "dwelltime": self.ui.dwelltime_entry,
  923. "startz": self.ui.estartz_entry,
  924. "endz": self.ui.eendz_entry,
  925. "ppname_e": self.ui.pp_excellon_name_cb,
  926. "gcode_type": self.ui.excellon_gcode_type_radio
  927. })
  928. for name in list(self.app.postprocessors.keys()):
  929. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  930. if name == 'hpgl':
  931. continue
  932. self.ui.pp_excellon_name_cb.addItem(name)
  933. # Fill form fields
  934. self.to_form()
  935. assert isinstance(self.ui, ExcellonObjectUI), \
  936. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  937. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  938. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  939. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  940. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  941. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  942. def get_selected_tools_list(self):
  943. """
  944. Returns the keys to the self.tools dictionary corresponding
  945. to the selections on the tool list in the GUI.
  946. :return: List of tools.
  947. :rtype: list
  948. """
  949. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  950. def get_selected_tools_table_items(self):
  951. """
  952. Returns a list of lists, each list in the list is made out of row elements
  953. :return: List of table_tools items.
  954. :rtype: list
  955. """
  956. table_tools_items = []
  957. for x in self.ui.tools_table.selectedItems():
  958. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  959. for column in range(0, self.ui.tools_table.columnCount())])
  960. for item in table_tools_items:
  961. item[0] = str(item[0])
  962. return table_tools_items
  963. def export_excellon(self):
  964. """
  965. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  966. :return: has_slots and Excellon_code
  967. """
  968. excellon_code = ''
  969. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  970. # store here if the file has slots, return 1 if any slots, 0 if only drills
  971. has_slots = 0
  972. # drills processing
  973. try:
  974. for tool in self.tools:
  975. if int(tool) < 10:
  976. excellon_code += 'T0' + str(tool) + '\n'
  977. else:
  978. excellon_code += 'T' + str(tool) + '\n'
  979. for drill in self.drills:
  980. if tool == drill['tool']:
  981. if units == 'MM':
  982. excellon_code += 'X' + '%.3f' % drill['point'].x + 'Y' + '%.3f' % drill['point'].y + '\n'
  983. else:
  984. excellon_code += 'X' + '%.4f' % drill['point'].x + 'Y' + '%.4f' % drill['point'].y + '\n'
  985. except Exception as e:
  986. log.debug(str(e))
  987. # slots processing
  988. try:
  989. if self.slots:
  990. has_slots = 1
  991. for tool in self.tools:
  992. if int(tool) < 10:
  993. excellon_code += 'T0' + str(tool) + '\n'
  994. else:
  995. excellon_code += 'T' + str(tool) + '\n'
  996. for slot in self.slots:
  997. if tool == slot['tool']:
  998. if units == 'MM':
  999. excellon_code += 'G00' + 'X' + '%.3f' % slot['start'].x + 'Y' + \
  1000. '%.3f' % slot['start'].y + '\n'
  1001. excellon_code += 'M15\n'
  1002. excellon_code += 'G01' + 'X' + '%.3f' % slot['stop'].x + 'Y' + \
  1003. '%.3f' % slot['stop'].y + '\n'
  1004. excellon_code += 'M16\n'
  1005. else:
  1006. excellon_code += 'G00' + 'X' + '%.4f' % slot['start'].x + 'Y' + \
  1007. '%.4f' % slot['start'].y + '\n'
  1008. excellon_code += 'M15\n'
  1009. excellon_code += 'G01' + 'X' + '%.4f' % slot['stop'].x + 'Y' + \
  1010. '%.4f' % slot['stop'].y + '\n'
  1011. excellon_code += 'M16\n'
  1012. except Exception as e:
  1013. log.debug(str(e))
  1014. return has_slots, excellon_code
  1015. def export_excellon_altium(self):
  1016. """
  1017. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1018. :return: has_slots and Excellon_code
  1019. """
  1020. excellon_code = ''
  1021. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  1022. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1023. has_slots = 0
  1024. # drills processing
  1025. try:
  1026. for tool in self.tools:
  1027. if int(tool) < 10:
  1028. excellon_code += 'T0' + str(tool) + '\n'
  1029. else:
  1030. excellon_code += 'T' + str(tool) + '\n'
  1031. for drill in self.drills:
  1032. if tool == drill['tool']:
  1033. drill_x = drill['point'].x
  1034. drill_y = drill['point'].y
  1035. if units == 'MM':
  1036. drill_x /= 25.4
  1037. drill_y /= 25.4
  1038. exc_x_formatted = ('%.4f' % drill_x).replace('.', '')
  1039. if drill_x < 10:
  1040. exc_x_formatted = '0' + exc_x_formatted
  1041. exc_y_formatted = ('%.4f' % drill_y).replace('.', '')
  1042. if drill_y < 10:
  1043. exc_y_formatted = '0' + exc_y_formatted
  1044. excellon_code += 'X' + exc_x_formatted + 'Y' + exc_y_formatted + '\n'
  1045. except Exception as e:
  1046. log.debug(str(e))
  1047. # slots processing
  1048. try:
  1049. if self.slots:
  1050. has_slots = 1
  1051. for tool in self.tools:
  1052. if int(tool) < 10:
  1053. excellon_code += 'T0' + str(tool) + '\n'
  1054. else:
  1055. excellon_code += 'T' + str(tool) + '\n'
  1056. for slot in self.slots:
  1057. if tool == slot['tool']:
  1058. start_slot_x = slot['start'].x
  1059. start_slot_y = slot['start'].y
  1060. stop_slot_x = slot['stop'].x
  1061. stop_slot_y = slot['stop'].y
  1062. if units == 'MM':
  1063. start_slot_x /= 25.4
  1064. start_slot_y /= 25.4
  1065. stop_slot_x /= 25.4
  1066. stop_slot_y /= 25.4
  1067. start_slot_x_formatted = ('%.4f' % start_slot_x).replace('.', '')
  1068. if start_slot_x < 10:
  1069. start_slot_x_formatted = '0' + start_slot_x_formatted
  1070. start_slot_y_formatted = ('%.4f' % start_slot_y).replace('.', '')
  1071. if start_slot_y < 10:
  1072. start_slot_y_formatted = '0' + start_slot_y_formatted
  1073. stop_slot_x_formatted = ('%.4f' % stop_slot_x).replace('.', '')
  1074. if stop_slot_x < 10:
  1075. stop_slot_x_formatted = '0' + stop_slot_x_formatted
  1076. stop_slot_y_formatted = ('%.4f' % stop_slot_y).replace('.', '')
  1077. if stop_slot_y < 10:
  1078. stop_slot_y_formatted = '0' + stop_slot_y_formatted
  1079. excellon_code += 'G00' + 'X' + start_slot_x_formatted + 'Y' + \
  1080. start_slot_y_formatted + '\n'
  1081. excellon_code += 'M15\n'
  1082. excellon_code += 'G01' + 'X' + stop_slot_x_formatted + 'Y' + \
  1083. stop_slot_y_formatted + '\n'
  1084. excellon_code += 'M16\n'
  1085. except Exception as e:
  1086. log.debug(str(e))
  1087. return has_slots, excellon_code
  1088. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1089. """
  1090. Note: This method is a good template for generic operations as
  1091. it takes it's options from parameters or otherwise from the
  1092. object's options and returns a (success, msg) tuple as feedback
  1093. for shell operations.
  1094. :return: Success/failure condition tuple (bool, str).
  1095. :rtype: tuple
  1096. """
  1097. # Get the tools from the list. These are keys
  1098. # to self.tools
  1099. if tools is None:
  1100. tools = self.get_selected_tools_list()
  1101. if outname is None:
  1102. outname = self.options["name"] + "_mill"
  1103. if tooldia is None:
  1104. tooldia = self.options["tooldia"]
  1105. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1106. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1107. sort = []
  1108. for k, v in self.tools.items():
  1109. sort.append((k, v.get('C')))
  1110. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1111. if tools == "all":
  1112. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1113. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1114. if len(tools) == 0:
  1115. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1116. return False, "Error: No tools."
  1117. for tool in tools:
  1118. if tooldia > self.tools[tool]["C"]:
  1119. self.app.inform.emit("[error_notcl] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1120. return False, "Error: Milling tool is larger than hole."
  1121. def geo_init(geo_obj, app_obj):
  1122. assert isinstance(geo_obj, FlatCAMGeometry), \
  1123. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1124. app_obj.progress.emit(20)
  1125. ### Add properties to the object
  1126. # get the tool_table items in a list of row items
  1127. tool_table_items = self.get_selected_tools_table_items()
  1128. # insert an information only element in the front
  1129. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1130. geo_obj.options['Tools_in_use'] = tool_table_items
  1131. geo_obj.options['type'] = 'Excellon Geometry'
  1132. geo_obj.solid_geometry = []
  1133. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1134. # for FlatCAM is 6 decimals,
  1135. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1136. for hole in self.drills:
  1137. if hole['tool'] in tools:
  1138. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1139. if buffer_value == 0:
  1140. geo_obj.solid_geometry.append(
  1141. Point(hole['point']).buffer(0.0000001).exterior)
  1142. else:
  1143. geo_obj.solid_geometry.append(
  1144. Point(hole['point']).buffer(buffer_value).exterior)
  1145. if use_thread:
  1146. def geo_thread(app_obj):
  1147. app_obj.new_object("geometry", outname, geo_init)
  1148. app_obj.progress.emit(100)
  1149. # Create a promise with the new name
  1150. self.app.collection.promise(outname)
  1151. # Send to worker
  1152. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1153. else:
  1154. self.app.new_object("geometry", outname, geo_init)
  1155. return True, ""
  1156. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1157. """
  1158. Note: This method is a good template for generic operations as
  1159. it takes it's options from parameters or otherwise from the
  1160. object's options and returns a (success, msg) tuple as feedback
  1161. for shell operations.
  1162. :return: Success/failure condition tuple (bool, str).
  1163. :rtype: tuple
  1164. """
  1165. # Get the tools from the list. These are keys
  1166. # to self.tools
  1167. if tools is None:
  1168. tools = self.get_selected_tools_list()
  1169. if outname is None:
  1170. outname = self.options["name"] + "_mill"
  1171. if tooldia is None:
  1172. tooldia = self.options["slot_tooldia"]
  1173. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1174. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1175. sort = []
  1176. for k, v in self.tools.items():
  1177. sort.append((k, v.get('C')))
  1178. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1179. if tools == "all":
  1180. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1181. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1182. if len(tools) == 0:
  1183. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1184. return False, "Error: No tools."
  1185. for tool in tools:
  1186. if tooldia > self.tools[tool]["C"]:
  1187. self.app.inform.emit("[error_notcl] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1188. return False, "Error: Milling tool is larger than hole."
  1189. def geo_init(geo_obj, app_obj):
  1190. assert isinstance(geo_obj, FlatCAMGeometry), \
  1191. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1192. app_obj.progress.emit(20)
  1193. ### Add properties to the object
  1194. # get the tool_table items in a list of row items
  1195. tool_table_items = self.get_selected_tools_table_items()
  1196. # insert an information only element in the front
  1197. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1198. geo_obj.options['Tools_in_use'] = tool_table_items
  1199. geo_obj.options['type'] = 'Excellon Geometry'
  1200. geo_obj.solid_geometry = []
  1201. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1202. # for FlatCAM is 6 decimals,
  1203. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1204. for slot in self.slots:
  1205. if slot['tool'] in tools:
  1206. buffer_value = self.tools[slot['tool']]["C"] / 2 - tooldia / 2
  1207. if buffer_value == 0:
  1208. start = slot['start']
  1209. stop = slot['stop']
  1210. lines_string = LineString([start, stop])
  1211. poly = lines_string.buffer(0.0000001, self.geo_steps_per_circle).exterior
  1212. geo_obj.solid_geometry.append(poly)
  1213. else:
  1214. start = slot['start']
  1215. stop = slot['stop']
  1216. lines_string = LineString([start, stop])
  1217. poly = lines_string.buffer(buffer_value, self.geo_steps_per_circle).exterior
  1218. geo_obj.solid_geometry.append(poly)
  1219. if use_thread:
  1220. def geo_thread(app_obj):
  1221. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1222. app_obj.progress.emit(100)
  1223. # Create a promise with the new name
  1224. self.app.collection.promise(outname)
  1225. # Send to worker
  1226. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1227. else:
  1228. self.app.new_object("geometry", outname + '_slot', geo_init)
  1229. return True, ""
  1230. def on_generate_milling_button_click(self, *args):
  1231. self.app.report_usage("excellon_on_create_milling_drills button")
  1232. self.read_form()
  1233. self.generate_milling_drills(use_thread=False)
  1234. def on_generate_milling_slots_button_click(self, *args):
  1235. self.app.report_usage("excellon_on_create_milling_slots_button")
  1236. self.read_form()
  1237. self.generate_milling_slots(use_thread=False)
  1238. def on_create_cncjob_button_click(self, *args):
  1239. self.app.report_usage("excellon_on_create_cncjob_button")
  1240. self.read_form()
  1241. # Get the tools from the list
  1242. tools = self.get_selected_tools_list()
  1243. if len(tools) == 0:
  1244. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1245. return
  1246. job_name = self.options["name"] + "_cnc"
  1247. pp_excellon_name = self.options["ppname_e"]
  1248. # Object initialization function for app.new_object()
  1249. def job_init(job_obj, app_obj):
  1250. assert isinstance(job_obj, FlatCAMCNCjob), \
  1251. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1252. # get the tool_table items in a list of row items
  1253. tool_table_items = self.get_selected_tools_table_items()
  1254. # insert an information only element in the front
  1255. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1256. ### Add properties to the object
  1257. job_obj.options['Tools_in_use'] = tool_table_items
  1258. job_obj.options['type'] = 'Excellon'
  1259. app_obj.progress.emit(20)
  1260. job_obj.z_cut = self.options["drillz"]
  1261. job_obj.z_move = self.options["travelz"]
  1262. job_obj.feedrate = self.options["feedrate"]
  1263. job_obj.feedrate_rapid = self.options["feedrate_rapid"]
  1264. job_obj.spindlespeed = self.options["spindlespeed"]
  1265. job_obj.dwell = self.options["dwell"]
  1266. job_obj.dwelltime = self.options["dwelltime"]
  1267. job_obj.pp_excellon_name = pp_excellon_name
  1268. job_obj.toolchange_xy = "excellon"
  1269. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1270. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1271. # There could be more than one drill size...
  1272. # job_obj.tooldia = # TODO: duplicate variable!
  1273. # job_obj.options["tooldia"] =
  1274. tools_csv = ','.join(tools)
  1275. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1276. drillz=self.options['drillz'],
  1277. toolchange=self.options["toolchange"],
  1278. toolchangez=self.options["toolchangez"],
  1279. toolchangexy=self.options["toolchangexy"],
  1280. startz=self.options["startz"],
  1281. endz=self.options["endz"],
  1282. excellon_optimization_type=self.options["optimization_type"])
  1283. app_obj.progress.emit(50)
  1284. job_obj.gcode_parse()
  1285. app_obj.progress.emit(60)
  1286. job_obj.create_geometry()
  1287. app_obj.progress.emit(80)
  1288. # To be run in separate thread
  1289. def job_thread(app_obj):
  1290. with self.app.proc_container.new("Generating CNC Code"):
  1291. app_obj.new_object("cncjob", job_name, job_init)
  1292. app_obj.progress.emit(100)
  1293. # Create promise for the new name.
  1294. self.app.collection.promise(job_name)
  1295. # Send to worker
  1296. # self.app.worker.add_task(job_thread, [self.app])
  1297. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1298. def on_plot_cb_click(self, *args):
  1299. if self.muted_ui:
  1300. return
  1301. self.read_form_item('plot')
  1302. def on_solid_cb_click(self, *args):
  1303. if self.muted_ui:
  1304. return
  1305. self.read_form_item('solid')
  1306. self.plot()
  1307. def convert_units(self, units):
  1308. factor = Excellon.convert_units(self, units)
  1309. self.options['drillz'] *= factor
  1310. self.options['travelz'] *= factor
  1311. self.options['feedrate'] *= factor
  1312. self.options['feedrate_rapid'] *= factor
  1313. self.options['toolchangez'] *= factor
  1314. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1315. coords_xy[0] *= factor
  1316. coords_xy[1] *= factor
  1317. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1318. if self.options['startz'] is not None:
  1319. self.options['startz'] *= factor
  1320. self.options['endz'] *= factor
  1321. def plot(self):
  1322. # Does all the required setup and returns False
  1323. # if the 'ptint' option is set to False.
  1324. if not FlatCAMObj.plot(self):
  1325. return
  1326. try:
  1327. _ = iter(self.solid_geometry)
  1328. except TypeError:
  1329. self.solid_geometry = [self.solid_geometry]
  1330. try:
  1331. # Plot excellon (All polygons?)
  1332. if self.options["solid"]:
  1333. for geo in self.solid_geometry:
  1334. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1335. layer=2)
  1336. else:
  1337. for geo in self.solid_geometry:
  1338. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1339. for ints in geo.interiors:
  1340. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1341. self.shapes.redraw()
  1342. except (ObjectDeleted, AttributeError):
  1343. self.shapes.clear(update=True)
  1344. # try:
  1345. # # Plot excellon (All polygons?)
  1346. # if self.options["solid"]:
  1347. # for geo_type in self.solid_geometry:
  1348. # if geo_type is not None:
  1349. # if type(geo_type) is dict:
  1350. # for tooldia in geo_type:
  1351. # geo_list = geo_type[tooldia]
  1352. # for geo in geo_list:
  1353. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1354. # visible=self.options['plot'],
  1355. # layer=2)
  1356. # else:
  1357. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1358. # visible=self.options['plot'],
  1359. # layer=2)
  1360. # else:
  1361. # for geo_type in self.solid_geometry:
  1362. # if geo_type is not None:
  1363. # if type(geo_type) is dict:
  1364. # for tooldia in geo_type:
  1365. # geo_list = geo_type[tooldia]
  1366. # for geo in geo_list:
  1367. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1368. # for ints in geo.interiors:
  1369. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1370. # else:
  1371. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1372. # for ints in geo_type.interiors:
  1373. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1374. # self.shapes.redraw()
  1375. # except (ObjectDeleted, AttributeError):
  1376. # self.shapes.clear(update=True)
  1377. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1378. """
  1379. Geometric object not associated with a specific
  1380. format.
  1381. """
  1382. optionChanged = QtCore.pyqtSignal(str)
  1383. ui_type = GeometryObjectUI
  1384. @staticmethod
  1385. def merge(geo_list, geo_final, multigeo=None):
  1386. """
  1387. Merges the geometry of objects in grb_list into
  1388. the geometry of geo_final.
  1389. :param geo_list: List of FlatCAMGerber Objects to join.
  1390. :param geo_final: Destination FlatCAMGerber object.
  1391. :return: None
  1392. """
  1393. if geo_final.solid_geometry is None:
  1394. geo_final.solid_geometry = []
  1395. if type(geo_final.solid_geometry) is not list:
  1396. geo_final.solid_geometry = [geo_final.solid_geometry]
  1397. for geo in geo_list:
  1398. for option in geo.options:
  1399. if option is not 'name':
  1400. try:
  1401. geo_final.options[option] = geo.options[option]
  1402. except:
  1403. log.warning("Failed to copy option.", option)
  1404. # Expand lists
  1405. if type(geo) is list:
  1406. FlatCAMGeometry.merge(geo, geo_final)
  1407. # If not list, just append
  1408. else:
  1409. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1410. if multigeo is None or multigeo == False:
  1411. geo_final.multigeo = False
  1412. try:
  1413. geo_final.solid_geometry.append(geo.solid_geometry)
  1414. except Exception as e:
  1415. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1416. else:
  1417. geo_final.multigeo = True
  1418. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1419. # tools object attribute, as a key value
  1420. geo_final.solid_geometry = []
  1421. # find the tool_uid maximum value in the geo_final
  1422. geo_final_uid_list = []
  1423. for key in geo_final.tools:
  1424. geo_final_uid_list.append(int(key))
  1425. try:
  1426. max_uid = max(geo_final_uid_list, key=int)
  1427. except ValueError:
  1428. max_uid = 0
  1429. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1430. # to merge the obj.tools as it is likely there is none to merge.
  1431. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1432. for tool_uid in geo.tools:
  1433. max_uid += 1
  1434. geo_final.tools[max_uid] = dict(geo.tools[tool_uid])
  1435. @staticmethod
  1436. def get_pts(o):
  1437. """
  1438. Returns a list of all points in the object, where
  1439. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1440. of such. Search is done recursively.
  1441. :param: geometric object
  1442. :return: List of points
  1443. :rtype: list
  1444. """
  1445. pts = []
  1446. ## Iterable: descend into each item.
  1447. try:
  1448. for subo in o:
  1449. pts += FlatCAMGeometry.get_pts(subo)
  1450. ## Non-iterable
  1451. except TypeError:
  1452. if o is not None:
  1453. if type(o) == MultiPolygon:
  1454. for poly in o:
  1455. pts += FlatCAMGeometry.get_pts(poly)
  1456. ## Descend into .exerior and .interiors
  1457. elif type(o) == Polygon:
  1458. pts += FlatCAMGeometry.get_pts(o.exterior)
  1459. for i in o.interiors:
  1460. pts += FlatCAMGeometry.get_pts(i)
  1461. elif type(o) == MultiLineString:
  1462. for line in o:
  1463. pts += FlatCAMGeometry.get_pts(line)
  1464. ## Has .coords: list them.
  1465. else:
  1466. pts += list(o.coords)
  1467. else:
  1468. return
  1469. return pts
  1470. def __init__(self, name):
  1471. FlatCAMObj.__init__(self, name)
  1472. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  1473. self.kind = "geometry"
  1474. self.options.update({
  1475. "plot": True,
  1476. "cutz": -0.002,
  1477. "vtipdia": 0.1,
  1478. "vtipangle": 30,
  1479. "travelz": 0.1,
  1480. "feedrate": 5.0,
  1481. "feedrate_z": 5.0,
  1482. "feedrate_rapid": 5.0,
  1483. "spindlespeed": None,
  1484. "dwell": True,
  1485. "dwelltime": 1000,
  1486. "multidepth": False,
  1487. "depthperpass": 0.002,
  1488. "extracut": False,
  1489. "endz": 2.0,
  1490. "toolchange": False,
  1491. "toolchangez": 1.0,
  1492. "toolchangexy": "0.0, 0.0",
  1493. "startz": None,
  1494. "ppname_g": 'default',
  1495. })
  1496. if "cnctooldia" not in self.options:
  1497. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  1498. self.options["startz"] = self.app.defaults["geometry_startz"]
  1499. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  1500. self.tooluid = 0
  1501. '''
  1502. self.tools = {}
  1503. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  1504. tool_id of the tools and the value is another dict that will hold the data under the following form:
  1505. {tooluid: {
  1506. 'tooldia': 1,
  1507. 'offset': 'Path',
  1508. 'offset_value': 0.0
  1509. 'type': 'Rough',
  1510. 'tool_type': 'C1',
  1511. 'data': self.default_tool_data
  1512. 'solid_geometry': []
  1513. }
  1514. }
  1515. '''
  1516. self.tools = {}
  1517. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  1518. # those elements are the ones used for generating GCode
  1519. self.sel_tools = {}
  1520. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  1521. self.type_item_options = ["Iso", "Rough", "Finish"]
  1522. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  1523. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  1524. self.v_tool_type = None
  1525. self.multigeo = False
  1526. # Attributes to be included in serialization
  1527. # Always append to it because it carries contents
  1528. # from predecessors.
  1529. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  1530. def build_ui(self):
  1531. self.ui_disconnect()
  1532. FlatCAMObj.build_ui(self)
  1533. offset = 0
  1534. tool_idx = 0
  1535. n = len(self.tools)
  1536. self.ui.geo_tools_table.setRowCount(n)
  1537. for tooluid_key, tooluid_value in self.tools.items():
  1538. tool_idx += 1
  1539. row_no = tool_idx - 1
  1540. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  1541. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1542. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  1543. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  1544. # There are no tool bits in MM with more than 3 decimals diameter.
  1545. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  1546. if self.units == 'MM':
  1547. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  1548. else:
  1549. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  1550. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1551. offset_item = QtWidgets.QComboBox()
  1552. for item in self.offset_item_options:
  1553. offset_item.addItem(item)
  1554. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  1555. idx = offset_item.findText(tooluid_value['offset'])
  1556. offset_item.setCurrentIndex(idx)
  1557. type_item = QtWidgets.QComboBox()
  1558. for item in self.type_item_options:
  1559. type_item.addItem(item)
  1560. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1561. idx = type_item.findText(tooluid_value['type'])
  1562. type_item.setCurrentIndex(idx)
  1563. tool_type_item = QtWidgets.QComboBox()
  1564. for item in self.tool_type_item_options:
  1565. tool_type_item.addItem(item)
  1566. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1567. idx = tool_type_item.findText(tooluid_value['tool_type'])
  1568. tool_type_item.setCurrentIndex(idx)
  1569. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  1570. plot_item = FCCheckBox()
  1571. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1572. if self.ui.plot_cb.isChecked():
  1573. plot_item.setChecked(True)
  1574. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  1575. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  1576. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  1577. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  1578. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  1579. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  1580. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  1581. try:
  1582. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  1583. except:
  1584. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  1585. # make the diameter column editable
  1586. for row in range(tool_idx):
  1587. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  1588. QtCore.Qt.ItemIsEditable |
  1589. QtCore.Qt.ItemIsEnabled)
  1590. # sort the tool diameter column
  1591. # self.ui.geo_tools_table.sortItems(1)
  1592. # all the tools are selected by default
  1593. # self.ui.geo_tools_table.selectColumn(0)
  1594. self.ui.geo_tools_table.resizeColumnsToContents()
  1595. self.ui.geo_tools_table.resizeRowsToContents()
  1596. vertical_header = self.ui.geo_tools_table.verticalHeader()
  1597. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1598. vertical_header.hide()
  1599. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1600. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  1601. horizontal_header.setMinimumSectionSize(10)
  1602. horizontal_header.setDefaultSectionSize(70)
  1603. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1604. horizontal_header.resizeSection(0, 20)
  1605. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1606. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1607. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1608. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  1609. horizontal_header.resizeSection(4, 40)
  1610. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  1611. horizontal_header.resizeSection(4, 17)
  1612. # horizontal_header.setStretchLastSection(True)
  1613. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1614. self.ui.geo_tools_table.setColumnWidth(0, 20)
  1615. self.ui.geo_tools_table.setColumnWidth(4, 40)
  1616. self.ui.geo_tools_table.setColumnWidth(6, 17)
  1617. # self.ui.geo_tools_table.setSortingEnabled(True)
  1618. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  1619. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  1620. # update UI for all rows - useful after units conversion but only if there is at least one row
  1621. row_cnt = self.ui.geo_tools_table.rowCount()
  1622. if row_cnt > 0:
  1623. for r in range(row_cnt):
  1624. self.update_ui(r)
  1625. # select only the first tool / row
  1626. selected_row = 0
  1627. try:
  1628. self.select_tools_table_row(selected_row, clearsel=True)
  1629. # update the Geometry UI
  1630. self.update_ui()
  1631. except Exception as e:
  1632. # when the tools table is empty there will be this error but once the table is populated it will go away
  1633. log.debug(str(e))
  1634. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  1635. # and can create some problems
  1636. if self.multigeo is False:
  1637. self.ui.geo_tools_table.setColumnHidden(6, True)
  1638. else:
  1639. self.ui.geo_tools_table.setColumnHidden(6, False)
  1640. self.set_tool_offset_visibility(selected_row)
  1641. self.ui_connect()
  1642. def set_ui(self, ui):
  1643. FlatCAMObj.set_ui(self, ui)
  1644. log.debug("FlatCAMGeometry.set_ui()")
  1645. assert isinstance(self.ui, GeometryObjectUI), \
  1646. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1647. # populate postprocessor names in the combobox
  1648. for name in list(self.app.postprocessors.keys()):
  1649. self.ui.pp_geometry_name_cb.addItem(name)
  1650. self.form_fields.update({
  1651. "plot": self.ui.plot_cb,
  1652. "cutz": self.ui.cutz_entry,
  1653. "vtipdia": self.ui.tipdia_entry,
  1654. "vtipangle": self.ui.tipangle_entry,
  1655. "travelz": self.ui.travelz_entry,
  1656. "feedrate": self.ui.cncfeedrate_entry,
  1657. "feedrate_z": self.ui.cncplunge_entry,
  1658. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  1659. "spindlespeed": self.ui.cncspindlespeed_entry,
  1660. "dwell": self.ui.dwell_cb,
  1661. "dwelltime": self.ui.dwelltime_entry,
  1662. "multidepth": self.ui.mpass_cb,
  1663. "ppname_g": self.ui.pp_geometry_name_cb,
  1664. "depthperpass": self.ui.maxdepth_entry,
  1665. "extracut": self.ui.extracut_cb,
  1666. "toolchange": self.ui.toolchangeg_cb,
  1667. "toolchangez": self.ui.toolchangez_entry,
  1668. "endz": self.ui.gendz_entry,
  1669. })
  1670. # Fill form fields only on object create
  1671. self.to_form()
  1672. self.ui.tipdialabel.hide()
  1673. self.ui.tipdia_entry.hide()
  1674. self.ui.tipanglelabel.hide()
  1675. self.ui.tipangle_entry.hide()
  1676. self.ui.cutz_entry.setDisabled(False)
  1677. # store here the default data for Geometry Data
  1678. self.default_data = {}
  1679. self.default_data.update({
  1680. "name": None,
  1681. "plot": None,
  1682. "cutz": None,
  1683. "vtipdia": None,
  1684. "vtipangle": None,
  1685. "travelz": None,
  1686. "feedrate": None,
  1687. "feedrate_z": None,
  1688. "feedrate_rapid": None,
  1689. "dwell": None,
  1690. "dwelltime": None,
  1691. "multidepth": None,
  1692. "ppname_g": None,
  1693. "depthperpass": None,
  1694. "extracut": None,
  1695. "toolchange": None,
  1696. "toolchangez": None,
  1697. "endz": None,
  1698. "spindlespeed": None,
  1699. "toolchangexy": None,
  1700. "startz": None
  1701. })
  1702. # fill in self.default_data values from self.options
  1703. for def_key in self.default_data:
  1704. for opt_key, opt_val in self.options.items():
  1705. if def_key == opt_key:
  1706. self.default_data[def_key] = opt_val
  1707. self.tooluid += 1
  1708. if not self.tools:
  1709. self.tools.update({
  1710. self.tooluid: {
  1711. 'tooldia': self.options["cnctooldia"],
  1712. 'offset': 'Path',
  1713. 'offset_value': 0.0,
  1714. 'type': 'Rough',
  1715. 'tool_type': 'C1',
  1716. 'data': self.default_data,
  1717. 'solid_geometry': []
  1718. }
  1719. })
  1720. else:
  1721. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  1722. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  1723. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  1724. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  1725. # following convoluted way of changing the keys from string to float type
  1726. temp_tools = {}
  1727. new_key = 0.0
  1728. for tooluid_key in self.tools:
  1729. val = dict(self.tools[tooluid_key])
  1730. new_key = deepcopy(int(tooluid_key))
  1731. temp_tools[new_key] = val
  1732. self.tools.clear()
  1733. self.tools = dict(temp_tools)
  1734. self.ui.tool_offset_entry.hide()
  1735. self.ui.tool_offset_lbl.hide()
  1736. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  1737. self.old_pp_state = self.default_data['multidepth']
  1738. self.old_toolchangeg_state = self.default_data['toolchange']
  1739. if not isinstance(self.ui, GeometryObjectUI):
  1740. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  1741. return
  1742. self.ui.geo_tools_table.setupContextMenu()
  1743. self.ui.geo_tools_table.addContextMenu(
  1744. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  1745. self.ui.geo_tools_table.addContextMenu(
  1746. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  1747. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1748. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1749. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  1750. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  1751. def set_tool_offset_visibility(self, current_row):
  1752. if current_row is None:
  1753. return
  1754. try:
  1755. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  1756. if tool_offset is not None:
  1757. tool_offset_txt = tool_offset.currentText()
  1758. if tool_offset_txt == 'Custom':
  1759. self.ui.tool_offset_entry.show()
  1760. self.ui.tool_offset_lbl.show()
  1761. else:
  1762. self.ui.tool_offset_entry.hide()
  1763. self.ui.tool_offset_lbl.hide()
  1764. except Exception as e:
  1765. log.debug("set_tool_offset_visibility() --> " + str(e))
  1766. return
  1767. def on_offset_value_edited(self):
  1768. '''
  1769. This will save the offset_value into self.tools storage whenever the oofset value is edited
  1770. :return:
  1771. '''
  1772. for current_row in self.ui.geo_tools_table.selectedItems():
  1773. # sometime the header get selected and it has row number -1
  1774. # we don't want to do anything with the header :)
  1775. if current_row.row() < 0:
  1776. continue
  1777. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1778. self.set_tool_offset_visibility(current_row.row())
  1779. for tooluid_key, tooluid_value in self.tools.items():
  1780. if int(tooluid_key) == tool_uid:
  1781. tooluid_value['offset_value'] = self.ui.tool_offset_entry.get_value()
  1782. def ui_connect(self):
  1783. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1784. # changes in geometry UI
  1785. for i in range(self.ui.grid3.count()):
  1786. try:
  1787. # works for CheckBoxes
  1788. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  1789. except:
  1790. # works for ComboBoxes
  1791. try:
  1792. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  1793. except:
  1794. # works for Entry
  1795. try:
  1796. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  1797. except:
  1798. pass
  1799. for row in range(self.ui.geo_tools_table.rowCount()):
  1800. for col in [2, 3, 4]:
  1801. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  1802. self.on_tooltable_cellwidget_change)
  1803. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1804. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  1805. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  1806. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  1807. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  1808. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  1809. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  1810. for row in range(self.ui.geo_tools_table.rowCount()):
  1811. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  1812. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1813. def ui_disconnect(self):
  1814. try:
  1815. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1816. # changes in geometry UI
  1817. for i in range(self.ui.grid3.count()):
  1818. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  1819. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  1820. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  1821. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  1822. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  1823. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  1824. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  1825. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  1826. except:
  1827. pass
  1828. try:
  1829. for row in range(self.ui.geo_tools_table.rowCount()):
  1830. for col in [2, 3, 4]:
  1831. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  1832. except:
  1833. pass
  1834. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1835. try:
  1836. self.ui.addtool_btn.clicked.disconnect()
  1837. except:
  1838. pass
  1839. try:
  1840. self.ui.copytool_btn.clicked.disconnect()
  1841. except:
  1842. pass
  1843. try:
  1844. self.ui.deltool_btn.clicked.disconnect()
  1845. except:
  1846. pass
  1847. try:
  1848. self.ui.geo_tools_table.currentItemChanged.disconnect()
  1849. except:
  1850. pass
  1851. try:
  1852. self.ui.geo_tools_table.itemChanged.disconnect()
  1853. except:
  1854. pass
  1855. try:
  1856. self.ui.tool_offset_entry.editingFinished.disconnect()
  1857. except:
  1858. pass
  1859. for row in range(self.ui.geo_tools_table.rowCount()):
  1860. try:
  1861. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  1862. except:
  1863. pass
  1864. try:
  1865. self.ui.plot_cb.stateChanged.disconnect()
  1866. except:
  1867. pass
  1868. def on_tool_add(self, dia=None):
  1869. self.ui_disconnect()
  1870. last_offset = None
  1871. last_offset_value = None
  1872. last_type = None
  1873. last_tool_type = None
  1874. last_data = None
  1875. last_solid_geometry = []
  1876. if dia is not None:
  1877. tooldia = dia
  1878. else:
  1879. tooldia = self.ui.addtool_entry.get_value()
  1880. if tooldia is None:
  1881. self.build_ui()
  1882. self.app.inform.emit("[error_notcl] Please enter the desired tool diameter in Float format.")
  1883. return
  1884. # construct a list of all 'tooluid' in the self.tools
  1885. tool_uid_list = []
  1886. for tooluid_key in self.tools:
  1887. tool_uid_item = int(tooluid_key)
  1888. tool_uid_list.append(tool_uid_item)
  1889. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1890. if not tool_uid_list:
  1891. max_uid = 0
  1892. else:
  1893. max_uid = max(tool_uid_list)
  1894. self.tooluid = max_uid + 1
  1895. if self.units == 'IN':
  1896. tooldia = float('%.4f' % tooldia)
  1897. else:
  1898. tooldia = float('%.2f' % tooldia)
  1899. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  1900. # otherwise we add a tool with data copied from last tool
  1901. if not self.tools:
  1902. self.tools.update({
  1903. self.tooluid: {
  1904. 'tooldia': tooldia,
  1905. 'offset': 'Path',
  1906. 'offset_value': 0.0,
  1907. 'type': 'Rough',
  1908. 'tool_type': 'C1',
  1909. 'data': dict(self.default_data),
  1910. 'solid_geometry': []
  1911. }
  1912. })
  1913. else:
  1914. # print("LAST", self.tools[maxuid])
  1915. last_data = self.tools[max_uid]['data']
  1916. last_offset = self.tools[max_uid]['offset']
  1917. last_offset_value = self.tools[max_uid]['offset_value']
  1918. last_type = self.tools[max_uid]['type']
  1919. last_tool_type = self.tools[max_uid]['tool_type']
  1920. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  1921. self.tools.update({
  1922. self.tooluid: {
  1923. 'tooldia': tooldia,
  1924. 'offset': last_offset,
  1925. 'offset_value': last_offset_value,
  1926. 'type': last_type,
  1927. 'tool_type': last_tool_type,
  1928. 'data': dict(last_data),
  1929. 'solid_geometry': deepcopy(last_solid_geometry)
  1930. }
  1931. })
  1932. # print("CURRENT", self.tools[-1])
  1933. self.ui.tool_offset_entry.hide()
  1934. self.ui.tool_offset_lbl.hide()
  1935. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  1936. try:
  1937. self.ser_attrs.remove('tools')
  1938. except:
  1939. pass
  1940. self.ser_attrs.append('tools')
  1941. self.app.inform.emit("[success] Tool added in Tool Table.")
  1942. self.build_ui()
  1943. def on_tool_copy(self, all=None):
  1944. self.ui_disconnect()
  1945. # find the tool_uid maximum value in the self.tools
  1946. uid_list = []
  1947. for key in self.tools:
  1948. uid_list.append(int(key))
  1949. try:
  1950. max_uid = max(uid_list, key=int)
  1951. except ValueError:
  1952. max_uid = 0
  1953. if all is None:
  1954. if self.ui.geo_tools_table.selectedItems():
  1955. for current_row in self.ui.geo_tools_table.selectedItems():
  1956. # sometime the header get selected and it has row number -1
  1957. # we don't want to do anything with the header :)
  1958. if current_row.row() < 0:
  1959. continue
  1960. try:
  1961. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1962. self.set_tool_offset_visibility(current_row.row())
  1963. max_uid += 1
  1964. self.tools[int(max_uid)] = dict(self.tools[tooluid_copy])
  1965. except AttributeError:
  1966. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  1967. self.build_ui()
  1968. return
  1969. except Exception as e:
  1970. log.debug("on_tool_copy() --> " + str(e))
  1971. # deselect the table
  1972. # self.ui.geo_tools_table.clearSelection()
  1973. else:
  1974. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  1975. self.build_ui()
  1976. return
  1977. else:
  1978. # we copy all tools in geo_tools_table
  1979. try:
  1980. temp_tools = dict(self.tools)
  1981. max_uid += 1
  1982. for tooluid in temp_tools:
  1983. self.tools[int(max_uid)] = dict(temp_tools[tooluid])
  1984. temp_tools.clear()
  1985. except Exception as e:
  1986. log.debug("on_tool_copy() --> " + str(e))
  1987. # if there are no more tools in geo tools table then hide the tool offset
  1988. if not self.tools:
  1989. self.ui.tool_offset_entry.hide()
  1990. self.ui.tool_offset_lbl.hide()
  1991. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  1992. try:
  1993. self.ser_attrs.remove('tools')
  1994. except:
  1995. pass
  1996. self.ser_attrs.append('tools')
  1997. self.build_ui()
  1998. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  1999. def on_tool_edit(self, current_item):
  2000. self.ui_disconnect()
  2001. current_row = current_item.row()
  2002. tool_dia = float('%.4f' % float(self.ui.geo_tools_table.item(current_row, 1).text()))
  2003. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2004. self.tools[tooluid]['tooldia'] = tool_dia
  2005. try:
  2006. self.ser_attrs.remove('tools')
  2007. self.ser_attrs.append('tools')
  2008. except:
  2009. pass
  2010. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2011. self.build_ui()
  2012. def on_tool_delete(self, all=None):
  2013. self.ui_disconnect()
  2014. if all is None:
  2015. if self.ui.geo_tools_table.selectedItems():
  2016. for current_row in self.ui.geo_tools_table.selectedItems():
  2017. # sometime the header get selected and it has row number -1
  2018. # we don't want to do anything with the header :)
  2019. if current_row.row() < 0:
  2020. continue
  2021. try:
  2022. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2023. self.set_tool_offset_visibility(current_row.row())
  2024. temp_tools = dict(self.tools)
  2025. for tooluid_key in self.tools:
  2026. if int(tooluid_key) == tooluid_del:
  2027. temp_tools.pop(tooluid_del, None)
  2028. self.tools = dict(temp_tools)
  2029. temp_tools.clear()
  2030. except AttributeError:
  2031. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2032. self.build_ui()
  2033. return
  2034. except Exception as e:
  2035. log.debug("on_tool_delete() --> " + str(e))
  2036. # deselect the table
  2037. # self.ui.geo_tools_table.clearSelection()
  2038. else:
  2039. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2040. self.build_ui()
  2041. return
  2042. else:
  2043. # we delete all tools in geo_tools_table
  2044. self.tools.clear()
  2045. self.app.plot_all()
  2046. # if there are no more tools in geo tools table then hide the tool offset
  2047. if not self.tools:
  2048. self.ui.tool_offset_entry.hide()
  2049. self.ui.tool_offset_lbl.hide()
  2050. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2051. try:
  2052. self.ser_attrs.remove('tools')
  2053. except:
  2054. pass
  2055. self.ser_attrs.append('tools')
  2056. self.build_ui()
  2057. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2058. obj_active = self.app.collection.get_active()
  2059. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2060. # we make it back SingleGeo
  2061. if self.ui.geo_tools_table.rowCount() <= 0:
  2062. obj_active.multigeo = False
  2063. obj_active.options['xmin'] = 0
  2064. obj_active.options['ymin'] = 0
  2065. obj_active.options['xmax'] = 0
  2066. obj_active.options['ymax'] = 0
  2067. if obj_active.multigeo is True:
  2068. try:
  2069. xmin, ymin, xmax, ymax = obj_active.bounds()
  2070. obj_active.options['xmin'] = xmin
  2071. obj_active.options['ymin'] = ymin
  2072. obj_active.options['xmax'] = xmax
  2073. obj_active.options['ymax'] = ymax
  2074. except:
  2075. obj_active.options['xmin'] = 0
  2076. obj_active.options['ymin'] = 0
  2077. obj_active.options['xmax'] = 0
  2078. obj_active.options['ymax'] = 0
  2079. def on_row_selection_change(self):
  2080. self.update_ui()
  2081. def update_ui(self, row=None):
  2082. self.ui_disconnect()
  2083. if row is None:
  2084. try:
  2085. current_row = self.ui.geo_tools_table.currentRow()
  2086. except:
  2087. current_row = 0
  2088. else:
  2089. current_row = row
  2090. if current_row < 0:
  2091. current_row = 0
  2092. self.set_tool_offset_visibility(current_row)
  2093. # populate the form with the data from the tool associated with the row parameter
  2094. try:
  2095. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2096. except Exception as e:
  2097. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2098. return
  2099. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2100. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2101. try:
  2102. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2103. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2104. except Exception as e:
  2105. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2106. return
  2107. try:
  2108. # set the form with data from the newly selected tool
  2109. for tooluid_key, tooluid_value in self.tools.items():
  2110. if int(tooluid_key) == tooluid:
  2111. for key, value in tooluid_value.items():
  2112. if key == 'data':
  2113. form_value_storage = tooluid_value[key]
  2114. self.update_form(form_value_storage)
  2115. if key == 'offset_value':
  2116. # update the offset value in the entry even if the entry is hidden
  2117. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2118. if key == 'tool_type' and value == 'V':
  2119. self.update_cutz()
  2120. except Exception as e:
  2121. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2122. self.ui_connect()
  2123. def ui_update_v_shape(self, tool_type_txt):
  2124. if tool_type_txt == 'V':
  2125. self.ui.tipdialabel.show()
  2126. self.ui.tipdia_entry.show()
  2127. self.ui.tipanglelabel.show()
  2128. self.ui.tipangle_entry.show()
  2129. self.ui.cutz_entry.setDisabled(True)
  2130. self.update_cutz()
  2131. else:
  2132. self.ui.tipdialabel.hide()
  2133. self.ui.tipdia_entry.hide()
  2134. self.ui.tipanglelabel.hide()
  2135. self.ui.tipangle_entry.hide()
  2136. self.ui.cutz_entry.setDisabled(False)
  2137. def update_cutz(self):
  2138. vdia = float(self.ui.tipdia_entry.get_value())
  2139. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2140. row = self.ui.geo_tools_table.currentRow()
  2141. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2142. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2143. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2144. new_cutz = float('%.4f' % -new_cutz)
  2145. self.ui.cutz_entry.set_value(new_cutz)
  2146. # store the new CutZ value into storage (self.tools)
  2147. for tooluid_key, tooluid_value in self.tools.items():
  2148. if int(tooluid_key) == tool_uid:
  2149. tooluid_value['data']['cutz'] = new_cutz
  2150. def on_tooltable_cellwidget_change(self):
  2151. cw = self.sender()
  2152. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2153. cw_row = cw_index.row()
  2154. cw_col = cw_index.column()
  2155. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2156. # store the text of the cellWidget that changed it's index in the self.tools
  2157. for tooluid_key, tooluid_value in self.tools.items():
  2158. if int(tooluid_key) == current_uid:
  2159. cb_txt = cw.currentText()
  2160. if cw_col == 2:
  2161. tooluid_value['offset'] = cb_txt
  2162. if cb_txt == 'Custom':
  2163. self.ui.tool_offset_entry.show()
  2164. self.ui.tool_offset_lbl.show()
  2165. else:
  2166. self.ui.tool_offset_entry.hide()
  2167. self.ui.tool_offset_lbl.hide()
  2168. # reset the offset_value in storage self.tools
  2169. tooluid_value['offset_value'] = 0.0
  2170. elif cw_col == 3:
  2171. # force toolpath type as 'Iso' if the tool type is V-Shape
  2172. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2173. tooluid_value['type'] = 'Iso'
  2174. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2175. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2176. else:
  2177. tooluid_value['type'] = cb_txt
  2178. elif cw_col == 4:
  2179. tooluid_value['tool_type'] = cb_txt
  2180. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2181. if cb_txt == 'V':
  2182. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2183. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2184. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2185. def update_form(self, dict_storage):
  2186. for form_key in self.form_fields:
  2187. for storage_key in dict_storage:
  2188. if form_key == storage_key:
  2189. try:
  2190. self.form_fields[form_key].set_value(dict_storage[form_key])
  2191. except Exception as e:
  2192. log.debug(str(e))
  2193. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2194. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2195. self.ui.ois_dwell_geo.on_cb_change()
  2196. self.ui.ois_mpass_geo.on_cb_change()
  2197. self.ui.ois_tcz_geo.on_cb_change()
  2198. def gui_form_to_storage(self):
  2199. self.ui_disconnect()
  2200. widget_changed = self.sender()
  2201. try:
  2202. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2203. except:
  2204. return
  2205. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2206. if widget_idx == 1 or widget_idx == 3:
  2207. self.update_cutz()
  2208. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2209. # ui_diconnect() so I use this 'hack'
  2210. if isinstance(widget_changed, FCCheckBox):
  2211. if widget_changed.text() == 'Multi-Depth:':
  2212. self.ui.ois_mpass_geo.on_cb_change()
  2213. if widget_changed.text() == 'Tool change':
  2214. self.ui.ois_tcz_geo.on_cb_change()
  2215. if widget_changed.text() == 'Dwell:':
  2216. self.ui.ois_dwell_geo.on_cb_change()
  2217. row = self.ui.geo_tools_table.currentRow()
  2218. if row < 0:
  2219. row = 0
  2220. # store all the data associated with the row parameter to the self.tools storage
  2221. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2222. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2223. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2224. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2225. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2226. offset_value_item = self.ui.tool_offset_entry.get_value()
  2227. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2228. temp_tools = {}
  2229. temp_dia = {}
  2230. temp_data = {}
  2231. for tooluid_key, tooluid_value in self.tools.items():
  2232. if int(tooluid_key) == tooluid_item:
  2233. for key, value in tooluid_value.items():
  2234. if key == 'tooldia':
  2235. temp_dia[key] = tooldia_item
  2236. # update the 'offset', 'type' and 'tool_type' sections
  2237. if key == 'offset':
  2238. temp_dia[key] = offset_item
  2239. if key == 'type':
  2240. temp_dia[key] = type_item
  2241. if key == 'tool_type':
  2242. temp_dia[key] = tool_type_item
  2243. if key == 'offset_value':
  2244. temp_dia[key] = offset_value_item
  2245. if key == 'data':
  2246. # update the 'data' section
  2247. for data_key in tooluid_value[key].keys():
  2248. for form_key, form_value in self.form_fields.items():
  2249. if form_key == data_key:
  2250. temp_data[data_key] = form_value.get_value()
  2251. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2252. # updated from self.app.defaults
  2253. if data_key not in self.form_fields:
  2254. temp_data[data_key] = value[data_key]
  2255. temp_dia[key] = dict(temp_data)
  2256. temp_data.clear()
  2257. if key == 'solid_geometry':
  2258. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2259. temp_tools[tooluid_key] = dict(temp_dia)
  2260. else:
  2261. temp_tools[tooluid_key] = dict(tooluid_value)
  2262. self.tools.clear()
  2263. self.tools = dict(temp_tools)
  2264. temp_tools.clear()
  2265. self.ui_connect()
  2266. def select_tools_table_row(self, row, clearsel=None):
  2267. if clearsel:
  2268. self.ui.geo_tools_table.clearSelection()
  2269. if self.ui.geo_tools_table.rowCount() > 0:
  2270. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2271. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2272. def export_dxf(self):
  2273. units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  2274. dwg = None
  2275. try:
  2276. dwg = ezdxf.new('R2010')
  2277. msp = dwg.modelspace()
  2278. def g2dxf(dxf_space, geo):
  2279. if isinstance(geo, MultiPolygon):
  2280. for poly in geo:
  2281. ext_points = list(poly.exterior.coords)
  2282. dxf_space.add_lwpolyline(ext_points)
  2283. for interior in poly.interiors:
  2284. dxf_space.add_lwpolyline(list(interior.coords))
  2285. if isinstance(geo, Polygon):
  2286. ext_points = list(geo.exterior.coords)
  2287. dxf_space.add_lwpolyline(ext_points)
  2288. for interior in geo.interiors:
  2289. dxf_space.add_lwpolyline(list(interior.coords))
  2290. if isinstance(geo, MultiLineString):
  2291. for line in geo:
  2292. dxf_space.add_lwpolyline(list(line.coords))
  2293. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2294. dxf_space.add_lwpolyline(list(geo.coords))
  2295. multigeo_solid_geometry = []
  2296. if self.multigeo:
  2297. for tool in self.tools:
  2298. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2299. else:
  2300. multigeo_solid_geometry = self.solid_geometry
  2301. for geo in multigeo_solid_geometry:
  2302. if type(geo) == list:
  2303. for g in geo:
  2304. g2dxf(msp, g)
  2305. else:
  2306. g2dxf(msp, geo)
  2307. # points = FlatCAMGeometry.get_pts(geo)
  2308. # msp.add_lwpolyline(points)
  2309. except Exception as e:
  2310. log.debug(str(e))
  2311. return dwg
  2312. def get_selected_tools_table_items(self):
  2313. """
  2314. Returns a list of lists, each list in the list is made out of row elements
  2315. :return: List of table_tools items.
  2316. :rtype: list
  2317. """
  2318. table_tools_items = []
  2319. for x in self.ui.geo_tools_table.selectedItems():
  2320. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2321. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2322. for item in table_tools_items:
  2323. item[0] = str(item[0])
  2324. return table_tools_items
  2325. def on_pp_changed(self):
  2326. current_pp = self.ui.pp_geometry_name_cb.get_value()
  2327. if current_pp == 'hpgl':
  2328. self.old_pp_state = self.ui.mpass_cb.get_value()
  2329. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  2330. self.ui.mpass_cb.set_value(False)
  2331. self.ui.mpass_cb.setDisabled(True)
  2332. self.ui.toolchangeg_cb.set_value(True)
  2333. self.ui.toolchangeg_cb.setDisabled(True)
  2334. else:
  2335. self.ui.mpass_cb.set_value(self.old_pp_state)
  2336. self.ui.mpass_cb.setDisabled(False)
  2337. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  2338. self.ui.toolchangeg_cb.setDisabled(False)
  2339. def on_generatecnc_button_click(self, *args):
  2340. self.app.report_usage("geometry_on_generatecnc_button")
  2341. self.read_form()
  2342. # test to see if we have tools available in the tool table
  2343. if self.ui.geo_tools_table.selectedItems():
  2344. for x in self.ui.geo_tools_table.selectedItems():
  2345. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  2346. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  2347. for tooluid_key, tooluid_value in self.tools.items():
  2348. if int(tooluid_key) == tooluid:
  2349. self.sel_tools.update({
  2350. tooluid: dict(tooluid_value)
  2351. })
  2352. self.mtool_gen_cncjob()
  2353. self.ui.geo_tools_table.clearSelection()
  2354. else:
  2355. self.app.inform.emit("[error_notcl] Failed. No tool selected in the tool table ...")
  2356. def mtool_gen_cncjob(self, use_thread=True):
  2357. """
  2358. Creates a multi-tool CNCJob out of this Geometry object.
  2359. The actual work is done by the target FlatCAMCNCjob object's
  2360. `generate_from_geometry_2()` method.
  2361. :param z_cut: Cut depth (negative)
  2362. :param z_move: Hight of the tool when travelling (not cutting)
  2363. :param feedrate: Feed rate while cutting on X - Y plane
  2364. :param feedrate_z: Feed rate while cutting on Z plane
  2365. :param feedrate_rapid: Feed rate while moving with rapids
  2366. :param tooldia: Tool diameter
  2367. :param outname: Name of the new object
  2368. :param spindlespeed: Spindle speed (RPM)
  2369. :param ppname_g Name of the postprocessor
  2370. :return: None
  2371. """
  2372. offset_str = ''
  2373. multitool_gcode = ''
  2374. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  2375. outname = "%s_%s" % (self.options["name"], 'cnc')
  2376. # Object initialization function for app.new_object()
  2377. # RUNNING ON SEPARATE THREAD!
  2378. def job_init_single_geometry(job_obj, app_obj):
  2379. assert isinstance(job_obj, FlatCAMCNCjob), \
  2380. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2381. # count the tools
  2382. tool_cnt = 0
  2383. dia_cnc_dict = {}
  2384. # this turn on the FlatCAMCNCJob plot for multiple tools
  2385. job_obj.multitool = True
  2386. job_obj.multigeo = False
  2387. job_obj.cnc_tools.clear()
  2388. # job_obj.create_geometry()
  2389. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  2390. for tooluid_key in self.sel_tools:
  2391. tool_cnt += 1
  2392. app_obj.progress.emit(20)
  2393. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2394. if diadict_key == 'tooldia':
  2395. tooldia_val = float('%.4f' % float(diadict_value))
  2396. dia_cnc_dict.update({
  2397. diadict_key: tooldia_val
  2398. })
  2399. if diadict_key == 'offset':
  2400. o_val = diadict_value.lower()
  2401. dia_cnc_dict.update({
  2402. diadict_key: o_val
  2403. })
  2404. if diadict_key == 'type':
  2405. t_val = diadict_value
  2406. dia_cnc_dict.update({
  2407. diadict_key: t_val
  2408. })
  2409. if diadict_key == 'tool_type':
  2410. tt_val = diadict_value
  2411. dia_cnc_dict.update({
  2412. diadict_key: tt_val
  2413. })
  2414. if diadict_key == 'data':
  2415. for data_key, data_value in diadict_value.items():
  2416. if data_key == "multidepth":
  2417. multidepth = data_value
  2418. if data_key == "depthperpass":
  2419. depthpercut = data_value
  2420. if data_key == "extracut":
  2421. extracut = data_value
  2422. if data_key == "startz":
  2423. startz = data_value
  2424. if data_key == "endz":
  2425. endz = data_value
  2426. if data_key == "toolchangez":
  2427. toolchangez =data_value
  2428. if data_key == "toolchangexy":
  2429. toolchangexy = data_value
  2430. if data_key == "toolchange":
  2431. toolchange = data_value
  2432. if data_key == "cutz":
  2433. z_cut = data_value
  2434. if data_key == "travelz":
  2435. z_move = data_value
  2436. if data_key == "feedrate":
  2437. feedrate = data_value
  2438. if data_key == "feedrate_z":
  2439. feedrate_z = data_value
  2440. if data_key == "feedrate_rapid":
  2441. feedrate_rapid = data_value
  2442. if data_key == "ppname_g":
  2443. pp_geometry_name = data_value
  2444. if data_key == "spindlespeed":
  2445. spindlespeed = data_value
  2446. if data_key == "dwell":
  2447. dwell = data_value
  2448. if data_key == "dwelltime":
  2449. dwelltime = data_value
  2450. datadict = dict(diadict_value)
  2451. dia_cnc_dict.update({
  2452. diadict_key: datadict
  2453. })
  2454. if dia_cnc_dict['offset'] == 'in':
  2455. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2456. offset_str = 'inside'
  2457. elif dia_cnc_dict['offset'].lower() == 'out':
  2458. tool_offset = dia_cnc_dict['tooldia'] / 2
  2459. offset_str = 'outside'
  2460. elif dia_cnc_dict['offset'].lower() == 'path':
  2461. offset_str = 'onpath'
  2462. tool_offset = 0.0
  2463. else:
  2464. offset_str = 'custom'
  2465. offset_value = self.ui.tool_offset_entry.get_value()
  2466. if offset_value:
  2467. tool_offset = float(offset_value)
  2468. else:
  2469. self.app.inform.emit(
  2470. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2471. "Add a Tool Offset or change the Offset Type."
  2472. )
  2473. return
  2474. dia_cnc_dict.update({
  2475. 'offset_value': tool_offset
  2476. })
  2477. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2478. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2479. # Propagate options
  2480. job_obj.options["tooldia"] = tooldia_val
  2481. job_obj.options['type'] = 'Geometry'
  2482. job_obj.options['tool_dia'] = tooldia_val
  2483. app_obj.progress.emit(40)
  2484. dia_cnc_dict['gcode'] = job_obj.generate_from_geometry_2(
  2485. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  2486. z_cut=z_cut, z_move=z_move,
  2487. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2488. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2489. multidepth=multidepth, depthpercut=depthpercut,
  2490. extracut=extracut, startz=startz, endz=endz,
  2491. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2492. pp_geometry_name=pp_geometry_name,
  2493. tool_no=tool_cnt)
  2494. app_obj.progress.emit(50)
  2495. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2496. # object is the source of gcode
  2497. job_obj.toolchange_xy = "geometry"
  2498. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2499. # TODO this serve for bounding box creation only; should be optimized
  2500. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2501. app_obj.progress.emit(80)
  2502. job_obj.cnc_tools.update({
  2503. tooluid_key: dict(dia_cnc_dict)
  2504. })
  2505. dia_cnc_dict.clear()
  2506. # Object initialization function for app.new_object()
  2507. # RUNNING ON SEPARATE THREAD!
  2508. def job_init_multi_geometry(job_obj, app_obj):
  2509. assert isinstance(job_obj, FlatCAMCNCjob), \
  2510. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2511. # count the tools
  2512. tool_cnt = 0
  2513. dia_cnc_dict = {}
  2514. current_uid = int(1)
  2515. # this turn on the FlatCAMCNCJob plot for multiple tools
  2516. job_obj.multitool = True
  2517. job_obj.multigeo = True
  2518. job_obj.cnc_tools.clear()
  2519. for tooluid_key in self.sel_tools:
  2520. tool_cnt += 1
  2521. app_obj.progress.emit(20)
  2522. # find the tool_dia associated with the tooluid_key
  2523. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  2524. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  2525. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  2526. for k, v in self.tools.items():
  2527. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  2528. current_uid = int(k)
  2529. break
  2530. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2531. if diadict_key == 'tooldia':
  2532. tooldia_val = float('%.4f' % float(diadict_value))
  2533. dia_cnc_dict.update({
  2534. diadict_key: tooldia_val
  2535. })
  2536. if diadict_key == 'offset':
  2537. o_val = diadict_value.lower()
  2538. dia_cnc_dict.update({
  2539. diadict_key: o_val
  2540. })
  2541. if diadict_key == 'type':
  2542. t_val = diadict_value
  2543. dia_cnc_dict.update({
  2544. diadict_key: t_val
  2545. })
  2546. if diadict_key == 'tool_type':
  2547. tt_val = diadict_value
  2548. dia_cnc_dict.update({
  2549. diadict_key: tt_val
  2550. })
  2551. if diadict_key == 'data':
  2552. for data_key, data_value in diadict_value.items():
  2553. if data_key == "multidepth":
  2554. multidepth = data_value
  2555. if data_key == "depthperpass":
  2556. depthpercut = data_value
  2557. if data_key == "extracut":
  2558. extracut = data_value
  2559. if data_key == "startz":
  2560. startz = data_value
  2561. if data_key == "endz":
  2562. endz = data_value
  2563. if data_key == "toolchangez":
  2564. toolchangez =data_value
  2565. if data_key == "toolchangexy":
  2566. toolchangexy = data_value
  2567. if data_key == "toolchange":
  2568. toolchange = data_value
  2569. if data_key == "cutz":
  2570. z_cut = data_value
  2571. if data_key == "travelz":
  2572. z_move = data_value
  2573. if data_key == "feedrate":
  2574. feedrate = data_value
  2575. if data_key == "feedrate_z":
  2576. feedrate_z = data_value
  2577. if data_key == "feedrate_rapid":
  2578. feedrate_rapid = data_value
  2579. if data_key == "ppname_g":
  2580. pp_geometry_name = data_value
  2581. if data_key == "spindlespeed":
  2582. spindlespeed = data_value
  2583. if data_key == "dwell":
  2584. dwell = data_value
  2585. if data_key == "dwelltime":
  2586. dwelltime = data_value
  2587. datadict = dict(diadict_value)
  2588. dia_cnc_dict.update({
  2589. diadict_key: datadict
  2590. })
  2591. if dia_cnc_dict['offset'] == 'in':
  2592. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2593. offset_str = 'inside'
  2594. elif dia_cnc_dict['offset'].lower() == 'out':
  2595. tool_offset = dia_cnc_dict['tooldia'] / 2
  2596. offset_str = 'outside'
  2597. elif dia_cnc_dict['offset'].lower() == 'path':
  2598. offset_str = 'onpath'
  2599. tool_offset = 0.0
  2600. else:
  2601. offset_str = 'custom'
  2602. offset_value = self.ui.tool_offset_entry.get_value()
  2603. if offset_value:
  2604. tool_offset = float(offset_value)
  2605. else:
  2606. self.app.inform.emit(
  2607. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2608. "Add a Tool Offset or change the Offset Type."
  2609. )
  2610. return
  2611. dia_cnc_dict.update({
  2612. 'offset_value': tool_offset
  2613. })
  2614. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2615. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2616. # Propagate options
  2617. job_obj.options["tooldia"] = tooldia_val
  2618. job_obj.options['type'] = 'Geometry'
  2619. job_obj.options['tool_dia'] = tooldia_val
  2620. app_obj.progress.emit(40)
  2621. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  2622. dia_cnc_dict['gcode'] = job_obj.generate_from_multitool_geometry(
  2623. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  2624. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  2625. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2626. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2627. multidepth=multidepth, depthpercut=depthpercut,
  2628. extracut=extracut, startz=startz, endz=endz,
  2629. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2630. pp_geometry_name=pp_geometry_name,
  2631. tool_no=tool_cnt)
  2632. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2633. # TODO this serve for bounding box creation only; should be optimized
  2634. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2635. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2636. # object is the source of gcode
  2637. job_obj.toolchange_xy = "geometry"
  2638. app_obj.progress.emit(80)
  2639. job_obj.cnc_tools.update({
  2640. tooluid_key: dict(dia_cnc_dict)
  2641. })
  2642. dia_cnc_dict.clear()
  2643. if use_thread:
  2644. # To be run in separate thread
  2645. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  2646. # separate solid_geometry in the self.tools dictionary
  2647. def job_thread(app_obj):
  2648. if self.solid_geometry:
  2649. with self.app.proc_container.new("Generating CNC Code"):
  2650. app_obj.new_object("cncjob", outname, job_init_single_geometry)
  2651. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2652. app_obj.progress.emit(100)
  2653. else:
  2654. with self.app.proc_container.new("Generating CNC Code"):
  2655. app_obj.new_object("cncjob", outname, job_init_multi_geometry)
  2656. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2657. app_obj.progress.emit(100)
  2658. # Create a promise with the name
  2659. self.app.collection.promise(outname)
  2660. # Send to worker
  2661. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2662. else:
  2663. if self.solid_geometry:
  2664. self.app.new_object("cncjob", outname, job_init_single_geometry)
  2665. else:
  2666. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  2667. def generatecncjob(self, outname=None,
  2668. tooldia=None, offset=None,
  2669. z_cut=None, z_move=None,
  2670. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  2671. spindlespeed=None, dwell=None, dwelltime=None,
  2672. multidepth=None, depthperpass=None,
  2673. toolchange=None, toolchangez=None, toolchangexy=None,
  2674. extracut=None, startz=None, endz=None,
  2675. ppname_g=None,
  2676. use_thread=True):
  2677. """
  2678. Only used for TCL Command.
  2679. Creates a CNCJob out of this Geometry object. The actual
  2680. work is done by the target FlatCAMCNCjob object's
  2681. `generate_from_geometry_2()` method.
  2682. :param z_cut: Cut depth (negative)
  2683. :param z_move: Hight of the tool when travelling (not cutting)
  2684. :param feedrate: Feed rate while cutting on X - Y plane
  2685. :param feedrate_z: Feed rate while cutting on Z plane
  2686. :param feedrate_rapid: Feed rate while moving with rapids
  2687. :param tooldia: Tool diameter
  2688. :param outname: Name of the new object
  2689. :param spindlespeed: Spindle speed (RPM)
  2690. :param ppname_g Name of the postprocessor
  2691. :return: None
  2692. """
  2693. tooldia = tooldia if tooldia else self.options["cnctooldia"]
  2694. outname = outname if outname is not None else self.options["name"]
  2695. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  2696. z_move = z_move if z_move is not None else self.options["travelz"]
  2697. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  2698. feedrate_z = feedrate_z if feedrate_z is not None else self.options["feedrate_z"]
  2699. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else self.options["feedrate_rapid"]
  2700. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  2701. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  2702. extracut = extracut if extracut is not None else self.options["extracut"]
  2703. startz = startz if startz is not None else self.options["startz"]
  2704. endz = endz if endz is not None else self.options["endz"]
  2705. toolchangez = toolchangez if toolchangez else self.options["toolchangez"]
  2706. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  2707. toolchange = toolchange if toolchange else self.options["toolchange"]
  2708. offset = offset if offset else 0.0
  2709. # int or None.
  2710. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  2711. dwell = dwell if dwell else self.options["dwell"]
  2712. dwelltime = dwelltime if dwelltime else self.options["dwelltime"]
  2713. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  2714. # Object initialization function for app.new_object()
  2715. # RUNNING ON SEPARATE THREAD!
  2716. def job_init(job_obj, app_obj):
  2717. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2718. # Propagate options
  2719. job_obj.options["tooldia"] = tooldia
  2720. app_obj.progress.emit(20)
  2721. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2722. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2723. app_obj.progress.emit(40)
  2724. job_obj.options['type'] = 'Geometry'
  2725. job_obj.options['tool_dia'] = tooldia
  2726. # TODO: The tolerance should not be hard coded. Just for testing.
  2727. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  2728. z_cut=z_cut, z_move=z_move,
  2729. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2730. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2731. multidepth=multidepth, depthpercut=depthperpass,
  2732. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2733. extracut=extracut, startz=startz, endz=endz,
  2734. pp_geometry_name=ppname_g
  2735. )
  2736. app_obj.progress.emit(50)
  2737. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  2738. # source of gcode
  2739. job_obj.toolchange_xy = "geometry"
  2740. job_obj.gcode_parse()
  2741. app_obj.progress.emit(80)
  2742. if use_thread:
  2743. # To be run in separate thread
  2744. def job_thread(app_obj):
  2745. with self.app.proc_container.new("Generating CNC Code"):
  2746. app_obj.new_object("cncjob", outname, job_init)
  2747. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2748. app_obj.progress.emit(100)
  2749. # Create a promise with the name
  2750. self.app.collection.promise(outname)
  2751. # Send to worker
  2752. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2753. else:
  2754. self.app.new_object("cncjob", outname, job_init)
  2755. # def on_plot_cb_click(self, *args): # TODO: args not needed
  2756. # if self.muted_ui:
  2757. # return
  2758. # self.read_form_item('plot')
  2759. def scale(self, xfactor, yfactor=None, point=None):
  2760. """
  2761. Scales all geometry by a given factor.
  2762. :param xfactor: Factor by which to scale the object's geometry/
  2763. :type xfactor: float
  2764. :param yfactor: Factor by which to scale the object's geometry/
  2765. :type yfactor: float
  2766. :return: None
  2767. :rtype: None
  2768. """
  2769. if yfactor is None:
  2770. yfactor = xfactor
  2771. if point is None:
  2772. px = 0
  2773. py = 0
  2774. else:
  2775. px, py = point
  2776. if type(self.solid_geometry) == list:
  2777. geo_list = self.flatten(self.solid_geometry)
  2778. self.solid_geometry = []
  2779. # for g in geo_list:
  2780. # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  2781. self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  2782. for g in geo_list]
  2783. else:
  2784. self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  2785. origin=(px, py))
  2786. def offset(self, vect):
  2787. """
  2788. Offsets all geometry by a given vector/
  2789. :param vect: (x, y) vector by which to offset the object's geometry.
  2790. :type vect: tuple
  2791. :return: None
  2792. :rtype: None
  2793. """
  2794. dx, dy = vect
  2795. def translate_recursion(geom):
  2796. if type(geom) == list:
  2797. geoms=list()
  2798. for local_geom in geom:
  2799. geoms.append(translate_recursion(local_geom))
  2800. return geoms
  2801. else:
  2802. return affinity.translate(geom, xoff=dx, yoff=dy)
  2803. if self.multigeo is True:
  2804. for tool in self.tools:
  2805. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  2806. else:
  2807. self.solid_geometry=translate_recursion(self.solid_geometry)
  2808. def convert_units(self, units):
  2809. self.ui_disconnect()
  2810. factor = Geometry.convert_units(self, units)
  2811. self.options['cutz'] *= factor
  2812. self.options['depthperpass'] *= factor
  2813. self.options['travelz'] *= factor
  2814. self.options['feedrate'] *= factor
  2815. self.options['feedrate_z'] *= factor
  2816. self.options['feedrate_rapid'] *= factor
  2817. self.options['endz'] *= factor
  2818. # self.options['cnctooldia'] *= factor
  2819. self.options['painttooldia'] *= factor
  2820. self.options['paintmargin'] *= factor
  2821. self.options['paintoverlap'] *= factor
  2822. self.options["toolchangez"] *= factor
  2823. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  2824. coords_xy[0] *= factor
  2825. coords_xy[1] *= factor
  2826. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2827. if self.options['startz'] is not None:
  2828. self.options['startz'] *= factor
  2829. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2830. 'endz', 'toolchangez']
  2831. temp_tools_dict = {}
  2832. tool_dia_copy = {}
  2833. data_copy = {}
  2834. for tooluid_key, tooluid_value in self.tools.items():
  2835. for dia_key, dia_value in tooluid_value.items():
  2836. if dia_key == 'tooldia':
  2837. dia_value *= factor
  2838. dia_value = float('%.4f' % dia_value)
  2839. tool_dia_copy[dia_key] = dia_value
  2840. if dia_key == 'offset':
  2841. tool_dia_copy[dia_key] = dia_value
  2842. if dia_key == 'offset_value':
  2843. dia_value *= factor
  2844. tool_dia_copy[dia_key] = dia_value
  2845. # convert the value in the Custom Tool Offset entry in UI
  2846. custom_offset = self.ui.tool_offset_entry.get_value()
  2847. if custom_offset:
  2848. custom_offset *= factor
  2849. self.ui.tool_offset_entry.set_value(custom_offset)
  2850. if dia_key == 'type':
  2851. tool_dia_copy[dia_key] = dia_value
  2852. if dia_key == 'tool_type':
  2853. tool_dia_copy[dia_key] = dia_value
  2854. if dia_key == 'data':
  2855. for data_key, data_value in dia_value.items():
  2856. # convert the form fields that are convertible
  2857. for param in param_list:
  2858. if data_key == param and data_value is not None:
  2859. data_copy[data_key] = data_value * factor
  2860. # copy the other dict entries that are not convertible
  2861. if data_key not in param_list:
  2862. data_copy[data_key] = data_value
  2863. tool_dia_copy[dia_key] = dict(data_copy)
  2864. data_copy.clear()
  2865. temp_tools_dict.update({
  2866. tooluid_key: dict(tool_dia_copy)
  2867. })
  2868. tool_dia_copy.clear()
  2869. self.tools.clear()
  2870. self.tools = dict(temp_tools_dict)
  2871. # if there is a value in the new tool field then convert that one too
  2872. tooldia = self.ui.addtool_entry.get_value()
  2873. if tooldia:
  2874. tooldia *= factor
  2875. # limit the decimals to 2 for METRIC and 3 for INCH
  2876. if units.lower() == 'in':
  2877. tooldia = float('%.4f' % tooldia)
  2878. else:
  2879. tooldia = float('%.2f' % tooldia)
  2880. self.ui.addtool_entry.set_value(tooldia)
  2881. return factor
  2882. def plot_element(self, element, color='red', visible=None):
  2883. visible = visible if visible else self.options['plot']
  2884. try:
  2885. for sub_el in element:
  2886. self.plot_element(sub_el)
  2887. except TypeError: # Element is not iterable...
  2888. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2889. def plot(self, visible=None):
  2890. """
  2891. Adds the object into collection.
  2892. :return: None
  2893. """
  2894. # Does all the required setup and returns False
  2895. # if the 'ptint' option is set to False.
  2896. if not FlatCAMObj.plot(self):
  2897. return
  2898. try:
  2899. # plot solid geometries found as members of self.tools attribute dict
  2900. # for MultiGeo
  2901. if self.multigeo == True: # geo multi tool usage
  2902. for tooluid_key in self.tools:
  2903. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2904. self.plot_element(solid_geometry, visible=visible)
  2905. # plot solid geometry that may be an direct attribute of the geometry object
  2906. # for SingleGeo
  2907. if self.solid_geometry:
  2908. self.plot_element(self.solid_geometry, visible=visible)
  2909. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  2910. self.shapes.redraw()
  2911. except (ObjectDeleted, AttributeError):
  2912. self.shapes.clear(update=True)
  2913. def on_plot_cb_click(self, *args):
  2914. if self.muted_ui:
  2915. return
  2916. self.plot()
  2917. self.read_form_item('plot')
  2918. self.ui_disconnect()
  2919. cb_flag = self.ui.plot_cb.isChecked()
  2920. for row in range(self.ui.geo_tools_table.rowCount()):
  2921. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  2922. if cb_flag:
  2923. table_cb.setChecked(True)
  2924. else:
  2925. table_cb.setChecked(False)
  2926. self.ui_connect()
  2927. def on_plot_cb_click_table(self):
  2928. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2929. self.ui_disconnect()
  2930. cw = self.sender()
  2931. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2932. cw_row = cw_index.row()
  2933. check_row = 0
  2934. self.shapes.clear(update=True)
  2935. for tooluid_key in self.tools:
  2936. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2937. # find the geo_tool_table row associated with the tooluid_key
  2938. for row in range(self.ui.geo_tools_table.rowCount()):
  2939. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2940. if tooluid_item == int(tooluid_key):
  2941. check_row = row
  2942. break
  2943. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  2944. self.plot_element(element=solid_geometry, visible=True)
  2945. self.shapes.redraw()
  2946. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2947. # if all the row plot's are enabled also enable the general plot checkbox
  2948. cb_cnt = 0
  2949. total_row = self.ui.geo_tools_table.rowCount()
  2950. for row in range(total_row):
  2951. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  2952. cb_cnt += 1
  2953. else:
  2954. cb_cnt -= 1
  2955. if cb_cnt < total_row:
  2956. self.ui.plot_cb.setChecked(False)
  2957. else:
  2958. self.ui.plot_cb.setChecked(True)
  2959. self.ui_connect()
  2960. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  2961. """
  2962. Represents G-Code.
  2963. """
  2964. optionChanged = QtCore.pyqtSignal(str)
  2965. ui_type = CNCObjectUI
  2966. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  2967. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  2968. spindlespeed=None):
  2969. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  2970. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  2971. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  2972. spindlespeed=spindlespeed, steps_per_circle=self.app.defaults["cncjob_steps_per_circle"])
  2973. FlatCAMObj.__init__(self, name)
  2974. self.kind = "cncjob"
  2975. self.options.update({
  2976. "plot": True,
  2977. "tooldia": 0.03937, # 0.4mm in inches
  2978. "append": "",
  2979. "prepend": "",
  2980. "dwell": False,
  2981. "dwelltime": 1,
  2982. "type": 'Geometry'
  2983. })
  2984. '''
  2985. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  2986. diameter of the tools and the value is another dict that will hold the data under the following form:
  2987. {tooldia: {
  2988. 'tooluid': 1,
  2989. 'offset': 'Path',
  2990. 'type_item': 'Rough',
  2991. 'tool_type': 'C1',
  2992. 'data': {} # a dict to hold the parameters
  2993. 'gcode': "" # a string with the actual GCODE
  2994. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  2995. 'solid_geometry': []
  2996. },
  2997. ...
  2998. }
  2999. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3000. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3001. '''
  3002. self.cnc_tools = {}
  3003. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3004. # (like the one in the TCL Command), False
  3005. self.multitool = False
  3006. # used for parsing the GCode lines to adjust the offset when the GCode was offseted
  3007. offsetx_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3008. self.g_offsetx_re = re.compile(offsetx_re_string)
  3009. offsety_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3010. self.g_offsety_re = re.compile(offsety_re_string)
  3011. # Attributes to be included in serialization
  3012. # Always append to it because it carries contents
  3013. # from predecessors.
  3014. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3015. self.annotation = self.app.plotcanvas.new_text_group()
  3016. def build_ui(self):
  3017. self.ui_disconnect()
  3018. FlatCAMObj.build_ui(self)
  3019. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3020. if self.cnc_tools:
  3021. self.ui.cnc_tools_table.show()
  3022. self.ui.plot_options_label.show()
  3023. else:
  3024. self.ui.cnc_tools_table.hide()
  3025. self.ui.plot_options_label.hide()
  3026. offset = 0
  3027. tool_idx = 0
  3028. n = len(self.cnc_tools)
  3029. self.ui.cnc_tools_table.setRowCount(n)
  3030. for dia_key, dia_value in self.cnc_tools.items():
  3031. tool_idx += 1
  3032. row_no = tool_idx - 1
  3033. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3034. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3035. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3036. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3037. # There are no tool bits in MM with more than 2 decimals diameter.
  3038. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3039. if self.units == 'MM':
  3040. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3041. else:
  3042. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3043. offset_txt = list(str(dia_value['offset']))
  3044. offset_txt[0] = offset_txt[0].upper()
  3045. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3046. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3047. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3048. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3049. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3050. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3051. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3052. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3053. # hack so the checkbox stay centered in the table cell
  3054. # used this:
  3055. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3056. # plot_item = QtWidgets.QWidget()
  3057. # checkbox = FCCheckBox()
  3058. # checkbox.setCheckState(QtCore.Qt.Checked)
  3059. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3060. # qhboxlayout.addWidget(checkbox)
  3061. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3062. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3063. plot_item = FCCheckBox()
  3064. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3065. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3066. if self.ui.plot_cb.isChecked():
  3067. plot_item.setChecked(True)
  3068. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3069. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3070. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3071. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3072. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3073. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3074. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3075. # make the diameter column editable
  3076. # for row in range(tool_idx):
  3077. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3078. # QtCore.Qt.ItemIsEnabled)
  3079. for row in range(tool_idx):
  3080. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3081. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3082. self.ui.cnc_tools_table.resizeColumnsToContents()
  3083. self.ui.cnc_tools_table.resizeRowsToContents()
  3084. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3085. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3086. vertical_header.hide()
  3087. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3088. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3089. horizontal_header.setMinimumSectionSize(10)
  3090. horizontal_header.setDefaultSectionSize(70)
  3091. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3092. horizontal_header.resizeSection(0, 20)
  3093. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3094. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3095. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3096. horizontal_header.resizeSection(4, 40)
  3097. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3098. horizontal_header.resizeSection(4, 17)
  3099. # horizontal_header.setStretchLastSection(True)
  3100. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3101. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  3102. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  3103. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  3104. # self.ui.geo_tools_table.setSortingEnabled(True)
  3105. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  3106. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  3107. self.ui_connect()
  3108. def set_ui(self, ui):
  3109. FlatCAMObj.set_ui(self, ui)
  3110. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  3111. assert isinstance(self.ui, CNCObjectUI), \
  3112. "Expected a CNCObjectUI, got %s" % type(self.ui)
  3113. self.form_fields.update({
  3114. "plot": self.ui.plot_cb,
  3115. # "tooldia": self.ui.tooldia_entry,
  3116. "append": self.ui.append_text,
  3117. "prepend": self.ui.prepend_text,
  3118. })
  3119. # Fill form fields only on object create
  3120. self.to_form()
  3121. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  3122. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  3123. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  3124. def ui_connect(self):
  3125. for row in range(self.ui.cnc_tools_table.rowCount()):
  3126. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3127. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3128. def ui_disconnect(self):
  3129. for row in range(self.ui.cnc_tools_table.rowCount()):
  3130. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  3131. try:
  3132. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  3133. except:
  3134. pass
  3135. def on_updateplot_button_click(self, *args):
  3136. """
  3137. Callback for the "Updata Plot" button. Reads the form for updates
  3138. and plots the object.
  3139. """
  3140. self.read_form()
  3141. self.plot()
  3142. def on_exportgcode_button_click(self, *args):
  3143. self.app.report_usage("cncjob_on_exportgcode_button")
  3144. self.read_form()
  3145. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3146. _filter_ = "RML1 Files (*.rol);;" \
  3147. "All Files (*.*)"
  3148. elif 'hpgl' in self.pp_geometry_name:
  3149. _filter_ = "HPGL Files (*.plt);;" \
  3150. "All Files (*.*)"
  3151. else:
  3152. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  3153. "G-Code Files (*.g-code);;All Files (*.*)"
  3154. try:
  3155. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3156. caption="Export Machine Code ...", directory=self.app.get_last_save_folder(), filter=_filter_)[0])
  3157. except TypeError:
  3158. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)[0])
  3159. preamble = str(self.ui.prepend_text.get_value())
  3160. postamble = str(self.ui.append_text.get_value())
  3161. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  3162. self.app.file_saved.emit("gcode", filename)
  3163. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  3164. def on_modifygcode_button_click(self, *args):
  3165. # add the tab if it was closed
  3166. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "CNC Code Editor")
  3167. # delete the absolute and relative position and messages in the infobar
  3168. self.app.ui.position_label.setText("")
  3169. self.app.ui.rel_position_label.setText("")
  3170. # Switch plot_area to CNCJob tab
  3171. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  3172. preamble = str(self.ui.prepend_text.get_value())
  3173. postamble = str(self.ui.append_text.get_value())
  3174. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  3175. # first clear previous text in text editor (if any)
  3176. self.app.ui.code_editor.clear()
  3177. # then append the text from GCode to the text editor
  3178. for line in self.app.gcode_edited:
  3179. proc_line = str(line).strip('\n')
  3180. self.app.ui.code_editor.append(proc_line)
  3181. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3182. self.app.handleTextChanged()
  3183. self.app.ui.show()
  3184. def gcode_header(self):
  3185. log.debug("FlatCAMCNCJob.gcode_header()")
  3186. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3187. marlin = False
  3188. hpgl = False
  3189. try:
  3190. for key in self.cnc_tools:
  3191. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  3192. marlin = True
  3193. break
  3194. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3195. hpgl = True
  3196. break
  3197. except Exception as e:
  3198. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  3199. try:
  3200. for key in self.cnc_tools:
  3201. if self.cnc_tools[key]['data']['ppname_e'] == 'marlin':
  3202. marlin = True
  3203. break
  3204. except:
  3205. pass
  3206. if marlin is True:
  3207. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  3208. (str(self.app.version), str(self.app.version_date)) + '\n'
  3209. gcode += ';Name: ' + str(self.options['name']) + '\n'
  3210. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  3211. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3212. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3213. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  3214. gcode += ';Created on ' + time_str + '\n' + '\n'
  3215. elif hpgl is True:
  3216. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  3217. (str(self.app.version), str(self.app.version_date)) + '";\n'
  3218. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  3219. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  3220. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3221. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3222. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  3223. gcode += 'CO "Created on ' + time_str + '";\n'
  3224. else:
  3225. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  3226. (str(self.app.version), str(self.app.version_date)) + '\n'
  3227. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  3228. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  3229. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3230. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3231. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  3232. gcode += '(Created on ' + time_str + ')\n' + '\n'
  3233. return gcode
  3234. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  3235. gcode = ''
  3236. roland = False
  3237. hpgl = False
  3238. # detect if using Roland postprocessor
  3239. try:
  3240. for key in self.cnc_tools:
  3241. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  3242. roland = True
  3243. break
  3244. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3245. hpgl = True
  3246. break
  3247. except:
  3248. try:
  3249. for key in self.cnc_tools:
  3250. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  3251. roland = True
  3252. break
  3253. except:
  3254. pass
  3255. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  3256. if roland is False and hpgl is False:
  3257. gcode = self.gcode_header()
  3258. # detect if using multi-tool and make the Gcode summation correctly for each case
  3259. if self.multitool is True:
  3260. for tooluid_key in self.cnc_tools:
  3261. for key, value in self.cnc_tools[tooluid_key].items():
  3262. if key == 'gcode':
  3263. gcode += value
  3264. break
  3265. else:
  3266. gcode += self.gcode
  3267. if roland is True:
  3268. g = preamble + gcode + postamble
  3269. elif hpgl is True:
  3270. g = self.gcode_header() + preamble + gcode + postamble
  3271. else:
  3272. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  3273. g_idx = gcode.rfind('G20')
  3274. # if it did not find 'G20' then search for 'G21'
  3275. if g_idx == -1:
  3276. g_idx = gcode.rfind('G21')
  3277. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  3278. if g_idx == -1:
  3279. self.app.inform.emit("[error_notcl] G-code does not have a units code: either G20 or G21")
  3280. return
  3281. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  3282. # lines = StringIO(self.gcode)
  3283. lines = StringIO(g)
  3284. ## Write
  3285. if filename is not None:
  3286. try:
  3287. with open(filename, 'w') as f:
  3288. for line in lines:
  3289. f.write(line)
  3290. except FileNotFoundError:
  3291. self.app.inform.emit("[warning_notcl] No such file or directory")
  3292. return
  3293. elif to_file is False:
  3294. # Just for adding it to the recent files list.
  3295. self.app.file_opened.emit("cncjob", filename)
  3296. self.app.inform.emit("[success] Saved to: " + filename)
  3297. else:
  3298. return lines
  3299. def get_gcode(self, preamble='', postamble=''):
  3300. #we need this to be able get_gcode separatelly for shell command export_gcode
  3301. return preamble + '\n' + self.gcode + "\n" + postamble
  3302. def get_svg(self):
  3303. # we need this to be able get_svg separately for shell command export_svg
  3304. pass
  3305. def on_plot_cb_click(self, *args):
  3306. if self.muted_ui:
  3307. return
  3308. self.plot()
  3309. self.read_form_item('plot')
  3310. self.ui_disconnect()
  3311. cb_flag = self.ui.plot_cb.isChecked()
  3312. for row in range(self.ui.cnc_tools_table.rowCount()):
  3313. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  3314. if cb_flag:
  3315. table_cb.setChecked(True)
  3316. else:
  3317. table_cb.setChecked(False)
  3318. self.ui_connect()
  3319. def on_plot_cb_click_table(self):
  3320. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3321. self.ui_disconnect()
  3322. cw = self.sender()
  3323. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  3324. cw_row = cw_index.row()
  3325. self.shapes.clear(update=True)
  3326. for tooluid_key in self.cnc_tools:
  3327. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3328. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3329. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  3330. if self.ui.cnc_tools_table.cellWidget((tooluid_key - 1), 6).isChecked():
  3331. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  3332. self.shapes.redraw()
  3333. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3334. # if all the row plot's are enabled also enable the general plot checkbox
  3335. cb_cnt = 0
  3336. total_row = self.ui.cnc_tools_table.rowCount()
  3337. for row in range(total_row):
  3338. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  3339. cb_cnt += 1
  3340. else:
  3341. cb_cnt -= 1
  3342. if cb_cnt < total_row:
  3343. self.ui.plot_cb.setChecked(False)
  3344. else:
  3345. self.ui.plot_cb.setChecked(True)
  3346. self.ui_connect()
  3347. def plot(self, visible=None):
  3348. # Does all the required setup and returns False
  3349. # if the 'ptint' option is set to False.
  3350. if not FlatCAMObj.plot(self):
  3351. return
  3352. visible = visible if visible else self.options['plot']
  3353. try:
  3354. if self.multitool is False: # single tool usage
  3355. self.plot2(tooldia=self.options["tooldia"], obj=self, visible=visible)
  3356. else:
  3357. # multiple tools usage
  3358. for tooluid_key in self.cnc_tools:
  3359. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3360. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3361. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed)
  3362. self.shapes.redraw()
  3363. except (ObjectDeleted, AttributeError):
  3364. self.shapes.clear(update=True)
  3365. self.annotation.clear(update=True)
  3366. def convert_units(self, units):
  3367. factor = CNCjob.convert_units(self, units)
  3368. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  3369. self.options["tooldia"] *= factor
  3370. # end of file