FlatCAMObj.py 273 KB

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