FlatCAMObj.py 299 KB

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