FlatCAMObj.py 212 KB

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