FlatCAMObj.py 305 KB

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