FlatCAMObj.py 300 KB

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