FlatCAMObj.py 299 KB

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