FlatCAMObj.py 220 KB

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