FlatCAMObj.py 247 KB

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