FlatCAMObj.py 275 KB

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