FlatCAMObj.py 273 KB

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