FlatCAMObj.py 244 KB

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