FlatCAMObj.py 274 KB

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