FlatCAMObj.py 319 KB

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