FlatCAMObj.py 307 KB

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