FlatCAMObj.py 307 KB

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