FlatCAMObj.py 342 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972
  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. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. import shapely.affinity as affinity
  14. from copy import deepcopy
  15. from copy import copy
  16. from io import StringIO
  17. import traceback
  18. import inspect # TODO: For debugging only.
  19. from datetime import datetime
  20. from flatcamEditors.FlatCAMTextEditor import TextEditor
  21. from flatcamGUI.ObjectUI import *
  22. from FlatCAMCommon import LoudDict
  23. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  24. from flatcamParsers.ParseExcellon import Excellon
  25. from flatcamParsers.ParseGerber import Gerber
  26. from camlib import Geometry, CNCjob
  27. import FlatCAMApp
  28. from flatcamGUI.VisPyVisuals import ShapeCollection
  29. import tkinter as tk
  30. import os, sys, itertools
  31. import ezdxf
  32. import math
  33. import numpy as np
  34. import gettext
  35. import FlatCAMTranslation as fcTranslate
  36. import builtins
  37. fcTranslate.apply_language('strings')
  38. if '_' not in builtins.__dict__:
  39. _ = gettext.gettext
  40. # Interrupts plotting process if FlatCAMObj has been deleted
  41. class ObjectDeleted(Exception):
  42. pass
  43. class ValidationError(Exception):
  44. def __init__(self, message, errors):
  45. super().__init__(message)
  46. self.errors = errors
  47. # #######################################
  48. # # FlatCAMObj ##
  49. # #######################################
  50. class FlatCAMObj(QtCore.QObject):
  51. """
  52. Base type of objects handled in FlatCAM. These become interactive
  53. in the GUI, can be plotted, and their options can be modified
  54. by the user in their respective forms.
  55. """
  56. # Instance of the application to which these are related.
  57. # The app should set this value.
  58. app = None
  59. # signal to plot a single object
  60. plot_single_object = QtCore.pyqtSignal()
  61. def __init__(self, name):
  62. """
  63. Constructor.
  64. :param name: Name of the object given by the user.
  65. :return: FlatCAMObj
  66. """
  67. QtCore.QObject.__init__(self)
  68. # View
  69. self.ui = None
  70. self.options = LoudDict(name=name)
  71. self.options.set_change_callback(self.on_options_change)
  72. self.form_fields = {}
  73. # store here the default data for Geometry Data
  74. self.default_data = {}
  75. # 2D mode
  76. # Axes must exist and be attached to canvas.
  77. self.axes = None
  78. self.kind = None # Override with proper name
  79. if self.app.is_legacy is False:
  80. self.shapes = self.app.plotcanvas.new_shape_group()
  81. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, pool=self.app.pool, layers=2)
  82. else:
  83. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name=name)
  84. self.mark_shapes = dict()
  85. self.item = None # Link with project view item
  86. self.muted_ui = False
  87. self.deleted = False
  88. try:
  89. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  90. self.app.defaults["global_tolerance"] else 0.01
  91. except ValueError:
  92. self._drawing_tolerance = 0.01
  93. self.isHovering = False
  94. self.notHovering = True
  95. # Flag to show if a selection shape is drawn
  96. self.selection_shape_drawn = False
  97. # self.units = 'IN'
  98. self.units = self.app.defaults['units']
  99. self.plot_single_object.connect(self.single_object_plot)
  100. def __del__(self):
  101. pass
  102. def __str__(self):
  103. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  104. def from_dict(self, d):
  105. """
  106. This supersedes ``from_dict`` in derived classes. Derived classes
  107. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  108. ``self.options`` is only updated, not overwritten. This ensures that
  109. options set by the app do not vanish when reading the objects
  110. from a project file.
  111. :param d: Dictionary with attributes to set.
  112. :return: None
  113. """
  114. for attr in self.ser_attrs:
  115. if attr == 'options':
  116. self.options.update(d[attr])
  117. else:
  118. try:
  119. setattr(self, attr, d[attr])
  120. except KeyError:
  121. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  122. "Means that we are loading an old project that don't"
  123. "have all attributes in the latest FlatCAM." % str(attr))
  124. pass
  125. def on_options_change(self, key):
  126. # Update form on programmatically options change
  127. self.set_form_item(key)
  128. # Set object visibility
  129. if key == 'plot':
  130. self.visible = self.options['plot']
  131. self.optionChanged.emit(key)
  132. def set_ui(self, ui):
  133. self.ui = ui
  134. self.form_fields = {"name": self.ui.name_entry}
  135. assert isinstance(self.ui, ObjectUI)
  136. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  137. try:
  138. # it will raise an exception for those FlatCAM objects that do not build UI with the common elements
  139. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  140. except (TypeError, AttributeError):
  141. pass
  142. try:
  143. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  144. except (TypeError, AttributeError):
  145. pass
  146. try:
  147. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  148. except (TypeError, AttributeError):
  149. pass
  150. # Creates problems on focusOut
  151. try:
  152. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  153. except (TypeError, AttributeError):
  154. pass
  155. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  156. def build_ui(self):
  157. """
  158. Sets up the UI/form for this object. Show the UI
  159. in the App.
  160. :return: None
  161. :rtype: None
  162. """
  163. self.muted_ui = True
  164. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  165. try:
  166. # HACK: disconnect the scale entry signal since on focus out event will trigger an undesired scale()
  167. # it seems that the takewidget() does generate a focus out event for the QDoubleSpinbox ...
  168. # and reconnect after the takeWidget() is done
  169. # self.ui.scale_entry.returnPressed.disconnect(self.on_scale_button_click)
  170. self.app.ui.selected_scroll_area.takeWidget()
  171. # self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  172. except Exception as e:
  173. self.app.log.debug("FlatCAMObj.build_ui() --> Nothing to remove: %s" % str(e))
  174. self.app.ui.selected_scroll_area.setWidget(self.ui)
  175. self.muted_ui = False
  176. def on_name_activate(self, silent=None):
  177. old_name = copy(self.options["name"])
  178. new_name = self.ui.name_entry.get_value()
  179. if new_name != old_name:
  180. # update the SHELL auto-completer model data
  181. try:
  182. self.app.myKeywords.remove(old_name)
  183. self.app.myKeywords.append(new_name)
  184. self.app.shell._edit.set_model_data(self.app.myKeywords)
  185. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  186. except Exception as e:
  187. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  188. self.options["name"] = self.ui.name_entry.get_value()
  189. self.default_data["name"] = self.ui.name_entry.get_value()
  190. self.app.collection.update_view()
  191. if silent:
  192. self.app.inform.emit('[success] %s: %s %s: %s' % (
  193. _("Name changed from"), str(old_name), _("to"), str(new_name)
  194. )
  195. )
  196. def on_offset_button_click(self):
  197. self.app.report_usage("obj_on_offset_button")
  198. self.read_form()
  199. vector_val = self.ui.offsetvector_entry.get_value()
  200. def worker_task():
  201. with self.app.proc_container.new(_("Offsetting...")):
  202. self.offset(vector_val)
  203. self.app.proc_container.update_view_text('')
  204. with self.app.proc_container.new('%s...' % _("Plotting")):
  205. self.plot()
  206. self.app.object_changed.emit(self)
  207. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  208. def on_scale_button_click(self):
  209. self.read_form()
  210. try:
  211. factor = float(eval(self.ui.scale_entry.get_value()))
  212. except Exception as e:
  213. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  214. log.debug("FlatCAMObj.on_scale_button_click() -- %s" % str(e))
  215. return
  216. if type(factor) != float:
  217. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  218. # if factor is 1.0 do nothing, there is no point in scaling with a factor of 1.0
  219. if factor == 1.0:
  220. self.app.inform.emit('[success] %s' % _("Scale done."))
  221. return
  222. log.debug("FlatCAMObj.on_scale_button_click()")
  223. def worker_task():
  224. with self.app.proc_container.new(_("Scaling...")):
  225. self.scale(factor)
  226. self.app.inform.emit('[success] %s' % _("Scale done."))
  227. self.app.proc_container.update_view_text('')
  228. with self.app.proc_container.new('%s...' % _("Plotting")):
  229. self.plot()
  230. self.app.object_changed.emit(self)
  231. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  232. def on_skew_button_click(self):
  233. self.app.report_usage("obj_on_skew_button")
  234. self.read_form()
  235. x_angle = self.ui.xangle_entry.get_value()
  236. y_angle = self.ui.yangle_entry.get_value()
  237. def worker_task():
  238. with self.app.proc_container.new(_("Skewing...")):
  239. self.skew(x_angle, y_angle)
  240. self.app.proc_container.update_view_text('')
  241. with self.app.proc_container.new('%s...' % _("Plotting")):
  242. self.plot()
  243. self.app.object_changed.emit(self)
  244. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  245. def to_form(self):
  246. """
  247. Copies options to the UI form.
  248. :return: None
  249. """
  250. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  251. for option in self.options:
  252. try:
  253. self.set_form_item(option)
  254. except Exception:
  255. self.app.log.warning("Unexpected error:", sys.exc_info())
  256. def read_form(self):
  257. """
  258. Reads form into ``self.options``.
  259. :return: None
  260. :rtype: None
  261. """
  262. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  263. for option in self.options:
  264. try:
  265. self.read_form_item(option)
  266. except Exception:
  267. self.app.log.warning("Unexpected error:", sys.exc_info())
  268. def set_form_item(self, option):
  269. """
  270. Copies the specified option to the UI form.
  271. :param option: Name of the option (Key in ``self.options``).
  272. :type option: str
  273. :return: None
  274. """
  275. try:
  276. self.form_fields[option].set_value(self.options[option])
  277. except KeyError:
  278. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  279. pass
  280. def read_form_item(self, option):
  281. """
  282. Reads the specified option from the UI form into ``self.options``.
  283. :param option: Name of the option.
  284. :type option: str
  285. :return: None
  286. """
  287. try:
  288. self.options[option] = self.form_fields[option].get_value()
  289. except KeyError:
  290. pass
  291. # self.app.log.warning("Failed to read option from field: %s" % option)
  292. def plot(self):
  293. """
  294. Plot this object (Extend this method to implement the actual plotting).
  295. Call this in descendants before doing the plotting.
  296. :return: Whether to continue plotting or not depending on the "plot" option.
  297. :rtype: bool
  298. """
  299. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  300. if self.deleted:
  301. return False
  302. self.clear()
  303. return True
  304. def single_object_plot(self):
  305. def plot_task():
  306. with self.app.proc_container.new('%s...' % _("Plotting")):
  307. self.plot()
  308. self.app.object_changed.emit(self)
  309. self.app.worker_task.emit({'fcn': plot_task, 'params': []})
  310. def serialize(self):
  311. """
  312. Returns a representation of the object as a dictionary so
  313. it can be later exported as JSON. Override this method.
  314. :return: Dictionary representing the object
  315. :rtype: dict
  316. """
  317. return
  318. def deserialize(self, obj_dict):
  319. """
  320. Re-builds an object from its serialized version.
  321. :param obj_dict: Dictionary representing a FlatCAMObj
  322. :type obj_dict: dict
  323. :return: None
  324. """
  325. return
  326. def add_shape(self, **kwargs):
  327. if self.deleted:
  328. raise ObjectDeleted()
  329. else:
  330. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  331. return key
  332. def add_mark_shape(self, apid, **kwargs):
  333. if self.deleted:
  334. raise ObjectDeleted()
  335. else:
  336. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, layer=0, **kwargs)
  337. return key
  338. def update_filters(self, last_ext, filter_string):
  339. """
  340. Will modify the filter string that is used when saving a file (a list of file extensions) to have the last
  341. used file extension as the first one in the special string
  342. :param last_ext: the file extension that was last used to save a file
  343. :param filter_string: a key in self.app.defaults that holds a string with the filter from QFileDialog
  344. used when saving a file
  345. :return: None
  346. """
  347. filters = copy(self.app.defaults[filter_string])
  348. filter_list = filters.split(';;')
  349. filter_list_enum_1 = enumerate(filter_list)
  350. # search for the last element in the filters which should always be "All Files (*.*)"
  351. last_elem = ''
  352. for elem in list(filter_list_enum_1):
  353. if '(*.*)' in elem[1]:
  354. last_elem = filter_list.pop(elem[0])
  355. filter_list_enum = enumerate(filter_list)
  356. for elem in list(filter_list_enum):
  357. if '.' + last_ext in elem[1]:
  358. used_ext = filter_list.pop(elem[0])
  359. # sort the extensions back
  360. filter_list.sort(key=lambda x: x.rpartition('.')[2])
  361. # add as a first element the last used extension
  362. filter_list.insert(0, used_ext)
  363. # add back the element that should always be the last (All Files)
  364. filter_list.append(last_elem)
  365. self.app.defaults[filter_string] = ';;'.join(filter_list)
  366. return
  367. @staticmethod
  368. def poly2rings(poly):
  369. return [poly.exterior] + [interior for interior in poly.interiors]
  370. @property
  371. def visible(self):
  372. return self.shapes.visible
  373. @visible.setter
  374. def visible(self, value, threaded=True):
  375. log.debug("FlatCAMObj.visible()")
  376. def worker_task(app_obj):
  377. self.shapes.visible = value
  378. if self.app.is_legacy is False:
  379. # Not all object types has annotations
  380. try:
  381. self.annotation.visible = value
  382. except Exception as e:
  383. pass
  384. if threaded is False:
  385. worker_task(app_obj=self.app)
  386. else:
  387. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  388. @property
  389. def drawing_tolerance(self):
  390. self.units = self.app.defaults['units'].upper()
  391. tol = self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  392. return tol
  393. @drawing_tolerance.setter
  394. def drawing_tolerance(self, value):
  395. self.units = self.app.defaults['units'].upper()
  396. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  397. def clear(self, update=False):
  398. self.shapes.clear(update)
  399. # Not all object types has annotations
  400. try:
  401. self.annotation.clear(update)
  402. except AttributeError:
  403. pass
  404. def delete(self):
  405. # Free resources
  406. del self.ui
  407. del self.options
  408. # Set flag
  409. self.deleted = True
  410. class FlatCAMGerber(FlatCAMObj, Gerber):
  411. """
  412. Represents Gerber code.
  413. """
  414. optionChanged = QtCore.pyqtSignal(str)
  415. replotApertures = QtCore.pyqtSignal()
  416. ui_type = GerberObjectUI
  417. def merge(self, grb_list, grb_final):
  418. """
  419. Merges the geometry of objects in geo_list into
  420. the geometry of geo_final.
  421. :param grb_list: List of FlatCAMGerber Objects to join.
  422. :param grb_final: Destination FlatCAMGeometry object.
  423. :return: None
  424. """
  425. if grb_final.solid_geometry is None:
  426. grb_final.solid_geometry = []
  427. grb_final.follow_geometry = []
  428. if not grb_final.apertures:
  429. grb_final.apertures = {}
  430. if type(grb_final.solid_geometry) is not list:
  431. grb_final.solid_geometry = [grb_final.solid_geometry]
  432. grb_final.follow_geometry = [grb_final.follow_geometry]
  433. for grb in grb_list:
  434. # Expand lists
  435. if type(grb) is list:
  436. FlatCAMGerber.merge(grb, grb_final)
  437. else: # If not list, just append
  438. for option in grb.options:
  439. if option is not 'name':
  440. try:
  441. grb_final.options[option] = grb.options[option]
  442. except KeyError:
  443. log.warning("Failed to copy option.", option)
  444. try:
  445. for geos in grb.solid_geometry:
  446. grb_final.solid_geometry.append(geos)
  447. grb_final.follow_geometry.append(geos)
  448. except TypeError:
  449. grb_final.solid_geometry.append(grb.solid_geometry)
  450. grb_final.follow_geometry.append(grb.solid_geometry)
  451. for ap in grb.apertures:
  452. if ap not in grb_final.apertures:
  453. grb_final.apertures[ap] = grb.apertures[ap]
  454. else:
  455. # create a list of integers out of the grb.apertures keys and find the max of that value
  456. # then, the aperture duplicate is assigned an id value incremented with 1,
  457. # and finally made string because the apertures dict keys are strings
  458. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  459. grb_final.apertures[max_ap] = {}
  460. grb_final.apertures[max_ap]['geometry'] = []
  461. for k, v in grb.apertures[ap].items():
  462. grb_final.apertures[max_ap][k] = deepcopy(v)
  463. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  464. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  465. def __init__(self, name):
  466. self.decimals = self.app.decimals
  467. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  468. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  469. FlatCAMObj.__init__(self, name)
  470. self.kind = "gerber"
  471. # The 'name' is already in self.options from FlatCAMObj
  472. # Automatically updates the UI
  473. self.options.update({
  474. "plot": True,
  475. "multicolored": False,
  476. "solid": False,
  477. "tool_type": 'circular',
  478. "vtipdia": 0.1,
  479. "vtipangle": 30,
  480. "vcutz": -0.05,
  481. "isotooldia": 0.016,
  482. "isopasses": 1,
  483. "isooverlap": 15,
  484. "milling_type": "cl",
  485. "combine_passes": True,
  486. "noncoppermargin": 0.0,
  487. "noncopperrounded": False,
  488. "bboxmargin": 0.0,
  489. "bboxrounded": False,
  490. "aperture_display": False,
  491. "follow": False,
  492. "iso_scope": 'all',
  493. "iso_type": 'full'
  494. })
  495. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  496. self.iso_type = 2
  497. self.multigeo = False
  498. self.follow = False
  499. self.apertures_row = 0
  500. # store the source file here
  501. self.source_file = ""
  502. # list of rows with apertures plotted
  503. self.marked_rows = []
  504. # Mouse events
  505. self.mr = None
  506. self.mm = None
  507. self.mp = None
  508. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  509. self.poly_dict = dict()
  510. # store the status of grid snapping
  511. self.grid_status_memory = None
  512. self.units_found = self.app.defaults['units']
  513. self.fill_color = self.app.defaults['gerber_plot_fill']
  514. self.outline_color = self.app.defaults['gerber_plot_line']
  515. self.alpha_level = 'bf'
  516. # keep track if the UI is built so we don't have to build it every time
  517. self.ui_build = False
  518. # build only once the aperture storage (takes time)
  519. self.build_aperture_storage = False
  520. # Attributes to be included in serialization
  521. # Always append to it because it carries contents
  522. # from predecessors.
  523. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  524. def set_ui(self, ui):
  525. """
  526. Maps options with GUI inputs.
  527. Connects GUI events to methods.
  528. :param ui: GUI object.
  529. :type ui: GerberObjectUI
  530. :return: None
  531. """
  532. FlatCAMObj.set_ui(self, ui)
  533. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  534. self.units = self.app.defaults['units'].upper()
  535. self.replotApertures.connect(self.on_mark_cb_click_table)
  536. self.form_fields.update({
  537. "plot": self.ui.plot_cb,
  538. "multicolored": self.ui.multicolored_cb,
  539. "solid": self.ui.solid_cb,
  540. "tool_type": self.ui.tool_type_radio,
  541. "vtipdia": self.ui.tipdia_spinner,
  542. "vtipangle": self.ui.tipangle_spinner,
  543. "vcutz": self.ui.cutz_spinner,
  544. "isotooldia": self.ui.iso_tool_dia_entry,
  545. "isopasses": self.ui.iso_width_entry,
  546. "isooverlap": self.ui.iso_overlap_entry,
  547. "milling_type": self.ui.milling_type_radio,
  548. "combine_passes": self.ui.combine_passes_cb,
  549. "noncoppermargin": self.ui.noncopper_margin_entry,
  550. "noncopperrounded": self.ui.noncopper_rounded_cb,
  551. "bboxmargin": self.ui.bbmargin_entry,
  552. "bboxrounded": self.ui.bbrounded_cb,
  553. "aperture_display": self.ui.aperture_table_visibility_cb,
  554. "follow": self.ui.follow_cb,
  555. "iso_scope": self.ui.iso_scope_radio,
  556. "iso_type": self.ui.iso_type_radio
  557. })
  558. # Fill form fields only on object create
  559. self.to_form()
  560. assert isinstance(self.ui, GerberObjectUI)
  561. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  562. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  563. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  564. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  565. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  566. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  567. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  568. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  569. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  570. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  571. # set the model for the Area Exception comboboxes
  572. self.ui.obj_combo.setModel(self.app.collection)
  573. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  574. self.ui.obj_combo.setCurrentIndex(1)
  575. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  576. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type_change)
  577. # establish visibility for the GUI elements found in the slot function
  578. self.ui.tool_type_radio.activated_custom.emit(self.options['tool_type'])
  579. # Show/Hide Advanced Options
  580. if self.app.defaults["global_app_level"] == 'b':
  581. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  582. self.options['tool_type'] = 'circular'
  583. self.ui.tool_type_label.hide()
  584. self.ui.tool_type_radio.hide()
  585. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  586. self.ui.tool_type_radio.set_value('circular')
  587. self.ui.tipdialabel.hide()
  588. self.ui.tipdia_spinner.hide()
  589. self.ui.tipanglelabel.hide()
  590. self.ui.tipangle_spinner.hide()
  591. self.ui.cutzlabel.hide()
  592. self.ui.cutz_spinner.hide()
  593. self.ui.apertures_table_label.hide()
  594. self.ui.aperture_table_visibility_cb.hide()
  595. self.ui.milling_type_label.hide()
  596. self.ui.milling_type_radio.hide()
  597. self.ui.iso_type_label.hide()
  598. self.ui.iso_type_radio.hide()
  599. self.ui.follow_cb.hide()
  600. self.ui.except_cb.setChecked(False)
  601. self.ui.except_cb.hide()
  602. else:
  603. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  604. self.ui.tipdia_spinner.valueChanged.connect(self.on_calculate_tooldia)
  605. self.ui.tipangle_spinner.valueChanged.connect(self.on_calculate_tooldia)
  606. self.ui.cutz_spinner.valueChanged.connect(self.on_calculate_tooldia)
  607. if self.app.defaults["gerber_buffering"] == 'no':
  608. self.ui.create_buffer_button.show()
  609. try:
  610. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  611. except TypeError:
  612. pass
  613. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  614. else:
  615. self.ui.create_buffer_button.hide()
  616. # set initial state of the aperture table and associated widgets
  617. self.on_aperture_table_visibility_change()
  618. self.build_ui()
  619. self.units_found = self.app.defaults['units']
  620. def on_calculate_tooldia(self):
  621. try:
  622. tdia = float(self.ui.tipdia_spinner.get_value())
  623. except Exception as e:
  624. return
  625. try:
  626. dang = float(self.ui.tipangle_spinner.get_value())
  627. except Exception as e:
  628. return
  629. try:
  630. cutz = float(self.ui.cutz_spinner.get_value())
  631. except Exception as e:
  632. return
  633. cutz *= -1
  634. if cutz < 0:
  635. cutz *= -1
  636. half_tip_angle = dang / 2
  637. tool_diameter = tdia + (2 * cutz * math.tan(math.radians(half_tip_angle)))
  638. self.ui.iso_tool_dia_entry.set_value(tool_diameter)
  639. def on_type_obj_index_changed(self, index):
  640. obj_type = self.ui.type_obj_combo.currentIndex()
  641. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  642. self.ui.obj_combo.setCurrentIndex(0)
  643. def on_tool_type_change(self, state):
  644. if state == 'circular':
  645. self.ui.tipdialabel.hide()
  646. self.ui.tipdia_spinner.hide()
  647. self.ui.tipanglelabel.hide()
  648. self.ui.tipangle_spinner.hide()
  649. self.ui.cutzlabel.hide()
  650. self.ui.cutz_spinner.hide()
  651. self.ui.iso_tool_dia_entry.setDisabled(False)
  652. # update the value in the self.iso_tool_dia_entry once this is selected
  653. self.ui.iso_tool_dia_entry.set_value(self.options['isotooldia'])
  654. else:
  655. self.ui.tipdialabel.show()
  656. self.ui.tipdia_spinner.show()
  657. self.ui.tipanglelabel.show()
  658. self.ui.tipangle_spinner.show()
  659. self.ui.cutzlabel.show()
  660. self.ui.cutz_spinner.show()
  661. self.ui.iso_tool_dia_entry.setDisabled(True)
  662. # update the value in the self.iso_tool_dia_entry once this is selected
  663. self.on_calculate_tooldia()
  664. def build_ui(self):
  665. FlatCAMObj.build_ui(self)
  666. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  667. self.ui_build = True
  668. try:
  669. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  670. self.ui.apertures_table.itemChanged.disconnect()
  671. except (TypeError, AttributeError):
  672. pass
  673. self.apertures_row = 0
  674. aper_no = self.apertures_row + 1
  675. sort = []
  676. for k, v in list(self.apertures.items()):
  677. sort.append(int(k))
  678. sorted_apertures = sorted(sort)
  679. n = len(sorted_apertures)
  680. self.ui.apertures_table.setRowCount(n)
  681. for ap_code in sorted_apertures:
  682. ap_code = str(ap_code)
  683. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  684. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  685. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  686. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  687. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  688. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  689. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  690. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  691. ap_dim_item = QtWidgets.QTableWidgetItem(
  692. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  693. self.decimals, self.apertures[ap_code]['height']
  694. )
  695. )
  696. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  697. elif str(self.apertures[ap_code]['type']) == 'P':
  698. ap_dim_item = QtWidgets.QTableWidgetItem(
  699. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  700. self.decimals, self.apertures[ap_code]['nVertices'])
  701. )
  702. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  703. else:
  704. ap_dim_item = QtWidgets.QTableWidgetItem('')
  705. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  706. try:
  707. if self.apertures[ap_code]['size'] is not None:
  708. ap_size_item = QtWidgets.QTableWidgetItem(
  709. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  710. else:
  711. ap_size_item = QtWidgets.QTableWidgetItem('')
  712. except KeyError:
  713. ap_size_item = QtWidgets.QTableWidgetItem('')
  714. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  715. mark_item = FCCheckBox()
  716. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  717. # if self.ui.aperture_table_visibility_cb.isChecked():
  718. # mark_item.setChecked(True)
  719. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  720. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  721. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  722. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  723. empty_plot_item = QtWidgets.QTableWidgetItem('')
  724. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  725. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  726. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  727. self.apertures_row += 1
  728. self.ui.apertures_table.selectColumn(0)
  729. self.ui.apertures_table.resizeColumnsToContents()
  730. self.ui.apertures_table.resizeRowsToContents()
  731. vertical_header = self.ui.apertures_table.verticalHeader()
  732. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  733. vertical_header.hide()
  734. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  735. horizontal_header = self.ui.apertures_table.horizontalHeader()
  736. horizontal_header.setMinimumSectionSize(10)
  737. horizontal_header.setDefaultSectionSize(70)
  738. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  739. horizontal_header.resizeSection(0, 27)
  740. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  741. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  742. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  743. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  744. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  745. horizontal_header.resizeSection(5, 17)
  746. self.ui.apertures_table.setColumnWidth(5, 17)
  747. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  748. self.ui.apertures_table.setSortingEnabled(False)
  749. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  750. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  751. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  752. if self.marked_rows:
  753. for row in range(self.ui.apertures_table.rowCount()):
  754. try:
  755. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  756. except IndexError:
  757. pass
  758. self.ui_connect()
  759. def ui_connect(self):
  760. for row in range(self.ui.apertures_table.rowCount()):
  761. try:
  762. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  763. except (TypeError, AttributeError):
  764. pass
  765. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  766. try:
  767. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  768. except (TypeError, AttributeError):
  769. pass
  770. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  771. def ui_disconnect(self):
  772. for row in range(self.ui.apertures_table.rowCount()):
  773. try:
  774. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  775. except (TypeError, AttributeError):
  776. pass
  777. try:
  778. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  779. except (TypeError, AttributeError):
  780. pass
  781. def on_generate_buffer(self):
  782. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  783. def buffer_task():
  784. with self.app.proc_container.new('%s...' % _("Buffering")):
  785. if isinstance(self.solid_geometry, list):
  786. self.solid_geometry = MultiPolygon(self.solid_geometry)
  787. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  788. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  789. self.app.inform.emit('[success] %s.' % _("Done"))
  790. self.plot_single_object.emit()
  791. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  792. def on_generatenoncopper_button_click(self, *args):
  793. self.app.report_usage("gerber_on_generatenoncopper_button")
  794. self.read_form()
  795. name = self.options["name"] + "_noncopper"
  796. def geo_init(geo_obj, app_obj):
  797. assert isinstance(geo_obj, FlatCAMGeometry)
  798. if isinstance(self.solid_geometry, list):
  799. try:
  800. self.solid_geometry = MultiPolygon(self.solid_geometry)
  801. except Exception:
  802. self.solid_geometry = cascaded_union(self.solid_geometry)
  803. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  804. if not self.options["noncopperrounded"]:
  805. bounding_box = bounding_box.envelope
  806. non_copper = bounding_box.difference(self.solid_geometry)
  807. if non_copper is None or non_copper.is_empty:
  808. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  809. return "fail"
  810. geo_obj.solid_geometry = non_copper
  811. self.app.new_object("geometry", name, geo_init)
  812. def on_generatebb_button_click(self, *args):
  813. self.app.report_usage("gerber_on_generatebb_button")
  814. self.read_form()
  815. name = self.options["name"] + "_bbox"
  816. def geo_init(geo_obj, app_obj):
  817. assert isinstance(geo_obj, FlatCAMGeometry)
  818. if isinstance(self.solid_geometry, list):
  819. try:
  820. self.solid_geometry = MultiPolygon(self.solid_geometry)
  821. except Exception:
  822. self.solid_geometry = cascaded_union(self.solid_geometry)
  823. # Bounding box with rounded corners
  824. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  825. if not self.options["bboxrounded"]: # Remove rounded corners
  826. bounding_box = bounding_box.envelope
  827. if bounding_box is None or bounding_box.is_empty:
  828. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  829. return "fail"
  830. geo_obj.solid_geometry = bounding_box
  831. self.app.new_object("geometry", name, geo_init)
  832. def on_iso_button_click(self, *args):
  833. obj = self.app.collection.get_active()
  834. self.iso_type = 2
  835. if self.ui.iso_type_radio.get_value() == 'ext':
  836. self.iso_type = 0
  837. if self.ui.iso_type_radio.get_value() == 'int':
  838. self.iso_type = 1
  839. def worker_task(obj, app_obj):
  840. with self.app.proc_container.new(_("Isolating...")):
  841. if self.ui.follow_cb.get_value() is True:
  842. obj.follow_geo()
  843. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  844. obj.ui.plot_cb.toggle()
  845. else:
  846. app_obj.report_usage("gerber_on_iso_button")
  847. self.read_form()
  848. iso_scope = 'all' if self.ui.iso_scope_radio.get_value() == 'all' else 'single'
  849. self.isolate_handler(iso_type=self.iso_type, iso_scope=iso_scope)
  850. self.app.worker_task.emit({'fcn': worker_task, 'params': [obj, self.app]})
  851. def follow_geo(self, outname=None):
  852. """
  853. Creates a geometry object "following" the gerber paths.
  854. :return: None
  855. """
  856. # default_name = self.options["name"] + "_follow"
  857. # follow_name = outname or default_name
  858. if outname is None:
  859. follow_name = self.options["name"] + "_follow"
  860. else:
  861. follow_name = outname
  862. def follow_init(follow_obj, app):
  863. # Propagate options
  864. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  865. follow_obj.solid_geometry = self.follow_geometry
  866. # TODO: Do something if this is None. Offer changing name?
  867. try:
  868. self.app.new_object("geometry", follow_name, follow_init)
  869. except Exception as e:
  870. return "Operation failed: %s" % str(e)
  871. def isolate_handler(self, iso_type, iso_scope):
  872. if iso_scope == 'all':
  873. self.isolate(iso_type=iso_type)
  874. else:
  875. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  876. if self.app.ui.grid_snap_btn.isChecked():
  877. self.grid_status_memory = True
  878. self.app.ui.grid_snap_btn.trigger()
  879. else:
  880. self.grid_status_memory = False
  881. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  882. if self.app.is_legacy is False:
  883. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  884. else:
  885. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  886. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  887. def on_mouse_click_release(self, event):
  888. if self.app.is_legacy is False:
  889. event_pos = event.pos
  890. right_button = 2
  891. self.app.event_is_dragging = self.app.event_is_dragging
  892. else:
  893. event_pos = (event.xdata, event.ydata)
  894. right_button = 3
  895. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  896. try:
  897. x = float(event_pos[0])
  898. y = float(event_pos[1])
  899. except TypeError:
  900. return
  901. event_pos = (x, y)
  902. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  903. if self.app.grid_status():
  904. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  905. else:
  906. curr_pos = (curr_pos[0], curr_pos[1])
  907. if event.button == 1:
  908. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]))
  909. if self.app.selection_type is not None:
  910. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  911. self.app.selection_type = None
  912. elif clicked_poly:
  913. if clicked_poly not in self.poly_dict.values():
  914. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  915. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  916. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  917. visible=True)
  918. self.poly_dict[shape_id] = clicked_poly
  919. self.app.inform.emit(
  920. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  921. _("Click to add next polygon or right click to start isolation."))
  922. )
  923. else:
  924. try:
  925. for k, v in list(self.poly_dict.items()):
  926. if v == clicked_poly:
  927. self.app.tool_shapes.remove(k)
  928. self.poly_dict.pop(k)
  929. break
  930. except TypeError:
  931. return
  932. self.app.inform.emit(
  933. '%s. %s' % (_("Removed polygon"),
  934. _("Click to add/remove next polygon or right click to start isolation."))
  935. )
  936. self.app.tool_shapes.redraw()
  937. else:
  938. self.app.inform.emit(_("No polygon detected under click position."))
  939. elif event.button == right_button and self.app.event_is_dragging is False:
  940. # restore the Grid snapping if it was active before
  941. if self.grid_status_memory is True:
  942. self.app.ui.grid_snap_btn.trigger()
  943. if self.app.is_legacy is False:
  944. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  945. else:
  946. self.app.plotcanvas.graph_event_disconnect(self.mr)
  947. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  948. self.app.on_mouse_click_release_over_plot)
  949. self.app.tool_shapes.clear(update=True)
  950. if self.poly_dict:
  951. poly_list = deepcopy(list(self.poly_dict.values()))
  952. self.isolate(iso_type=self.iso_type, geometry=poly_list)
  953. self.poly_dict.clear()
  954. else:
  955. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  956. def selection_area_handler(self, start_pos, end_pos, sel_type):
  957. """
  958. :param start_pos: mouse position when the selection LMB click was done
  959. :param end_pos: mouse position when the left mouse button is released
  960. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  961. :return:
  962. """
  963. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  964. # delete previous selection shape
  965. self.app.delete_selection_shape()
  966. added_poly_count = 0
  967. try:
  968. for geo in self.solid_geometry:
  969. if geo not in self.poly_dict.values():
  970. if sel_type is True:
  971. if geo.within(poly_selection):
  972. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  973. shape=geo,
  974. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  975. face_color=self.app.defaults[
  976. 'global_sel_draw_color'] + 'AF',
  977. visible=True)
  978. self.poly_dict[shape_id] = geo
  979. added_poly_count += 1
  980. else:
  981. if poly_selection.intersects(geo):
  982. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  983. shape=geo,
  984. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  985. face_color=self.app.defaults[
  986. 'global_sel_draw_color'] + 'AF',
  987. visible=True)
  988. self.poly_dict[shape_id] = geo
  989. added_poly_count += 1
  990. except TypeError:
  991. if self.solid_geometry not in self.poly_dict.values():
  992. if sel_type is True:
  993. if self.solid_geometry.within(poly_selection):
  994. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  995. shape=self.solid_geometry,
  996. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  997. face_color=self.app.defaults[
  998. 'global_sel_draw_color'] + 'AF',
  999. visible=True)
  1000. self.poly_dict[shape_id] = self.solid_geometry
  1001. added_poly_count += 1
  1002. else:
  1003. if poly_selection.intersects(self.solid_geometry):
  1004. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1005. shape=self.solid_geometry,
  1006. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1007. face_color=self.app.defaults[
  1008. 'global_sel_draw_color'] + 'AF',
  1009. visible=True)
  1010. self.poly_dict[shape_id] = self.solid_geometry
  1011. added_poly_count += 1
  1012. if added_poly_count > 0:
  1013. self.app.tool_shapes.redraw()
  1014. self.app.inform.emit(
  1015. '%s: %d. %s' % (_("Added polygon"),
  1016. int(added_poly_count),
  1017. _("Click to add next polygon or right click to start isolation."))
  1018. )
  1019. else:
  1020. self.app.inform.emit(_("No polygon in selection."))
  1021. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  1022. milling_type=None, follow=None, plot=True):
  1023. """
  1024. Creates an isolation routing geometry object in the project.
  1025. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  1026. :param geometry: specific geometry to isolate
  1027. :param dia: Tool diameter
  1028. :param passes: Number of tool widths to cut
  1029. :param overlap: Overlap between passes in fraction of tool diameter
  1030. :param outname: Base name of the output object
  1031. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  1032. :param milling_type: type of milling: conventional or climbing
  1033. :param follow: Boolean: if to generate a 'follow' geometry
  1034. :param plot: Boolean: if to plot the resulting geometry object
  1035. :return: None
  1036. """
  1037. if geometry is None:
  1038. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  1039. else:
  1040. work_geo = geometry
  1041. if dia is None:
  1042. dia = float(self.options["isotooldia"])
  1043. if passes is None:
  1044. passes = int(self.options["isopasses"])
  1045. if overlap is None:
  1046. overlap = float(self.options["isooverlap"])
  1047. overlap /= 100.0
  1048. combine = self.options["combine_passes"] if combine is None else bool(combine)
  1049. if milling_type is None:
  1050. milling_type = self.options["milling_type"]
  1051. if iso_type is None:
  1052. iso_t = 2
  1053. else:
  1054. iso_t = iso_type
  1055. base_name = self.options["name"]
  1056. if combine:
  1057. if outname is None:
  1058. if self.iso_type == 0:
  1059. iso_name = base_name + "_ext_iso"
  1060. elif self.iso_type == 1:
  1061. iso_name = base_name + "_int_iso"
  1062. else:
  1063. iso_name = base_name + "_iso"
  1064. else:
  1065. iso_name = outname
  1066. def iso_init(geo_obj, app_obj):
  1067. # Propagate options
  1068. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1069. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  1070. geo_obj.solid_geometry = list()
  1071. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1072. if self.ui.tool_type_radio.get_value() == 'v':
  1073. new_cutz = self.ui.cutz_spinner.get_value()
  1074. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1075. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1076. tool_type = 'V'
  1077. else:
  1078. new_cutz = self.app.defaults['geometry_cutz']
  1079. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1080. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1081. tool_type = 'C1'
  1082. # store here the default data for Geometry Data
  1083. default_data = {}
  1084. default_data.update({
  1085. "name": iso_name,
  1086. "plot": self.app.defaults['geometry_plot'],
  1087. "cutz": new_cutz,
  1088. "vtipdia": new_vtipdia,
  1089. "vtipangle": new_vtipangle,
  1090. "travelz": self.app.defaults['geometry_travelz'],
  1091. "feedrate": self.app.defaults['geometry_feedrate'],
  1092. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1093. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1094. "dwell": self.app.defaults['geometry_dwell'],
  1095. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1096. "multidepth": self.app.defaults['geometry_multidepth'],
  1097. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1098. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1099. "extracut": self.app.defaults['geometry_extracut'],
  1100. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1101. "toolchange": self.app.defaults['geometry_toolchange'],
  1102. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1103. "endz": self.app.defaults['geometry_endz'],
  1104. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1105. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1106. "startz": self.app.defaults['geometry_startz']
  1107. })
  1108. geo_obj.tools = dict()
  1109. geo_obj.tools['1'] = dict()
  1110. geo_obj.tools.update({
  1111. '1': {
  1112. 'tooldia': float(self.options["isotooldia"]),
  1113. 'offset': 'Path',
  1114. 'offset_value': 0.0,
  1115. 'type': _('Rough'),
  1116. 'tool_type': tool_type,
  1117. 'data': default_data,
  1118. 'solid_geometry': geo_obj.solid_geometry
  1119. }
  1120. })
  1121. for i in range(passes):
  1122. iso_offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  1123. # if milling type is climb then the move is counter-clockwise around features
  1124. mill_dir = 1 if milling_type == 'cl' else 0
  1125. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1126. follow=follow, nr_passes=i)
  1127. if geom == 'fail':
  1128. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1129. return 'fail'
  1130. geo_obj.solid_geometry.append(geom)
  1131. # update the geometry in the tools
  1132. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  1133. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1134. # or just looking in the lists (they are one level depth) and if any is not empty
  1135. # proceed with object creation, if there are empty and the number of them is the length
  1136. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1137. empty_cnt = 0
  1138. if not isinstance(geo_obj.solid_geometry, list) and \
  1139. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1140. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1141. for g in geo_obj.solid_geometry:
  1142. if g:
  1143. break
  1144. else:
  1145. empty_cnt += 1
  1146. if empty_cnt == len(geo_obj.solid_geometry):
  1147. raise ValidationError("Empty Geometry", None)
  1148. else:
  1149. app_obj.inform.emit('[success] %s" %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1150. # even if combine is checked, one pass is still single-geo
  1151. geo_obj.multigeo = True if passes > 1 else False
  1152. # ############################################################
  1153. # ########## AREA SUBTRACTION ################################
  1154. # ############################################################
  1155. if self.ui.except_cb.get_value():
  1156. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1157. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1158. # TODO: Do something if this is None. Offer changing name?
  1159. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1160. else:
  1161. for i in range(passes):
  1162. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  1163. if passes > 1:
  1164. if outname is None:
  1165. if self.iso_type == 0:
  1166. iso_name = base_name + "_ext_iso" + str(i + 1)
  1167. elif self.iso_type == 1:
  1168. iso_name = base_name + "_int_iso" + str(i + 1)
  1169. else:
  1170. iso_name = base_name + "_iso" + str(i + 1)
  1171. else:
  1172. iso_name = outname
  1173. else:
  1174. if outname is None:
  1175. if self.iso_type == 0:
  1176. iso_name = base_name + "_ext_iso"
  1177. elif self.iso_type == 1:
  1178. iso_name = base_name + "_int_iso"
  1179. else:
  1180. iso_name = base_name + "_iso"
  1181. else:
  1182. iso_name = outname
  1183. def iso_init(geo_obj, app_obj):
  1184. # Propagate options
  1185. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1186. if self.ui.tool_type_radio.get_value() == 'v':
  1187. geo_obj.tool_type = 'V'
  1188. else:
  1189. geo_obj.tool_type = 'C1'
  1190. # if milling type is climb then the move is counter-clockwise around features
  1191. mill_dir = 1 if milling_type == 'cl' else 0
  1192. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1193. follow=follow,
  1194. nr_passes=i)
  1195. if geom == 'fail':
  1196. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1197. return 'fail'
  1198. geo_obj.solid_geometry = geom
  1199. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1200. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  1201. # required to be transfered to the Geometry object
  1202. if self.ui.tool_type_radio.get_value() == 'v':
  1203. new_cutz = self.ui.cutz_spinner.get_value()
  1204. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1205. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1206. tool_type = 'V'
  1207. else:
  1208. new_cutz = self.app.defaults['geometry_cutz']
  1209. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1210. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1211. tool_type = 'C1'
  1212. # store here the default data for Geometry Data
  1213. default_data = {}
  1214. default_data.update({
  1215. "name": iso_name,
  1216. "plot": self.app.defaults['geometry_plot'],
  1217. "cutz": new_cutz,
  1218. "vtipdia": new_vtipdia,
  1219. "vtipangle": new_vtipangle,
  1220. "travelz": self.app.defaults['geometry_travelz'],
  1221. "feedrate": self.app.defaults['geometry_feedrate'],
  1222. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1223. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1224. "dwell": self.app.defaults['geometry_dwell'],
  1225. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1226. "multidepth": self.app.defaults['geometry_multidepth'],
  1227. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1228. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1229. "extracut": self.app.defaults['geometry_extracut'],
  1230. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1231. "toolchange": self.app.defaults['geometry_toolchange'],
  1232. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1233. "endz": self.app.defaults['geometry_endz'],
  1234. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1235. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1236. "startz": self.app.defaults['geometry_startz']
  1237. })
  1238. geo_obj.tools = dict()
  1239. geo_obj.tools['1'] = dict()
  1240. geo_obj.tools.update({
  1241. '1': {
  1242. 'tooldia': float(self.options["isotooldia"]),
  1243. 'offset': 'Path',
  1244. 'offset_value': 0.0,
  1245. 'type': _('Rough'),
  1246. 'tool_type': tool_type,
  1247. 'data': default_data,
  1248. 'solid_geometry': geo_obj.solid_geometry
  1249. }
  1250. })
  1251. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1252. # or just looking in the lists (they are one level depth) and if any is not empty
  1253. # proceed with object creation, if there are empty and the number of them is the length
  1254. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1255. empty_cnt = 0
  1256. if not isinstance(geo_obj.solid_geometry, list):
  1257. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1258. for g in geo_obj.solid_geometry:
  1259. if g:
  1260. break
  1261. else:
  1262. empty_cnt += 1
  1263. if empty_cnt == len(geo_obj.solid_geometry):
  1264. raise ValidationError("Empty Geometry", None)
  1265. else:
  1266. app_obj.inform.emit('[success] %s: %s' %
  1267. (_("Isolation geometry created"), geo_obj.options["name"]))
  1268. geo_obj.multigeo = False
  1269. # ############################################################
  1270. # ########## AREA SUBTRACTION ################################
  1271. # ############################################################
  1272. if self.ui.except_cb.get_value():
  1273. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1274. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1275. # TODO: Do something if this is None. Offer changing name?
  1276. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1277. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  1278. # isolation_geometry produces an envelope that is going on the left of the geometry
  1279. # (the copper features). To leave the least amount of burrs on the features
  1280. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1281. # the first pass is the one cutting all of the features, so it needs to be reversed
  1282. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1283. # to cut on the right side of the left over copper i.e on the left side of the features.
  1284. if follow:
  1285. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  1286. else:
  1287. try:
  1288. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  1289. except Exception as e:
  1290. log.debug('FlatCAMGerber.isolate().generate_envelope() --> %s' % str(e))
  1291. return 'fail'
  1292. if invert:
  1293. try:
  1294. pl = []
  1295. for p in geom:
  1296. if p is not None:
  1297. if isinstance(p, Polygon):
  1298. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1299. elif isinstance(p, LinearRing):
  1300. pl.append(Polygon(p.coords[::-1]))
  1301. geom = MultiPolygon(pl)
  1302. except TypeError:
  1303. if isinstance(geom, Polygon) and geom is not None:
  1304. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1305. elif isinstance(geom, LinearRing) and geom is not None:
  1306. geom = Polygon(geom.coords[::-1])
  1307. else:
  1308. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  1309. type(geom))
  1310. except Exception as e:
  1311. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  1312. return 'fail'
  1313. return geom
  1314. def area_subtraction(self, geo, subtractor_geo=None):
  1315. """
  1316. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1317. :param geo: target geometry from which to subtract
  1318. :param subtractor_geo: geometry that acts as subtractor
  1319. :return:
  1320. """
  1321. new_geometry = []
  1322. target_geo = geo
  1323. if subtractor_geo:
  1324. sub_union = cascaded_union(subtractor_geo)
  1325. else:
  1326. name = self.ui.obj_combo.currentText()
  1327. subtractor_obj = self.app.collection.get_by_name(name)
  1328. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1329. try:
  1330. for geo_elem in target_geo:
  1331. if isinstance(geo_elem, Polygon):
  1332. for ring in self.poly2rings(geo_elem):
  1333. new_geo = ring.difference(sub_union)
  1334. if new_geo and not new_geo.is_empty:
  1335. new_geometry.append(new_geo)
  1336. elif isinstance(geo_elem, MultiPolygon):
  1337. for poly in geo_elem:
  1338. for ring in self.poly2rings(poly):
  1339. new_geo = ring.difference(sub_union)
  1340. if new_geo and not new_geo.is_empty:
  1341. new_geometry.append(new_geo)
  1342. elif isinstance(geo_elem, LineString):
  1343. new_geo = geo_elem.difference(sub_union)
  1344. if new_geo:
  1345. if not new_geo.is_empty:
  1346. new_geometry.append(new_geo)
  1347. elif isinstance(geo_elem, MultiLineString):
  1348. for line_elem in geo_elem:
  1349. new_geo = line_elem.difference(sub_union)
  1350. if new_geo and not new_geo.is_empty:
  1351. new_geometry.append(new_geo)
  1352. except TypeError:
  1353. if isinstance(target_geo, Polygon):
  1354. for ring in self.poly2rings(target_geo):
  1355. new_geo = ring.difference(sub_union)
  1356. if new_geo:
  1357. if not new_geo.is_empty:
  1358. new_geometry.append(new_geo)
  1359. elif isinstance(target_geo, LineString):
  1360. new_geo = target_geo.difference(sub_union)
  1361. if new_geo and not new_geo.is_empty:
  1362. new_geometry.append(new_geo)
  1363. elif isinstance(target_geo, MultiLineString):
  1364. for line_elem in target_geo:
  1365. new_geo = line_elem.difference(sub_union)
  1366. if new_geo and not new_geo.is_empty:
  1367. new_geometry.append(new_geo)
  1368. return new_geometry
  1369. def on_plot_cb_click(self, *args):
  1370. if self.muted_ui:
  1371. return
  1372. self.read_form_item('plot')
  1373. self.plot()
  1374. def on_solid_cb_click(self, *args):
  1375. if self.muted_ui:
  1376. return
  1377. self.read_form_item('solid')
  1378. self.plot()
  1379. def on_multicolored_cb_click(self, *args):
  1380. if self.muted_ui:
  1381. return
  1382. self.read_form_item('multicolored')
  1383. self.plot()
  1384. def on_follow_cb_click(self):
  1385. if self.muted_ui:
  1386. return
  1387. self.plot()
  1388. def on_aperture_table_visibility_change(self):
  1389. if self.ui.aperture_table_visibility_cb.isChecked():
  1390. # add the shapes storage for marking apertures
  1391. if self.build_aperture_storage is False:
  1392. self.build_aperture_storage = True
  1393. if self.app.is_legacy is False:
  1394. for ap_code in self.apertures:
  1395. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  1396. else:
  1397. for ap_code in self.apertures:
  1398. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  1399. name=self.options['name'] + str(ap_code))
  1400. self.ui.apertures_table.setVisible(True)
  1401. for ap in self.mark_shapes:
  1402. self.mark_shapes[ap].enabled = True
  1403. self.ui.mark_all_cb.setVisible(True)
  1404. self.ui.mark_all_cb.setChecked(False)
  1405. self.build_ui()
  1406. else:
  1407. self.ui.apertures_table.setVisible(False)
  1408. self.ui.mark_all_cb.setVisible(False)
  1409. # on hide disable all mark plots
  1410. try:
  1411. for row in range(self.ui.apertures_table.rowCount()):
  1412. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  1413. self.clear_plot_apertures()
  1414. # for ap in list(self.mark_shapes.keys()):
  1415. # # self.mark_shapes[ap].enabled = False
  1416. # del self.mark_shapes[ap]
  1417. except Exception as e:
  1418. log.debug(" FlatCAMGerber.on_aperture_visibility_changed() --> %s" % str(e))
  1419. def convert_units(self, units):
  1420. """
  1421. Converts the units of the object by scaling dimensions in all geometry
  1422. and options.
  1423. :param units: Units to which to convert the object: "IN" or "MM".
  1424. :type units: str
  1425. :return: None
  1426. :rtype: None
  1427. """
  1428. # units conversion to get a conversion should be done only once even if we found multiple
  1429. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  1430. if self.conversion_done is True:
  1431. log.debug("Gerber units conversion cancelled. Already done.")
  1432. return
  1433. log.debug("FlatCAMObj.FlatCAMGerber.convert_units()")
  1434. factor = Gerber.convert_units(self, units)
  1435. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  1436. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  1437. def plot(self, **kwargs):
  1438. """
  1439. :param kwargs: color and face_color
  1440. :return:
  1441. """
  1442. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  1443. # Does all the required setup and returns False
  1444. # if the 'ptint' option is set to False.
  1445. if not FlatCAMObj.plot(self):
  1446. return
  1447. if 'color' in kwargs:
  1448. color = kwargs['color']
  1449. else:
  1450. color = self.outline_color
  1451. if 'face_color' in kwargs:
  1452. face_color = kwargs['face_color']
  1453. else:
  1454. face_color = self.fill_color
  1455. if 'visible' not in kwargs:
  1456. visible = self.options['plot']
  1457. else:
  1458. visible = kwargs['visible']
  1459. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  1460. if self.ui.follow_cb.get_value():
  1461. geometry = self.follow_geometry
  1462. else:
  1463. geometry = self.solid_geometry
  1464. # Make sure geometry is iterable.
  1465. try:
  1466. __ = iter(geometry)
  1467. except TypeError:
  1468. geometry = [geometry]
  1469. if self.app.is_legacy is False:
  1470. def random_color():
  1471. r_color = np.random.rand(4)
  1472. r_color[3] = 1
  1473. return r_color
  1474. else:
  1475. def random_color():
  1476. while True:
  1477. r_color = np.random.rand(4)
  1478. r_color[3] = 1
  1479. new_color = '#'
  1480. for idx in range(len(r_color)):
  1481. new_color += '%x' % int(r_color[idx] * 255)
  1482. # do it until a valid color is generated
  1483. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1484. # for a total of 9 chars
  1485. if len(new_color) == 9:
  1486. break
  1487. return new_color
  1488. try:
  1489. if self.options["solid"]:
  1490. for g in geometry:
  1491. if type(g) == Polygon or type(g) == LineString:
  1492. self.add_shape(shape=g, color=color,
  1493. face_color=random_color() if self.options['multicolored']
  1494. else face_color, visible=visible)
  1495. elif type(g) == Point:
  1496. pass
  1497. else:
  1498. try:
  1499. for el in g:
  1500. self.add_shape(shape=el, color=color,
  1501. face_color=random_color() if self.options['multicolored']
  1502. else face_color, visible=visible)
  1503. except TypeError:
  1504. self.add_shape(shape=g, color=color,
  1505. face_color=random_color() if self.options['multicolored']
  1506. else face_color, visible=visible)
  1507. else:
  1508. for g in geometry:
  1509. if type(g) == Polygon or type(g) == LineString:
  1510. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  1511. visible=visible)
  1512. elif type(g) == Point:
  1513. pass
  1514. else:
  1515. for el in g:
  1516. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  1517. visible=visible)
  1518. self.shapes.redraw(
  1519. # update_colors=(self.fill_color, self.outline_color),
  1520. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  1521. )
  1522. except (ObjectDeleted, AttributeError):
  1523. self.shapes.clear(update=True)
  1524. except Exception as e:
  1525. log.debug("FlatCAMGerber.plot() --> %s" % str(e))
  1526. # experimental plot() when the solid_geometry is stored in the self.apertures
  1527. def plot_aperture(self, run_thread=True, **kwargs):
  1528. """
  1529. :param run_thread: if True run the aperture plot as a thread in a worker
  1530. :param kwargs: color and face_color
  1531. :return:
  1532. """
  1533. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  1534. # Does all the required setup and returns False
  1535. # if the 'ptint' option is set to False.
  1536. # if not FlatCAMObj.plot(self):
  1537. # return
  1538. # for marking apertures, line color and fill color are the same
  1539. if 'color' in kwargs:
  1540. color = kwargs['color']
  1541. else:
  1542. color = self.app.defaults['gerber_plot_fill']
  1543. if 'marked_aperture' not in kwargs:
  1544. return
  1545. else:
  1546. aperture_to_plot_mark = kwargs['marked_aperture']
  1547. if aperture_to_plot_mark is None:
  1548. return
  1549. if 'visible' not in kwargs:
  1550. visibility = True
  1551. else:
  1552. visibility = kwargs['visible']
  1553. with self.app.proc_container.new(_("Plotting Apertures")):
  1554. def job_thread(app_obj):
  1555. try:
  1556. if aperture_to_plot_mark in self.apertures:
  1557. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  1558. if 'solid' in elem:
  1559. geo = elem['solid']
  1560. if type(geo) == Polygon or type(geo) == LineString:
  1561. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  1562. face_color=color, visible=visibility)
  1563. else:
  1564. for el in geo:
  1565. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  1566. face_color=color, visible=visibility)
  1567. self.mark_shapes[aperture_to_plot_mark].redraw()
  1568. except (ObjectDeleted, AttributeError):
  1569. self.clear_plot_apertures()
  1570. except Exception as e:
  1571. log.debug("FlatCAMGerber.plot_aperture() --> %s" % str(e))
  1572. if run_thread:
  1573. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  1574. else:
  1575. job_thread(self)
  1576. def clear_plot_apertures(self, aperture='all'):
  1577. """
  1578. :param aperture: string; aperture for which to clear the mark shapes
  1579. :return:
  1580. """
  1581. if self.mark_shapes:
  1582. if aperture == 'all':
  1583. for apid in list(self.apertures.keys()):
  1584. try:
  1585. if self.app.is_legacy is True:
  1586. self.mark_shapes[apid].clear(update=False)
  1587. else:
  1588. self.mark_shapes[apid].clear(update=True)
  1589. except Exception as e:
  1590. log.debug("FlatCAMGerber.clear_plot_apertures() 'all' --> %s" % str(e))
  1591. else:
  1592. try:
  1593. if self.app.is_legacy is True:
  1594. self.mark_shapes[aperture].clear(update=False)
  1595. else:
  1596. self.mark_shapes[aperture].clear(update=True)
  1597. except Exception as e:
  1598. log.debug("FlatCAMGerber.clear_plot_apertures() 'aperture' --> %s" % str(e))
  1599. def clear_mark_all(self):
  1600. self.ui.mark_all_cb.set_value(False)
  1601. self.marked_rows[:] = []
  1602. def on_mark_cb_click_table(self):
  1603. """
  1604. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  1605. :return:
  1606. """
  1607. self.ui_disconnect()
  1608. cw = self.sender()
  1609. try:
  1610. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  1611. cw_row = cw_index.row()
  1612. except AttributeError:
  1613. cw_row = 0
  1614. except TypeError:
  1615. return
  1616. self.marked_rows[:] = []
  1617. try:
  1618. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  1619. except AttributeError:
  1620. return
  1621. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  1622. self.marked_rows.append(True)
  1623. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1624. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1625. marked_aperture=aperture, visible=True, run_thread=True)
  1626. # self.mark_shapes[aperture].redraw()
  1627. else:
  1628. self.marked_rows.append(False)
  1629. self.clear_plot_apertures(aperture=aperture)
  1630. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1631. # if all the row mark's are enabled also enable the Mark All checkbox
  1632. cb_cnt = 0
  1633. total_row = self.ui.apertures_table.rowCount()
  1634. for row in range(total_row):
  1635. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1636. cb_cnt += 1
  1637. else:
  1638. cb_cnt -= 1
  1639. if cb_cnt < total_row:
  1640. self.ui.mark_all_cb.setChecked(False)
  1641. else:
  1642. self.ui.mark_all_cb.setChecked(True)
  1643. self.ui_connect()
  1644. def on_mark_all_click(self, signal):
  1645. self.ui_disconnect()
  1646. mark_all = self.ui.mark_all_cb.isChecked()
  1647. for row in range(self.ui.apertures_table.rowCount()):
  1648. # update the mark_rows list
  1649. if mark_all:
  1650. self.marked_rows.append(True)
  1651. else:
  1652. self.marked_rows[:] = []
  1653. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1654. mark_cb.setChecked(mark_all)
  1655. if mark_all:
  1656. for aperture in self.apertures:
  1657. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1658. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1659. marked_aperture=aperture, visible=True)
  1660. # HACK: enable/disable the grid for a better look
  1661. self.app.ui.grid_snap_btn.trigger()
  1662. self.app.ui.grid_snap_btn.trigger()
  1663. else:
  1664. self.clear_plot_apertures()
  1665. self.marked_rows[:] = []
  1666. self.ui_connect()
  1667. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1668. """
  1669. Creates a Gerber file content to be exported to a file.
  1670. :param whole: how many digits in the whole part of coordinates
  1671. :param fract: how many decimals in coordinates
  1672. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  1673. :param factor: factor to be applied onto the Gerber coordinates
  1674. :return: Gerber_code
  1675. """
  1676. log.debug("FlatCAMGerber.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  1677. def tz_format(x, y, fac):
  1678. x_c = x * fac
  1679. y_c = y * fac
  1680. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1681. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1682. # extract whole part and decimal part
  1683. x_form = x_form.partition('.')
  1684. y_form = y_form.partition('.')
  1685. # left padd the 'whole' part with zeros
  1686. x_whole = x_form[0].rjust(whole, '0')
  1687. y_whole = y_form[0].rjust(whole, '0')
  1688. # restore the coordinate padded in the left with 0 and added the decimal part
  1689. # without the decinal dot
  1690. x_form = x_whole + x_form[2]
  1691. y_form = y_whole + y_form[2]
  1692. return x_form, y_form
  1693. def lz_format(x, y, fac):
  1694. x_c = x * fac
  1695. y_c = y * fac
  1696. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1697. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1698. # pad with rear zeros
  1699. x_form.ljust(length, '0')
  1700. y_form.ljust(length, '0')
  1701. return x_form, y_form
  1702. # Gerber code is stored here
  1703. gerber_code = ''
  1704. # apertures processing
  1705. try:
  1706. length = whole + fract
  1707. if '0' in self.apertures:
  1708. if 'geometry' in self.apertures['0']:
  1709. for geo_elem in self.apertures['0']['geometry']:
  1710. if 'solid' in geo_elem:
  1711. geo = geo_elem['solid']
  1712. if not geo.is_empty:
  1713. gerber_code += 'G36*\n'
  1714. geo_coords = list(geo.exterior.coords)
  1715. # first command is a move with pen-up D02 at the beginning of the geo
  1716. if g_zeros == 'T':
  1717. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1718. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1719. yform=y_formatted)
  1720. else:
  1721. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1722. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1723. yform=y_formatted)
  1724. for coord in geo_coords[1:]:
  1725. if g_zeros == 'T':
  1726. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1727. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1728. yform=y_formatted)
  1729. else:
  1730. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1731. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1732. yform=y_formatted)
  1733. gerber_code += 'D02*\n'
  1734. gerber_code += 'G37*\n'
  1735. clear_list = list(geo.interiors)
  1736. if clear_list:
  1737. gerber_code += '%LPC*%\n'
  1738. for clear_geo in clear_list:
  1739. gerber_code += 'G36*\n'
  1740. geo_coords = list(clear_geo.coords)
  1741. # first command is a move with pen-up D02 at the beginning of the geo
  1742. if g_zeros == 'T':
  1743. x_formatted, y_formatted = tz_format(
  1744. geo_coords[0][0], geo_coords[0][1], factor)
  1745. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1746. yform=y_formatted)
  1747. else:
  1748. x_formatted, y_formatted = lz_format(
  1749. geo_coords[0][0], geo_coords[0][1], factor)
  1750. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1751. yform=y_formatted)
  1752. prev_coord = geo_coords[0]
  1753. for coord in geo_coords[1:]:
  1754. if coord != prev_coord:
  1755. if g_zeros == 'T':
  1756. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1757. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1758. yform=y_formatted)
  1759. else:
  1760. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1761. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1762. yform=y_formatted)
  1763. prev_coord = coord
  1764. gerber_code += 'D02*\n'
  1765. gerber_code += 'G37*\n'
  1766. gerber_code += '%LPD*%\n'
  1767. if 'clear' in geo_elem:
  1768. geo = geo_elem['clear']
  1769. if not geo.is_empty:
  1770. gerber_code += '%LPC*%\n'
  1771. gerber_code += 'G36*\n'
  1772. geo_coords = list(geo.exterior.coords)
  1773. # first command is a move with pen-up D02 at the beginning of the geo
  1774. if g_zeros == 'T':
  1775. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1776. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1777. yform=y_formatted)
  1778. else:
  1779. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1780. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1781. yform=y_formatted)
  1782. prev_coord = geo_coords[0]
  1783. for coord in geo_coords[1:]:
  1784. if coord != prev_coord:
  1785. if g_zeros == 'T':
  1786. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1787. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1788. yform=y_formatted)
  1789. else:
  1790. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1791. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1792. yform=y_formatted)
  1793. prev_coord = coord
  1794. gerber_code += 'D02*\n'
  1795. gerber_code += 'G37*\n'
  1796. gerber_code += '%LPD*%\n'
  1797. for apid in self.apertures:
  1798. if apid == '0':
  1799. continue
  1800. else:
  1801. gerber_code += 'D%s*\n' % str(apid)
  1802. if 'geometry' in self.apertures[apid]:
  1803. for geo_elem in self.apertures[apid]['geometry']:
  1804. if 'follow' in geo_elem:
  1805. geo = geo_elem['follow']
  1806. if not geo.is_empty:
  1807. if isinstance(geo, Point):
  1808. if g_zeros == 'T':
  1809. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1810. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1811. yform=y_formatted)
  1812. else:
  1813. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1814. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1815. yform=y_formatted)
  1816. else:
  1817. geo_coords = list(geo.coords)
  1818. # first command is a move with pen-up D02 at the beginning of the geo
  1819. if g_zeros == 'T':
  1820. x_formatted, y_formatted = tz_format(
  1821. geo_coords[0][0], geo_coords[0][1], factor)
  1822. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1823. yform=y_formatted)
  1824. else:
  1825. x_formatted, y_formatted = lz_format(
  1826. geo_coords[0][0], geo_coords[0][1], factor)
  1827. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1828. yform=y_formatted)
  1829. prev_coord = geo_coords[0]
  1830. for coord in geo_coords[1:]:
  1831. if coord != prev_coord:
  1832. if g_zeros == 'T':
  1833. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1834. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1835. yform=y_formatted)
  1836. else:
  1837. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1838. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1839. yform=y_formatted)
  1840. prev_coord = coord
  1841. # gerber_code += "D02*\n"
  1842. if 'clear' in geo_elem:
  1843. gerber_code += '%LPC*%\n'
  1844. geo = geo_elem['clear']
  1845. if not geo.is_empty:
  1846. if isinstance(geo, Point):
  1847. if g_zeros == 'T':
  1848. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1849. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1850. yform=y_formatted)
  1851. else:
  1852. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1853. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1854. yform=y_formatted)
  1855. else:
  1856. geo_coords = list(geo.coords)
  1857. # first command is a move with pen-up D02 at the beginning of the geo
  1858. if g_zeros == 'T':
  1859. x_formatted, y_formatted = tz_format(
  1860. geo_coords[0][0], geo_coords[0][1], factor)
  1861. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1862. yform=y_formatted)
  1863. else:
  1864. x_formatted, y_formatted = lz_format(
  1865. geo_coords[0][0], geo_coords[0][1], factor)
  1866. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1867. yform=y_formatted)
  1868. prev_coord = geo_coords[0]
  1869. for coord in geo_coords[1:]:
  1870. if coord != prev_coord:
  1871. if g_zeros == 'T':
  1872. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1873. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1874. yform=y_formatted)
  1875. else:
  1876. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1877. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1878. yform=y_formatted)
  1879. prev_coord = coord
  1880. # gerber_code += "D02*\n"
  1881. gerber_code += '%LPD*%\n'
  1882. except Exception as e:
  1883. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> %s" % str(e))
  1884. if not self.apertures:
  1885. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1886. return 'fail'
  1887. return gerber_code
  1888. def mirror(self, axis, point):
  1889. Gerber.mirror(self, axis=axis, point=point)
  1890. self.replotApertures.emit()
  1891. def offset(self, vect):
  1892. Gerber.offset(self, vect=vect)
  1893. self.replotApertures.emit()
  1894. def rotate(self, angle, point):
  1895. Gerber.rotate(self, angle=angle, point=point)
  1896. self.replotApertures.emit()
  1897. def scale(self, xfactor, yfactor=None, point=None):
  1898. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1899. self.replotApertures.emit()
  1900. def skew(self, angle_x, angle_y, point):
  1901. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1902. self.replotApertures.emit()
  1903. def buffer(self, distance, join, factor=None):
  1904. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1905. self.replotApertures.emit()
  1906. def serialize(self):
  1907. return {
  1908. "options": self.options,
  1909. "kind": self.kind
  1910. }
  1911. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1912. """
  1913. Represents Excellon/Drill code.
  1914. """
  1915. ui_type = ExcellonObjectUI
  1916. optionChanged = QtCore.pyqtSignal(str)
  1917. def __init__(self, name):
  1918. self.decimals = self.app.decimals
  1919. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  1920. Excellon.__init__(self, geo_steps_per_circle=self.circle_steps)
  1921. FlatCAMObj.__init__(self, name)
  1922. self.kind = "excellon"
  1923. self.options.update({
  1924. "plot": True,
  1925. "solid": False,
  1926. "drillz": -0.1,
  1927. "travelz": 0.1,
  1928. "feedrate": 5.0,
  1929. "feedrate_rapid": 5.0,
  1930. "tooldia": 0.1,
  1931. "slot_tooldia": 0.1,
  1932. "toolchange": False,
  1933. "toolchangez": 1.0,
  1934. "toolchangexy": "0.0, 0.0",
  1935. "endz": 2.0,
  1936. "startz": None,
  1937. "spindlespeed": 0,
  1938. "dwell": True,
  1939. "dwelltime": 1000,
  1940. "ppname_e": 'defaults',
  1941. "z_pdepth": -0.02,
  1942. "feedrate_probe": 3.0,
  1943. "optimization_type": "R",
  1944. "gcode_type": "drills"
  1945. })
  1946. # TODO: Document this.
  1947. self.tool_cbs = dict()
  1948. # dict to hold the tool number as key and tool offset as value
  1949. self.tool_offset = dict()
  1950. # default set of data to be added to each tool in self.tools as self.tools[tool]['data'] = self.default_data
  1951. self.default_data = dict()
  1952. # fill in self.default_data values from self.options
  1953. for opt_key, opt_val in self.app.options.items():
  1954. if opt_key.find('excellon_') == 0:
  1955. self.default_data[opt_key] = deepcopy(opt_val)
  1956. for opt_key, opt_val in self.app.options.items():
  1957. if opt_key.find('geometry_') == 0:
  1958. self.default_data[opt_key] = deepcopy(opt_val)
  1959. # variable to store the total amount of drills per job
  1960. self.tot_drill_cnt = 0
  1961. self.tool_row = 0
  1962. # variable to store the total amount of slots per job
  1963. self.tot_slot_cnt = 0
  1964. self.tool_row_slots = 0
  1965. # variable to store the distance travelled
  1966. self.travel_distance = 0.0
  1967. # store the source file here
  1968. self.source_file = ""
  1969. self.multigeo = False
  1970. self.units_found = self.app.defaults['units']
  1971. self.fill_color = self.app.defaults['excellon_plot_fill']
  1972. self.outline_color = self.app.defaults['excellon_plot_line']
  1973. self.alpha_level = 'bf'
  1974. # Attributes to be included in serialization
  1975. # Always append to it because it carries contents
  1976. # from predecessors.
  1977. self.ser_attrs += ['options', 'kind',]
  1978. def merge(self, exc_list, exc_final):
  1979. """
  1980. Merge Excellon objects found in exc_list parameter into exc_final object.
  1981. Options are always copied from source .
  1982. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1983. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1984. tool_name to be used in the final Excellon object, exc_final.
  1985. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1986. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1987. :param exc_final: Destination FlatCAMExcellon object.
  1988. :return: None
  1989. """
  1990. try:
  1991. decimals_exc = self.decimals
  1992. except AttributeError:
  1993. decimals_exc = 4
  1994. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1995. flag_order = False
  1996. try:
  1997. flattened_list = list(itertools.chain(*exc_list))
  1998. except TypeError:
  1999. flattened_list = exc_list
  2000. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2001. # values will be list of Shapely Points; for drills
  2002. custom_dict_drills = {}
  2003. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2004. # values will be list of Shapely Points; for slots
  2005. custom_dict_slots = {}
  2006. for exc in flattened_list:
  2007. # copy options of the current excellon obj to the final excellon obj
  2008. for option in exc.options:
  2009. if option is not 'name':
  2010. try:
  2011. exc_final.options[option] = exc.options[option]
  2012. except Exception as e:
  2013. exc.app.log.warning("Failed to copy option.", option)
  2014. for drill in exc.drills:
  2015. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[drill['tool']]['C']))
  2016. if exc_tool_dia not in custom_dict_drills:
  2017. custom_dict_drills[exc_tool_dia] = [drill['point']]
  2018. else:
  2019. custom_dict_drills[exc_tool_dia].append(drill['point'])
  2020. for slot in exc.slots:
  2021. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[slot['tool']]['C']))
  2022. if exc_tool_dia not in custom_dict_slots:
  2023. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  2024. else:
  2025. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  2026. # add the zeros and units to the exc_final object
  2027. exc_final.zeros = exc.zeros
  2028. exc_final.units = exc.units
  2029. # ##########################################
  2030. # Here we add data to the exc_final object #
  2031. # ##########################################
  2032. # variable to make tool_name for the tools
  2033. current_tool = 0
  2034. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  2035. # drills
  2036. for tool_dia in custom_dict_drills:
  2037. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  2038. current_tool += 1
  2039. tool_name = str(current_tool)
  2040. spec = {"C": float(tool_dia)}
  2041. exc_final.tools[tool_name] = spec
  2042. # rebuild the drills list of dict's that belong to the exc_final object
  2043. for point in custom_dict_drills[tool_dia]:
  2044. exc_final.drills.append(
  2045. {
  2046. "point": point,
  2047. "tool": str(current_tool)
  2048. }
  2049. )
  2050. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  2051. # of two Shapely Points in case of slots
  2052. for tool_dia in custom_dict_slots:
  2053. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  2054. # but only if there are no drills
  2055. if not exc_final.tools:
  2056. current_tool += 1
  2057. tool_name = str(current_tool)
  2058. spec = {"C": float(tool_dia)}
  2059. exc_final.tools[tool_name] = spec
  2060. else:
  2061. dia_list = []
  2062. for v in exc_final.tools.values():
  2063. dia_list.append(float(v["C"]))
  2064. if tool_dia not in dia_list:
  2065. flag_order = True
  2066. current_tool = len(dia_list) + 1
  2067. tool_name = str(current_tool)
  2068. spec = {"C": float(tool_dia)}
  2069. exc_final.tools[tool_name] = spec
  2070. else:
  2071. for k, v in exc_final.tools.items():
  2072. if v["C"] == tool_dia:
  2073. current_tool = int(k)
  2074. break
  2075. # rebuild the slots list of dict's that belong to the exc_final object
  2076. for point in custom_dict_slots[tool_dia]:
  2077. exc_final.slots.append(
  2078. {
  2079. "start": point[0],
  2080. "stop": point[1],
  2081. "tool": str(current_tool)
  2082. }
  2083. )
  2084. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  2085. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  2086. current_tool = 0
  2087. if flag_order is True:
  2088. dia_list = []
  2089. temp_drills = []
  2090. temp_slots = []
  2091. temp_tools = {}
  2092. for v in exc_final.tools.values():
  2093. dia_list.append(float(v["C"]))
  2094. dia_list.sort()
  2095. for ordered_dia in dia_list:
  2096. current_tool += 1
  2097. tool_name_temp = str(current_tool)
  2098. spec_temp = {"C": float(ordered_dia)}
  2099. temp_tools[tool_name_temp] = spec_temp
  2100. for drill in exc_final.drills:
  2101. exc_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[drill['tool']]['C']))
  2102. if exc_tool_dia == ordered_dia:
  2103. temp_drills.append(
  2104. {
  2105. "point": drill["point"],
  2106. "tool": str(current_tool)
  2107. }
  2108. )
  2109. for slot in exc_final.slots:
  2110. slot_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[slot['tool']]['C']))
  2111. if slot_tool_dia == ordered_dia:
  2112. temp_slots.append(
  2113. {
  2114. "start": slot["start"],
  2115. "stop": slot["stop"],
  2116. "tool": str(current_tool)
  2117. }
  2118. )
  2119. # delete the exc_final tools, drills and slots
  2120. exc_final.tools = dict()
  2121. exc_final.drills[:] = []
  2122. exc_final.slots[:] = []
  2123. # update the exc_final tools, drills and slots with the ordered values
  2124. exc_final.tools = temp_tools
  2125. exc_final.drills[:] = temp_drills
  2126. exc_final.slots[:] = temp_slots
  2127. # create the geometry for the exc_final object
  2128. exc_final.create_geometry()
  2129. def build_ui(self):
  2130. FlatCAMObj.build_ui(self)
  2131. self.units = self.app.defaults['units'].upper()
  2132. for row in range(self.ui.tools_table.rowCount()):
  2133. try:
  2134. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2135. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2136. offset_spin_widget.valueChanged.disconnect()
  2137. except (TypeError, AttributeError):
  2138. pass
  2139. n = len(self.tools)
  2140. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  2141. self.ui.tools_table.setRowCount(n + 2)
  2142. self.tot_drill_cnt = 0
  2143. self.tot_slot_cnt = 0
  2144. self.tool_row = 0
  2145. sort = []
  2146. for k, v in list(self.tools.items()):
  2147. sort.append((k, v.get('C')))
  2148. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2149. tools = [i[0] for i in sorted_tools]
  2150. for tool_no in tools:
  2151. drill_cnt = 0 # variable to store the nr of drills per tool
  2152. slot_cnt = 0 # variable to store the nr of slots per tool
  2153. # Find no of drills for the current tool
  2154. for drill in self.drills:
  2155. if drill['tool'] == tool_no:
  2156. drill_cnt += 1
  2157. self.tot_drill_cnt += drill_cnt
  2158. # Find no of slots for the current tool
  2159. for slot in self.slots:
  2160. if slot['tool'] == tool_no:
  2161. slot_cnt += 1
  2162. self.tot_slot_cnt += slot_cnt
  2163. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  2164. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2165. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.tools[tool_no]['C']))
  2166. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2167. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  2168. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2169. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  2170. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  2171. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  2172. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2173. try:
  2174. t_offset = self.tool_offset[float('%.*f' % (self.decimals, float(self.tools[tool_no]['C'])))]
  2175. except KeyError:
  2176. t_offset = self.app.defaults['excellon_offset']
  2177. tool_offset_item = FCDoubleSpinner()
  2178. tool_offset_item.set_precision(self.decimals)
  2179. tool_offset_item.set_range(-9999.9999, 9999.9999)
  2180. tool_offset_item.setWrapping(True)
  2181. tool_offset_item.setSingleStep(0.1) if self.units == 'MM' else tool_offset_item.setSingleStep(0.01)
  2182. tool_offset_item.set_value(t_offset)
  2183. plot_item = FCCheckBox()
  2184. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2185. if self.ui.plot_cb.isChecked():
  2186. plot_item.setChecked(True)
  2187. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  2188. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  2189. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  2190. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  2191. self.ui.tools_table.setCellWidget(self.tool_row, 4, tool_offset_item) # Tool offset
  2192. empty_plot_item = QtWidgets.QTableWidgetItem('')
  2193. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2194. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  2195. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  2196. self.tool_row += 1
  2197. # add a last row with the Total number of drills
  2198. empty_1 = QtWidgets.QTableWidgetItem('')
  2199. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2200. empty_1_1 = QtWidgets.QTableWidgetItem('')
  2201. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2202. empty_1_2 = QtWidgets.QTableWidgetItem('')
  2203. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2204. empty_1_3 = QtWidgets.QTableWidgetItem('')
  2205. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2206. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  2207. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  2208. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2209. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2210. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  2211. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  2212. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  2213. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  2214. self.ui.tools_table.setItem(self.tool_row, 4, empty_1_2)
  2215. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  2216. font = QtGui.QFont()
  2217. font.setBold(True)
  2218. font.setWeight(75)
  2219. for k in [1, 2]:
  2220. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  2221. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  2222. self.tool_row += 1
  2223. # add a last row with the Total number of slots
  2224. empty_2 = QtWidgets.QTableWidgetItem('')
  2225. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2226. empty_2_1 = QtWidgets.QTableWidgetItem('')
  2227. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2228. empty_2_2 = QtWidgets.QTableWidgetItem('')
  2229. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2230. empty_2_3 = QtWidgets.QTableWidgetItem('')
  2231. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2232. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  2233. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  2234. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2235. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2236. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  2237. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  2238. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  2239. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  2240. self.ui.tools_table.setItem(self.tool_row, 4, empty_2_2)
  2241. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  2242. for kl in [1, 2, 3]:
  2243. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  2244. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  2245. # sort the tool diameter column
  2246. # self.ui.tools_table.sortItems(1)
  2247. # all the tools are selected by default
  2248. self.ui.tools_table.selectColumn(0)
  2249. self.ui.tools_table.resizeColumnsToContents()
  2250. self.ui.tools_table.resizeRowsToContents()
  2251. vertical_header = self.ui.tools_table.verticalHeader()
  2252. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2253. vertical_header.hide()
  2254. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2255. horizontal_header = self.ui.tools_table.horizontalHeader()
  2256. horizontal_header.setMinimumSectionSize(10)
  2257. horizontal_header.setDefaultSectionSize(70)
  2258. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2259. horizontal_header.resizeSection(0, 20)
  2260. if self.app.defaults["global_app_level"] == 'b':
  2261. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2262. else:
  2263. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  2264. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  2265. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2266. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  2267. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  2268. horizontal_header.resizeSection(5, 17)
  2269. self.ui.tools_table.setColumnWidth(5, 17)
  2270. # horizontal_header.setStretchLastSection(True)
  2271. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2272. # horizontal_header.setStretchLastSection(True)
  2273. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2274. self.ui.tools_table.setSortingEnabled(False)
  2275. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  2276. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  2277. if not self.drills:
  2278. self.ui.tooldia_entry.hide()
  2279. self.ui.generate_milling_button.hide()
  2280. else:
  2281. self.ui.tooldia_entry.show()
  2282. self.ui.generate_milling_button.show()
  2283. if not self.slots:
  2284. self.ui.slot_tooldia_entry.hide()
  2285. self.ui.generate_milling_slots_button.hide()
  2286. else:
  2287. self.ui.slot_tooldia_entry.show()
  2288. self.ui.generate_milling_slots_button.show()
  2289. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  2290. for row in range(self.ui.tools_table.rowCount()):
  2291. try:
  2292. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2293. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2294. except (TypeError, AttributeError):
  2295. pass
  2296. # set the text on tool_data_label after loading the object
  2297. sel_rows = list()
  2298. sel_items = self.ui.tools_table.selectedItems()
  2299. for it in sel_items:
  2300. sel_rows.append(it.row())
  2301. if len(sel_rows) > 1:
  2302. self.ui.tool_data_label.setText(
  2303. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2304. )
  2305. self.ui_connect()
  2306. def set_ui(self, ui):
  2307. """
  2308. Configures the user interface for this object.
  2309. Connects options to form fields.
  2310. :param ui: User interface object.
  2311. :type ui: ExcellonObjectUI
  2312. :return: None
  2313. """
  2314. FlatCAMObj.set_ui(self, ui)
  2315. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  2316. self.units = self.app.defaults['units'].upper()
  2317. self.form_fields.update({
  2318. "plot": self.ui.plot_cb,
  2319. "solid": self.ui.solid_cb,
  2320. "drillz": self.ui.cutz_entry,
  2321. "travelz": self.ui.travelz_entry,
  2322. "feedrate": self.ui.feedrate_z_entry,
  2323. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  2324. "tooldia": self.ui.tooldia_entry,
  2325. "slot_tooldia": self.ui.slot_tooldia_entry,
  2326. "toolchange": self.ui.toolchange_cb,
  2327. "toolchangez": self.ui.toolchangez_entry,
  2328. "spindlespeed": self.ui.spindlespeed_entry,
  2329. "dwell": self.ui.dwell_cb,
  2330. "dwelltime": self.ui.dwelltime_entry,
  2331. "startz": self.ui.estartz_entry,
  2332. "endz": self.ui.endz_entry,
  2333. "ppname_e": self.ui.pp_excellon_name_cb,
  2334. "z_pdepth": self.ui.pdepth_entry,
  2335. "feedrate_probe": self.ui.feedrate_probe_entry,
  2336. "gcode_type": self.ui.excellon_gcode_type_radio
  2337. })
  2338. for name in list(self.app.preprocessors.keys()):
  2339. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  2340. if name == 'hpgl':
  2341. continue
  2342. self.ui.pp_excellon_name_cb.addItem(name)
  2343. # Fill form fields
  2344. self.to_form()
  2345. # update the changes in UI depending on the selected preprocessor in Preferences
  2346. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  2347. # self.ui.pp_excellon_name_cb combobox
  2348. self.on_pp_changed()
  2349. # initialize the dict that holds the tools offset
  2350. t_default_offset = self.app.defaults["excellon_offset"]
  2351. if not self.tool_offset:
  2352. for value in self.tools.values():
  2353. dia = float('%.*f' % (self.decimals, float(value['C'])))
  2354. self.tool_offset[dia] = t_default_offset
  2355. # Show/Hide Advanced Options
  2356. if self.app.defaults["global_app_level"] == 'b':
  2357. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  2358. self.ui.tools_table.setColumnHidden(4, True)
  2359. self.ui.tools_table.setColumnHidden(5, True)
  2360. self.ui.estartz_label.hide()
  2361. self.ui.estartz_entry.hide()
  2362. self.ui.feedrate_rapid_label.hide()
  2363. self.ui.feedrate_rapid_entry.hide()
  2364. self.ui.pdepth_label.hide()
  2365. self.ui.pdepth_entry.hide()
  2366. self.ui.feedrate_probe_label.hide()
  2367. self.ui.feedrate_probe_entry.hide()
  2368. else:
  2369. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  2370. assert isinstance(self.ui, ExcellonObjectUI), \
  2371. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  2372. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2373. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  2374. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  2375. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  2376. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  2377. self.on_operation_type(val='drill')
  2378. self.ui.operation_radio.activated_custom.connect(self.on_operation_type)
  2379. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  2380. self.units_found = self.app.defaults['units']
  2381. def ui_connect(self):
  2382. # selective plotting
  2383. for row in range(self.ui.tools_table.rowCount() - 2):
  2384. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  2385. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2386. # rows selected
  2387. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2388. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  2389. def ui_disconnect(self):
  2390. # selective plotting
  2391. for row in range(self.ui.tools_table.rowCount()):
  2392. try:
  2393. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  2394. except (TypeError, AttributeError):
  2395. pass
  2396. try:
  2397. self.ui.plot_cb.stateChanged.disconnect()
  2398. except (TypeError, AttributeError):
  2399. pass
  2400. # rows selected
  2401. try:
  2402. self.ui.tools_table.clicked.disconnect()
  2403. except (TypeError, AttributeError):
  2404. pass
  2405. try:
  2406. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2407. except (TypeError, AttributeError):
  2408. pass
  2409. def on_row_selection_change(self):
  2410. self.update_ui()
  2411. def update_ui(self, row=None):
  2412. self.ui_disconnect()
  2413. if row is None:
  2414. sel_rows = list()
  2415. sel_items = self.ui.tools_table.selectedItems()
  2416. for it in sel_items:
  2417. sel_rows.append(it.row())
  2418. else:
  2419. sel_rows = row if type(row) == list else [row]
  2420. if not sel_rows:
  2421. self.ui.tool_data_label.setText(
  2422. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  2423. )
  2424. self.ui.generate_cnc_button.setDisabled(True)
  2425. self.ui.generate_milling_button.setDisabled(True)
  2426. self.ui.generate_milling_slots_button.setDisabled(True)
  2427. self.ui_connect()
  2428. return
  2429. else:
  2430. self.ui.generate_cnc_button.setDisabled(False)
  2431. self.ui.generate_milling_button.setDisabled(False)
  2432. self.ui.generate_milling_slots_button.setDisabled(False)
  2433. if len(sel_rows) == 1:
  2434. # update the QLabel that shows for which Tool we have the parameters in the UI form
  2435. tooluid = int(self.ui.tools_table.item(sel_rows[0], 0).text())
  2436. self.ui.tool_data_label.setText(
  2437. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  2438. )
  2439. else:
  2440. self.ui.tool_data_label.setText(
  2441. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2442. )
  2443. for c_row in sel_rows:
  2444. # populate the form with the data from the tool associated with the row parameter
  2445. try:
  2446. item = self.ui.tools_table.item(c_row, 0)
  2447. if type(item) is not None:
  2448. tooluid = int(item.text())
  2449. else:
  2450. self.ui_connect()
  2451. return
  2452. except Exception as e:
  2453. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2454. self.ui_connect()
  2455. return
  2456. # try:
  2457. # # set the form with data from the newly selected tool
  2458. # for tooluid_key, tooluid_value in list(self.tools.items()):
  2459. # if int(tooluid_key) == tooluid:
  2460. # for key, value in tooluid_value.items():
  2461. # if key == 'data':
  2462. # form_value_storage = tooluid_value[key]
  2463. # self.update_form(form_value_storage)
  2464. # except Exception as e:
  2465. # log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2466. self.ui_connect()
  2467. def on_operation_type(self, val):
  2468. if val == 'mill':
  2469. self.ui.mill_type_label.show()
  2470. self.ui.mill_type_radio.show()
  2471. self.ui.mill_dia_label.show()
  2472. self.ui.mill_dia_entry.show()
  2473. self.ui.frxylabel.show()
  2474. self.ui.xyfeedrate_entry.show()
  2475. self.ui.extracut_cb.show()
  2476. self.ui.e_cut_entry.show()
  2477. if 'laser' not in self.ui.pp_excellon_name_cb.get_value().lower():
  2478. self.ui.mpass_cb.show()
  2479. self.ui.maxdepth_entry.show()
  2480. else:
  2481. self.ui.mill_type_label.hide()
  2482. self.ui.mill_type_radio.hide()
  2483. self.ui.mill_dia_label.hide()
  2484. self.ui.mill_dia_entry.hide()
  2485. self.ui.mpass_cb.hide()
  2486. self.ui.maxdepth_entry.hide()
  2487. self.ui.frxylabel.hide()
  2488. self.ui.xyfeedrate_entry.hide()
  2489. self.ui.extracut_cb.hide()
  2490. self.ui.e_cut_entry.hide()
  2491. def on_tool_offset_edit(self):
  2492. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2493. for row in range(self.ui.tools_table.rowCount()):
  2494. try:
  2495. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2496. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2497. offset_spin_widget.valueChanged.disconnect()
  2498. except (TypeError, AttributeError):
  2499. pass
  2500. self.units = self.app.defaults['units'].upper()
  2501. self.is_modified = True
  2502. row_of_item_changed = self.ui.tools_table.currentRow()
  2503. dia = float('%.*f' % (self.decimals, float(self.ui.tools_table.item(row_of_item_changed, 1).text())))
  2504. self.tool_offset[dia] = self.sender().get_value()
  2505. # we reactivate the signals after the after the tool editing
  2506. for row in range(self.ui.tools_table.rowCount()):
  2507. try:
  2508. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2509. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2510. except (TypeError, AttributeError):
  2511. pass
  2512. def get_selected_tools_list(self):
  2513. """
  2514. Returns the keys to the self.tools dictionary corresponding
  2515. to the selections on the tool list in the GUI.
  2516. :return: List of tools.
  2517. :rtype: list
  2518. """
  2519. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  2520. def get_selected_tools_table_items(self):
  2521. """
  2522. Returns a list of lists, each list in the list is made out of row elements
  2523. :return: List of table_tools items.
  2524. :rtype: list
  2525. """
  2526. table_tools_items = []
  2527. for x in self.ui.tools_table.selectedItems():
  2528. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  2529. # which does not have text
  2530. txt = ''
  2531. elem = list()
  2532. for column in range(0, self.ui.tools_table.columnCount() - 1):
  2533. try:
  2534. txt = self.ui.tools_table.item(x.row(), column).text()
  2535. except AttributeError:
  2536. try:
  2537. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  2538. except AttributeError:
  2539. pass
  2540. elem.append(txt)
  2541. table_tools_items.append(deepcopy(elem))
  2542. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  2543. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  2544. for item in table_tools_items:
  2545. item[0] = str(item[0])
  2546. return table_tools_items
  2547. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  2548. """
  2549. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  2550. :return: has_slots and Excellon_code
  2551. """
  2552. excellon_code = ''
  2553. # store here if the file has slots, return 1 if any slots, 0 if only drills
  2554. has_slots = 0
  2555. # drills processing
  2556. try:
  2557. if self.drills:
  2558. length = whole + fract
  2559. for tool in self.tools:
  2560. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  2561. for drill in self.drills:
  2562. if form == 'dec' and tool == drill['tool']:
  2563. drill_x = drill['point'].x * factor
  2564. drill_y = drill['point'].y * factor
  2565. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  2566. elif e_zeros == 'LZ' and tool == drill['tool']:
  2567. drill_x = drill['point'].x * factor
  2568. drill_y = drill['point'].y * factor
  2569. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  2570. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  2571. # extract whole part and decimal part
  2572. exc_x_formatted = exc_x_formatted.partition('.')
  2573. exc_y_formatted = exc_y_formatted.partition('.')
  2574. # left padd the 'whole' part with zeros
  2575. x_whole = exc_x_formatted[0].rjust(whole, '0')
  2576. y_whole = exc_y_formatted[0].rjust(whole, '0')
  2577. # restore the coordinate padded in the left with 0 and added the decimal part
  2578. # without the decinal dot
  2579. exc_x_formatted = x_whole + exc_x_formatted[2]
  2580. exc_y_formatted = y_whole + exc_y_formatted[2]
  2581. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2582. yform=exc_y_formatted)
  2583. elif tool == drill['tool']:
  2584. drill_x = drill['point'].x * factor
  2585. drill_y = drill['point'].y * factor
  2586. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  2587. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  2588. # pad with rear zeros
  2589. exc_x_formatted.ljust(length, '0')
  2590. exc_y_formatted.ljust(length, '0')
  2591. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2592. yform=exc_y_formatted)
  2593. except Exception as e:
  2594. log.debug(str(e))
  2595. # slots processing
  2596. try:
  2597. if self.slots:
  2598. has_slots = 1
  2599. for tool in self.tools:
  2600. excellon_code += 'G05\n'
  2601. if int(tool) < 10:
  2602. excellon_code += 'T0' + str(tool) + '\n'
  2603. else:
  2604. excellon_code += 'T' + str(tool) + '\n'
  2605. for slot in self.slots:
  2606. if form == 'dec' and tool == slot['tool']:
  2607. start_slot_x = slot['start'].x * factor
  2608. start_slot_y = slot['start'].y * factor
  2609. stop_slot_x = slot['stop'].x * factor
  2610. stop_slot_y = slot['stop'].y * factor
  2611. if slot_type == 'routing':
  2612. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  2613. start_slot_y,
  2614. dec=fract)
  2615. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  2616. stop_slot_y,
  2617. dec=fract)
  2618. elif slot_type == 'drilling':
  2619. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  2620. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  2621. )
  2622. elif e_zeros == 'LZ' and tool == slot['tool']:
  2623. start_slot_x = slot['start'].x * factor
  2624. start_slot_y = slot['start'].y * factor
  2625. stop_slot_x = slot['stop'].x * factor
  2626. stop_slot_y = slot['stop'].y * factor
  2627. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2628. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2629. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2630. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2631. # extract whole part and decimal part
  2632. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  2633. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  2634. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  2635. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  2636. # left padd the 'whole' part with zeros
  2637. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  2638. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  2639. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  2640. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  2641. # restore the coordinate padded in the left with 0 and added the decimal part
  2642. # without the decinal dot
  2643. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  2644. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  2645. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  2646. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  2647. if slot_type == 'routing':
  2648. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2649. ystart=start_slot_y_formatted)
  2650. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2651. ystop=stop_slot_y_formatted)
  2652. elif slot_type == 'drilling':
  2653. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2654. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2655. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2656. )
  2657. elif tool == slot['tool']:
  2658. start_slot_x = slot['start'].x * factor
  2659. start_slot_y = slot['start'].y * factor
  2660. stop_slot_x = slot['stop'].x * factor
  2661. stop_slot_y = slot['stop'].y * factor
  2662. length = whole + fract
  2663. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2664. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2665. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2666. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2667. # pad with rear zeros
  2668. start_slot_x_formatted.ljust(length, '0')
  2669. start_slot_y_formatted.ljust(length, '0')
  2670. stop_slot_x_formatted.ljust(length, '0')
  2671. stop_slot_y_formatted.ljust(length, '0')
  2672. if slot_type == 'routing':
  2673. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2674. ystart=start_slot_y_formatted)
  2675. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2676. ystop=stop_slot_y_formatted)
  2677. elif slot_type == 'drilling':
  2678. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2679. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2680. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2681. )
  2682. except Exception as e:
  2683. log.debug(str(e))
  2684. if not self.drills and not self.slots:
  2685. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  2686. return 'fail'
  2687. return has_slots, excellon_code
  2688. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  2689. """
  2690. Note: This method is a good template for generic operations as
  2691. it takes it's options from parameters or otherwise from the
  2692. object's options and returns a (success, msg) tuple as feedback
  2693. for shell operations.
  2694. :return: Success/failure condition tuple (bool, str).
  2695. :rtype: tuple
  2696. """
  2697. # Get the tools from the list. These are keys
  2698. # to self.tools
  2699. if tools is None:
  2700. tools = self.get_selected_tools_list()
  2701. if outname is None:
  2702. outname = self.options["name"] + "_mill"
  2703. if tooldia is None:
  2704. tooldia = float(self.options["tooldia"])
  2705. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2706. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2707. sort = []
  2708. for k, v in self.tools.items():
  2709. sort.append((k, v.get('C')))
  2710. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2711. if tools == "all":
  2712. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2713. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2714. if len(tools) == 0:
  2715. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2716. _("Please select one or more tools from the list and try again."))
  2717. return False, "Error: No tools."
  2718. for tool in tools:
  2719. if tooldia > self.tools[tool]["C"]:
  2720. self.app.inform.emit(
  2721. '[ERROR_NOTCL] %s %s: %s' % (
  2722. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  2723. _("Tool"),
  2724. str(tool)
  2725. )
  2726. )
  2727. return False, "Error: Milling tool is larger than hole."
  2728. def geo_init(geo_obj, app_obj):
  2729. assert isinstance(geo_obj, FlatCAMGeometry), \
  2730. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2731. # ## Add properties to the object
  2732. # get the tool_table items in a list of row items
  2733. tool_table_items = self.get_selected_tools_table_items()
  2734. # insert an information only element in the front
  2735. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2736. geo_obj.options['Tools_in_use'] = tool_table_items
  2737. geo_obj.options['type'] = 'Excellon Geometry'
  2738. geo_obj.options["cnctooldia"] = str(tooldia)
  2739. geo_obj.solid_geometry = []
  2740. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2741. # for FlatCAM is 6 decimals,
  2742. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2743. for hole in self.drills:
  2744. if hole['tool'] in tools:
  2745. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  2746. if buffer_value == 0:
  2747. geo_obj.solid_geometry.append(
  2748. Point(hole['point']).buffer(0.0000001).exterior)
  2749. else:
  2750. geo_obj.solid_geometry.append(
  2751. Point(hole['point']).buffer(buffer_value).exterior)
  2752. if use_thread:
  2753. def geo_thread(app_obj):
  2754. app_obj.new_object("geometry", outname, geo_init, plot=plot)
  2755. # Create a promise with the new name
  2756. self.app.collection.promise(outname)
  2757. # Send to worker
  2758. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2759. else:
  2760. self.app.new_object("geometry", outname, geo_init, plot=plot)
  2761. return True, ""
  2762. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=True, use_thread=False):
  2763. """
  2764. Note: This method is a good template for generic operations as
  2765. it takes it's options from parameters or otherwise from the
  2766. object's options and returns a (success, msg) tuple as feedback
  2767. for shell operations.
  2768. :return: Success/failure condition tuple (bool, str).
  2769. :rtype: tuple
  2770. """
  2771. # Get the tools from the list. These are keys
  2772. # to self.tools
  2773. if tools is None:
  2774. tools = self.get_selected_tools_list()
  2775. if outname is None:
  2776. outname = self.options["name"] + "_mill"
  2777. if tooldia is None:
  2778. tooldia = float(self.options["slot_tooldia"])
  2779. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2780. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2781. sort = []
  2782. for k, v in self.tools.items():
  2783. sort.append((k, v.get('C')))
  2784. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2785. if tools == "all":
  2786. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2787. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2788. if len(tools) == 0:
  2789. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2790. _("Please select one or more tools from the list and try again."))
  2791. return False, "Error: No tools."
  2792. for tool in tools:
  2793. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2794. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  2795. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2796. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  2797. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2798. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  2799. return False, "Error: Milling tool is larger than hole."
  2800. def geo_init(geo_obj, app_obj):
  2801. assert isinstance(geo_obj, FlatCAMGeometry), \
  2802. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2803. # ## Add properties to the object
  2804. # get the tool_table items in a list of row items
  2805. tool_table_items = self.get_selected_tools_table_items()
  2806. # insert an information only element in the front
  2807. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2808. geo_obj.options['Tools_in_use'] = tool_table_items
  2809. geo_obj.options['type'] = 'Excellon Geometry'
  2810. geo_obj.options["cnctooldia"] = str(tooldia)
  2811. geo_obj.solid_geometry = []
  2812. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2813. # for FlatCAM is 6 decimals,
  2814. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2815. for slot in self.slots:
  2816. if slot['tool'] in tools:
  2817. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  2818. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2819. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2820. # for the file_tool (tooldia actually)
  2821. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2822. if buffer_value == 0:
  2823. start = slot['start']
  2824. stop = slot['stop']
  2825. lines_string = LineString([start, stop])
  2826. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2827. geo_obj.solid_geometry.append(poly)
  2828. else:
  2829. start = slot['start']
  2830. stop = slot['stop']
  2831. lines_string = LineString([start, stop])
  2832. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2833. geo_obj.solid_geometry.append(poly)
  2834. if use_thread:
  2835. def geo_thread(app_obj):
  2836. app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2837. # Create a promise with the new name
  2838. self.app.collection.promise(outname)
  2839. # Send to worker
  2840. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2841. else:
  2842. self.app.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2843. return True, ""
  2844. def on_generate_milling_button_click(self, *args):
  2845. self.app.report_usage("excellon_on_create_milling_drills button")
  2846. self.read_form()
  2847. self.generate_milling_drills(use_thread=False)
  2848. def on_generate_milling_slots_button_click(self, *args):
  2849. self.app.report_usage("excellon_on_create_milling_slots_button")
  2850. self.read_form()
  2851. self.generate_milling_slots(use_thread=False)
  2852. def on_pp_changed(self):
  2853. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2854. if "toolchange_probe" in current_pp.lower():
  2855. self.ui.pdepth_entry.setVisible(True)
  2856. self.ui.pdepth_label.show()
  2857. self.ui.feedrate_probe_entry.setVisible(True)
  2858. self.ui.feedrate_probe_label.show()
  2859. else:
  2860. self.ui.pdepth_entry.setVisible(False)
  2861. self.ui.pdepth_label.hide()
  2862. self.ui.feedrate_probe_entry.setVisible(False)
  2863. self.ui.feedrate_probe_label.hide()
  2864. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2865. self.ui.feedrate_rapid_label.show()
  2866. self.ui.feedrate_rapid_entry.show()
  2867. else:
  2868. self.ui.feedrate_rapid_label.hide()
  2869. self.ui.feedrate_rapid_entry.hide()
  2870. if 'laser' in current_pp.lower():
  2871. self.ui.cutzlabel.hide()
  2872. self.ui.cutz_entry.hide()
  2873. try:
  2874. self.ui.mpass_cb.hide()
  2875. self.ui.maxdepth_entry.hide()
  2876. except AttributeError:
  2877. pass
  2878. if 'marlin' in current_pp.lower():
  2879. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  2880. self.ui.endz_label.show()
  2881. self.ui.endz_entry.show()
  2882. else:
  2883. self.ui.travelzlabel.hide()
  2884. self.ui.travelz_entry.hide()
  2885. self.ui.endz_label.hide()
  2886. self.ui.endz_entry.hide()
  2887. try:
  2888. self.ui.frzlabel.hide()
  2889. self.ui.feedrate_z_entry.hide()
  2890. except AttributeError:
  2891. pass
  2892. self.ui.dwell_cb.hide()
  2893. self.ui.dwelltime_entry.hide()
  2894. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  2895. try:
  2896. self.ui.tool_offset_label.hide()
  2897. self.ui.offset_entry.hide()
  2898. except AttributeError:
  2899. pass
  2900. else:
  2901. self.ui.cutzlabel.show()
  2902. self.ui.cutz_entry.show()
  2903. try:
  2904. self.ui.mpass_cb.show()
  2905. self.ui.maxdepth_entry.show()
  2906. except AttributeError:
  2907. pass
  2908. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  2909. self.ui.travelzlabel.show()
  2910. self.ui.travelz_entry.show()
  2911. self.ui.endz_label.show()
  2912. self.ui.endz_entry.show()
  2913. try:
  2914. self.ui.frzlabel.show()
  2915. self.ui.feedrate_z_entry.show()
  2916. except AttributeError:
  2917. pass
  2918. self.ui.dwell_cb.show()
  2919. self.ui.dwelltime_entry.show()
  2920. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  2921. try:
  2922. self.ui.tool_offset_lbl.show()
  2923. self.ui.offset_entry.show()
  2924. except AttributeError:
  2925. pass
  2926. def on_create_cncjob_button_click(self, *args):
  2927. self.app.report_usage("excellon_on_create_cncjob_button")
  2928. self.read_form()
  2929. # Get the tools from the list
  2930. tools = self.get_selected_tools_list()
  2931. if len(tools) == 0:
  2932. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  2933. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  2934. # in this case regardless of the selection status of that tool, use it.
  2935. if self.ui.tools_table.rowCount() == 3:
  2936. tools.append(self.ui.tools_table.item(0, 0).text())
  2937. else:
  2938. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2939. _("Please select one or more tools from the list and try again."))
  2940. return
  2941. xmin = self.options['xmin']
  2942. ymin = self.options['ymin']
  2943. xmax = self.options['xmax']
  2944. ymax = self.options['ymax']
  2945. job_name = self.options["name"] + "_cnc"
  2946. pp_excellon_name = self.options["ppname_e"]
  2947. # Object initialization function for app.new_object()
  2948. def job_init(job_obj, app_obj):
  2949. assert isinstance(job_obj, FlatCAMCNCjob), \
  2950. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2951. # get the tool_table items in a list of row items
  2952. tool_table_items = self.get_selected_tools_table_items()
  2953. # insert an information only element in the front
  2954. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2955. # ## Add properties to the object
  2956. job_obj.origin_kind = 'excellon'
  2957. job_obj.options['Tools_in_use'] = tool_table_items
  2958. job_obj.options['type'] = 'Excellon'
  2959. job_obj.options['ppname_e'] = pp_excellon_name
  2960. job_obj.z_cut = float(self.options["drillz"])
  2961. job_obj.tool_offset = self.tool_offset
  2962. job_obj.z_move = float(self.options["travelz"])
  2963. job_obj.feedrate = float(self.options["feedrate"])
  2964. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  2965. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  2966. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  2967. job_obj.dwell = self.options["dwell"]
  2968. job_obj.dwelltime = float(self.options["dwelltime"])
  2969. job_obj.pp_excellon_name = pp_excellon_name
  2970. job_obj.toolchange_xy_type = "excellon"
  2971. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  2972. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  2973. job_obj.options['xmin'] = xmin
  2974. job_obj.options['ymin'] = ymin
  2975. job_obj.options['xmax'] = xmax
  2976. job_obj.options['ymax'] = ymax
  2977. job_obj.z_pdepth = float(self.options["z_pdepth"])
  2978. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  2979. # There could be more than one drill size...
  2980. # job_obj.tooldia = # TODO: duplicate variable!
  2981. # job_obj.options["tooldia"] =
  2982. tools_csv = ','.join(tools)
  2983. ret_val = job_obj.generate_from_excellon_by_tool(
  2984. self, tools_csv,
  2985. drillz=float(self.options['drillz']),
  2986. toolchange=self.options["toolchange"],
  2987. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  2988. toolchangez=float(self.options["toolchangez"]),
  2989. startz=float(self.options["startz"]) if self.options["startz"] else None,
  2990. endz=float(self.options["endz"]),
  2991. excellon_optimization_type=self.app.defaults["excellon_optimization_type"])
  2992. if ret_val == 'fail':
  2993. return 'fail'
  2994. job_obj.gcode_parse()
  2995. job_obj.create_geometry()
  2996. # To be run in separate thread
  2997. def job_thread(app_obj):
  2998. with self.app.proc_container.new(_("Generating CNC Code")):
  2999. app_obj.new_object("cncjob", job_name, job_init)
  3000. # Create promise for the new name.
  3001. self.app.collection.promise(job_name)
  3002. # Send to worker
  3003. # self.app.worker.add_task(job_thread, [self.app])
  3004. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3005. def convert_units(self, units):
  3006. log.debug("FlatCAMObj.FlatCAMExcellon.convert_units()")
  3007. Excellon.convert_units(self, units)
  3008. # factor = Excellon.convert_units(self, units)
  3009. # self.options['drillz'] = float(self.options['drillz']) * factor
  3010. # self.options['travelz'] = float(self.options['travelz']) * factor
  3011. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  3012. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3013. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  3014. #
  3015. # if self.app.defaults["excellon_toolchangexy"] == '':
  3016. # self.options['toolchangexy'] = "0.0, 0.0"
  3017. # else:
  3018. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  3019. # if len(coords_xy) < 2:
  3020. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3021. # "in the format (x, y) \n"
  3022. # "but now there is only one value, not two. "))
  3023. # return 'fail'
  3024. # coords_xy[0] *= factor
  3025. # coords_xy[1] *= factor
  3026. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3027. #
  3028. # if self.options['startz'] is not None:
  3029. # self.options['startz'] = float(self.options['startz']) * factor
  3030. # self.options['endz'] = float(self.options['endz']) * factor
  3031. def on_solid_cb_click(self, *args):
  3032. if self.muted_ui:
  3033. return
  3034. self.read_form_item('solid')
  3035. self.plot()
  3036. def on_plot_cb_click(self, *args):
  3037. if self.muted_ui:
  3038. return
  3039. self.plot()
  3040. self.read_form_item('plot')
  3041. self.ui_disconnect()
  3042. cb_flag = self.ui.plot_cb.isChecked()
  3043. for row in range(self.ui.tools_table.rowCount() - 2):
  3044. table_cb = self.ui.tools_table.cellWidget(row, 5)
  3045. if cb_flag:
  3046. table_cb.setChecked(True)
  3047. else:
  3048. table_cb.setChecked(False)
  3049. self.ui_connect()
  3050. def on_plot_cb_click_table(self):
  3051. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3052. self.ui_disconnect()
  3053. # cw = self.sender()
  3054. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  3055. # cw_row = cw_index.row()
  3056. check_row = 0
  3057. self.shapes.clear(update=True)
  3058. for tool_key in self.tools:
  3059. solid_geometry = self.tools[tool_key]['solid_geometry']
  3060. # find the geo_tool_table row associated with the tool_key
  3061. for row in range(self.ui.tools_table.rowCount()):
  3062. tool_item = int(self.ui.tools_table.item(row, 0).text())
  3063. if tool_item == int(tool_key):
  3064. check_row = row
  3065. break
  3066. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  3067. self.options['plot'] = True
  3068. # self.plot_element(element=solid_geometry, visible=True)
  3069. # Plot excellon (All polygons?)
  3070. if self.options["solid"]:
  3071. for geo in solid_geometry:
  3072. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3073. visible=self.options['plot'],
  3074. layer=2)
  3075. else:
  3076. for geo in solid_geometry:
  3077. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3078. for ints in geo.interiors:
  3079. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  3080. self.shapes.redraw()
  3081. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3082. # if all the row plot's are enabled also enable the general plot checkbox
  3083. cb_cnt = 0
  3084. total_row = self.ui.tools_table.rowCount()
  3085. for row in range(total_row - 2):
  3086. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  3087. cb_cnt += 1
  3088. else:
  3089. cb_cnt -= 1
  3090. if cb_cnt < total_row - 2:
  3091. self.ui.plot_cb.setChecked(False)
  3092. else:
  3093. self.ui.plot_cb.setChecked(True)
  3094. self.ui_connect()
  3095. # def plot_element(self, element, color='red', visible=None, layer=None):
  3096. #
  3097. # visible = visible if visible else self.options['plot']
  3098. #
  3099. # try:
  3100. # for sub_el in element:
  3101. # self.plot_element(sub_el)
  3102. #
  3103. # except TypeError: # Element is not iterable...
  3104. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3105. def plot(self, visible=None, kind=None):
  3106. # Does all the required setup and returns False
  3107. # if the 'ptint' option is set to False.
  3108. if not FlatCAMObj.plot(self):
  3109. return
  3110. # try:
  3111. # # Plot Excellon (All polygons?)
  3112. # if self.options["solid"]:
  3113. # for tool in self.tools:
  3114. # for geo in self.tools[tool]['solid_geometry']:
  3115. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3116. # visible=self.options['plot'],
  3117. # layer=2)
  3118. # else:
  3119. # for tool in self.tools:
  3120. # for geo in self.tools[tool]['solid_geometry']:
  3121. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3122. # for ints in geo.interiors:
  3123. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  3124. #
  3125. # self.shapes.redraw()
  3126. # return
  3127. # except (ObjectDeleted, AttributeError, KeyError):
  3128. # self.shapes.clear(update=True)
  3129. # this stays for compatibility reasons, in case we try to open old projects
  3130. try:
  3131. __ = iter(self.solid_geometry)
  3132. except TypeError:
  3133. self.solid_geometry = [self.solid_geometry]
  3134. visible = visible if visible else self.options['plot']
  3135. try:
  3136. # Plot Excellon (All polygons?)
  3137. if self.options["solid"]:
  3138. for geo in self.solid_geometry:
  3139. self.add_shape(shape=geo,
  3140. color=self.outline_color,
  3141. face_color=self.fill_color,
  3142. visible=visible,
  3143. layer=2)
  3144. else:
  3145. for geo in self.solid_geometry:
  3146. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  3147. for ints in geo.interiors:
  3148. self.add_shape(shape=ints, color='orange', visible=visible)
  3149. self.shapes.redraw()
  3150. except (ObjectDeleted, AttributeError):
  3151. self.shapes.clear(update=True)
  3152. class FlatCAMGeometry(FlatCAMObj, Geometry):
  3153. """
  3154. Geometric object not associated with a specific
  3155. format.
  3156. """
  3157. optionChanged = QtCore.pyqtSignal(str)
  3158. ui_type = GeometryObjectUI
  3159. def __init__(self, name):
  3160. self.decimals = self.app.decimals
  3161. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  3162. FlatCAMObj.__init__(self, name)
  3163. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  3164. self.kind = "geometry"
  3165. self.options.update({
  3166. "plot": True,
  3167. "cutz": -0.002,
  3168. "vtipdia": 0.1,
  3169. "vtipangle": 30,
  3170. "travelz": 0.1,
  3171. "feedrate": 5.0,
  3172. "feedrate_z": 5.0,
  3173. "feedrate_rapid": 5.0,
  3174. "spindlespeed": 0,
  3175. "dwell": True,
  3176. "dwelltime": 1000,
  3177. "multidepth": False,
  3178. "depthperpass": 0.002,
  3179. "extracut": False,
  3180. "extracut_length": 0.1,
  3181. "endz": 2.0,
  3182. "startz": None,
  3183. "toolchange": False,
  3184. "toolchangez": 1.0,
  3185. "toolchangexy": "0.0, 0.0",
  3186. "ppname_g": 'default',
  3187. "z_pdepth": -0.02,
  3188. "feedrate_probe": 3.0,
  3189. })
  3190. if "cnctooldia" not in self.options:
  3191. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  3192. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  3193. else:
  3194. try:
  3195. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3196. tools_diameters = [eval(a) for a in tools_string if a != '']
  3197. self.options["cnctooldia"] = tools_diameters[0] if tools_diameters else 0.0
  3198. except Exception as e:
  3199. log.debug("FlatCAMObj.FlatCAMGeometry.init() --> %s" % str(e))
  3200. self.options["startz"] = self.app.defaults["geometry_startz"]
  3201. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  3202. self.tooluid = 0
  3203. '''
  3204. self.tools = {}
  3205. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  3206. tool_id of the tools and the value is another dict that will hold the data under the following form:
  3207. {tooluid: {
  3208. 'tooldia': 1,
  3209. 'offset': 'Path',
  3210. 'offset_value': 0.0
  3211. 'type': 'Rough',
  3212. 'tool_type': 'C1',
  3213. 'data': self.default_tool_data
  3214. 'solid_geometry': []
  3215. }
  3216. }
  3217. '''
  3218. self.tools = {}
  3219. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  3220. # those elements are the ones used for generating GCode
  3221. self.sel_tools = {}
  3222. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  3223. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  3224. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  3225. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  3226. self.v_tool_type = None
  3227. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  3228. # the default value is False
  3229. self.multigeo = False
  3230. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  3231. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  3232. self.special_group = None
  3233. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  3234. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  3235. self.units_found = self.app.defaults['units']
  3236. # this variable can be updated by the Object that generates the geometry
  3237. self.tool_type = 'C1'
  3238. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  3239. self.old_cutz = self.app.defaults["geometry_cutz"]
  3240. self.fill_color = self.app.defaults['geometry_plot_line']
  3241. self.outline_color = self.app.defaults['geometry_plot_line']
  3242. self.alpha_level = 'FF'
  3243. # Attributes to be included in serialization
  3244. # Always append to it because it carries contents
  3245. # from predecessors.
  3246. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  3247. def build_ui(self):
  3248. self.ui_disconnect()
  3249. FlatCAMObj.build_ui(self)
  3250. self.units = self.app.defaults['units']
  3251. offset = 0
  3252. tool_idx = 0
  3253. n = len(self.tools)
  3254. self.ui.geo_tools_table.setRowCount(n)
  3255. for tooluid_key, tooluid_value in self.tools.items():
  3256. tool_idx += 1
  3257. row_no = tool_idx - 1
  3258. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3259. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3260. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  3261. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3262. # There are no tool bits in MM with more than 3 decimals diameter.
  3263. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  3264. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  3265. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3266. offset_item = QtWidgets.QComboBox()
  3267. for item in self.offset_item_options:
  3268. offset_item.addItem(item)
  3269. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  3270. idx = offset_item.findText(tooluid_value['offset'])
  3271. offset_item.setCurrentIndex(idx)
  3272. type_item = QtWidgets.QComboBox()
  3273. for item in self.type_item_options:
  3274. type_item.addItem(item)
  3275. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3276. idx = type_item.findText(tooluid_value['type'])
  3277. type_item.setCurrentIndex(idx)
  3278. tool_type_item = QtWidgets.QComboBox()
  3279. for item in self.tool_type_item_options:
  3280. tool_type_item.addItem(item)
  3281. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3282. idx = tool_type_item.findText(tooluid_value['tool_type'])
  3283. tool_type_item.setCurrentIndex(idx)
  3284. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  3285. plot_item = FCCheckBox()
  3286. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3287. if self.ui.plot_cb.isChecked():
  3288. plot_item.setChecked(True)
  3289. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3290. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  3291. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  3292. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  3293. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3294. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  3295. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  3296. try:
  3297. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3298. except Exception as e:
  3299. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  3300. # make the diameter column editable
  3301. for row in range(tool_idx):
  3302. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3303. QtCore.Qt.ItemIsEditable |
  3304. QtCore.Qt.ItemIsEnabled)
  3305. # sort the tool diameter column
  3306. # self.ui.geo_tools_table.sortItems(1)
  3307. # all the tools are selected by default
  3308. # self.ui.geo_tools_table.selectColumn(0)
  3309. self.ui.geo_tools_table.resizeColumnsToContents()
  3310. self.ui.geo_tools_table.resizeRowsToContents()
  3311. vertical_header = self.ui.geo_tools_table.verticalHeader()
  3312. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3313. vertical_header.hide()
  3314. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3315. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  3316. horizontal_header.setMinimumSectionSize(10)
  3317. horizontal_header.setDefaultSectionSize(70)
  3318. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3319. horizontal_header.resizeSection(0, 20)
  3320. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3321. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  3322. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3323. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3324. horizontal_header.resizeSection(4, 40)
  3325. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3326. horizontal_header.resizeSection(4, 17)
  3327. # horizontal_header.setStretchLastSection(True)
  3328. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3329. self.ui.geo_tools_table.setColumnWidth(0, 20)
  3330. self.ui.geo_tools_table.setColumnWidth(4, 40)
  3331. self.ui.geo_tools_table.setColumnWidth(6, 17)
  3332. # self.ui.geo_tools_table.setSortingEnabled(True)
  3333. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  3334. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  3335. # update UI for all rows - useful after units conversion but only if there is at least one row
  3336. row_cnt = self.ui.geo_tools_table.rowCount()
  3337. if row_cnt > 0:
  3338. for r in range(row_cnt):
  3339. self.update_ui(r)
  3340. # select only the first tool / row
  3341. selected_row = 0
  3342. try:
  3343. self.select_tools_table_row(selected_row, clearsel=True)
  3344. # update the Geometry UI
  3345. self.update_ui()
  3346. except Exception as e:
  3347. # when the tools table is empty there will be this error but once the table is populated it will go away
  3348. log.debug(str(e))
  3349. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  3350. # and can create some problems
  3351. if self.multigeo is False:
  3352. self.ui.geo_tools_table.setColumnHidden(6, True)
  3353. else:
  3354. self.ui.geo_tools_table.setColumnHidden(6, False)
  3355. self.set_tool_offset_visibility(selected_row)
  3356. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  3357. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  3358. self.ui.name_entry.set_value(self.options['name'])
  3359. self.ui_connect()
  3360. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  3361. self.ui.e_cut_entry.setDisabled(True)
  3362. # set the text on tool_data_label after loading the object
  3363. sel_rows = list()
  3364. sel_items = self.ui.geo_tools_table.selectedItems()
  3365. for it in sel_items:
  3366. sel_rows.append(it.row())
  3367. if len(sel_rows) > 1:
  3368. self.ui.tool_data_label.setText(
  3369. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3370. )
  3371. def set_ui(self, ui):
  3372. FlatCAMObj.set_ui(self, ui)
  3373. log.debug("FlatCAMGeometry.set_ui()")
  3374. assert isinstance(self.ui, GeometryObjectUI), \
  3375. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  3376. self.units = self.app.defaults['units'].upper()
  3377. self.units_found = self.app.defaults['units']
  3378. # populate preprocessor names in the combobox
  3379. for name in list(self.app.preprocessors.keys()):
  3380. self.ui.pp_geometry_name_cb.addItem(name)
  3381. self.form_fields.update({
  3382. "plot": self.ui.plot_cb,
  3383. "cutz": self.ui.cutz_entry,
  3384. "vtipdia": self.ui.tipdia_entry,
  3385. "vtipangle": self.ui.tipangle_entry,
  3386. "travelz": self.ui.travelz_entry,
  3387. "feedrate": self.ui.cncfeedrate_entry,
  3388. "feedrate_z": self.ui.feedrate_z_entry,
  3389. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  3390. "spindlespeed": self.ui.cncspindlespeed_entry,
  3391. "dwell": self.ui.dwell_cb,
  3392. "dwelltime": self.ui.dwelltime_entry,
  3393. "multidepth": self.ui.mpass_cb,
  3394. "ppname_g": self.ui.pp_geometry_name_cb,
  3395. "z_pdepth": self.ui.pdepth_entry,
  3396. "feedrate_probe": self.ui.feedrate_probe_entry,
  3397. "depthperpass": self.ui.maxdepth_entry,
  3398. "extracut": self.ui.extracut_cb,
  3399. "extracut_length": self.ui.e_cut_entry,
  3400. "toolchange": self.ui.toolchangeg_cb,
  3401. "toolchangez": self.ui.toolchangez_entry,
  3402. "endz": self.ui.endz_entry,
  3403. "cnctooldia": self.ui.addtool_entry
  3404. })
  3405. # Fill form fields only on object create
  3406. self.to_form()
  3407. # update the changes in UI depending on the selected preprocessor in Preferences
  3408. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  3409. # self.ui.pp_geometry_name_cb combobox
  3410. self.on_pp_changed()
  3411. self.ui.tipdialabel.hide()
  3412. self.ui.tipdia_entry.hide()
  3413. self.ui.tipanglelabel.hide()
  3414. self.ui.tipangle_entry.hide()
  3415. self.ui.cutz_entry.setDisabled(False)
  3416. # store here the default data for Geometry Data
  3417. self.default_data = dict()
  3418. self.default_data.update({
  3419. "name": None,
  3420. "plot": None,
  3421. "cutz": None,
  3422. "vtipdia": None,
  3423. "vtipangle": None,
  3424. "travelz": None,
  3425. "feedrate": None,
  3426. "feedrate_z": None,
  3427. "feedrate_rapid": None,
  3428. "dwell": None,
  3429. "dwelltime": None,
  3430. "multidepth": None,
  3431. "ppname_g": None,
  3432. "depthperpass": None,
  3433. "extracut": None,
  3434. "extracut_length": None,
  3435. "toolchange": None,
  3436. "toolchangez": None,
  3437. "endz": None,
  3438. "spindlespeed": 0,
  3439. "toolchangexy": None,
  3440. "startz": None
  3441. })
  3442. # fill in self.default_data values from self.options
  3443. for def_key in self.default_data:
  3444. for opt_key, opt_val in self.options.items():
  3445. if def_key == opt_key:
  3446. self.default_data[def_key] = deepcopy(opt_val)
  3447. if type(self.options["cnctooldia"]) == float:
  3448. tools_list = [self.options["cnctooldia"]]
  3449. else:
  3450. try:
  3451. temp_tools = self.options["cnctooldia"].split(",")
  3452. tools_list = [
  3453. float(eval(dia)) for dia in temp_tools if dia != ''
  3454. ]
  3455. except Exception as e:
  3456. log.error("FlatCAMGeometry.set_ui() -> At least one tool diameter needed. "
  3457. "Verify in Edit -> Preferences -> Geometry General -> Tool dia. %s" % str(e))
  3458. return
  3459. self.tooluid += 1
  3460. if not self.tools:
  3461. for toold in tools_list:
  3462. new_data = deepcopy(self.default_data)
  3463. self.tools.update({
  3464. self.tooluid: {
  3465. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  3466. 'offset': 'Path',
  3467. 'offset_value': 0.0,
  3468. 'type': _('Rough'),
  3469. 'tool_type': self.tool_type,
  3470. 'data': new_data,
  3471. 'solid_geometry': self.solid_geometry
  3472. }
  3473. })
  3474. self.tooluid += 1
  3475. else:
  3476. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  3477. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  3478. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  3479. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  3480. # following convoluted way of changing the keys from string to float type
  3481. temp_tools = {}
  3482. for tooluid_key in self.tools:
  3483. val = deepcopy(self.tools[tooluid_key])
  3484. new_key = deepcopy(int(tooluid_key))
  3485. temp_tools[new_key] = val
  3486. self.tools.clear()
  3487. self.tools = deepcopy(temp_tools)
  3488. self.ui.tool_offset_entry.hide()
  3489. self.ui.tool_offset_lbl.hide()
  3490. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  3491. self.old_pp_state = self.default_data['multidepth']
  3492. self.old_toolchangeg_state = self.default_data['toolchange']
  3493. if not isinstance(self.ui, GeometryObjectUI):
  3494. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  3495. return
  3496. self.ui.geo_tools_table.setupContextMenu()
  3497. self.ui.geo_tools_table.addContextMenu(
  3498. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  3499. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  3500. self.ui.geo_tools_table.addContextMenu(
  3501. _("Copy"), self.on_tool_copy,
  3502. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  3503. self.ui.geo_tools_table.addContextMenu(
  3504. _("Delete"), lambda: self.on_tool_delete(all=None),
  3505. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  3506. # Show/Hide Advanced Options
  3507. if self.app.defaults["global_app_level"] == 'b':
  3508. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  3509. self.ui.geo_tools_table.setColumnHidden(2, True)
  3510. self.ui.geo_tools_table.setColumnHidden(3, True)
  3511. # self.ui.geo_tools_table.setColumnHidden(4, True)
  3512. self.ui.addtool_entry_lbl.hide()
  3513. self.ui.addtool_entry.hide()
  3514. self.ui.addtool_btn.hide()
  3515. self.ui.copytool_btn.hide()
  3516. self.ui.deltool_btn.hide()
  3517. # self.ui.endz_label.hide()
  3518. # self.ui.endz_entry.hide()
  3519. self.ui.fr_rapidlabel.hide()
  3520. self.ui.feedrate_rapid_entry.hide()
  3521. self.ui.extracut_cb.hide()
  3522. self.ui.e_cut_entry.hide()
  3523. self.ui.pdepth_label.hide()
  3524. self.ui.pdepth_entry.hide()
  3525. self.ui.feedrate_probe_label.hide()
  3526. self.ui.feedrate_probe_entry.hide()
  3527. else:
  3528. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  3529. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  3530. self.ui.e_cut_entry.setDisabled(True)
  3531. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  3532. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3533. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  3534. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  3535. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  3536. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  3537. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  3538. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  3539. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  3540. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  3541. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  3542. def on_cut_z_changed(self):
  3543. self.old_cutz = self.ui.cutz_entry.get_value()
  3544. def set_tool_offset_visibility(self, current_row):
  3545. if current_row is None:
  3546. return
  3547. try:
  3548. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  3549. if tool_offset is not None:
  3550. tool_offset_txt = tool_offset.currentText()
  3551. if tool_offset_txt == 'Custom':
  3552. self.ui.tool_offset_entry.show()
  3553. self.ui.tool_offset_lbl.show()
  3554. else:
  3555. self.ui.tool_offset_entry.hide()
  3556. self.ui.tool_offset_lbl.hide()
  3557. except Exception as e:
  3558. log.debug("set_tool_offset_visibility() --> " + str(e))
  3559. return
  3560. def on_offset_value_edited(self):
  3561. """
  3562. This will save the offset_value into self.tools storage whenever the offset value is edited
  3563. :return:
  3564. """
  3565. for current_row in self.ui.geo_tools_table.selectedItems():
  3566. # sometime the header get selected and it has row number -1
  3567. # we don't want to do anything with the header :)
  3568. if current_row.row() < 0:
  3569. continue
  3570. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3571. self.set_tool_offset_visibility(current_row.row())
  3572. for tooluid_key, tooluid_value in self.tools.items():
  3573. if int(tooluid_key) == tool_uid:
  3574. try:
  3575. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  3576. except ValueError:
  3577. # try to convert comma to decimal point. if it's still not working error message and return
  3578. try:
  3579. tooluid_value['offset_value'] = float(
  3580. self.ui.tool_offset_entry.get_value().replace(',', '.')
  3581. )
  3582. except ValueError:
  3583. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3584. _("Wrong value format entered, use a number."))
  3585. return
  3586. def ui_connect(self):
  3587. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3588. # changes in geometry UI
  3589. for i in range(self.ui.grid3.count()):
  3590. current_widget = self.ui.grid3.itemAt(i).widget()
  3591. if isinstance(current_widget, FCCheckBox):
  3592. current_widget.stateChanged.connect(self.gui_form_to_storage)
  3593. elif isinstance(current_widget, FCComboBox):
  3594. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  3595. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  3596. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  3597. current_widget.editingFinished.connect(self.gui_form_to_storage)
  3598. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3599. current_widget.returnPressed.connect(self.gui_form_to_storage)
  3600. for row in range(self.ui.geo_tools_table.rowCount()):
  3601. for col in [2, 3, 4]:
  3602. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  3603. self.on_tooltable_cellwidget_change)
  3604. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  3605. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  3606. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  3607. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  3608. # self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  3609. self.ui.geo_tools_table.clicked.connect(self.on_row_selection_change)
  3610. self.ui.geo_tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  3611. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  3612. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  3613. for row in range(self.ui.geo_tools_table.rowCount()):
  3614. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3615. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3616. # common parameters update
  3617. self.ui.pp_geometry_name_cb.currentIndexChanged.connect(self.update_common_param_in_storage)
  3618. def ui_disconnect(self):
  3619. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3620. # changes in geometry UI
  3621. for i in range(self.ui.grid3.count()):
  3622. current_widget = self.ui.grid3.itemAt(i).widget()
  3623. if isinstance(current_widget, FCCheckBox):
  3624. try:
  3625. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  3626. except (TypeError, AttributeError):
  3627. pass
  3628. elif isinstance(current_widget, FCComboBox):
  3629. try:
  3630. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  3631. except (TypeError, AttributeError):
  3632. pass
  3633. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  3634. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  3635. try:
  3636. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  3637. except (TypeError, AttributeError):
  3638. pass
  3639. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3640. try:
  3641. self.ui.grid3.itemAt(i).widget().returnPressed.disconnect(self.gui_form_to_storage)
  3642. except TypeError:
  3643. pass
  3644. for row in range(self.ui.geo_tools_table.rowCount()):
  3645. for col in [2, 3, 4]:
  3646. try:
  3647. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3648. except (TypeError, AttributeError):
  3649. pass
  3650. try:
  3651. self.ui.addtool_btn.clicked.disconnect()
  3652. except (TypeError, AttributeError):
  3653. pass
  3654. try:
  3655. self.ui.copytool_btn.clicked.disconnect()
  3656. except (TypeError, AttributeError):
  3657. pass
  3658. try:
  3659. self.ui.deltool_btn.clicked.disconnect()
  3660. except (TypeError, AttributeError):
  3661. pass
  3662. try:
  3663. self.ui.geo_tools_table.clicked.disconnect()
  3664. except (TypeError, AttributeError):
  3665. pass
  3666. try:
  3667. self.ui.geo_tools_table.horizontalHeader().sectionClicked.disconnect()
  3668. except (TypeError, AttributeError):
  3669. pass
  3670. try:
  3671. self.ui.geo_tools_table.itemChanged.disconnect()
  3672. except (TypeError, AttributeError):
  3673. pass
  3674. try:
  3675. self.ui.tool_offset_entry.returnPressed.disconnect()
  3676. except (TypeError, AttributeError):
  3677. pass
  3678. for row in range(self.ui.geo_tools_table.rowCount()):
  3679. try:
  3680. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  3681. except (TypeError, AttributeError):
  3682. pass
  3683. try:
  3684. self.ui.plot_cb.stateChanged.disconnect()
  3685. except (TypeError, AttributeError):
  3686. pass
  3687. def on_row_selection_change(self):
  3688. self.update_ui()
  3689. def update_ui(self, row=None):
  3690. self.ui_disconnect()
  3691. if row is None:
  3692. sel_rows = list()
  3693. sel_items = self.ui.geo_tools_table.selectedItems()
  3694. for it in sel_items:
  3695. sel_rows.append(it.row())
  3696. else:
  3697. sel_rows = row if type(row) == list else [row]
  3698. if not sel_rows:
  3699. sel_rows = [0]
  3700. for current_row in sel_rows:
  3701. self.set_tool_offset_visibility(current_row)
  3702. # populate the form with the data from the tool associated with the row parameter
  3703. try:
  3704. item = self.ui.geo_tools_table.item(current_row, 5)
  3705. if type(item) is not None:
  3706. tooluid = int(item.text())
  3707. else:
  3708. self.ui_connect()
  3709. return
  3710. except Exception as e:
  3711. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3712. self.ui_connect()
  3713. return
  3714. # update the QLabel that shows for which Tool we have the parameters in the UI form
  3715. if len(sel_rows) == 1:
  3716. self.ui.tool_data_label.setText(
  3717. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  3718. )
  3719. else:
  3720. self.ui.tool_data_label.setText(
  3721. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3722. )
  3723. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3724. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3725. try:
  3726. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3727. if item is not None:
  3728. tool_type_txt = item.currentText()
  3729. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3730. else:
  3731. self.ui_connect()
  3732. return
  3733. except Exception as e:
  3734. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  3735. return
  3736. try:
  3737. # set the form with data from the newly selected tool
  3738. for tooluid_key, tooluid_value in self.tools.items():
  3739. if int(tooluid_key) == tooluid:
  3740. for key, value in tooluid_value.items():
  3741. if key == 'data':
  3742. form_value_storage = tooluid_value['data']
  3743. self.update_form(form_value_storage)
  3744. if key == 'offset_value':
  3745. # update the offset value in the entry even if the entry is hidden
  3746. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3747. if key == 'tool_type' and value == 'V':
  3748. self.update_cutz()
  3749. except Exception as e:
  3750. log.debug("FlatCAMGeometry.update_ui() -> %s " % str(e))
  3751. self.ui_connect()
  3752. def on_tool_add(self, dia=None):
  3753. self.ui_disconnect()
  3754. self.units = self.app.defaults['units'].upper()
  3755. if dia is not None:
  3756. tooldia = dia
  3757. else:
  3758. tooldia = float(self.ui.addtool_entry.get_value())
  3759. # construct a list of all 'tooluid' in the self.tools
  3760. # tool_uid_list = list()
  3761. # for tooluid_key in self.tools:
  3762. # tool_uid_list.append(int(tooluid_key))
  3763. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  3764. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3765. max_uid = max(tool_uid_list) if tool_uid_list else 0
  3766. self.tooluid = max_uid + 1
  3767. tooldia = float('%.*f' % (self.decimals, tooldia))
  3768. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  3769. # otherwise we add a tool with data copied from last tool
  3770. if self.tools:
  3771. last_data = self.tools[max_uid]['data']
  3772. last_offset = self.tools[max_uid]['offset']
  3773. last_offset_value = self.tools[max_uid]['offset_value']
  3774. last_type = self.tools[max_uid]['type']
  3775. last_tool_type = self.tools[max_uid]['tool_type']
  3776. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  3777. # if previous geometry was empty (it may happen for the first tool added)
  3778. # then copy the object.solid_geometry
  3779. if not last_solid_geometry:
  3780. last_solid_geometry = self.solid_geometry
  3781. self.tools.update({
  3782. self.tooluid: {
  3783. 'tooldia': tooldia,
  3784. 'offset': last_offset,
  3785. 'offset_value': last_offset_value,
  3786. 'type': last_type,
  3787. 'tool_type': last_tool_type,
  3788. 'data': deepcopy(last_data),
  3789. 'solid_geometry': deepcopy(last_solid_geometry)
  3790. }
  3791. })
  3792. else:
  3793. self.tools.update({
  3794. self.tooluid: {
  3795. 'tooldia': tooldia,
  3796. 'offset': 'Path',
  3797. 'offset_value': 0.0,
  3798. 'type': _('Rough'),
  3799. 'tool_type': 'C1',
  3800. 'data': deepcopy(self.default_data),
  3801. 'solid_geometry': self.solid_geometry
  3802. }
  3803. })
  3804. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3805. self.ui.tool_offset_entry.hide()
  3806. self.ui.tool_offset_lbl.hide()
  3807. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3808. try:
  3809. self.ser_attrs.remove('tools')
  3810. except TypeError:
  3811. pass
  3812. self.ser_attrs.append('tools')
  3813. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  3814. self.ui_connect()
  3815. self.build_ui()
  3816. # if there is no tool left in the Tools Table, enable the parameters GUI
  3817. if self.ui.geo_tools_table.rowCount() != 0:
  3818. self.ui.geo_param_frame.setDisabled(False)
  3819. def on_tool_add_from_db_clicked(self):
  3820. """
  3821. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3822. and display the Tools Database tab in the form needed for the Tool adding
  3823. :return: None
  3824. """
  3825. # if the Tools Database is already opened focus on it
  3826. for idx in range(self.app.ui.plot_tab_area.count()):
  3827. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3828. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3829. break
  3830. self.app.on_tools_database()
  3831. self.app.tools_db_tab.buttons_frame.hide()
  3832. self.app.tools_db_tab.add_tool_from_db.show()
  3833. self.app.tools_db_tab.cancel_tool_from_db.show()
  3834. def on_tool_from_db_inserted(self, tool):
  3835. """
  3836. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3837. :param tool: a dict with the tool data
  3838. :return: None
  3839. """
  3840. self.ui_disconnect()
  3841. self.units = self.app.defaults['units'].upper()
  3842. tooldia = float(tool['tooldia'])
  3843. # construct a list of all 'tooluid' in the self.tools
  3844. tool_uid_list = []
  3845. for tooluid_key in self.tools:
  3846. tool_uid_item = int(tooluid_key)
  3847. tool_uid_list.append(tool_uid_item)
  3848. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3849. if not tool_uid_list:
  3850. max_uid = 0
  3851. else:
  3852. max_uid = max(tool_uid_list)
  3853. self.tooluid = max_uid + 1
  3854. tooldia = float('%.*f' % (self.decimals, tooldia))
  3855. self.tools.update({
  3856. self.tooluid: {
  3857. 'tooldia': tooldia,
  3858. 'offset': tool['offset'],
  3859. 'offset_value': float(tool['offset_value']),
  3860. 'type': tool['type'],
  3861. 'tool_type': tool['tool_type'],
  3862. 'data': deepcopy(tool['data']),
  3863. 'solid_geometry': self.solid_geometry
  3864. }
  3865. })
  3866. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3867. self.ui.tool_offset_entry.hide()
  3868. self.ui.tool_offset_lbl.hide()
  3869. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3870. try:
  3871. self.ser_attrs.remove('tools')
  3872. except TypeError:
  3873. pass
  3874. self.ser_attrs.append('tools')
  3875. self.ui_connect()
  3876. self.build_ui()
  3877. # if there is no tool left in the Tools Table, enable the parameters GUI
  3878. if self.ui.geo_tools_table.rowCount() != 0:
  3879. self.ui.geo_param_frame.setDisabled(False)
  3880. def on_tool_copy(self, all=None):
  3881. self.ui_disconnect()
  3882. # find the tool_uid maximum value in the self.tools
  3883. uid_list = []
  3884. for key in self.tools:
  3885. uid_list.append(int(key))
  3886. try:
  3887. max_uid = max(uid_list, key=int)
  3888. except ValueError:
  3889. max_uid = 0
  3890. if all is None:
  3891. if self.ui.geo_tools_table.selectedItems():
  3892. for current_row in self.ui.geo_tools_table.selectedItems():
  3893. # sometime the header get selected and it has row number -1
  3894. # we don't want to do anything with the header :)
  3895. if current_row.row() < 0:
  3896. continue
  3897. try:
  3898. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3899. self.set_tool_offset_visibility(current_row.row())
  3900. max_uid += 1
  3901. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3902. except AttributeError:
  3903. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  3904. self.ui_connect()
  3905. self.build_ui()
  3906. return
  3907. except Exception as e:
  3908. log.debug("on_tool_copy() --> " + str(e))
  3909. # deselect the table
  3910. # self.ui.geo_tools_table.clearSelection()
  3911. else:
  3912. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  3913. self.ui_connect()
  3914. self.build_ui()
  3915. return
  3916. else:
  3917. # we copy all tools in geo_tools_table
  3918. try:
  3919. temp_tools = deepcopy(self.tools)
  3920. max_uid += 1
  3921. for tooluid in temp_tools:
  3922. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3923. temp_tools.clear()
  3924. except Exception as e:
  3925. log.debug("on_tool_copy() --> " + str(e))
  3926. # if there are no more tools in geo tools table then hide the tool offset
  3927. if not self.tools:
  3928. self.ui.tool_offset_entry.hide()
  3929. self.ui.tool_offset_lbl.hide()
  3930. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3931. try:
  3932. self.ser_attrs.remove('tools')
  3933. except ValueError:
  3934. pass
  3935. self.ser_attrs.append('tools')
  3936. self.ui_connect()
  3937. self.build_ui()
  3938. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  3939. def on_tool_edit(self, current_item):
  3940. self.ui_disconnect()
  3941. current_row = current_item.row()
  3942. try:
  3943. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3944. except ValueError:
  3945. # try to convert comma to decimal point. if it's still not working error message and return
  3946. try:
  3947. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3948. except ValueError:
  3949. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  3950. return
  3951. tool_dia = float('%.*f' % (self.decimals, d))
  3952. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3953. self.tools[tooluid]['tooldia'] = tool_dia
  3954. try:
  3955. self.ser_attrs.remove('tools')
  3956. self.ser_attrs.append('tools')
  3957. except (TypeError, ValueError):
  3958. pass
  3959. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  3960. self.ui_connect()
  3961. self.build_ui()
  3962. def on_tool_delete(self, all=None):
  3963. self.ui_disconnect()
  3964. if all is None:
  3965. if self.ui.geo_tools_table.selectedItems():
  3966. for current_row in self.ui.geo_tools_table.selectedItems():
  3967. # sometime the header get selected and it has row number -1
  3968. # we don't want to do anything with the header :)
  3969. if current_row.row() < 0:
  3970. continue
  3971. try:
  3972. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3973. self.set_tool_offset_visibility(current_row.row())
  3974. temp_tools = deepcopy(self.tools)
  3975. for tooluid_key in self.tools:
  3976. if int(tooluid_key) == tooluid_del:
  3977. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3978. # as a property of the object otherwise there will be nothing to hold it
  3979. if len(self.tools) == 1:
  3980. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3981. temp_tools.pop(tooluid_del, None)
  3982. self.tools = deepcopy(temp_tools)
  3983. temp_tools.clear()
  3984. except AttributeError:
  3985. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  3986. self.ui_connect()
  3987. self.build_ui()
  3988. return
  3989. except Exception as e:
  3990. log.debug("on_tool_delete() --> " + str(e))
  3991. # deselect the table
  3992. # self.ui.geo_tools_table.clearSelection()
  3993. else:
  3994. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  3995. self.ui_connect()
  3996. self.build_ui()
  3997. return
  3998. else:
  3999. # we delete all tools in geo_tools_table
  4000. self.tools.clear()
  4001. self.app.plot_all()
  4002. # if there are no more tools in geo tools table then hide the tool offset
  4003. if not self.tools:
  4004. self.ui.tool_offset_entry.hide()
  4005. self.ui.tool_offset_lbl.hide()
  4006. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  4007. try:
  4008. self.ser_attrs.remove('tools')
  4009. except TypeError:
  4010. pass
  4011. self.ser_attrs.append('tools')
  4012. self.ui_connect()
  4013. self.build_ui()
  4014. self.app.inform.emit('[success] %s' % _("Tool was deleted in Tool Table."))
  4015. obj_active = self.app.collection.get_active()
  4016. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  4017. # we make it back SingleGeo
  4018. if self.ui.geo_tools_table.rowCount() <= 0:
  4019. obj_active.multigeo = False
  4020. obj_active.options['xmin'] = 0
  4021. obj_active.options['ymin'] = 0
  4022. obj_active.options['xmax'] = 0
  4023. obj_active.options['ymax'] = 0
  4024. if obj_active.multigeo is True:
  4025. try:
  4026. xmin, ymin, xmax, ymax = obj_active.bounds()
  4027. obj_active.options['xmin'] = xmin
  4028. obj_active.options['ymin'] = ymin
  4029. obj_active.options['xmax'] = xmax
  4030. obj_active.options['ymax'] = ymax
  4031. except Exception as e:
  4032. obj_active.options['xmin'] = 0
  4033. obj_active.options['ymin'] = 0
  4034. obj_active.options['xmax'] = 0
  4035. obj_active.options['ymax'] = 0
  4036. # if there is no tool left in the Tools Table, disable the parameters GUI
  4037. if self.ui.geo_tools_table.rowCount() == 0:
  4038. self.ui.geo_param_frame.setDisabled(True)
  4039. def ui_update_v_shape(self, tool_type_txt):
  4040. if tool_type_txt == 'V':
  4041. self.ui.tipdialabel.show()
  4042. self.ui.tipdia_entry.show()
  4043. self.ui.tipanglelabel.show()
  4044. self.ui.tipangle_entry.show()
  4045. self.ui.cutz_entry.setDisabled(True)
  4046. self.update_cutz()
  4047. else:
  4048. self.ui.tipdialabel.hide()
  4049. self.ui.tipdia_entry.hide()
  4050. self.ui.tipanglelabel.hide()
  4051. self.ui.tipangle_entry.hide()
  4052. self.ui.cutz_entry.setDisabled(False)
  4053. def update_cutz(self):
  4054. vdia = float(self.ui.tipdia_entry.get_value())
  4055. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  4056. row = self.ui.geo_tools_table.currentRow()
  4057. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  4058. if tool_uid_item is None:
  4059. return
  4060. tool_uid = int(tool_uid_item.text())
  4061. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  4062. if tool_dia_item is None:
  4063. return
  4064. tooldia = float(tool_dia_item.text())
  4065. try:
  4066. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  4067. except ZeroDivisionError:
  4068. new_cutz = self.old_cutz
  4069. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  4070. self.ui.cutz_entry.set_value(new_cutz)
  4071. # store the new CutZ value into storage (self.tools)
  4072. for tooluid_key, tooluid_value in self.tools.items():
  4073. if int(tooluid_key) == tool_uid:
  4074. tooluid_value['data']['cutz'] = new_cutz
  4075. def on_tooltable_cellwidget_change(self):
  4076. cw = self.sender()
  4077. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4078. cw_row = cw_index.row()
  4079. cw_col = cw_index.column()
  4080. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  4081. # store the text of the cellWidget that changed it's index in the self.tools
  4082. for tooluid_key, tooluid_value in self.tools.items():
  4083. if int(tooluid_key) == current_uid:
  4084. cb_txt = cw.currentText()
  4085. if cw_col == 2:
  4086. tooluid_value['offset'] = cb_txt
  4087. if cb_txt == 'Custom':
  4088. self.ui.tool_offset_entry.show()
  4089. self.ui.tool_offset_lbl.show()
  4090. else:
  4091. self.ui.tool_offset_entry.hide()
  4092. self.ui.tool_offset_lbl.hide()
  4093. # reset the offset_value in storage self.tools
  4094. tooluid_value['offset_value'] = 0.0
  4095. elif cw_col == 3:
  4096. # force toolpath type as 'Iso' if the tool type is V-Shape
  4097. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  4098. tooluid_value['type'] = _('Iso')
  4099. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4100. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4101. else:
  4102. tooluid_value['type'] = cb_txt
  4103. elif cw_col == 4:
  4104. tooluid_value['tool_type'] = cb_txt
  4105. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  4106. if cb_txt == 'V':
  4107. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4108. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4109. else:
  4110. self.ui.cutz_entry.set_value(self.old_cutz)
  4111. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  4112. def update_form(self, dict_storage):
  4113. for form_key in self.form_fields:
  4114. for storage_key in dict_storage:
  4115. if form_key == storage_key:
  4116. try:
  4117. self.form_fields[form_key].set_value(dict_storage[form_key])
  4118. except Exception as e:
  4119. log.debug(str(e))
  4120. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  4121. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  4122. self.ui.ois_dwell_geo.on_cb_change()
  4123. self.ui.ois_mpass_geo.on_cb_change()
  4124. self.ui.ois_tcz_geo.on_cb_change()
  4125. def on_apply_param_to_all_clicked(self):
  4126. if self.ui.geo_tools_table.rowCount() == 0:
  4127. # there is no tool in tool table so we can't save the GUI elements values to storage
  4128. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4129. return
  4130. self.ui_disconnect()
  4131. row = self.ui.geo_tools_table.currentRow()
  4132. if row < 0:
  4133. row = 0
  4134. # store all the data associated with the row parameter to the self.tools storage
  4135. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4136. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4137. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4138. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4139. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4140. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4141. temp_tools = {}
  4142. temp_dia = {}
  4143. temp_data = {}
  4144. for tooluid_key, tooluid_value in self.tools.items():
  4145. for key, value in tooluid_value.items():
  4146. if key == 'tooldia':
  4147. temp_dia[key] = tooldia_item
  4148. # update the 'offset', 'type' and 'tool_type' sections
  4149. if key == 'offset':
  4150. temp_dia[key] = offset_item
  4151. if key == 'type':
  4152. temp_dia[key] = type_item
  4153. if key == 'tool_type':
  4154. temp_dia[key] = tool_type_item
  4155. if key == 'offset_value':
  4156. temp_dia[key] = offset_value_item
  4157. if key == 'data':
  4158. # update the 'data' section
  4159. for data_key in tooluid_value[key].keys():
  4160. for form_key, form_value in self.form_fields.items():
  4161. if form_key == data_key:
  4162. temp_data[data_key] = form_value.get_value()
  4163. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4164. # updated from self.app.defaults
  4165. if data_key not in self.form_fields:
  4166. temp_data[data_key] = value[data_key]
  4167. temp_dia[key] = deepcopy(temp_data)
  4168. temp_data.clear()
  4169. if key == 'solid_geometry':
  4170. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4171. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4172. self.tools.clear()
  4173. self.tools = deepcopy(temp_tools)
  4174. temp_tools.clear()
  4175. self.ui_connect()
  4176. def gui_form_to_storage(self):
  4177. if self.ui.geo_tools_table.rowCount() == 0:
  4178. # there is no tool in tool table so we can't save the GUI elements values to storage
  4179. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4180. return
  4181. self.ui_disconnect()
  4182. widget_changed = self.sender()
  4183. try:
  4184. widget_idx = self.ui.grid3.indexOf(widget_changed)
  4185. except Exception as e:
  4186. return
  4187. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  4188. if widget_idx == 1 or widget_idx == 3:
  4189. self.update_cutz()
  4190. # the original connect() function of the OptionalInputSelection is no longer working because of the
  4191. # ui_diconnect() so I use this 'hack'
  4192. if isinstance(widget_changed, FCCheckBox):
  4193. if widget_changed.text() == 'Multi-Depth:':
  4194. self.ui.ois_mpass_geo.on_cb_change()
  4195. if widget_changed.text() == 'Tool change':
  4196. self.ui.ois_tcz_geo.on_cb_change()
  4197. if widget_changed.text() == 'Dwell:':
  4198. self.ui.ois_dwell_geo.on_cb_change()
  4199. row = self.ui.geo_tools_table.currentRow()
  4200. if row < 0:
  4201. row = 0
  4202. # store all the data associated with the row parameter to the self.tools storage
  4203. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4204. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4205. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4206. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4207. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4208. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4209. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4210. temp_tools = {}
  4211. temp_dia = {}
  4212. temp_data = {}
  4213. for tooluid_key, tooluid_value in self.tools.items():
  4214. if int(tooluid_key) == tooluid_item:
  4215. for key, value in tooluid_value.items():
  4216. if key == 'tooldia':
  4217. temp_dia[key] = tooldia_item
  4218. # update the 'offset', 'type' and 'tool_type' sections
  4219. if key == 'offset':
  4220. temp_dia[key] = offset_item
  4221. if key == 'type':
  4222. temp_dia[key] = type_item
  4223. if key == 'tool_type':
  4224. temp_dia[key] = tool_type_item
  4225. if key == 'offset_value':
  4226. temp_dia[key] = offset_value_item
  4227. if key == 'data':
  4228. # update the 'data' section
  4229. for data_key in tooluid_value[key].keys():
  4230. for form_key, form_value in self.form_fields.items():
  4231. if form_key == data_key:
  4232. temp_data[data_key] = form_value.get_value()
  4233. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4234. # updated from self.app.defaults
  4235. if data_key not in self.form_fields:
  4236. temp_data[data_key] = value[data_key]
  4237. temp_dia[key] = deepcopy(temp_data)
  4238. temp_data.clear()
  4239. if key == 'solid_geometry':
  4240. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4241. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4242. else:
  4243. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  4244. self.tools.clear()
  4245. self.tools = deepcopy(temp_tools)
  4246. temp_tools.clear()
  4247. self.ui_connect()
  4248. def update_common_param_in_storage(self):
  4249. for tooluid_value in self.tools.values():
  4250. tooluid_value['data']['ppname_g'] = self.ui.pp_geometry_name_cb.get_value()
  4251. def select_tools_table_row(self, row, clearsel=None):
  4252. if clearsel:
  4253. self.ui.geo_tools_table.clearSelection()
  4254. if self.ui.geo_tools_table.rowCount() > 0:
  4255. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  4256. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  4257. def export_dxf(self):
  4258. units = self.app.defaults['units'].upper()
  4259. dwg = None
  4260. try:
  4261. dwg = ezdxf.new('R2010')
  4262. msp = dwg.modelspace()
  4263. def g2dxf(dxf_space, geo):
  4264. if isinstance(geo, MultiPolygon):
  4265. for poly in geo:
  4266. ext_points = list(poly.exterior.coords)
  4267. dxf_space.add_lwpolyline(ext_points)
  4268. for interior in poly.interiors:
  4269. dxf_space.add_lwpolyline(list(interior.coords))
  4270. if isinstance(geo, Polygon):
  4271. ext_points = list(geo.exterior.coords)
  4272. dxf_space.add_lwpolyline(ext_points)
  4273. for interior in geo.interiors:
  4274. dxf_space.add_lwpolyline(list(interior.coords))
  4275. if isinstance(geo, MultiLineString):
  4276. for line in geo:
  4277. dxf_space.add_lwpolyline(list(line.coords))
  4278. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  4279. dxf_space.add_lwpolyline(list(geo.coords))
  4280. multigeo_solid_geometry = []
  4281. if self.multigeo:
  4282. for tool in self.tools:
  4283. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  4284. else:
  4285. multigeo_solid_geometry = self.solid_geometry
  4286. for geo in multigeo_solid_geometry:
  4287. if type(geo) == list:
  4288. for g in geo:
  4289. g2dxf(msp, g)
  4290. else:
  4291. g2dxf(msp, geo)
  4292. # points = FlatCAMGeometry.get_pts(geo)
  4293. # msp.add_lwpolyline(points)
  4294. except Exception as e:
  4295. log.debug(str(e))
  4296. return dwg
  4297. def get_selected_tools_table_items(self):
  4298. """
  4299. Returns a list of lists, each list in the list is made out of row elements
  4300. :return: List of table_tools items.
  4301. :rtype: list
  4302. """
  4303. table_tools_items = []
  4304. if self.multigeo:
  4305. for x in self.ui.geo_tools_table.selectedItems():
  4306. elem = list()
  4307. txt = ''
  4308. for column in range(0, self.ui.geo_tools_table.columnCount()):
  4309. try:
  4310. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4311. except AttributeError:
  4312. try:
  4313. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4314. except AttributeError:
  4315. pass
  4316. elem.append(txt)
  4317. table_tools_items.append(deepcopy(elem))
  4318. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  4319. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  4320. else:
  4321. for x in self.ui.geo_tools_table.selectedItems():
  4322. r = []
  4323. txt = ''
  4324. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  4325. # so we don't read them
  4326. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  4327. # the columns have items that have text but also have items that are widgets
  4328. # for which the text they hold has to be read differently
  4329. try:
  4330. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4331. except AttributeError:
  4332. try:
  4333. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4334. except AttributeError:
  4335. pass
  4336. r.append(txt)
  4337. table_tools_items.append(r)
  4338. for item in table_tools_items:
  4339. item[0] = str(item[0])
  4340. return table_tools_items
  4341. def on_pp_changed(self):
  4342. current_pp = self.ui.pp_geometry_name_cb.get_value()
  4343. if current_pp == 'hpgl':
  4344. self.old_pp_state = self.ui.mpass_cb.get_value()
  4345. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  4346. self.ui.mpass_cb.set_value(False)
  4347. self.ui.mpass_cb.setDisabled(True)
  4348. self.ui.toolchangeg_cb.set_value(True)
  4349. self.ui.toolchangeg_cb.setDisabled(True)
  4350. else:
  4351. self.ui.mpass_cb.set_value(self.old_pp_state)
  4352. self.ui.mpass_cb.setDisabled(False)
  4353. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  4354. self.ui.toolchangeg_cb.setDisabled(False)
  4355. if "toolchange_probe" in current_pp.lower():
  4356. self.ui.pdepth_entry.setVisible(True)
  4357. self.ui.pdepth_label.show()
  4358. self.ui.feedrate_probe_entry.setVisible(True)
  4359. self.ui.feedrate_probe_label.show()
  4360. else:
  4361. self.ui.pdepth_entry.setVisible(False)
  4362. self.ui.pdepth_label.hide()
  4363. self.ui.feedrate_probe_entry.setVisible(False)
  4364. self.ui.feedrate_probe_label.hide()
  4365. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  4366. self.ui.fr_rapidlabel.show()
  4367. self.ui.feedrate_rapid_entry.show()
  4368. else:
  4369. self.ui.fr_rapidlabel.hide()
  4370. self.ui.feedrate_rapid_entry.hide()
  4371. if 'laser' in current_pp.lower():
  4372. self.ui.cutzlabel.hide()
  4373. self.ui.cutz_entry.hide()
  4374. try:
  4375. self.ui.mpass_cb.hide()
  4376. self.ui.maxdepth_entry.hide()
  4377. except AttributeError:
  4378. pass
  4379. if 'marlin' in current_pp.lower():
  4380. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  4381. self.ui.endz_label.show()
  4382. self.ui.endz_entry.show()
  4383. else:
  4384. self.ui.travelzlabel.hide()
  4385. self.ui.travelz_entry.hide()
  4386. self.ui.endz_label.hide()
  4387. self.ui.endz_entry.hide()
  4388. try:
  4389. self.ui.frzlabel.hide()
  4390. self.ui.feedrate_z_entry.hide()
  4391. except AttributeError:
  4392. pass
  4393. self.ui.dwell_cb.hide()
  4394. self.ui.dwelltime_entry.hide()
  4395. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  4396. try:
  4397. self.ui.tool_offset_label.hide()
  4398. self.ui.offset_entry.hide()
  4399. except AttributeError:
  4400. pass
  4401. else:
  4402. self.ui.cutzlabel.show()
  4403. self.ui.cutz_entry.show()
  4404. try:
  4405. self.ui.mpass_cb.show()
  4406. self.ui.maxdepth_entry.show()
  4407. except AttributeError:
  4408. pass
  4409. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  4410. self.ui.travelzlabel.show()
  4411. self.ui.travelz_entry.show()
  4412. self.ui.endz_label.show()
  4413. self.ui.endz_entry.show()
  4414. try:
  4415. self.ui.frzlabel.show()
  4416. self.ui.feedrate_z_entry.show()
  4417. except AttributeError:
  4418. pass
  4419. self.ui.dwell_cb.show()
  4420. self.ui.dwelltime_entry.show()
  4421. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  4422. try:
  4423. self.ui.tool_offset_lbl.show()
  4424. self.ui.offset_entry.show()
  4425. except AttributeError:
  4426. pass
  4427. def on_generatecnc_button_click(self, *args):
  4428. log.debug("Generating CNCJob from Geometry ...")
  4429. self.app.report_usage("geometry_on_generatecnc_button")
  4430. # this reads the values in the UI form to the self.options dictionary
  4431. self.read_form()
  4432. self.sel_tools = dict()
  4433. try:
  4434. if self.special_group:
  4435. self.app.inform.emit(
  4436. '[WARNING_NOTCL] %s %s %s.' %
  4437. (_("This Geometry can't be processed because it is"), str(self.special_group), _("geometry"))
  4438. )
  4439. return
  4440. except AttributeError:
  4441. pass
  4442. # test to see if we have tools available in the tool table
  4443. if self.ui.geo_tools_table.selectedItems():
  4444. for x in self.ui.geo_tools_table.selectedItems():
  4445. # try:
  4446. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  4447. # except ValueError:
  4448. # # try to convert comma to decimal point. if it's still not working error message and return
  4449. # try:
  4450. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  4451. # except ValueError:
  4452. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  4453. # _("Wrong value format entered, use a number."))
  4454. # return
  4455. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  4456. for tooluid_key, tooluid_value in self.tools.items():
  4457. if int(tooluid_key) == tooluid:
  4458. self.sel_tools.update({
  4459. tooluid: deepcopy(tooluid_value)
  4460. })
  4461. self.mtool_gen_cncjob()
  4462. self.ui.geo_tools_table.clearSelection()
  4463. elif self.ui.geo_tools_table.rowCount() == 1:
  4464. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  4465. for tooluid_key, tooluid_value in self.tools.items():
  4466. if int(tooluid_key) == tooluid:
  4467. self.sel_tools.update({
  4468. tooluid: deepcopy(tooluid_value)
  4469. })
  4470. self.mtool_gen_cncjob()
  4471. self.ui.geo_tools_table.clearSelection()
  4472. else:
  4473. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No tool selected in the tool table ..."))
  4474. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  4475. plot=True, use_thread=True):
  4476. """
  4477. Creates a multi-tool CNCJob out of this Geometry object.
  4478. The actual work is done by the target FlatCAMCNCjob object's
  4479. `generate_from_geometry_2()` method.
  4480. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  4481. (including the solid_geometry)
  4482. :param tools_in_use: the tools that are used, needed by some preprocessors
  4483. :type list of lists, each list in the list is made out of row elements of tools table from GUI
  4484. :param segx: number of segments on the X axis, for auto-levelling
  4485. :param segy: number of segments on the Y axis, for auto-levelling
  4486. :param plot: if True the generated object will be plotted; if False will not be plotted
  4487. :param use_thread: if True use threading
  4488. :return: None
  4489. """
  4490. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  4491. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  4492. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  4493. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  4494. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4495. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4496. try:
  4497. xmin = self.options['xmin']
  4498. ymin = self.options['ymin']
  4499. xmax = self.options['xmax']
  4500. ymax = self.options['ymax']
  4501. except Exception as e:
  4502. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  4503. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  4504. msg += '%s %s' % ('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() -->', str(e))
  4505. msg += traceback.format_exc()
  4506. self.app.inform.emit(msg)
  4507. return
  4508. # Object initialization function for app.new_object()
  4509. # RUNNING ON SEPARATE THREAD!
  4510. def job_init_single_geometry(job_obj, app_obj):
  4511. log.debug("Creating a CNCJob out of a single-geometry")
  4512. assert isinstance(job_obj, FlatCAMCNCjob), \
  4513. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4514. job_obj.options['xmin'] = xmin
  4515. job_obj.options['ymin'] = ymin
  4516. job_obj.options['xmax'] = xmax
  4517. job_obj.options['ymax'] = ymax
  4518. # count the tools
  4519. tool_cnt = 0
  4520. dia_cnc_dict = dict()
  4521. # this turn on the FlatCAMCNCJob plot for multiple tools
  4522. job_obj.multitool = True
  4523. job_obj.multigeo = False
  4524. job_obj.cnc_tools.clear()
  4525. job_obj.options['Tools_in_use'] = tools_in_use
  4526. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4527. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4528. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4529. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4530. for tooluid_key in list(tools_dict.keys()):
  4531. tool_cnt += 1
  4532. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4533. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4534. dia_cnc_dict.update({
  4535. 'tooldia': tooldia_val
  4536. })
  4537. if dia_cnc_dict['offset'] == 'in':
  4538. tool_offset = -dia_cnc_dict['tooldia'] / 2
  4539. elif dia_cnc_dict['offset'].lower() == 'out':
  4540. tool_offset = dia_cnc_dict['tooldia'] / 2
  4541. elif dia_cnc_dict['offset'].lower() == 'custom':
  4542. try:
  4543. offset_value = float(self.ui.tool_offset_entry.get_value())
  4544. except ValueError:
  4545. # try to convert comma to decimal point. if it's still not working error message and return
  4546. try:
  4547. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4548. except ValueError:
  4549. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  4550. return
  4551. if offset_value:
  4552. tool_offset = float(offset_value)
  4553. else:
  4554. self.app.inform.emit(
  4555. '[WARNING] %s' % _("Tool Offset is selected in Tool Table but no value is provided.\n"
  4556. "Add a Tool Offset or change the Offset Type.")
  4557. )
  4558. return
  4559. else:
  4560. tool_offset = 0.0
  4561. dia_cnc_dict.update({
  4562. 'offset_value': tool_offset
  4563. })
  4564. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4565. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4566. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4567. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4568. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4569. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4570. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4571. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4572. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4573. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4574. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4575. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4576. startz = tools_dict[tooluid_key]['data']["startz"]
  4577. endz = tools_dict[tooluid_key]['data']["endz"]
  4578. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4579. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4580. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4581. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4582. spindledir = self.app.defaults['geometry_spindledir']
  4583. tool_solid_geometry = self.solid_geometry
  4584. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4585. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4586. # Propagate options
  4587. job_obj.options["tooldia"] = tooldia_val
  4588. job_obj.options['type'] = 'Geometry'
  4589. job_obj.options['tool_dia'] = tooldia_val
  4590. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4591. # to a value of 0.0005 which is 20 times less than 0.01
  4592. tol = float(self.app.defaults['global_tolerance']) / 20
  4593. res = job_obj.generate_from_geometry_2(
  4594. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  4595. z_cut=z_cut, z_move=z_move,
  4596. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4597. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4598. multidepth=multidepth, depthpercut=depthpercut,
  4599. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4600. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4601. pp_geometry_name=pp_geometry_name,
  4602. tool_no=tool_cnt)
  4603. if res == 'fail':
  4604. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4605. return 'fail'
  4606. else:
  4607. dia_cnc_dict['gcode'] = res
  4608. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4609. # object is the source of gcode
  4610. job_obj.toolchange_xy_type = "geometry"
  4611. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4612. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4613. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4614. # TODO this serve for bounding box creation only; should be optimized
  4615. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4616. # for bounding box values
  4617. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  4618. try:
  4619. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  4620. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  4621. except Exception as e:
  4622. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4623. job_obj.cnc_tools.update({
  4624. tooluid_key: deepcopy(dia_cnc_dict)
  4625. })
  4626. dia_cnc_dict.clear()
  4627. # Object initialization function for app.new_object()
  4628. # RUNNING ON SEPARATE THREAD!
  4629. def job_init_multi_geometry(job_obj, app_obj):
  4630. log.debug("Creating a CNCJob out of a multi-geometry")
  4631. assert isinstance(job_obj, FlatCAMCNCjob), \
  4632. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4633. current_uid = int(1)
  4634. job_obj.options['xmin'] = xmin
  4635. job_obj.options['ymin'] = ymin
  4636. job_obj.options['xmax'] = xmax
  4637. job_obj.options['ymax'] = ymax
  4638. # count the tools
  4639. tool_cnt = 0
  4640. dia_cnc_dict = dict()
  4641. # this turn on the FlatCAMCNCJob plot for multiple tools
  4642. job_obj.multitool = True
  4643. job_obj.multigeo = True
  4644. job_obj.cnc_tools.clear()
  4645. job_obj.options['Tools_in_use'] = tools_in_use
  4646. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4647. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4648. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4649. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4650. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  4651. if not self.solid_geometry:
  4652. a = 0
  4653. for tooluid_key in self.tools:
  4654. if self.tools[tooluid_key]['solid_geometry'] is None:
  4655. a += 1
  4656. if a == len(self.tools):
  4657. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  4658. return 'fail'
  4659. for tooluid_key in list(tools_dict.keys()):
  4660. tool_cnt += 1
  4661. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4662. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4663. dia_cnc_dict.update({
  4664. 'tooldia': tooldia_val
  4665. })
  4666. # find the tool_dia associated with the tooluid_key
  4667. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  4668. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  4669. for k, v in self.tools.items():
  4670. if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  4671. current_uid = int(k)
  4672. break
  4673. if dia_cnc_dict['offset'] == 'in':
  4674. tool_offset = -tooldia_val / 2
  4675. elif dia_cnc_dict['offset'].lower() == 'out':
  4676. tool_offset = tooldia_val / 2
  4677. elif dia_cnc_dict['offset'].lower() == 'custom':
  4678. offset_value = float(self.ui.tool_offset_entry.get_value())
  4679. if offset_value:
  4680. tool_offset = float(offset_value)
  4681. else:
  4682. self.app.inform.emit('[WARNING] %s' %
  4683. _("Tool Offset is selected in Tool Table but "
  4684. "no value is provided.\n"
  4685. "Add a Tool Offset or change the Offset Type."))
  4686. return
  4687. else:
  4688. tool_offset = 0.0
  4689. dia_cnc_dict.update({
  4690. 'offset_value': tool_offset
  4691. })
  4692. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4693. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4694. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4695. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4696. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4697. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4698. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4699. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4700. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4701. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4702. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4703. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4704. startz = tools_dict[tooluid_key]['data']["startz"]
  4705. endz = tools_dict[tooluid_key]['data']["endz"]
  4706. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4707. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4708. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4709. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4710. spindledir = self.app.defaults['geometry_spindledir']
  4711. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  4712. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4713. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4714. # Propagate options
  4715. job_obj.options["tooldia"] = tooldia_val
  4716. job_obj.options['type'] = 'Geometry'
  4717. job_obj.options['tool_dia'] = tooldia_val
  4718. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4719. # to a value of 0.0005 which is 20 times less than 0.01
  4720. tol = float(self.app.defaults['global_tolerance']) / 20
  4721. res = job_obj.generate_from_multitool_geometry(
  4722. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  4723. tolerance=tol, z_cut=z_cut, z_move=z_move,
  4724. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4725. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4726. multidepth=multidepth, depthpercut=depthpercut,
  4727. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4728. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4729. pp_geometry_name=pp_geometry_name,
  4730. tool_no=tool_cnt)
  4731. if res == 'fail':
  4732. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4733. return 'fail'
  4734. else:
  4735. dia_cnc_dict['gcode'] = res
  4736. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4737. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4738. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4739. # TODO this serve for bounding box creation only; should be optimized
  4740. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4741. # for bounding box values
  4742. # geo_for_bound_values = cascaded_union([
  4743. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  4744. # ])
  4745. try:
  4746. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  4747. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4748. except Exception as e:
  4749. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4750. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4751. # object is the source of gcode
  4752. job_obj.toolchange_xy_type = "geometry"
  4753. job_obj.cnc_tools.update({
  4754. tooluid_key: deepcopy(dia_cnc_dict)
  4755. })
  4756. dia_cnc_dict.clear()
  4757. if use_thread:
  4758. # To be run in separate thread
  4759. def job_thread(app_obj):
  4760. if self.multigeo is False:
  4761. with self.app.proc_container.new(_("Generating CNC Code")):
  4762. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  4763. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4764. else:
  4765. with self.app.proc_container.new(_("Generating CNC Code")):
  4766. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  4767. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4768. # Create a promise with the name
  4769. self.app.collection.promise(outname)
  4770. # Send to worker
  4771. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4772. else:
  4773. if self.solid_geometry:
  4774. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  4775. else:
  4776. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  4777. def generatecncjob(
  4778. self, outname=None,
  4779. dia=None, offset=None,
  4780. z_cut=None, z_move=None,
  4781. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  4782. spindlespeed=None, dwell=None, dwelltime=None,
  4783. multidepth=None, depthperpass=None,
  4784. toolchange=None, toolchangez=None, toolchangexy=None,
  4785. extracut=None, extracut_length=None, startz=None, endz=None,
  4786. pp=None,
  4787. segx=None, segy=None,
  4788. use_thread=True,
  4789. plot=True):
  4790. """
  4791. Only used for TCL Command.
  4792. Creates a CNCJob out of this Geometry object. The actual
  4793. work is done by the target camlib.CNCjob
  4794. `generate_from_geometry_2()` method.
  4795. :param z_cut: Cut depth (negative)
  4796. :param z_move: Hight of the tool when travelling (not cutting)
  4797. :param feedrate: Feed rate while cutting on X - Y plane
  4798. :param feedrate_z: Feed rate while cutting on Z plane
  4799. :param feedrate_rapid: Feed rate while moving with rapids
  4800. :param dia: Tool diameter
  4801. :param outname: Name of the new object
  4802. :param spindlespeed: Spindle speed (RPM)
  4803. :param pp Name of the preprocessor
  4804. :return: None
  4805. """
  4806. tooldia = dia if dia else float(self.options["cnctooldia"])
  4807. outname = outname if outname is not None else self.options["name"]
  4808. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4809. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4810. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4811. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4812. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4813. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4814. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4815. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4816. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4817. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4818. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  4819. startz = startz if startz is not None else self.options["startz"]
  4820. endz = endz if endz is not None else float(self.options["endz"])
  4821. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4822. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4823. toolchange = toolchange if toolchange else self.options["toolchange"]
  4824. offset = offset if offset else 0.0
  4825. # int or None.
  4826. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4827. dwell = dwell if dwell else self.options["dwell"]
  4828. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4829. ppname_g = pp if pp else self.options["ppname_g"]
  4830. # Object initialization function for app.new_object()
  4831. # RUNNING ON SEPARATE THREAD!
  4832. def job_init(job_obj, app_obj):
  4833. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4834. # Propagate options
  4835. job_obj.options["tooldia"] = tooldia
  4836. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4837. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4838. job_obj.options['type'] = 'Geometry'
  4839. job_obj.options['tool_dia'] = tooldia
  4840. job_obj.segx = segx
  4841. job_obj.segy = segy
  4842. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4843. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4844. job_obj.options['xmin'] = self.options['xmin']
  4845. job_obj.options['ymin'] = self.options['ymin']
  4846. job_obj.options['xmax'] = self.options['xmax']
  4847. job_obj.options['ymax'] = self.options['ymax']
  4848. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4849. # to a value of 0.0005 which is 20 times less than 0.01
  4850. tol = float(self.app.defaults['global_tolerance']) / 20
  4851. job_obj.generate_from_geometry_2(
  4852. self, tooldia=tooldia, offset=offset, tolerance=tol,
  4853. z_cut=z_cut, z_move=z_move,
  4854. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4855. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4856. multidepth=multidepth, depthpercut=depthperpass,
  4857. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4858. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4859. pp_geometry_name=ppname_g
  4860. )
  4861. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4862. # source of gcode
  4863. job_obj.toolchange_xy_type = "geometry"
  4864. job_obj.gcode_parse()
  4865. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4866. if use_thread:
  4867. # To be run in separate thread
  4868. def job_thread(app_obj):
  4869. with self.app.proc_container.new(_("Generating CNC Code")):
  4870. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  4871. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created")), outname)
  4872. # Create a promise with the name
  4873. self.app.collection.promise(outname)
  4874. # Send to worker
  4875. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4876. else:
  4877. self.app.new_object("cncjob", outname, job_init, plot=plot)
  4878. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4879. # if self.muted_ui:
  4880. # return
  4881. # self.read_form_item('plot')
  4882. def scale(self, xfactor, yfactor=None, point=None):
  4883. """
  4884. Scales all geometry by a given factor.
  4885. :param xfactor: Factor by which to scale the object's geometry/
  4886. :type xfactor: float
  4887. :param yfactor: Factor by which to scale the object's geometry/
  4888. :type yfactor: float
  4889. :return: None
  4890. :rtype: None
  4891. """
  4892. log.debug("FlatCAMObj.FlatCAMGeometry.scale()")
  4893. try:
  4894. xfactor = float(xfactor)
  4895. except Exception:
  4896. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4897. return
  4898. if yfactor is None:
  4899. yfactor = xfactor
  4900. else:
  4901. try:
  4902. yfactor = float(yfactor)
  4903. except Exception:
  4904. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4905. return
  4906. if xfactor == 1 and yfactor == 1:
  4907. return
  4908. if point is None:
  4909. px = 0
  4910. py = 0
  4911. else:
  4912. px, py = point
  4913. self.geo_len = 0
  4914. self.old_disp_number = 0
  4915. self.el_count = 0
  4916. def scale_recursion(geom):
  4917. if type(geom) is list:
  4918. geoms = list()
  4919. for local_geom in geom:
  4920. geoms.append(scale_recursion(local_geom))
  4921. return geoms
  4922. else:
  4923. try:
  4924. self.el_count += 1
  4925. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4926. if self.old_disp_number < disp_number <= 100:
  4927. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4928. self.old_disp_number = disp_number
  4929. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4930. except AttributeError:
  4931. return geom
  4932. if self.multigeo is True:
  4933. for tool in self.tools:
  4934. # variables to display the percentage of work done
  4935. self.geo_len = 0
  4936. try:
  4937. for g in self.tools[tool]['solid_geometry']:
  4938. self.geo_len += 1
  4939. except TypeError:
  4940. self.geo_len = 1
  4941. self.old_disp_number = 0
  4942. self.el_count = 0
  4943. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4944. try:
  4945. # variables to display the percentage of work done
  4946. self.geo_len = 0
  4947. try:
  4948. self.geo_len = len(self.solid_geometry)
  4949. except TypeError:
  4950. self.geo_len = 1
  4951. self.old_disp_number = 0
  4952. self.el_count = 0
  4953. self.solid_geometry = scale_recursion(self.solid_geometry)
  4954. except AttributeError:
  4955. self.solid_geometry = []
  4956. return
  4957. self.app.proc_container.new_text = ''
  4958. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  4959. def offset(self, vect):
  4960. """
  4961. Offsets all geometry by a given vector/
  4962. :param vect: (x, y) vector by which to offset the object's geometry.
  4963. :type vect: tuple
  4964. :return: None
  4965. :rtype: None
  4966. """
  4967. log.debug("FlatCAMObj.FlatCAMGeometry.offset()")
  4968. try:
  4969. dx, dy = vect
  4970. except TypeError:
  4971. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4972. _("An (x,y) pair of values are needed. "
  4973. "Probable you entered only one value in the Offset field.")
  4974. )
  4975. return
  4976. if dx == 0 and dy == 0:
  4977. return
  4978. self.geo_len = 0
  4979. self.old_disp_number = 0
  4980. self.el_count = 0
  4981. def translate_recursion(geom):
  4982. if type(geom) is list:
  4983. geoms = list()
  4984. for local_geom in geom:
  4985. geoms.append(translate_recursion(local_geom))
  4986. return geoms
  4987. else:
  4988. try:
  4989. self.el_count += 1
  4990. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4991. if self.old_disp_number < disp_number <= 100:
  4992. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4993. self.old_disp_number = disp_number
  4994. return affinity.translate(geom, xoff=dx, yoff=dy)
  4995. except AttributeError:
  4996. return geom
  4997. if self.multigeo is True:
  4998. for tool in self.tools:
  4999. # variables to display the percentage of work done
  5000. self.geo_len = 0
  5001. try:
  5002. for g in self.tools[tool]['solid_geometry']:
  5003. self.geo_len += 1
  5004. except TypeError:
  5005. self.geo_len = 1
  5006. self.old_disp_number = 0
  5007. self.el_count = 0
  5008. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  5009. # variables to display the percentage of work done
  5010. self.geo_len = 0
  5011. try:
  5012. for g in self.solid_geometry:
  5013. self.geo_len += 1
  5014. except TypeError:
  5015. self.geo_len = 1
  5016. self.old_disp_number = 0
  5017. self.el_count = 0
  5018. self.solid_geometry = translate_recursion(self.solid_geometry)
  5019. self.app.proc_container.new_text = ''
  5020. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  5021. def convert_units(self, units):
  5022. log.debug("FlatCAMObj.FlatCAMGeometry.convert_units()")
  5023. self.ui_disconnect()
  5024. factor = Geometry.convert_units(self, units)
  5025. self.options['cutz'] = float(self.options['cutz']) * factor
  5026. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  5027. self.options['travelz'] = float(self.options['travelz']) * factor
  5028. self.options['feedrate'] = float(self.options['feedrate']) * factor
  5029. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  5030. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  5031. self.options['endz'] = float(self.options['endz']) * factor
  5032. # self.options['cnctooldia'] *= factor
  5033. # self.options['painttooldia'] *= factor
  5034. # self.options['paintmargin'] *= factor
  5035. # self.options['paintoverlap'] *= factor
  5036. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  5037. if self.app.defaults["geometry_toolchangexy"] == '':
  5038. self.options['toolchangexy'] = "0.0, 0.0"
  5039. else:
  5040. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  5041. if len(coords_xy) < 2:
  5042. self.app.inform.emit('[ERROR] %s' %
  5043. _("The Toolchange X,Y field in Edit -> Preferences "
  5044. "has to be in the format (x, y)\n"
  5045. "but now there is only one value, not two.")
  5046. )
  5047. return 'fail'
  5048. coords_xy[0] *= factor
  5049. coords_xy[1] *= factor
  5050. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  5051. if self.options['startz'] is not None:
  5052. self.options['startz'] = float(self.options['startz']) * factor
  5053. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  5054. 'endz', 'toolchangez']
  5055. if isinstance(self, FlatCAMGeometry):
  5056. temp_tools_dict = {}
  5057. tool_dia_copy = {}
  5058. data_copy = {}
  5059. for tooluid_key, tooluid_value in self.tools.items():
  5060. for dia_key, dia_value in tooluid_value.items():
  5061. if dia_key == 'tooldia':
  5062. dia_value *= factor
  5063. dia_value = float('%.*f' % (self.decimals, dia_value))
  5064. tool_dia_copy[dia_key] = dia_value
  5065. if dia_key == 'offset':
  5066. tool_dia_copy[dia_key] = dia_value
  5067. if dia_key == 'offset_value':
  5068. dia_value *= factor
  5069. tool_dia_copy[dia_key] = dia_value
  5070. # convert the value in the Custom Tool Offset entry in UI
  5071. custom_offset = None
  5072. try:
  5073. custom_offset = float(self.ui.tool_offset_entry.get_value())
  5074. except ValueError:
  5075. # try to convert comma to decimal point. if it's still not working error message and return
  5076. try:
  5077. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  5078. except ValueError:
  5079. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5080. _("Wrong value format entered, use a number."))
  5081. return
  5082. except TypeError:
  5083. pass
  5084. if custom_offset:
  5085. custom_offset *= factor
  5086. self.ui.tool_offset_entry.set_value(custom_offset)
  5087. if dia_key == 'type':
  5088. tool_dia_copy[dia_key] = dia_value
  5089. if dia_key == 'tool_type':
  5090. tool_dia_copy[dia_key] = dia_value
  5091. if dia_key == 'data':
  5092. for data_key, data_value in dia_value.items():
  5093. # convert the form fields that are convertible
  5094. for param in param_list:
  5095. if data_key == param and data_value is not None:
  5096. data_copy[data_key] = data_value * factor
  5097. # copy the other dict entries that are not convertible
  5098. if data_key not in param_list:
  5099. data_copy[data_key] = data_value
  5100. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5101. data_copy.clear()
  5102. temp_tools_dict.update({
  5103. tooluid_key: deepcopy(tool_dia_copy)
  5104. })
  5105. tool_dia_copy.clear()
  5106. self.tools.clear()
  5107. self.tools = deepcopy(temp_tools_dict)
  5108. # if there is a value in the new tool field then convert that one too
  5109. try:
  5110. self.ui.addtool_entry.returnPressed.disconnect()
  5111. except TypeError:
  5112. pass
  5113. tooldia = self.ui.addtool_entry.get_value()
  5114. if tooldia:
  5115. tooldia *= factor
  5116. tooldia = float('%.*f' % (self.decimals, tooldia))
  5117. self.ui.addtool_entry.set_value(tooldia)
  5118. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  5119. return factor
  5120. def plot_element(self, element, color=None, visible=None):
  5121. if color is None:
  5122. color = '#FF0000FF'
  5123. visible = visible if visible else self.options['plot']
  5124. try:
  5125. for sub_el in element:
  5126. self.plot_element(sub_el, color=color)
  5127. except TypeError: # Element is not iterable...
  5128. # if self.app.is_legacy is False:
  5129. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  5130. def plot(self, visible=None, kind=None):
  5131. """
  5132. Plot the object.
  5133. :param visible: Controls if the added shape is visible of not
  5134. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  5135. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  5136. :return:
  5137. """
  5138. # Does all the required setup and returns False
  5139. # if the 'ptint' option is set to False.
  5140. if not FlatCAMObj.plot(self):
  5141. return
  5142. try:
  5143. # plot solid geometries found as members of self.tools attribute dict
  5144. # for MultiGeo
  5145. if self.multigeo is True: # geo multi tool usage
  5146. for tooluid_key in self.tools:
  5147. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5148. self.plot_element(solid_geometry, visible=visible,
  5149. color=self.app.defaults["geometry_plot_line"])
  5150. else:
  5151. # plot solid geometry that may be an direct attribute of the geometry object
  5152. # for SingleGeo
  5153. if self.solid_geometry:
  5154. self.plot_element(self.solid_geometry, visible=visible,
  5155. color=self.app.defaults["geometry_plot_line"])
  5156. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  5157. self.shapes.redraw()
  5158. except (ObjectDeleted, AttributeError):
  5159. self.shapes.clear(update=True)
  5160. def on_plot_cb_click(self, *args):
  5161. if self.muted_ui:
  5162. return
  5163. self.read_form_item('plot')
  5164. self.plot()
  5165. self.ui_disconnect()
  5166. cb_flag = self.ui.plot_cb.isChecked()
  5167. for row in range(self.ui.geo_tools_table.rowCount()):
  5168. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  5169. if cb_flag:
  5170. table_cb.setChecked(True)
  5171. else:
  5172. table_cb.setChecked(False)
  5173. self.ui_connect()
  5174. def on_plot_cb_click_table(self):
  5175. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  5176. self.ui_disconnect()
  5177. # cw = self.sender()
  5178. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  5179. # cw_row = cw_index.row()
  5180. check_row = 0
  5181. self.shapes.clear(update=True)
  5182. for tooluid_key in self.tools:
  5183. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5184. # find the geo_tool_table row associated with the tooluid_key
  5185. for row in range(self.ui.geo_tools_table.rowCount()):
  5186. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  5187. if tooluid_item == int(tooluid_key):
  5188. check_row = row
  5189. break
  5190. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  5191. self.plot_element(element=solid_geometry, visible=True)
  5192. self.shapes.redraw()
  5193. # make sure that the general plot is disabled if one of the row plot's are disabled and
  5194. # if all the row plot's are enabled also enable the general plot checkbox
  5195. cb_cnt = 0
  5196. total_row = self.ui.geo_tools_table.rowCount()
  5197. for row in range(total_row):
  5198. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  5199. cb_cnt += 1
  5200. else:
  5201. cb_cnt -= 1
  5202. if cb_cnt < total_row:
  5203. self.ui.plot_cb.setChecked(False)
  5204. else:
  5205. self.ui.plot_cb.setChecked(True)
  5206. self.ui_connect()
  5207. def merge(self, geo_list, geo_final, multigeo=None):
  5208. """
  5209. Merges the geometry of objects in grb_list into
  5210. the geometry of geo_final.
  5211. :param geo_list: List of FlatCAMGerber Objects to join.
  5212. :param geo_final: Destination FlatCAMGerber object.
  5213. :param multigeo: if the merged geometry objects are of type MultiGeo
  5214. :return: None
  5215. """
  5216. if geo_final.solid_geometry is None:
  5217. geo_final.solid_geometry = []
  5218. if type(geo_final.solid_geometry) is not list:
  5219. geo_final.solid_geometry = [geo_final.solid_geometry]
  5220. for geo in geo_list:
  5221. for option in geo.options:
  5222. if option is not 'name':
  5223. try:
  5224. geo_final.options[option] = deepcopy(geo.options[option])
  5225. except Exception as e:
  5226. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  5227. # Expand lists
  5228. if type(geo) is list:
  5229. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  5230. # If not list, just append
  5231. else:
  5232. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  5233. if multigeo is None or multigeo is False:
  5234. geo_final.multigeo = False
  5235. try:
  5236. geo_final.solid_geometry.append(deepcopy(geo.solid_geometry))
  5237. except Exception as e:
  5238. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  5239. else:
  5240. geo_final.multigeo = True
  5241. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  5242. # tools object attribute, as a key value
  5243. geo_final.solid_geometry = []
  5244. # find the tool_uid maximum value in the geo_final
  5245. geo_final_uid_list = []
  5246. for key in geo_final.tools:
  5247. geo_final_uid_list.append(int(key))
  5248. try:
  5249. max_uid = max(geo_final_uid_list, key=int)
  5250. except ValueError:
  5251. max_uid = 0
  5252. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  5253. # to merge the obj.tools as it is likely there is none to merge.
  5254. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  5255. for tool_uid in geo.tools:
  5256. max_uid += 1
  5257. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  5258. @staticmethod
  5259. def get_pts(o):
  5260. """
  5261. Returns a list of all points in the object, where
  5262. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  5263. of such. Search is done recursively.
  5264. :param: geometric object
  5265. :return: List of points
  5266. :rtype: list
  5267. """
  5268. pts = []
  5269. # Iterable: descend into each item.
  5270. try:
  5271. for subo in o:
  5272. pts += FlatCAMGeometry.get_pts(subo)
  5273. # Non-iterable
  5274. except TypeError:
  5275. if o is not None:
  5276. if type(o) == MultiPolygon:
  5277. for poly in o:
  5278. pts += FlatCAMGeometry.get_pts(poly)
  5279. # ## Descend into .exerior and .interiors
  5280. elif type(o) == Polygon:
  5281. pts += FlatCAMGeometry.get_pts(o.exterior)
  5282. for i in o.interiors:
  5283. pts += FlatCAMGeometry.get_pts(i)
  5284. elif type(o) == MultiLineString:
  5285. for line in o:
  5286. pts += FlatCAMGeometry.get_pts(line)
  5287. # ## Has .coords: list them.
  5288. else:
  5289. pts += list(o.coords)
  5290. else:
  5291. return
  5292. return pts
  5293. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  5294. """
  5295. Represents G-Code.
  5296. """
  5297. optionChanged = QtCore.pyqtSignal(str)
  5298. ui_type = CNCObjectUI
  5299. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  5300. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  5301. spindlespeed=None):
  5302. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  5303. self.decimals = self.app.decimals
  5304. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  5305. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  5306. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  5307. FlatCAMObj.__init__(self, name)
  5308. self.kind = "cncjob"
  5309. self.options.update({
  5310. "plot": True,
  5311. "tooldia": 0.03937, # 0.4mm in inches
  5312. "append": "",
  5313. "prepend": "",
  5314. "dwell": False,
  5315. "dwelltime": 1,
  5316. "type": 'Geometry',
  5317. "toolchange_macro": '',
  5318. "toolchange_macro_enable": False
  5319. })
  5320. '''
  5321. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5322. diameter of the tools and the value is another dict that will hold the data under the following form:
  5323. {tooldia: {
  5324. 'tooluid': 1,
  5325. 'offset': 'Path',
  5326. 'type_item': 'Rough',
  5327. 'tool_type': 'C1',
  5328. 'data': {} # a dict to hold the parameters
  5329. 'gcode': "" # a string with the actual GCODE
  5330. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  5331. (cut or move)
  5332. 'solid_geometry': []
  5333. },
  5334. ...
  5335. }
  5336. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  5337. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5338. '''
  5339. self.cnc_tools = dict()
  5340. '''
  5341. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5342. diameter of the tools and the value is another dict that will hold the data under the following form:
  5343. {tooldia: {
  5344. 'tool': int,
  5345. 'nr_drills': int,
  5346. 'nr_slots': int,
  5347. 'offset': float,
  5348. 'data': {} # a dict to hold the parameters
  5349. 'gcode': "" # a string with the actual GCODE
  5350. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  5351. 'solid_geometry': []
  5352. },
  5353. ...
  5354. }
  5355. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  5356. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  5357. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5358. '''
  5359. self.exc_cnc_tools = dict()
  5360. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  5361. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  5362. self.special_group = None
  5363. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  5364. # (like the one in the TCL Command), False
  5365. self.multitool = False
  5366. # determine if the GCode was generated out of a Excellon object or a Geometry object
  5367. self.origin_kind = None
  5368. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  5369. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  5370. self.g_x_re = re.compile(gcodex_re_string)
  5371. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  5372. self.g_y_re = re.compile(gcodey_re_string)
  5373. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  5374. self.g_z_re = re.compile(gcodez_re_string)
  5375. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  5376. self.g_f_re = re.compile(gcodef_re_string)
  5377. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  5378. self.g_t_re = re.compile(gcodet_re_string)
  5379. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  5380. self.g_nr_re = re.compile(gcodenr_re_string)
  5381. # Attributes to be included in serialization
  5382. # Always append to it because it carries contents
  5383. # from predecessors.
  5384. self.ser_attrs += ['options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool']
  5385. if self.app.is_legacy is False:
  5386. self.text_col = self.app.plotcanvas.new_text_collection()
  5387. self.text_col.enabled = True
  5388. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  5389. self.gcode_editor_tab = None
  5390. self.units_found = self.app.defaults['units']
  5391. def build_ui(self):
  5392. self.ui_disconnect()
  5393. FlatCAMObj.build_ui(self)
  5394. self.units = self.app.defaults['units'].upper()
  5395. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  5396. self.ui.cnc_tools_table.hide()
  5397. if self.cnc_tools:
  5398. self.ui.cnc_tools_table.show()
  5399. self.build_cnc_tools_table()
  5400. self.ui.exc_cnc_tools_table.hide()
  5401. if self.exc_cnc_tools:
  5402. self.ui.exc_cnc_tools_table.show()
  5403. self.build_excellon_cnc_tools()
  5404. #
  5405. self.ui_connect()
  5406. def build_cnc_tools_table(self):
  5407. offset = 0
  5408. tool_idx = 0
  5409. n = len(self.cnc_tools)
  5410. self.ui.cnc_tools_table.setRowCount(n)
  5411. for dia_key, dia_value in self.cnc_tools.items():
  5412. tool_idx += 1
  5413. row_no = tool_idx - 1
  5414. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5415. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  5416. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5417. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  5418. # There are no tool bits in MM with more than 2 decimals diameter.
  5419. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  5420. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  5421. offset_txt = list(str(dia_value['offset']))
  5422. offset_txt[0] = offset_txt[0].upper()
  5423. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  5424. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  5425. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  5426. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5427. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5428. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5429. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5430. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5431. # hack so the checkbox stay centered in the table cell
  5432. # used this:
  5433. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5434. # plot_item = QtWidgets.QWidget()
  5435. # checkbox = FCCheckBox()
  5436. # checkbox.setCheckState(QtCore.Qt.Checked)
  5437. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5438. # qhboxlayout.addWidget(checkbox)
  5439. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5440. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5441. plot_item = FCCheckBox()
  5442. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5443. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  5444. if self.ui.plot_cb.isChecked():
  5445. plot_item.setChecked(True)
  5446. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5447. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  5448. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  5449. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  5450. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5451. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  5452. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5453. # make the diameter column editable
  5454. # for row in range(tool_idx):
  5455. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  5456. # QtCore.Qt.ItemIsEnabled)
  5457. for row in range(tool_idx):
  5458. self.ui.cnc_tools_table.item(row, 0).setFlags(
  5459. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5460. self.ui.cnc_tools_table.resizeColumnsToContents()
  5461. self.ui.cnc_tools_table.resizeRowsToContents()
  5462. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  5463. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  5464. vertical_header.hide()
  5465. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5466. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  5467. horizontal_header.setMinimumSectionSize(10)
  5468. horizontal_header.setDefaultSectionSize(70)
  5469. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5470. horizontal_header.resizeSection(0, 20)
  5471. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5472. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5473. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  5474. horizontal_header.resizeSection(4, 40)
  5475. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5476. horizontal_header.resizeSection(4, 17)
  5477. # horizontal_header.setStretchLastSection(True)
  5478. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5479. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  5480. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  5481. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  5482. # self.ui.geo_tools_table.setSortingEnabled(True)
  5483. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  5484. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  5485. def build_excellon_cnc_tools(self):
  5486. tool_idx = 0
  5487. n = len(self.exc_cnc_tools)
  5488. self.ui.exc_cnc_tools_table.setRowCount(n)
  5489. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  5490. tool_idx += 1
  5491. row_no = tool_idx - 1
  5492. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5493. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  5494. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  5495. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  5496. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset_z']) + self.z_cut))
  5497. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5498. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5499. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5500. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5501. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5502. # hack so the checkbox stay centered in the table cell
  5503. # used this:
  5504. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5505. # plot_item = QtWidgets.QWidget()
  5506. # checkbox = FCCheckBox()
  5507. # checkbox.setCheckState(QtCore.Qt.Checked)
  5508. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5509. # qhboxlayout.addWidget(checkbox)
  5510. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5511. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5512. plot_item = FCCheckBox()
  5513. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5514. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  5515. if self.ui.plot_cb.isChecked():
  5516. plot_item.setChecked(True)
  5517. # TODO until the feature of individual plot for an Excellon tool is implemented
  5518. plot_item.setDisabled(True)
  5519. self.ui.exc_cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5520. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5521. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  5522. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  5523. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5524. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  5525. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  5526. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5527. for row in range(tool_idx):
  5528. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  5529. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5530. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  5531. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  5532. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  5533. vertical_header.hide()
  5534. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5535. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  5536. horizontal_header.setMinimumSectionSize(10)
  5537. horizontal_header.setDefaultSectionSize(70)
  5538. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5539. horizontal_header.resizeSection(0, 20)
  5540. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5541. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  5542. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5543. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  5544. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5545. # horizontal_header.setStretchLastSection(True)
  5546. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5547. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  5548. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  5549. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5550. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5551. def set_ui(self, ui):
  5552. FlatCAMObj.set_ui(self, ui)
  5553. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  5554. assert isinstance(self.ui, CNCObjectUI), \
  5555. "Expected a CNCObjectUI, got %s" % type(self.ui)
  5556. self.units = self.app.defaults['units'].upper()
  5557. self.units_found = self.app.defaults['units']
  5558. # this signal has to be connected to it's slot before the defaults are populated
  5559. # the decision done in the slot has to override the default value set bellow
  5560. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  5561. self.form_fields.update({
  5562. "plot": self.ui.plot_cb,
  5563. "tooldia": self.ui.tooldia_entry,
  5564. "append": self.ui.append_text,
  5565. "prepend": self.ui.prepend_text,
  5566. "toolchange_macro": self.ui.toolchange_text,
  5567. "toolchange_macro_enable": self.ui.toolchange_cb
  5568. })
  5569. # Fill form fields only on object create
  5570. self.to_form()
  5571. # this means that the object that created this CNCJob was an Excellon or Geometry
  5572. try:
  5573. if self.travel_distance:
  5574. self.ui.t_distance_label.show()
  5575. self.ui.t_distance_entry.setVisible(True)
  5576. self.ui.t_distance_entry.setDisabled(True)
  5577. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  5578. self.ui.units_label.setText(str(self.units).lower())
  5579. self.ui.units_label.setDisabled(True)
  5580. self.ui.t_time_label.show()
  5581. self.ui.t_time_entry.setVisible(True)
  5582. self.ui.t_time_entry.setDisabled(True)
  5583. # if time is more than 1 then we have minutes, else we have seconds
  5584. if self.routing_time > 1:
  5585. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  5586. self.ui.units_time_label.setText('min')
  5587. else:
  5588. time_r = self.routing_time * 60
  5589. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  5590. self.ui.units_time_label.setText('sec')
  5591. self.ui.units_time_label.setDisabled(True)
  5592. except AttributeError:
  5593. pass
  5594. if self.multitool is False:
  5595. self.ui.tooldia_entry.show()
  5596. self.ui.updateplot_button.show()
  5597. else:
  5598. self.ui.tooldia_entry.hide()
  5599. self.ui.updateplot_button.hide()
  5600. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  5601. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  5602. try:
  5603. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  5604. except (TypeError, AttributeError):
  5605. pass
  5606. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  5607. # set if to display text annotations
  5608. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  5609. # Show/Hide Advanced Options
  5610. if self.app.defaults["global_app_level"] == 'b':
  5611. self.ui.level.setText(_(
  5612. '<span style="color:green;"><b>Basic</b></span>'
  5613. ))
  5614. self.ui.cnc_frame.hide()
  5615. else:
  5616. self.ui.level.setText(_(
  5617. '<span style="color:red;"><b>Advanced</b></span>'
  5618. ))
  5619. self.ui.cnc_frame.show()
  5620. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  5621. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  5622. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  5623. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  5624. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  5625. def on_cnc_custom_parameters(self, signal_text):
  5626. if signal_text == 'Parameters':
  5627. return
  5628. else:
  5629. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5630. def ui_connect(self):
  5631. for row in range(self.ui.cnc_tools_table.rowCount()):
  5632. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  5633. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  5634. def ui_disconnect(self):
  5635. for row in range(self.ui.cnc_tools_table.rowCount()):
  5636. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  5637. try:
  5638. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  5639. except (TypeError, AttributeError):
  5640. pass
  5641. def on_updateplot_button_click(self, *args):
  5642. """
  5643. Callback for the "Updata Plot" button. Reads the form for updates
  5644. and plots the object.
  5645. """
  5646. self.read_form()
  5647. self.on_plot_kind_change()
  5648. def on_plot_kind_change(self):
  5649. kind = self.ui.cncplot_method_combo.get_value()
  5650. def worker_task():
  5651. with self.app.proc_container.new(_("Plotting...")):
  5652. self.plot(kind=kind)
  5653. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  5654. def on_exportgcode_button_click(self, *args):
  5655. self.app.report_usage("cncjob_on_exportgcode_button")
  5656. self.read_form()
  5657. name = self.app.collection.get_active().options['name']
  5658. save_gcode = False
  5659. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5660. _filter_ = "RML1 Files (*.rol);;All Files (*.*)"
  5661. elif 'hpgl' in self.pp_geometry_name:
  5662. _filter_ = "HPGL Files (*.plt);;All Files (*.*)"
  5663. else:
  5664. save_gcode = True
  5665. _filter_ = self.app.defaults['cncjob_save_filters']
  5666. try:
  5667. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  5668. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5669. caption=_("Export Machine Code ..."),
  5670. directory=dir_file_to_save,
  5671. filter=_filter_
  5672. )
  5673. except TypeError:
  5674. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  5675. filename = str(filename)
  5676. if filename == '':
  5677. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  5678. return
  5679. else:
  5680. if save_gcode is True:
  5681. used_extension = filename.rpartition('.')[2]
  5682. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  5683. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  5684. self.ui.name_entry.set_value(new_name)
  5685. self.on_name_activate(silent=True)
  5686. preamble = str(self.ui.prepend_text.get_value())
  5687. postamble = str(self.ui.append_text.get_value())
  5688. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  5689. if gc == 'fail':
  5690. return
  5691. if self.app.defaults["global_open_style"] is False:
  5692. self.app.file_opened.emit("gcode", filename)
  5693. self.app.file_saved.emit("gcode", filename)
  5694. self.app.inform.emit('[success] %s: %s' %
  5695. (_("Machine Code file saved to"), filename))
  5696. def on_edit_code_click(self, *args):
  5697. self.app.proc_container.view.set_busy(_("Loading..."))
  5698. preamble = str(self.ui.prepend_text.get_value())
  5699. postamble = str(self.ui.append_text.get_value())
  5700. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  5701. if gco == 'fail':
  5702. return
  5703. else:
  5704. self.app.gcode_edited = gco
  5705. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  5706. # add the tab if it was closed
  5707. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  5708. self.gcode_editor_tab.setObjectName('code_editor_tab')
  5709. # delete the absolute and relative position and messages in the infobar
  5710. self.app.ui.position_label.setText("")
  5711. self.app.ui.rel_position_label.setText("")
  5712. # first clear previous text in text editor (if any)
  5713. self.gcode_editor_tab.code_editor.clear()
  5714. self.gcode_editor_tab.code_editor.setReadOnly(False)
  5715. self.gcode_editor_tab.code_editor.completer_enable = False
  5716. self.gcode_editor_tab.buttonRun.hide()
  5717. # Switch plot_area to CNCJob tab
  5718. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  5719. self.gcode_editor_tab.t_frame.hide()
  5720. # then append the text from GCode to the text editor
  5721. try:
  5722. self.gcode_editor_tab.code_editor.setPlainText(self.app.gcode_edited.getvalue())
  5723. # for line in self.app.gcode_edited:
  5724. # QtWidgets.QApplication.processEvents()
  5725. #
  5726. # proc_line = str(line).strip('\n')
  5727. # self.gcode_editor_tab.code_editor.append(proc_line)
  5728. except Exception as e:
  5729. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  5730. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  5731. return
  5732. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5733. self.gcode_editor_tab.handleTextChanged()
  5734. self.gcode_editor_tab.t_frame.show()
  5735. self.app.proc_container.view.set_idle()
  5736. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  5737. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  5738. """
  5739. Will create a header to be added to all GCode files generated by FlatCAM
  5740. :param comment_start_symbol: a symbol to be used as the first symbol in a comment
  5741. :param comment_stop_symbol: a symbol to be used as the last symbol in a comment
  5742. :return: a string with a GCode header
  5743. """
  5744. log.debug("FlatCAMCNCJob.gcode_header()")
  5745. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5746. marlin = False
  5747. hpgl = False
  5748. probe_pp = False
  5749. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  5750. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  5751. try:
  5752. for key in self.cnc_tools:
  5753. ppg = self.cnc_tools[key]['data']['ppname_g']
  5754. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower() :
  5755. marlin = True
  5756. break
  5757. if ppg == 'hpgl':
  5758. hpgl = True
  5759. break
  5760. if "toolchange_probe" in ppg.lower():
  5761. probe_pp = True
  5762. break
  5763. except KeyError:
  5764. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  5765. pass
  5766. try:
  5767. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  5768. marlin = True
  5769. except KeyError:
  5770. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5771. pass
  5772. try:
  5773. if "toolchange_probe" in self.options['ppname_e'].lower():
  5774. probe_pp = True
  5775. except KeyError:
  5776. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5777. pass
  5778. if marlin is True:
  5779. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5780. (str(self.app.version), str(self.app.version_date)) + '\n'
  5781. gcode += ';Name: ' + str(self.options['name']) + '\n'
  5782. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  5783. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5784. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5785. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  5786. gcode += ';Created on ' + time_str + '\n' + '\n'
  5787. elif hpgl is True:
  5788. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  5789. (str(self.app.version), str(self.app.version_date)) + '";\n'
  5790. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  5791. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  5792. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5793. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5794. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  5795. gcode += 'CO "Created on ' + time_str + '";\n'
  5796. elif probe_pp is True:
  5797. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  5798. (str(self.app.version), str(self.app.version_date)) + '\n'
  5799. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  5800. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  5801. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  5802. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  5803. 'Then zero the Z axis.)\n' + '\n'
  5804. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  5805. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  5806. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5807. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5808. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  5809. gcode += '(Created on ' + time_str + ')\n' + '\n'
  5810. else:
  5811. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  5812. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  5813. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  5814. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  5815. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5816. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5817. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  5818. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  5819. return gcode
  5820. def gcode_footer(self, end_command=None):
  5821. """
  5822. :param end_command: 'M02' or 'M30' - String
  5823. :return:
  5824. """
  5825. if end_command:
  5826. return end_command
  5827. else:
  5828. return 'M02'
  5829. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  5830. """
  5831. This will save the GCode from the Gcode object to a file on the OS filesystem
  5832. :param filename: filename for the GCode file
  5833. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  5834. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  5835. :param to_file: if False then no actual file is saved but the app will know that a file was created
  5836. :return: None
  5837. """
  5838. # gcode = ''
  5839. # roland = False
  5840. # hpgl = False
  5841. # isel_icp = False
  5842. include_header = True
  5843. try:
  5844. if self.special_group:
  5845. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  5846. (_("This CNCJob object can't be processed because it is a"),
  5847. str(self.special_group),
  5848. _("CNCJob object")))
  5849. return 'fail'
  5850. except AttributeError:
  5851. pass
  5852. # if this dict is not empty then the object is a Geometry object
  5853. if self.cnc_tools:
  5854. first_key = next(iter(self.cnc_tools))
  5855. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  5856. # if this dict is not empty then the object is an Excellon object
  5857. if self.exc_cnc_tools:
  5858. first_key = next(iter(self.exc_cnc_tools))
  5859. include_header = self.app.preprocessors[self.exc_cnc_tools[first_key]['data']['ppname_e']].include_header
  5860. # # detect if using Roland preprocessor
  5861. # try:
  5862. # for key in self.cnc_tools:
  5863. # if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  5864. # roland = True
  5865. # break
  5866. # except Exception:
  5867. # try:
  5868. # for key in self.cnc_tools:
  5869. # if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  5870. # roland = True
  5871. # break
  5872. # except Exception:
  5873. # pass
  5874. #
  5875. # # detect if using HPGL preprocessor
  5876. # try:
  5877. # for key in self.cnc_tools:
  5878. # if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  5879. # hpgl = True
  5880. # break
  5881. # except Exception:
  5882. # try:
  5883. # for key in self.cnc_tools:
  5884. # if self.cnc_tools[key]['data']['ppname_e'] == 'hpgl':
  5885. # hpgl = True
  5886. # break
  5887. # except Exception:
  5888. # pass
  5889. #
  5890. # # detect if using ISEL_ICP_CNC preprocessor
  5891. # try:
  5892. # for key in self.cnc_tools:
  5893. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_g'].upper():
  5894. # isel_icp = True
  5895. # break
  5896. # except Exception:
  5897. # try:
  5898. # for key in self.cnc_tools:
  5899. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_e'].upper():
  5900. # isel_icp = True
  5901. # break
  5902. # except Exception:
  5903. # pass
  5904. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  5905. # if roland is False and hpgl is False and isel_icp is False:
  5906. # gcode = self.gcode_header()
  5907. # do not add gcode_header when using the Roland, HPGL or ISEP_ICP_CNC preprocessor (or any other preprocessor
  5908. # that has the include_header attribute set as False, add it for every other preprocessor
  5909. # if include_header:
  5910. # gcode = self.gcode_header()
  5911. # else:
  5912. # gcode = ''
  5913. # # detect if using multi-tool and make the Gcode summation correctly for each case
  5914. # if self.multitool is True:
  5915. # for tooluid_key in self.cnc_tools:
  5916. # for key, value in self.cnc_tools[tooluid_key].items():
  5917. # if key == 'gcode':
  5918. # gcode += value
  5919. # break
  5920. # else:
  5921. # gcode += self.gcode
  5922. # if roland is True:
  5923. # g = preamble + gcode + postamble
  5924. # elif hpgl is True:
  5925. # g = self.gcode_header() + preamble + gcode + postamble
  5926. # else:
  5927. # # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5928. # g_idx = gcode.rfind('G20')
  5929. #
  5930. # # if it did not find 'G20' then search for 'G21'
  5931. # if g_idx == -1:
  5932. # g_idx = gcode.rfind('G21')
  5933. #
  5934. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5935. # # but only when the preprocessor is not ISEL_ICP who is allowed not to have the G20/G21 command
  5936. # if g_idx == -1 and isel_icp is False:
  5937. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5938. # return
  5939. #
  5940. # footer = self.app.defaults['cncjob_footer']
  5941. # end_gcode = self.gcode_footer() if footer is True else ''
  5942. # g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  5943. gcode = ''
  5944. if include_header is False:
  5945. g = preamble
  5946. # detect if using multi-tool and make the Gcode summation correctly for each case
  5947. if self.multitool is True:
  5948. for tooluid_key in self.cnc_tools:
  5949. for key, value in self.cnc_tools[tooluid_key].items():
  5950. if key == 'gcode':
  5951. gcode += value
  5952. break
  5953. else:
  5954. gcode += self.gcode
  5955. g = g + gcode + postamble
  5956. else:
  5957. # search for the GCode beginning which is usually a G20 or G21
  5958. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5959. # g_idx = gcode.rfind('G20')
  5960. #
  5961. # # if it did not find 'G20' then search for 'G21'
  5962. # if g_idx == -1:
  5963. # g_idx = gcode.rfind('G21')
  5964. #
  5965. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5966. # if g_idx == -1:
  5967. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5968. # return
  5969. # detect if using multi-tool and make the Gcode summation correctly for each case
  5970. if self.multitool is True:
  5971. for tooluid_key in self.cnc_tools:
  5972. for key, value in self.cnc_tools[tooluid_key].items():
  5973. if key == 'gcode':
  5974. gcode += value
  5975. break
  5976. else:
  5977. gcode += self.gcode
  5978. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  5979. # detect if using a HPGL preprocessor
  5980. hpgl = False
  5981. if self.cnc_tools:
  5982. for key in self.cnc_tools:
  5983. if 'ppname_g' in self.cnc_tools[key]['data']:
  5984. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  5985. hpgl = True
  5986. break
  5987. elif self.exc_cnc_tools:
  5988. for key in self.cnc_tools:
  5989. if 'ppname_e' in self.cnc_tools[key]['data']:
  5990. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  5991. hpgl = True
  5992. break
  5993. if hpgl:
  5994. processed_gcode = ''
  5995. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  5996. for gline in gcode.splitlines():
  5997. match = pa_re.search(gline)
  5998. if match:
  5999. x_int = int(float(match.group(1)))
  6000. y_int = int(float(match.group(2)))
  6001. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  6002. processed_gcode += new_line
  6003. else:
  6004. processed_gcode += gline + '\n'
  6005. gcode = processed_gcode
  6006. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  6007. else:
  6008. try:
  6009. g_idx = gcode.index('G94')
  6010. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  6011. gcode[(g_idx + 3):] + postamble + end_gcode
  6012. except ValueError:
  6013. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6014. _("G-code does not have a G94 code and we will not include the code in the "
  6015. "'Prepend to GCode' text box"))
  6016. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  6017. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  6018. if self.ui.toolchange_cb.get_value() is True:
  6019. # match = self.re_toolchange.search(g)
  6020. if 'M6' in g:
  6021. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  6022. if m6_code is None or m6_code == '':
  6023. self.app.inform.emit(
  6024. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  6025. )
  6026. return 'fail'
  6027. g = g.replace('M6', m6_code)
  6028. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  6029. lines = StringIO(g)
  6030. # Write
  6031. if filename is not None:
  6032. try:
  6033. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  6034. if force_windows_line_endings and sys.platform != 'win32':
  6035. with open(filename, 'w', newline='\r\n') as f:
  6036. for line in lines:
  6037. f.write(line)
  6038. else:
  6039. with open(filename, 'w') as f:
  6040. for line in lines:
  6041. f.write(line)
  6042. except FileNotFoundError:
  6043. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  6044. return
  6045. except PermissionError:
  6046. self.app.inform.emit(
  6047. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  6048. "Most likely another app is holding the file open and not accessible.")
  6049. )
  6050. return 'fail'
  6051. elif to_file is False:
  6052. # Just for adding it to the recent files list.
  6053. if self.app.defaults["global_open_style"] is False:
  6054. self.app.file_opened.emit("cncjob", filename)
  6055. self.app.file_saved.emit("cncjob", filename)
  6056. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  6057. else:
  6058. return lines
  6059. def on_toolchange_custom_clicked(self, signal):
  6060. try:
  6061. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  6062. if self.ui.toolchange_cb.get_value():
  6063. self.ui.toolchange_cb.set_value(False)
  6064. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6065. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  6066. except KeyError:
  6067. try:
  6068. for key in self.cnc_tools:
  6069. ppg = self.cnc_tools[key]['data']['ppname_g']
  6070. if 'toolchange_custom' not in str(ppg).lower():
  6071. print(ppg)
  6072. if self.ui.toolchange_cb.get_value():
  6073. self.ui.toolchange_cb.set_value(False)
  6074. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6075. _("The used preprocessor file has to have in it's name: "
  6076. "'toolchange_custom'"))
  6077. except KeyError:
  6078. self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  6079. def get_gcode(self, preamble='', postamble=''):
  6080. # we need this to be able get_gcode separatelly for shell command export_gcode
  6081. return preamble + '\n' + self.gcode + "\n" + postamble
  6082. def get_svg(self):
  6083. # we need this to be able get_svg separately for shell command export_svg
  6084. pass
  6085. def on_plot_cb_click(self, *args):
  6086. if self.muted_ui:
  6087. return
  6088. kind = self.ui.cncplot_method_combo.get_value()
  6089. self.plot(kind=kind)
  6090. self.read_form_item('plot')
  6091. self.ui_disconnect()
  6092. cb_flag = self.ui.plot_cb.isChecked()
  6093. for row in range(self.ui.cnc_tools_table.rowCount()):
  6094. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  6095. if cb_flag:
  6096. table_cb.setChecked(True)
  6097. else:
  6098. table_cb.setChecked(False)
  6099. self.ui_connect()
  6100. def on_plot_cb_click_table(self):
  6101. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  6102. self.ui_disconnect()
  6103. # cw = self.sender()
  6104. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  6105. # cw_row = cw_index.row()
  6106. kind = self.ui.cncplot_method_combo.get_value()
  6107. self.shapes.clear(update=True)
  6108. for tooluid_key in self.cnc_tools:
  6109. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6110. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6111. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  6112. for r in range(self.ui.cnc_tools_table.rowCount()):
  6113. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  6114. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  6115. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  6116. self.shapes.redraw()
  6117. # make sure that the general plot is disabled if one of the row plot's are disabled and
  6118. # if all the row plot's are enabled also enable the general plot checkbox
  6119. cb_cnt = 0
  6120. total_row = self.ui.cnc_tools_table.rowCount()
  6121. for row in range(total_row):
  6122. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  6123. cb_cnt += 1
  6124. else:
  6125. cb_cnt -= 1
  6126. if cb_cnt < total_row:
  6127. self.ui.plot_cb.setChecked(False)
  6128. else:
  6129. self.ui.plot_cb.setChecked(True)
  6130. self.ui_connect()
  6131. def plot(self, visible=None, kind='all'):
  6132. # Does all the required setup and returns False
  6133. # if the 'ptint' option is set to False.
  6134. if not FlatCAMObj.plot(self):
  6135. return
  6136. visible = visible if visible else self.options['plot']
  6137. if self.app.is_legacy is False:
  6138. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  6139. self.text_col.enabled = True
  6140. else:
  6141. self.text_col.enabled = False
  6142. self.annotation.redraw()
  6143. try:
  6144. if self.multitool is False: # single tool usage
  6145. try:
  6146. dia_plot = float(self.options["tooldia"])
  6147. except ValueError:
  6148. # we may have a tuple with only one element and a comma
  6149. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  6150. self.plot2(dia_plot, obj=self, visible=visible, kind=kind)
  6151. else:
  6152. # multiple tools usage
  6153. if self.cnc_tools:
  6154. for tooluid_key in self.cnc_tools:
  6155. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6156. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6157. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6158. # TODO: until the gcode parsed will be stored on each Excellon tool this will not get executed
  6159. if self.exc_cnc_tools:
  6160. for tooldia_key in self.exc_cnc_tools:
  6161. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  6162. # gcode_parsed = self.cnc_tools[tooldia_key]['gcode_parsed']
  6163. gcode_parsed = self.gcode_parsed
  6164. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6165. self.shapes.redraw()
  6166. except (ObjectDeleted, AttributeError):
  6167. self.shapes.clear(update=True)
  6168. if self.app.is_legacy is False:
  6169. self.annotation.clear(update=True)
  6170. def on_annotation_change(self):
  6171. if self.app.is_legacy is False:
  6172. if self.ui.annotation_cb.get_value():
  6173. self.text_col.enabled = True
  6174. else:
  6175. self.text_col.enabled = False
  6176. # kind = self.ui.cncplot_method_combo.get_value()
  6177. # self.plot(kind=kind)
  6178. self.annotation.redraw()
  6179. else:
  6180. kind = self.ui.cncplot_method_combo.get_value()
  6181. self.plot(kind=kind)
  6182. def convert_units(self, units):
  6183. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  6184. factor = CNCjob.convert_units(self, units)
  6185. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  6186. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  6187. 'endz', 'toolchangez']
  6188. temp_tools_dict = {}
  6189. tool_dia_copy = {}
  6190. data_copy = {}
  6191. for tooluid_key, tooluid_value in self.cnc_tools.items():
  6192. for dia_key, dia_value in tooluid_value.items():
  6193. if dia_key == 'tooldia':
  6194. dia_value *= factor
  6195. dia_value = float('%.*f' % (self.decimals, dia_value))
  6196. tool_dia_copy[dia_key] = dia_value
  6197. if dia_key == 'offset':
  6198. tool_dia_copy[dia_key] = dia_value
  6199. if dia_key == 'offset_value':
  6200. dia_value *= factor
  6201. tool_dia_copy[dia_key] = dia_value
  6202. if dia_key == 'type':
  6203. tool_dia_copy[dia_key] = dia_value
  6204. if dia_key == 'tool_type':
  6205. tool_dia_copy[dia_key] = dia_value
  6206. if dia_key == 'data':
  6207. for data_key, data_value in dia_value.items():
  6208. # convert the form fields that are convertible
  6209. for param in param_list:
  6210. if data_key == param and data_value is not None:
  6211. data_copy[data_key] = data_value * factor
  6212. # copy the other dict entries that are not convertible
  6213. if data_key not in param_list:
  6214. data_copy[data_key] = data_value
  6215. tool_dia_copy[dia_key] = deepcopy(data_copy)
  6216. data_copy.clear()
  6217. if dia_key == 'gcode':
  6218. tool_dia_copy[dia_key] = dia_value
  6219. if dia_key == 'gcode_parsed':
  6220. tool_dia_copy[dia_key] = dia_value
  6221. if dia_key == 'solid_geometry':
  6222. tool_dia_copy[dia_key] = dia_value
  6223. # if dia_key == 'solid_geometry':
  6224. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  6225. # if dia_key == 'gcode_parsed':
  6226. # for g in dia_value:
  6227. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  6228. #
  6229. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  6230. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  6231. temp_tools_dict.update({
  6232. tooluid_key: deepcopy(tool_dia_copy)
  6233. })
  6234. tool_dia_copy.clear()
  6235. self.cnc_tools.clear()
  6236. self.cnc_tools = deepcopy(temp_tools_dict)
  6237. class FlatCAMScript(FlatCAMObj):
  6238. """
  6239. Represents a TCL script object.
  6240. """
  6241. optionChanged = QtCore.pyqtSignal(str)
  6242. ui_type = ScriptObjectUI
  6243. def __init__(self, name):
  6244. self.decimals = self.app.decimals
  6245. FlatCAMApp.App.log.debug("Creating a FlatCAMScript object...")
  6246. FlatCAMObj.__init__(self, name)
  6247. self.kind = "script"
  6248. self.options.update({
  6249. "plot": True,
  6250. "type": 'Script',
  6251. "source_file": '',
  6252. })
  6253. self.units = ''
  6254. self.ser_attrs = ['options', 'kind', 'source_file']
  6255. self.source_file = ''
  6256. self.script_code = ''
  6257. self.units_found = self.app.defaults['units']
  6258. # self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6259. self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6260. def set_ui(self, ui):
  6261. FlatCAMObj.set_ui(self, ui)
  6262. FlatCAMApp.App.log.debug("FlatCAMScript.set_ui()")
  6263. assert isinstance(self.ui, ScriptObjectUI), \
  6264. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  6265. self.units = self.app.defaults['units'].upper()
  6266. self.units_found = self.app.defaults['units']
  6267. # Fill form fields only on object create
  6268. self.to_form()
  6269. # Show/Hide Advanced Options
  6270. if self.app.defaults["global_app_level"] == 'b':
  6271. self.ui.level.setText(_(
  6272. '<span style="color:green;"><b>Basic</b></span>'
  6273. ))
  6274. else:
  6275. self.ui.level.setText(_(
  6276. '<span style="color:red;"><b>Advanced</b></span>'
  6277. ))
  6278. # tab_here = False
  6279. # # try to not add too many times a tab that it is already installed
  6280. # for idx in range(self.app.ui.plot_tab_area.count()):
  6281. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6282. # tab_here = True
  6283. # break
  6284. #
  6285. # # add the tab if it is not already added
  6286. # if tab_here is False:
  6287. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6288. # self.script_editor_tab.setObjectName(self.options['name'])
  6289. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6290. self.script_editor_tab.setObjectName(self.options['name'])
  6291. # first clear previous text in text editor (if any)
  6292. # self.script_editor_tab.code_editor.clear()
  6293. # self.script_editor_tab.code_editor.setReadOnly(False)
  6294. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  6295. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  6296. self.script_editor_tab.buttonRun.show()
  6297. # Switch plot_area to CNCJob tab
  6298. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  6299. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6300. self.script_editor_tab.buttonOpen.clicked.disconnect()
  6301. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  6302. self.script_editor_tab.buttonSave.clicked.disconnect()
  6303. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  6304. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  6305. self.script_editor_tab.handleTextChanged()
  6306. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6307. self.ser_attrs = ['options', 'kind', 'source_file']
  6308. # ---------------------------------------------------- #
  6309. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  6310. # ---------------------------------------------------- #
  6311. self.app.proc_container.view.set_busy(_("Loading..."))
  6312. self.script_editor_tab.t_frame.hide()
  6313. try:
  6314. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  6315. # for line in self.source_file.splitlines():
  6316. # QtWidgets.QApplication.processEvents()
  6317. # self.script_editor_tab.code_editor.append(line)
  6318. except Exception as e:
  6319. log.debug("FlatCAMScript.set_ui() --> %s" % str(e))
  6320. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  6321. self.script_editor_tab.t_frame.show()
  6322. self.app.proc_container.view.set_idle()
  6323. self.build_ui()
  6324. def build_ui(self):
  6325. FlatCAMObj.build_ui(self)
  6326. def handle_run_code(self):
  6327. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  6328. # tries to print on a hidden widget, therefore show the dock if hidden
  6329. if self.app.ui.shell_dock.isHidden():
  6330. self.app.ui.shell_dock.show()
  6331. self.script_code = deepcopy(self.script_editor_tab.code_editor.toPlainText())
  6332. old_line = ''
  6333. for tcl_command_line in self.script_code.splitlines():
  6334. # do not process lines starting with '#' = comment and empty lines
  6335. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  6336. # id FlatCAM is run in Windows then replace all the slashes with
  6337. # the UNIX style slash that TCL understands
  6338. if sys.platform == 'win32':
  6339. if "open" in tcl_command_line:
  6340. tcl_command_line = tcl_command_line.replace('\\', '/')
  6341. if old_line != '':
  6342. new_command = old_line + tcl_command_line + '\n'
  6343. else:
  6344. new_command = tcl_command_line
  6345. # execute the actual Tcl command
  6346. try:
  6347. self.app.shell.open_processing() # Disables input box.
  6348. result = self.app.tcl.eval(str(new_command))
  6349. if result != 'None':
  6350. self.app.shell.append_output(result + '\n')
  6351. old_line = ''
  6352. except tk.TclError:
  6353. old_line = old_line + tcl_command_line + '\n'
  6354. except Exception as e:
  6355. log.debug("FlatCAMScript.handleRunCode() --> %s" % str(e))
  6356. if old_line != '':
  6357. # it means that the script finished with an error
  6358. result = self.app.tcl.eval("set errorInfo")
  6359. log.error("Exec command Exception: %s" % (result + '\n'))
  6360. self.app.shell.append_error('ERROR: ' + result + '\n')
  6361. self.app.shell.close_processing()
  6362. def on_autocomplete_changed(self, state):
  6363. if state:
  6364. self.script_editor_tab.code_editor.completer_enable = True
  6365. else:
  6366. self.script_editor_tab.code_editor.completer_enable = False
  6367. def to_dict(self):
  6368. """
  6369. Returns a representation of the object as a dictionary.
  6370. Attributes to include are listed in ``self.ser_attrs``.
  6371. :return: A dictionary-encoded copy of the object.
  6372. :rtype: dict
  6373. """
  6374. d = {}
  6375. for attr in self.ser_attrs:
  6376. d[attr] = getattr(self, attr)
  6377. return d
  6378. def from_dict(self, d):
  6379. """
  6380. Sets object's attributes from a dictionary.
  6381. Attributes to include are listed in ``self.ser_attrs``.
  6382. This method will look only for only and all the
  6383. attributes in ``self.ser_attrs``. They must all
  6384. be present. Use only for deserializing saved
  6385. objects.
  6386. :param d: Dictionary of attributes to set in the object.
  6387. :type d: dict
  6388. :return: None
  6389. """
  6390. for attr in self.ser_attrs:
  6391. setattr(self, attr, d[attr])
  6392. class FlatCAMDocument(FlatCAMObj):
  6393. """
  6394. Represents a Document object.
  6395. """
  6396. optionChanged = QtCore.pyqtSignal(str)
  6397. ui_type = DocumentObjectUI
  6398. def __init__(self, name):
  6399. self.decimals = self.app.decimals
  6400. FlatCAMApp.App.log.debug("Creating a Document object...")
  6401. FlatCAMObj.__init__(self, name)
  6402. self.kind = "document"
  6403. self.units = ''
  6404. self.ser_attrs = ['options', 'kind', 'source_file']
  6405. self.source_file = ''
  6406. self.doc_code = ''
  6407. self.font_italic = None
  6408. self.font_bold = None
  6409. self.font_underline =None
  6410. self.document_editor_tab = None
  6411. self._read_only = False
  6412. self.units_found = self.app.defaults['units']
  6413. def set_ui(self, ui):
  6414. FlatCAMObj.set_ui(self, ui)
  6415. FlatCAMApp.App.log.debug("FlatCAMDocument.set_ui()")
  6416. assert isinstance(self.ui, DocumentObjectUI), \
  6417. "Expected a DocumentObjectUI, got %s" % type(self.ui)
  6418. self.units = self.app.defaults['units'].upper()
  6419. self.units_found = self.app.defaults['units']
  6420. # Fill form fields only on object create
  6421. self.to_form()
  6422. # Show/Hide Advanced Options
  6423. if self.app.defaults["global_app_level"] == 'b':
  6424. self.ui.level.setText(_(
  6425. '<span style="color:green;"><b>Basic</b></span>'
  6426. ))
  6427. else:
  6428. self.ui.level.setText(_(
  6429. '<span style="color:red;"><b>Advanced</b></span>'
  6430. ))
  6431. self.document_editor_tab = TextEditor(app=self.app)
  6432. stylesheet = """
  6433. QTextEdit {selection-background-color:%s;
  6434. selection-color:white;
  6435. }
  6436. """ % self.app.defaults["document_sel_color"]
  6437. self.document_editor_tab.code_editor.setStyleSheet(stylesheet)
  6438. # first clear previous text in text editor (if any)
  6439. self.document_editor_tab.code_editor.clear()
  6440. self.document_editor_tab.code_editor.setReadOnly(self._read_only)
  6441. self.document_editor_tab.buttonRun.hide()
  6442. self.ui.autocomplete_cb.set_value(self.app.defaults['document_autocompleter'])
  6443. self.on_autocomplete_changed(state=self.app.defaults['document_autocompleter'])
  6444. self.on_tab_size_change(val=self.app.defaults['document_tab_size'])
  6445. flt = "FlatCAM Docs (*.FlatDoc);;All Files (*.*)"
  6446. # ######################################################################
  6447. # ######################## SIGNALS #####################################
  6448. # ######################################################################
  6449. self.document_editor_tab.buttonOpen.clicked.disconnect()
  6450. self.document_editor_tab.buttonOpen.clicked.connect(lambda: self.document_editor_tab.handleOpen(filt=flt))
  6451. self.document_editor_tab.buttonSave.clicked.disconnect()
  6452. self.document_editor_tab.buttonSave.clicked.connect(lambda: self.document_editor_tab.handleSaveGCode(filt=flt))
  6453. self.document_editor_tab.code_editor.textChanged.connect(self.on_text_changed)
  6454. self.ui.font_type_cb.currentFontChanged.connect(self.font_family)
  6455. self.ui.font_size_cb.activated.connect(self.font_size)
  6456. self.ui.font_bold_tb.clicked.connect(self.on_bold_button)
  6457. self.ui.font_italic_tb.clicked.connect(self.on_italic_button)
  6458. self.ui.font_under_tb.clicked.connect(self.on_underline_button)
  6459. self.ui.font_color_entry.editingFinished.connect(self.on_font_color_entry)
  6460. self.ui.font_color_button.clicked.connect(self.on_font_color_button)
  6461. self.ui.sel_color_entry.editingFinished.connect(self.on_selection_color_entry)
  6462. self.ui.sel_color_button.clicked.connect(self.on_selection_color_button)
  6463. self.ui.al_left_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignLeft))
  6464. self.ui.al_center_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignCenter))
  6465. self.ui.al_right_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignRight))
  6466. self.ui.al_justify_tb.clicked.connect(
  6467. lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignJustify)
  6468. )
  6469. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6470. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6471. # #######################################################################
  6472. self.ui.font_color_entry.set_value(self.app.defaults['document_font_color'])
  6473. self.ui.font_color_button.setStyleSheet(
  6474. "background-color:%s" % str(self.app.defaults['document_font_color']))
  6475. self.ui.sel_color_entry.set_value(self.app.defaults['document_sel_color'])
  6476. self.ui.sel_color_button.setStyleSheet(
  6477. "background-color:%s" % self.app.defaults['document_sel_color'])
  6478. self.ui.font_size_cb.setCurrentIndex(int(self.app.defaults['document_font_size']))
  6479. self.document_editor_tab.handleTextChanged()
  6480. self.ser_attrs = ['options', 'kind', 'source_file']
  6481. if Qt.mightBeRichText(self.source_file):
  6482. self.document_editor_tab.code_editor.setHtml(self.source_file)
  6483. else:
  6484. for line in self.source_file.splitlines():
  6485. self.document_editor_tab.code_editor.append(line)
  6486. self.build_ui()
  6487. @property
  6488. def read_only(self):
  6489. return self._read_only
  6490. @read_only.setter
  6491. def read_only(self, val):
  6492. if val:
  6493. self._read_only = True
  6494. else:
  6495. self._read_only = False
  6496. def build_ui(self):
  6497. FlatCAMObj.build_ui(self)
  6498. tab_here = False
  6499. # try to not add too many times a tab that it is already installed
  6500. for idx in range(self.app.ui.plot_tab_area.count()):
  6501. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6502. tab_here = True
  6503. break
  6504. # add the tab if it is not already added
  6505. if tab_here is False:
  6506. self.app.ui.plot_tab_area.addTab(self.document_editor_tab, '%s' % _("Document Editor"))
  6507. self.document_editor_tab.setObjectName(self.options['name'])
  6508. # Switch plot_area to CNCJob tab
  6509. self.app.ui.plot_tab_area.setCurrentWidget(self.document_editor_tab)
  6510. def on_autocomplete_changed(self, state):
  6511. if state:
  6512. self.document_editor_tab.code_editor.completer_enable = True
  6513. else:
  6514. self.document_editor_tab.code_editor.completer_enable = False
  6515. def on_tab_size_change(self, val=None):
  6516. try:
  6517. self.ui.tab_size_spinner.returnPressed.disconnect(self.on_tab_size_change)
  6518. except TypeError:
  6519. pass
  6520. if val:
  6521. self.ui.tab_size_spinner.set_value(val)
  6522. tab_balue = int(self.ui.tab_size_spinner.get_value())
  6523. self.document_editor_tab.code_editor.setTabStopWidth(tab_balue)
  6524. self.app.defaults['document_tab_size'] = tab_balue
  6525. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6526. def on_text_changed(self):
  6527. self.source_file = self.document_editor_tab.code_editor.toHtml()
  6528. # print(self.source_file)
  6529. def font_family(self, font):
  6530. # self.document_editor_tab.code_editor.selectAll()
  6531. font.setPointSize(float(self.ui.font_size_cb.get_value()))
  6532. self.document_editor_tab.code_editor.setCurrentFont(font)
  6533. self.font_name = self.ui.font_type_cb.currentFont().family()
  6534. def font_size(self):
  6535. # self.document_editor_tab.code_editor.selectAll()
  6536. self.document_editor_tab.code_editor.setFontPointSize(float(self.ui.font_size_cb.get_value()))
  6537. def on_bold_button(self):
  6538. if self.ui.font_bold_tb.isChecked():
  6539. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Bold)
  6540. self.font_bold = True
  6541. else:
  6542. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Normal)
  6543. self.font_bold = False
  6544. def on_italic_button(self):
  6545. if self.ui.font_italic_tb.isChecked():
  6546. self.document_editor_tab.code_editor.setFontItalic(True)
  6547. self.font_italic = True
  6548. else:
  6549. self.document_editor_tab.code_editor.setFontItalic(False)
  6550. self.font_italic = False
  6551. def on_underline_button(self):
  6552. if self.ui.font_under_tb.isChecked():
  6553. self.document_editor_tab.code_editor.setFontUnderline(True)
  6554. self.font_underline = True
  6555. else:
  6556. self.document_editor_tab.code_editor.setFontUnderline(False)
  6557. self.font_underline = False
  6558. # Setting font colors handlers
  6559. def on_font_color_entry(self):
  6560. self.app.defaults['document_font_color'] = self.ui.font_color_entry.get_value()
  6561. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_font_color']))
  6562. def on_font_color_button(self):
  6563. current_color = QtGui.QColor(self.app.defaults['document_font_color'])
  6564. c_dialog = QtWidgets.QColorDialog()
  6565. font_color = c_dialog.getColor(initial=current_color)
  6566. if font_color.isValid() is False:
  6567. return
  6568. self.document_editor_tab.code_editor.setTextColor(font_color)
  6569. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(font_color.name()))
  6570. new_val = str(font_color.name())
  6571. self.ui.font_color_entry.set_value(new_val)
  6572. self.app.defaults['document_font_color'] = new_val
  6573. # Setting selection colors handlers
  6574. def on_selection_color_entry(self):
  6575. self.app.defaults['document_sel_color'] = self.ui.sel_color_entry.get_value()
  6576. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_sel_color']))
  6577. def on_selection_color_button(self):
  6578. current_color = QtGui.QColor(self.app.defaults['document_sel_color'])
  6579. c_dialog = QtWidgets.QColorDialog()
  6580. sel_color = c_dialog.getColor(initial=current_color)
  6581. if sel_color.isValid() is False:
  6582. return
  6583. p = QtGui.QPalette()
  6584. p.setColor(QtGui.QPalette.Highlight, sel_color)
  6585. p.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('white'))
  6586. self.document_editor_tab.code_editor.setPalette(p)
  6587. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(sel_color.name()))
  6588. new_val = str(sel_color.name())
  6589. self.ui.sel_color_entry.set_value(new_val)
  6590. self.app.defaults['document_sel_color'] = new_val
  6591. def to_dict(self):
  6592. """
  6593. Returns a representation of the object as a dictionary.
  6594. Attributes to include are listed in ``self.ser_attrs``.
  6595. :return: A dictionary-encoded copy of the object.
  6596. :rtype: dict
  6597. """
  6598. d = {}
  6599. for attr in self.ser_attrs:
  6600. d[attr] = getattr(self, attr)
  6601. return d
  6602. def from_dict(self, d):
  6603. """
  6604. Sets object's attributes from a dictionary.
  6605. Attributes to include are listed in ``self.ser_attrs``.
  6606. This method will look only for only and all the
  6607. attributes in ``self.ser_attrs``. They must all
  6608. be present. Use only for deserializing saved
  6609. objects.
  6610. :param d: Dictionary of attributes to set in the object.
  6611. :type d: dict
  6612. :return: None
  6613. """
  6614. for attr in self.ser_attrs:
  6615. setattr(self, attr, d[attr])
  6616. # end of file