FlatCAMObj.py 306 KB

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