FlatCAMObj.py 275 KB

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