FlatCAMObj.py 236 KB

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