FlatCAMObj.py 343 KB

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