FlatCAMObj.py 298 KB

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