FlatCAMObj.py 299 KB

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