FlatCAMObj.py 196 KB

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