FlatCAMObj.py 279 KB

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